Week-06 · ML-2026
RNNs and Transformer encoders
Alexei Kornaev,
Dr. Sc., Prof.
Innopolis University
Researcher at the RC for AI,
National RC for Oncology n.a. N.N. Blokhin

Session 1: Parts 1–2. Session 2: Parts 3–4.
Code inspection remains a separate, flexible part of each session.
Track positions, feature widths, parameter sharing, and permitted inputs.
| Symbol | Meaning |
|---|---|
| Position within one sequence | |
| Input row vector at position | |
| Preactivation and recurrent state | |
| All token representations at encoder layer | |
| Trainable parameters and the stated loss |
Subscripts locate a position. Superscripts locate a layer.
How can the current prediction use earlier observations?
The position axis adds structure to the feature axis.
| Task | Observed input | Output | Example |
|---|---|---|---|
| Sequence classification | One label | Classify an utterance | |
| Position-wise labeling | One label per position | Label each word’s role | |
| Next-observation prediction | Predict position | Forecast a measurement |
Specify the information available at the moment of prediction.
Task: classify the direction of the trend. Can the mean distinguish these sequences?
Both means are . Their ordered changes have opposite signs.
An MLP can use order
Each window position occupies distinct input coordinates.
Its input width is fixed
A new window length needs an explicit handling rule.
An RNN offers a shared update for successive positions.
The state changes at each position. The cell parameters are shared.
Two input coordinates, two state coordinates. Here .
1 · Current input
2 · Previous state
3 · Affine sum
4 · Activation
Every state coordinate has its own weights and bias.
RNN formulation: Goodfellow, Bengio & Courville, Chapter 10. Original course diagram.
| Quantity | Shape | Role |
|---|---|---|
| , | , | Current features, previous state |
| , | , | One row per state unit |
| , , | Bias, affine sum, activation |
The same row-vector convention extends Week 04’s affine layer.
Three observations from two numerical features. Illustrative, untrained parameters.
| Position | Input |
|---|---|
Both input coordinates may be signed, as with standardized sensor features.
All three steps reuse these same ten cell parameters.
and .
1 · Current-input contribution
2 · Previous-state contribution
3 · Add the bias
4 · Apply tanh to each coordinate
A zero initial state leaves the input and bias paths active.
and the computed .
1 · Current-input contribution
2 · Previous-state contribution
3 · Add both contributions and the bias
4 · Apply tanh
| 0 | |||
| 1 | |||
| 2 |
Each state depends on a prefix through repeated uses of one cell.
Our cell has .
If we process six positions instead of three, how many trainable cell parameters do we use?
Still . There are more computations and saved states.
Classification
logits support a distribution over classes.
Regression
An affine head can predict a continuous target directly.
Hidden coordinates, logits, and probabilities have different roles.
A shared parameter receives a contribution from every use.
First microscope: identity readout, target .
A loss derivative describes sensitivity, not a parameter update.
At : ,
Three steps, . Here for a target vector .
1 · Loss and final activation
2 · Previous state receives a signal
3 · Repeat the local chain rule
4 · Sum contributions to one shared matrix
and are row vectors.
Chain rule and parameter sharing: Goodfellow, Bengio & Courville, Chapter 10. and the square act coordinate-wise.
| Backward order | |||
|---|---|---|---|
Read the ledger from the final position back to the first.
Rows index receiving units. Columns index previous-state coordinates.
Use at t = 0
Use at t = 1
Use at t = 2
Sum
The contributions add to one matrix. They may reinforce or cancel.
Only the final state has a loss. The matrix appears at .
Should its gradient include just the last use, or all three uses?
Sum all uses. In this example, the term is zero because .
Second microscope: classes, target IDs .
For this mean objective, divide by once at the loss derivative.
At the final position:
Target ID: .
Mean loss across all three positions:
The output head changes the objective and its direct gradient paths.
1 · Direct signal through this position’s output head
2 · Add the signal from the next recurrent use
3 · Pass through the local activation
At the final position, the future contribution is zero.
Goodfellow, Bengio & Courville (2016), Chapter 10. Derivatives independently checked.
The local input changes by position. The parameter is shared.
Compute the complete gradient before the optimizer changes parameters.
| Objective | Checked parameters | Max. finite-difference error | Max. autograd error |
|---|---|---|---|
| Final-state squared error | 10 scalars | ||
| Mean three-position CE | 19 scalars |
Finite differences and PyTorch autograd agree with manual BPTT.
Original float64 calculations. Full numerical ledger.
Along one future-loss path, every transition changes the sensitivity.
Toy scalar case: a constant local derivative gives .
Original illustrative calculation; Pascanu et al. (2013) analyzes the matrix case.
Clipping caps large gradients. It cannot recover a vanished signal.
A gate near one retains that coordinate. A gate near zero favors the candidate.
PyTorch GRU equations. Here names its update gate .
. is the logistic sigmoid.
Retention/update gate
Reset gate
Candidate state
Retention controls the mixture. Reset controls recurrent input to the candidate.
PyTorch GRU: reset after the recurrent affine operation.
Forget, input, and output gates control retention, writing, and reading.
PyTorch LSTM equations. Plain LSTM, without projection or peephole connections.
| Cell | Carried state | Update structure |
|---|---|---|
| Simple RNN | Affine mixing followed by activation | |
| GRU | Gated mixture of old state and candidate | |
| LSTM | Gated storage, writing, and visible readout |
Attention offers another route: combine source representations directly.
Each position forms a weighted combination of permitted source representations.
A contextual representation depends on the surrounding sequence.
Token information
A learned table maps categories to vectors.
Position information
identifies where a token occurs.
Token IDs are labels; their numerical magnitude has no semantic meaning.
The query row chooses weights over source value rows.
| Weights | Shape | Projected rows |
|---|---|---|
| Queries and keys: | ||
| Values: |
Matching needs equal query/key widths. Value width may differ.
Positions : “the”, “cat”, “sleeps”. , , .
Query weights
Key weights
Value weights
These illustrative parameters expose arithmetic, not learned language semantics.
The same input row produces three vectors with different roles.
Update position : . Source index .
Raw dot-product scores
Scale by the square root of query/key width
Rows locate queries; columns locate sources
A score measures query–key compatibility before normalization.
Toy assumptions: all query/key coordinates are independent, with mean and variance .
Scaling counters larger score variance as the head width grows.
Weights are nonnegative and sum to one within a query row.
Source values
Weighted combination
One contextual output row
The output is a feature vector; its coordinates need not sum to one.
Weights A
Outputs O
mixes positions. contains output features.
Original checked arithmetic. Full numeric ledger.
has shape : rows are queries, columns are source positions.
Which axis sums to one, and which vectors form ?
Each query row sums to one across sources. combines the source value vectors.
Position 1 can use sources 0 and 1, while source 2 receives zero weight.
Each head can form a different combination of source features.
| Query position | Head 1 output | Head 2 output |
|---|---|---|
| 0 | ||
| 1 | ||
| 2 |
Two width-2 outputs concatenate to width 4 at every query position.
The projection mixes features within a row and returns width .
Track the representation through one block, then through the stack.
Pre-norm teaching variant
Attention branch
MLP branch
Input, both additions, and output: .
Each branch computes a change and adds it to its own input.
Pre/post-norm distinction: Xiong et al. (2020).
| Operation | What interacts? | Parameters across positions |
|---|---|---|
| Attention | Permitted source rows | Shared projection maps |
| LayerNorm | Features within one row | Shared scale and shift |
| MLP | Features within one row | Shared affine maps |
Only attention introduces new interactions between positions inside this block.
Three positions, , one head with . Fixed, untrained values.
Track row 0 through both branches; every row is computed.
Both LN modules: , , . No attention bias or dropout.
Mean and population variance across D features
Normalize, then apply learned feature scale and shift
; one statistic pair per row.
LayerNorm uses the current row in both training and inference.
| Position | Mean | Population variance | Normalized row |
|---|---|---|---|
| 0 | 0.5000 | 1.2500 | |
| 1 | 0.5000 | 1.2500 | |
| 2 | 1.0000 | 0.5000 |
Changing another token does not change this row’s LayerNorm statistics.
The attention output has width 2; the residual input has width 4.
Add the attention branch to , with matching position and feature axes.
Every token uses the same network; no connection crosses token rows here.
Bias vectors broadcast across rows; the output returns to width .
Here and ; all parameters are illustrative.
ReLU removes the negative preactivation in this row.
The second addition carries around the normalized MLP branch.
| Position | Input | After attention | Block output |
|---|---|---|---|
| 0 | |||
| 1 | |||
| 2 |
Encoder depth changes the representations while preserving their axes.
Original checked example. Complete parameters and intermediate values.
when , otherwise ; are positions, are features.
Bypass
The input can influence the output without passing through the branch’s transformations.
Branch
Gradients also follow the learned transformations and their cross-position dependencies.
An identity contribution helps preserve a route; it does not guarantee stable gradients.
LayerNorm is inside the branch.
LayerNorm follows the addition.
The diagrams describe different computations, even with matching parameter shapes.
Original post-norm: Vaswani et al. (2017), §3.1. Comparison: Xiong et al. (2020).
Sharing over positions does not imply sharing parameters over depth.
permutes matrix rows; identifies the input row moved to position .
Equivariance
Reordering input rows reorders output rows when no position-dependent features or masks are present.
Pooling
A mean of those rows gives the same sequence representation after a permutation.
A bidirectional block needs a position signal to distinguish supplied order.
Even ; position-vector feature indices start at . .
Move a token to another position and its initial representation changes.
Sinusoidal example: Vaswani et al. (2017), §3.5.
for a real token and for padding.
Mask padded sources at every layer; omit padded outputs from loss and pooling.
Token classification
One class distribution per real token.
Sequence classification
One distribution after pooling.
Both examples may use the complete input sequence when the task permits it.
: vocabulary size. : positions with a valid next-token target.
Position may read while predicting the unseen .
Which operation mixes source positions inside one block?
If row predicts , which sources must be hidden?
Attention mixes positions. Hide sources at every layer; keep the target shifted to .
Patch embeddings change the input; the encoder still uses width .
| Connection structure | Consequence within one layer |
|---|---|
| Recurrent state chain | State updates depend on earlier updates |
| Full self-attention | Query rows can be computed in parallel |
Short interaction paths trade against the cost of considering all source pairs.
Structural comparison: Vaswani et al. (2017), §4.
| Question | Recurrent state | Transformer block |
|---|---|---|
| How do positions interact? | Shared state update along the sequence | Input-dependent mixtures of permitted source values |
| What is shared? | Cell parameters across positions | Projection and MLP parameters across positions |
| How does learning reach parameters? | Backpropagation through all uses of the cell | Backpropagation through projections, mixing, row maps, and residual branches |
| What determines visibility? | Direction of the state computation | Input availability and the attention mask |
Representation, task head, target alignment, and visibility must agree.
2003 · Learned word representations
Bengio, Ducharme, Vincent, and Jauvin jointly learn word vectors and a neural language model.
2014/2015 · Attention with recurrence
Bahdanau, Cho, and Bengio learn soft alignment for neural translation.
2017 · Attention without a recurrent state chain
The eight-author Transformer team builds sequence transduction around attention.
The Transformer combines a sequence of advances in representation and information access.
Ashish Vaswani · Noam Shazeer · Niki Parmar · Jakob Uszkoreit
Llion Jones · Aidan N. Gomez · Łukasz Kaiser · Illia Polosukhin
| Contribution recorded in the paper | Researchers |
|---|---|
| Proposed replacing RNNs with self-attention | Jakob Uszkoreit |
| Designed and implemented the first Transformer models | Ashish Vaswani with Illia Polosukhin |
| Proposed scaled dot products, multiple heads, and the fixed positional representation | Noam Shazeer |
The paper declares equal contribution and randomized author order.

A pioneer of learned representations for language
2003 · Learn representations with the task
Word vectors and next-word probabilities are learned together with Ducharme, Vincent, and Jauvin. Paper
2014/2015 · Learn which source information to read
With Bahdanau and Cho, soft alignment becomes part of neural translation. Paper
2018 · ACM A.M. Turing Award
Shared with Geoffrey Hinton and Yann LeCun for breakthroughs in deep neural networks. ACM
Learn useful vectors, then learn how context should shape them.
← Lectures Introduction to Machine Learning · Week 06