Decoding the Architecture Logic of Four Major Transformer Variants
This article breaks down how four major Transformer variants differ by examining four design dimensions: input construction, visibility constraints, positional information and bias, and training objectives. It explains the bidirectional encoding route based on masked language modeling, the unidirectional generation route based on causal masking, and two vision adaptations—patch-based global attention and hierarchical windowed attention. A comparison table and a practical checklist help readers quickly place unfamiliar architectures and evaluate design trade-offs for their own tasks.
1. Why the “Same Transformer” Ends Up Looking Completely Different
A common question from beginners is this: if these models are all called Transformers, why are some good at reading sentences while others can recognize image content? The answer is not mysterious. Only two things are genuinely reused: first, splitting the input into a sequence of vectors that carry positional information (a token sequence); second, using self-attention to exchange global information across that sequence. Beyond this, how the input is split, who is allowed to see whom, how positional information is supplied, and whether a locality assumption is introduced are all “modifiable items” that can be rewritten per task.
So when comparing variants, don’t memorize architecture diagrams. Instead, ask questions along four threads:
- Input construction: what granularity a sample is split into, and what extra embeddings are attached.
- Visibility constraints: whether attention needs a causal mask, and whether bidirectional access is allowed.
- Position and bias: absolute position, relative position, or position implied by the structure itself.
- Training objective: masked reconstruction, next-unit prediction, or discriminative fine-tuning for downstream tasks.
2. The Bidirectional Encoding Route: Trading Masked Language Modeling for Contextual Understanding
Before the bidirectional route appeared, the mainstream approach was “task-specific supervised learning plus a unidirectional language model.” The weakness of unidirectional modeling is direct: each position can only see the content on its left and cannot truly exploit cues on the right. Concatenating two unidirectional models does cover both sides, but the objective is still local prediction, and sentence-level semantics is not explicitly modeled.
The bidirectional encoding route makes three core changes.
First, the structure stacks encoders, and self-attention adds no causal mask, so any position can see any other. Second, the input is constructed as a structured sequence: a start marker + sentence A + a separator marker + sentence B + a separator marker. The output at the start marker position is often treated as the representation of the whole sentence, while separator markers are used to split and distinguish segments. Third, the representation of each unit is the sum of three types of embeddings:
Input = TokenEmbedding + PositionEmbedding + SegmentEmbedding
- Token embedding: maps discrete symbols to vectors, with special markers participating in the same table.
- Position embedding: attention itself is insensitive to order, so position must be supplied explicitly; a common choice is learnable absolute position.
- Segment embedding: identifies which sentence the current unit belongs to, supporting sentence-pair tasks.
The training objective is usually a combination of masked language modeling (randomly masking some units and reconstructing them) and sentence-pair relationship discrimination (judging whether two sentences are adjacent). Its capability boundary must also be recognized: because masking exists during training but not during inference, the input distributions differ; and global bidirectionality means true left-to-right streaming generation is impossible at inference time.
3. The Unidirectional Generation Route: Turning the Model into a “Probability Continuator” with a Causal Mask
The generation route keeps the decoder form from the encoder-decoder design but adds a causal mask to self-attention: position t can only see units no greater than t. This one line of masking has two consequences: the input form during training and inference is exactly the same, enabling unit-by-unit streaming output; and what the model learns is not “understanding the whole sentence” but “the conditional distribution of the next unit given a prefix.”
In engineering practice, this is usually simplified into a single-tower structure. The input does not need segment embeddings, and positional information can use learnable absolute positions or rotary and other relative position schemes to extrapolate better to longer contexts. The training objective is next-unit prediction, combined with training-stability techniques such as weight tying, residual connections, and pre-layer normalization. Its shortcoming is equally clear: intermediate positions cannot directly access right-side information and need the model to “look back” indirectly through multiple layers, making it less direct than bidirectional encoding on tasks requiring precise bidirectional retrieval.
4. Vision Adaptation One: Treating an Image as a Sentence via Patch Sequences
The key move in feeding a 2D image to attention is “patch + flatten + linear projection”: cut the image into fixed-size blocks, flatten each block and map it to a vector as wide as the text model, then concatenate them into a sequence. A class marker is appended at the front of the sequence, and its output is used for image-level discrimination. Positional information must be added, because patch order itself carries no geometric relationship; common choices are learnable absolute position embeddings or 2D relative position encoding.
# Illustration: splitting an image into a sequencepatches = reshape(image, (B, num_patches, patch_size * patch_size * C))tokens = linear(patches) # project to model widthtokens = concat([cls_token, tokens], dim=1) # prepend class markertokens = tokens + pos_embed # inject positional information
The cost of this adaptation is data hunger: global attention has no built-in assumptions of locality or translation invariance, so it overfits easily on small datasets and typically relies on large-scale pretraining, strong data augmentation, and regularization. Its advantage is that the receptive field is global from the very first layer, making long-range dependency modeling natural.
5. Vision Adaptation Two: Hierarchical and Windowed Design, Bringing Inductive Bias Back
The second line of thinking does not pursue a “pure sequence” but reinjects the locality and multi-scale properties of convolution: attention is computed only within local windows, and information flows between windows through shifting or grouping. The overall design is hierarchical, with resolution decreasing and channel count increasing layer by layer, naturally producing multi-scale features that fit downstream tasks such as detection and segmentation.
Windowing reduces complexity from quadratic in sequence length to a linear scale related to window size, which is the fundamental reason it can handle high-resolution inputs. The cost is higher implementation complexity: window partitioning and restoration, mask handling for boundary blocks, and cross-window connection design. The selection advice is practical: with small data, high resolution, and a need for multi-scale output, prefer the hierarchical window scheme; with ample data and a preference for the simplicity of global modeling, the patch-based global scheme is an option.
6. A Unified View and a Deployment Checklist
Filling the four threads into one table makes the differences obvious:
| Dimension | Bidirectional Encoding | Unidirectional Generation | Patch-Based Global Vision | Hierarchical Windowed Vision |
|---|---|---|---|---|
| Input unit | Subword unit | Subword unit | Image patch | Multi-scale block |
| Visibility | Fully bidirectional | Causal mask | Fully bidirectional | Visible within window |
| Position injection | Learnable absolute | Absolute/relative | Absolute or 2D relative | Hierarchical relative |
| Typical objective | Masked reconstruction + sentence-pair discrimination | Next-unit prediction | Image-level discrimination | Multi-scale dense prediction |
When deploying, self-check in order: whether input granularity matches the task; whether the mask direction is consistent with the inference mode; whether the position scheme covers the target length; whether the inductive bias matches the data scale; and whether the pretraining objective and the downstream objective share the same distribution. To reproduce on your own data, you can use a container platform to run distributed training, object storage to hold checkpoints and datasets, a message queue to decouple the data pipeline, and logging services with monitoring and alerting to track loss and throughput. On Baidu AI Cloud, these capabilities are available as general categories that can be combined on demand, without being bound to a specific implementation.
The conclusion is a single sentence: a variant’s “modifications” almost always happen in these four places—input construction, visibility, position and bias, and training objective. Grasp these four points, and even an unfamiliar architecture can be quickly placed.
