Forward Deployed EngineeringAI EngineeringTransformer Architecture

Walk me through the transformer architecture end-to-end, minus the heavy math.

Question 13 of 13 · Updated

On this page

Interview-ready answer#

A transformer is a neural network architecture that builds context-aware representations of tokens using attention rather than processing the sequence through a recurrent hidden state.

I would explain it in five steps. First, the tokenizer converts text into token IDs, which are mapped to learned embeddings. Second, positional information lets the model distinguish token order. Third, a stack of transformer blocks repeatedly refines those representations. Within each block, self-attention lets tokens exchange relevant contextual information, while a feed-forward network transforms each token's representation independently. Residual connections and normalization help maintain stable information flow through deep networks.

Finally, the output head converts the resulting representations into task-specific predictions. In a decoder-only LLM, it predicts the next token, and generation repeats autoregressively.

The architecture is powerful because attention can connect distant parts of a sequence directly and its training computations can be parallelized across token positions. The main trade-offs are the cost of attention on long sequences and the memory and latency requirements of serving large models.

Architecture at a glance#

  1. Input text — The user message, instructions, and other supplied context.
  2. Tokenization and embeddings — Convert text into token IDs and then dense numerical vectors.
  3. Positional information — Represent where tokens occur in the sequence.
  4. Repeated transformer blocks — Self-attention, feed-forward transformations, residual connections, and normalization.
  5. Final representation and output head — Produce vocabulary scores for generation or task-specific outputs for classification and other applications.

The following explanation focuses on a conventional decoder-only transformer, the architecture used by many generative LLMs. The original transformer also has an encoder and a decoder.

1. Token embeddings and position#

Tokens are pieces of text, not necessarily complete words. An embedding table maps each token ID to a vector in the model's hidden space.

The initial embedding for a given token is generally the same wherever that token appears. Its representation becomes context-dependent as it passes through transformer layers. For example, the representation of the word "bank" can change depending on whether surrounding text concerns a river or financial transactions.

Position matters because attention alone does not provide the full order information needed for language understanding. Transformers can use learned or sinusoidal position embeddings, relative position mechanisms, or rotary position embeddings (RoPE). RoPE incorporates position through rotations of attention queries and keys rather than simply adding a position vector to every input embedding.

2. Self-attention: how tokens exchange information#

Imagine the sentence: "The customer rejected the proposal because it was too expensive."

To interpret "it," the model benefits from information about the proposal and other surrounding words. Attention gives the network a mechanism for combining information from relevant token positions.

Each token representation is projected into three vectors:

ComponentIntuitive purpose
Query (Q)What information is this position looking for?
Key (K)What characteristics make this position relevant?
Value (V)What information can this position contribute?

The model compares queries with keys, converts the resulting scores into attention weights, and computes weighted combinations of the value vectors. These operations are learned numerical transformations, not literal searches for human-readable questions or facts.

In causal self-attention, a token can attend to itself and earlier positions, but not future ones. In a conventional encoder, bidirectional self-attention can use both preceding and following positions. Padding and other masks may impose additional restrictions.

Why multiple attention heads?#

A single attention pattern is not enough to represent every useful relationship. Multiple heads allow the model to compute several attention patterns in parallel using different learned projections. Their outputs are combined and projected back into the model's hidden dimension.

Some heads may capture positional or syntactic relationships, but it is incorrect to assume that each head has one fixed, human-interpretable responsibility. The behavior is distributed across heads and layers.

3. The feed-forward network#

Attention primarily mixes information across token positions. The feed-forward network, often called an MLP, applies a learned nonlinear transformation separately to each position.

A useful mental model is that attention gathers context, while the MLP processes the resulting representation. Both contribute to the model's learned capabilities; the distinction does not mean all knowledge lives exclusively in one component.

Many architectures expand the hidden dimension inside the MLP, apply nonlinear transformations or gating, and project back to the original hidden dimension. Mixture-of-experts models can route tokens to selected feed-forward experts instead of applying the same dense MLP to every token.

4. Residual connections, normalization and depth#

A residual connection adds a sublayer's output back to its input, allowing each block to refine the existing representation rather than replace it entirely. Normalization helps control activation scales and supports stable optimization.

A representative pre-normalization decoder block performs these operations:

  1. Normalize the incoming representation, apply causal self-attention, and add the attention output to the incoming representation.
  2. Normalize the updated representation, apply the MLP, and add its output back again.
  3. Pass the resulting representation into the next block.

The exact order depends on the architecture. The original transformer used post-normalization, while many modern LLMs use pre-normalization and may use RMSNorm rather than LayerNorm.

Stacking blocks allows information to be repeatedly combined and transformed. It is not necessary to assign rigid meanings to individual layers, such as claiming that a specific layer always detects grammar or factual knowledge.

5. Encoder-only, decoder-only and encoder-decoder#

ArchitectureMain attention patternTypical applications
Encoder-only (e.g., BERT)Bidirectional self-attention over the inputClassification, representation learning, embeddings
Decoder-only (e.g., GPT-style models)Causal self-attention over a growing sequenceAutoregressive text and code generation
Encoder-decoder (e.g., T5)Encoder self-attention, decoder causal self-attention, and decoder cross-attention to encoder outputsTranslation, summarization and other sequence-to-sequence tasks

Cross-attention differs from self-attention because the decoder's queries interact with keys and values derived from the encoder's representations. A decoder-only LLM instead typically receives the prompt and generated continuation as one causal sequence.

6. Training versus inference#

For a typical decoder-only model, pretraining teaches next-token prediction using many text sequences. With the training tokens already available, the model can compute predictions at multiple positions in parallel under a causal mask. Backpropagation updates its parameters to reduce prediction loss. Later training stages may further adapt the model's instruction-following behavior.

At inference, model weights normally remain fixed. The output projection produces vocabulary logits, a decoding strategy chooses a token, and the model conditions subsequent predictions on that token. A KV cache reuses previously computed attention keys and values to reduce redundant computation.

The architecture explains how representations are computed; the serving loop explains how those computations become a response. These are related but distinct concepts.

7. Practical FDE engineering trade-offs#

  • Context length: Conventional dense attention has quadratic attention work in sequence length during prefill, with model dimensions held fixed. Long inputs can increase latency and memory requirements. Evaluate context selection and retrieval rather than assuming the largest possible prompt is best.
  • Attention variants: Multi-head, grouped-query, and multi-query attention differ in how query heads share key/value heads. Sharing can reduce KV cache requirements, but model quality and serving performance must be evaluated.
  • Efficient attention kernels: FlashAttention reduces memory traffic for exact attention. It does not, by itself, turn ordinary dense attention into a linear-time algorithm.
  • Model size and serving: More parameters, longer context, and greater concurrency affect hardware capacity and latency. Quantization, batching, and appropriately sized models can help, but the correct choice depends on measured customer workloads.
  • Grounding: Attention is not a factual database or an authorization mechanism. Use trusted retrieval, tools, and external access controls when an enterprise task requires current, private, or verifiable information.

For example, suppose a customer needs both semantic search over internal documents and a conversational assistant. I would evaluate an embedding model for retrieval and a suitable generative model for answering, rather than assume one architecture or checkpoint is best for both. I would benchmark retrieval recall, answer correctness, latency, and cost on the customer's own labeled tasks. This is a hypothetical design, not a reported deployment outcome.

Likely interviewer follow-ups#

  • Why not use an RNN? Transformers can combine information across positions directly and parallelize many training computations; RNNs process recurrent state sequentially. The trade-off is the potentially high cost of full attention on long sequences.
  • What is the difference between attention and an MLP? Attention mixes information across positions; the MLP transforms each position independently.
  • Why does a decoder need a causal mask? It prevents next-token predictions from using future target tokens during training and preserves the autoregressive dependency structure.
  • Do attention weights explain the model's decisions? Not reliably on their own. Outputs depend on multiple heads, value vectors, residual pathways, and nonlinear transformations across layers.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models