Transformer Architecture Explained: From Self-Attention to Tensor Flow
This article breaks down the Transformer architecture through three core problems: representation, interaction, and transformation. It explains why sequence modeling moved away from recurrent structures, how the encoder and decoder are organized, and how tensor shapes determine implementation details. You will also find code examples for sinusoidal position encoding and self-attention, plus practical notes on masked attention, multi-head design, and tuning intuition for sequence length, learning rate, and evaluation.
1. Why Sequence Modeling Needed a Rethink
Before Transformers, the dominant approach to sequences was recurrence: tokens were read one at a time, and a hidden state was passed forward through time steps. This design has two natural bottlenecks. First, sequential dependency: step t must wait for step t-1 to finish, which makes it hard to exploit parallel compute. Second, long-range dependency decay: information from the beginning of a sentence passes through many state updates before reaching the end, and gradients tend to shrink layer by layer during backpropagation, so distant relationships are learned poorly.
The core assumption behind the Transformer is that many dependencies in language are not strictly constrained by distance. There is no need to force sequential, position-by-position processing; instead, any two positions in a sentence can interact directly. Around this assumption, the architecture is split into three independently understandable problems: how to represent (embeddings and tensor shapes), how to interact (attention), and how to transform (feed-forward layers and stacking). The sections below follow that order.
2. High-Level Overview: Encoder and Decoder as a Black Box
Start by treating the model as a black box. In a scenario like machine translation, it takes a source-language sentence and outputs a target-language sentence. Open the box and you see two major parts: the encoder reads the source sentence into a structured set of representations, and the decoder generates the target sentence position by position based on those representations, repeatedly looking back at the source while generating.
The encoder is built by stacking several structurally identical layers. The original design used six layers, but this number carries no special meaning; it is simply a trade-off between capacity and cost, and other values can be tried. The decoder typically uses the same number of layers as the encoder, which keeps the overall design symmetric and the implementation simple. All encoder layers share the same structure but do not share parameters: each layer has its own independent set of weights. This is also where “deeper means more capacity” comes from.
A single encoder layer can be split into two sub-layers:
- Self-attention layer: re-encodes every position in the input sequence, with each result fusing that position’s relationship with other positions in the sentence.
- Feed-forward network: applies a nonlinear transformation to each position independently, handling re-mapping in the feature space.
The decoder contains the same two sub-layers, but inserts an encoder-decoder attention layer before them. This layer lets each decoding position attend to relevant parts of the source sentence as needed, playing a role similar to the alignment mechanism in early sequence-to-sequence models. In addition, the decoder’s self-attention requires masking to ensure that when predicting position t, only earlier content is visible, preventing information leakage.
Two engineering components are often overlooked but cannot be omitted: each sub-layer is wrapped with a residual connection and normalization to keep gradients propagating in deep networks; and within each sub-layer, the common arrangement is “normalize first, then enter the sub-layer,” which makes training more stable.
3. The Tensor View: Shapes Drive Implementation Details
When the abstract structure lands in code, the key is to pin down tensor shapes. Let the sequence length be L and the model dimension be d_model (512 in the original design). Then:
- The input embedding tensor has shape
[L, d_model], or[B, L, d_model]when batched. - The self-attention output keeps the same shape, still
[B, L, d_model]. - Inside the feed-forward network, the dimension is first raised to
d_ff(commonly 2048) and then lowered back tod_model. - The attention score matrix has shape
[B, heads, L, L], which is where memory cost grows quadratically with sequence length.
Embedding happens only at the input of the bottom encoder. After that, every layer receives a list of 512-dimensional vectors. The difference is that the bottom layer gets word embeddings, while the other layers get the output of the layer below. The length of this list is a configurable hyperparameter, usually set to the maximum sentence length in the training set; longer inputs are truncated, shorter ones are padded, and masking is used to hide the padding.
Positional information must be injected in some way, because attention itself is insensitive to order. A common approach is to add positional encodings to the embeddings. These can be generated with sine and cosine functions at different frequencies, or with learnable position vectors. Illustrative code:
import mathdef sinusoidal_position_encoding(L, d_model):pe = [[0.0] * d_model for _ in range(L)]for pos in range(L):for i in range(d_model // 2):div = math.exp(-math.log(10000.0) * (2 * i) / d_model)pe[pos][2 * i] = math.sin(pos * div)pe[pos][2 * i + 1] = math.cos(pos * div)return pe # Shape [L, d_model], added element-wise to word embeddings
4. Self-Attention: Turning “Relationships” into Computable Weights
Self-attention can be summarized in one sentence: each position queries all positions and aggregates information weighted by relevance. In implementation, each position’s vector is projected into three parts—query, key, and value. A dot product between the query and all keys produces scores; after scaling and normalization, these become weights; finally, the values are summed with those weights.
def self_attention(x, w_q, w_k, w_v, mask=None):Q, K, V = x @ w_q, x @ w_k, x @ w_v # [B, L, d_k]scores = Q @ K.transpose(-1, -2) / (d_k ** 0.5) # [B, L, L]if mask is not None:scores = scores + mask # Masked positions get a very large negative valueweights = softmax(scores, axis=-1) # Normalize each row so it sums to 1return weights @ V # [B, L, d_k]
Three design points are worth emphasizing. The scaling factor offsets the larger variance of dot products as the dimension grows, which would otherwise push normalization into a saturated region. Masking uses addition rather than multiplication, avoiding abnormal gradients after multiplying by zero. Multi-head parallelism lets different subspaces attend to different relationships: some heads lean toward grammatical collocations, others toward coreference. The heads are then concatenated and projected back to d_model.
5. The Decoder’s Two Attention Paths
The decoder “looks” twice. The first is masked self-attention, which builds connections only within the already-generated prefix and keeps training consistent with inference. The second is encoder-decoder attention, where queries come from the decoder’s current state and keys and values come from the encoder output. During training, the whole sentence is processed in parallel, with masking simulating word-by-word generation. This turns sequential inference into a single matrix operation, which is key to training efficiency.
6. Engineering Practice and Tuning Intuition
When deploying in a general cloud environment, organize by capability: use a container platform to run training and inference workloads with elastic scaling, use object storage for corpora and checkpoints, use a message queue to decouple data preprocessing from training consumption, and use logging and monitoring with alerts to track loss curves, throughput, and memory usage.
A few rules of thumb:
- Adding layers brings capacity but also increases memory and latency; fixing the layer count first and tuning other items makes problems easier to isolate.
- Sequence length is the main amplifier of cost; for long-text scenarios, consider general ideas such as sparse or chunked attention first.
- The learning rate usually needs linear warmup followed by cosine decay, together with gradient clipping to avoid early divergence.
- Evaluation should not rely only on accuracy-style metrics; also look at long-sentence performance and the latency distribution.
7. Summary
The Transformer’s contribution is not any isolated module, but replacing sequential recurrence with attention and splitting representation, interaction, and transformation into structures that are parallelizable, stackable, and interpretable. The shortest path to understanding it is to grasp tensor shapes and the two attention paths, then return to the two input-side details: embeddings and positional encoding. Once you have this skeleton, both reading later improvements and doing engineering tuning become easier with a stable reference frame.
