Transformer evolution

Basic Transformer

  • Symbols
    • B – batch size
    • L – sequence length
    • d_model – embedding dims
  • Step 1 – input pre-processing ( embeddings and position )
    • get token embedding
    • get pos embedding of size d_model for each token as func(pos, index)
      • there are d_model(say 128) index for each each token
      • even index with sign and old with cosine
  • Step 2 – Multi head projection
    • Query, Key and Values
      • Different matrix for each attention head
      • If k heads, d_k = d_model / k
    • Intuition
      • allows model to look at same sentence from different angles in parallel
      • Group of experts looking at painting
        • one expert looks at colors
        • another at shops
        • 3rd historical context of artist
  • Step 3 – Attention equation
  • 𝐀h=Softmax(𝐐h𝐊hTdk+𝐌)𝐕h,where 𝐌ij={0amp;keep−∞amp;mask\mathbf{A}_h = \text{Softmax}\left( \frac{\mathbf{Q}_h \mathbf{K}_h^T}{\sqrt{d_k}} + \mathbf{M} \right) \mathbf{V}_h, \quad \text{where } \mathbf{M}_{ij} = \begin{cases} 0 & \text{keep} \\ -\infty & \text{mask} \end{cases}
    • Intuitions
      • 1) query matches all keys softly ( weight 0 to 1 ), values are multiplied by the weight and summed
        • In python dictionary, query matches just one key, returning its value
      • 2) query – what am I looking for ?
        • key – what do I contain ?
        • value – what information do I provide ?
  • Step 4 – head aggregation
    • concat and project
    • intuition
      • head never talked to each other before
      • weighed matrix act as committee chair
      • get vector of d_model from d_h
      • W0 is d_model x d_model
  • Step 5 – residual connection and layer norm
  • Step 6 – Position wise FFN
    • Token wise, there is no mixing
      • Same weight applied to each token
    • Two linear transformation
      • Expansion-contraction loop
      • First one has activation, second one does not
    • Intuition
      • 1) Information funnel
        • expansion creates features
        • activation selects those
        • contraction brings them back to match residual connection
        • ReLU after contraction will clamp negative values to zero resulting in information loss
      • 2) Residual connection
        • Model will loose ability to subtract value, dampen signals or reverse feature directions
      • 3) Separation of concerns
        • Attention layer as token mixer
          • Look across and let tokens talk to each other
        • FFN layer as channel mixer
          • Look inside individual token’s vector to process its features
  • Step 7 – second residual connection
  • Intuition of residual connections
    • 1) Arch argument
      • Creates residual stream, nothing overwrites, everything accumulates
      • Allows to learn identify function
        • without it, it becomes hard to reconstruct input using non linear weights
      • Preserving low level features ( position, syntax )
        • deeper layer extract higher level semantic meaning like sentiment
    • 2) Optimization argument
      • Avoid vanishing in deep networks
        • even if gradient through complex layer shrinks to 0, +1 guarantees gradient can pass till first layer
  • Math behind attention scaling
    • when d_k grows large, dot product grows large in magnitude, pushing softmax to region with extremely small gradients ( vanishing gradient problem )
    • Mathematical proof shows variance of d_k and std deviation of sqrt(d_k)
    • We kept the variance of 1, we don’t want to loose expressive power either

Norms

  • Moved layer norms in the residual branch, keeping the highway clear.
    • Its also called pre-norm
  • Recent models are moving from layerNorm to RMS because
    • 1) Few params means better bandwidth utilization ( memory bandwidth being GPU perf bottleneck )
    • 2) Single pass kernel fusion
      • don’t need to calculate and store mean
    • 3) Fewer intermediary states in memory for backprop
  • Inspired by this people are dropping bias terms too
  • On batch norms
    • Not used in transformers
    • Batch statistics are unstable and unreliable for variable length data ( padding zero skews mean, variance )
    • Autoregressive decoding makes it impossible

Position Embeddings

  • RoPE
    • Rotary position embeddings
    • Goal – relative position <f(x,i), f(y,j)> = g(x, y, i-j)
    • The distance between token matters, wherever they occur in the sentence
    • Core idea
      • We know inner product are invariant to arbitrary rotation
      • Position i vector gets rotated by i position

Activation Units

  • Gated activation units
    • ReLU shuts down some channel in single shot
      • 𝐹𝐹_𝑥 = max(0, 𝑥𝑊 1 )𝑊 2
    • GLU allows to do that as a function, looking at all channels
      • FF_ReGLU 𝑥 = (max (0, 𝑥𝑊 1) ⊗ 𝑥𝑉) 𝑊 2
      • element wise multiplication
        • max (0, 𝑥𝑊 1) is ReLU gating it is decided by looking at all channel
        • xV is the content of x, controlled by the gate above
  • GLU idea can be applied to GeLU and Swish as well
    • Which results in GeGLU and SwiGLU
    • On their own GeLU and Swish are self gated – x is multiplied by gate computed from x itself
      • Swish = x * sigma(beta * x)
      • GeLU = x * phi(x)
      • GLU unities two giving gate, its own weight and more freedom

Group query attention

Attention TypeQuery MatricesKey MatricesValue Matrices
Multi-Head (MHA)H distinct matricesH distinct matricesH distinct matrices
Grouped-Query (GQA)H distinct matricesG distinct matrices (G < H)G distinct matrices (G < H)
Multi-Query (MQA)H distinct matrices1 shared matrix1 shared matrix
  • Intution
    • MHA – asking 32 detective to solve mystery, asking them to read same book from personal topic
    • GQA
      • 8 groups of 4
      • Every 4 heads share single key/value ( shared book )
      • Unique query matrix means detective still form their individual conclusions
  • Advantages
    • Very successful, performance close to MHA
    • Reduces KV cache size

Mixture Of Experts

  • Different FFN layer for different tokens
    • Not at the sentence level
  • Router is important architecture component
    • Decides which token should go to which expert
      • Top k based on inner product
        • Most common approach
        • Have some learnable weight vector for each expert
        • Use softmax to select it, given its differentiable gradient can propagate back
        • But “topK” is not differentiable
          • problem of “expert collapse” – some experts are abandoned
          • Noisy gating, add some gaussian noise to dot product logits before “topK”
      • RL to learn router
        • Lot of overhead, not used anymore, 2013 paper
      • Hashing
        • Simple yet works
  • Intuition
    • Receptionist at hospital route to expert doctor
      • You don’t ask everyone yourself
    • Sparse activation
      • Only tiny fraction of model is activated for a given token
  • Key Ideas
    • Specializaton
      • Individual sub network naturally learn to specialize – code, grammar, language
    • Router
      • Assigns probabilities
    • Separating size from cost
      • Scale model params without cost
  • Main advantages
    • Scale without FLOPs
    • Parallizable across devices
      • GPU 0 hosts expert 1 and 2
      • Earlier we were slicing the matrix
  • Memory bottleneck
    • Results are showing improvement by keeping the params constant with MoE

On Regularization

  • SGD with single pass is hard to memorize
  • In the compute constraint deep learning its not needed
    • Dropout is not used anymore
    • But weight decay ( L2 regularization) is still used with different purpose though
      • Studies have shown that it helps with optimization

Sparse/Sliding Window Attention

  • Instead of entire attending entire context, can we focus on some nearby ( sliding windows )
  • Standard practice –
    • Interleave full and local attentions
    • Ex – one full attention after every 3 layers

vLLM fundamentals – paged attention and batching

KV cache problem

  • At the time of decoding we store key and value of past tokens in cache
    • New token need to attend to them
  • Decoding is memory bandwidth bound. It reads
    • model weights
    • KV cache
    • just to get back one token
  • How to get good throughput
    • Batch many sequence in each step
    • Helps with single read of weights
  • So model weight is solved, KV cache is the bottleneck for throughput
    • The number of sequences whose caches fit in leftover GPU memory sets your batch size.
  • Before vLLM
    • Each request got one continuous chunk size for maximum possible sequence length
    • Issues
      • memory reserved for token that were never generated
      • gaps between chunk too small to reuse
      • request with same system prompt their own copy

Paged Attention

  • PagedAttention = KV cache in pages
  • OS idea
    • doesn’t allocate large chunk of RAM
    • Gets pages on demand
    • Makes RAM look bigger
    • Maintains mapping table
  • vLLM
    • splits KV cache on blocks
    • blocks are not contiguous
    • Each sequence gets a block table for mapping
  • Standard attention kernel will not work
    • key values are no longer contiguous
  • vLLM ships PagedAttentionKernel
    • follows block table to gather block
    • It’s a memory manager and a kernel
    • Some cost of indirection compensated by increased batch size
  • More advantages
    • Sharing is easy, system prompt, beam search
    • We can preempt some sequence, move them to CPU etc

Continuous Batching

  • Shortcoming of static batching
    • Some sequence finish early, they need to wait for large one to finish
  • Continuous batching makes scheduling decision at every decode step
    • step = generating one token
  • end token can leave the batch, KV blocks are feed, new sequence can join batch
    • Made possible by pagedAttention
  • Once concern
    • Long pre-fill is compute heavy and can stall decoding
    • Solution – chunked pre-fill
      • mixing chunked pre-fill with token budget
    • newer version stopped distinguishing them and simply decided how many tokens each request gets to process
  • Knobs to tune
    • Max sequence per batch
    • Max tokens per step ( token budget )
  • Trade off / metrics
    • Bigger batch raise throughput but each step takes longer.
      • Increase TPOT – time per output token
    • TTFT – time to first token
      • depends on suing delay and how fast refill is scheduled

Just a python process

  • vLLM is user space python process
  • At startup
    • it measure GPU weight memory needed
    • allocates one large tensor for rest
      • after that plays within this tensor
  • OS and GPU drivers just see big allocation that never changes
    • They don’t know about block tables
  • Scheduling and block management runs on CPU
    • At each step
      • Engine packs blocks tables into tensors and sends the to GPU
    • Downside
      • For small model CPU overhead can become a bottleneck
        • Newer vLLM address this by running engines core in a separate process from the API server
  • PagedAttentionKernel follow that map

On RL Environments

Where environments fit

A modern LLM goes through roughly four stages of training:

  1. Pre-training. Next-token prediction on trillions of tokens of web text, books and code. The model picks up knowledge and language.
  2. Supervised fine-tuning (SFT). Pairs of prompts and ideal answers. The model learns to follow instructions and formats.
  3. Preference tuning (RLHF). Humans pick the better of two answers, a reward model learns those preferences, and the LLM is optimized against the reward model.
  4. Reinforcement learning on verifiable rewards. The model attempts tasks whose outcome can be checked automatically, and is rewarded when it succeeds.

The fourth stage is the new one. Around late 2024 and early 2025, OpenAI’s o1 and DeepSeek-R1 showed that rewarding only checkable outcomes, like a correct math answer or a passing unit test, teaches models to reason longer and better. The natural next step was to apply the same idea to multi-step work: fixing a bug in a real codebase, operating a CRM, or preparing a report from data spread across several apps.

To train on that kind of work, you need somewhere for the model to act and a way to score what it did. That somewhere is an environment.

What vendor ship to labs

task-0417/
task.yaml instruction + metadata
Dockerfile repo pinned at a commit, deps installed
tools.json what the model is allowed to call
tests/ hidden from the model
test_fail_to_pass.py
test_pass_to_pass.py
solution.patch reference fix, proves it's solvable
grade.sh runs tests, returns 0 or 1
One environment is one folder. A delivery is hundreds to thousands of these.

What model sees


instruction: |
  Invoice totals are off by one cent when a line
  item ends in half a cent. 3 x 2.345 shows 7.03,
  expected 7.04. Fix it without changing the API.
repo:      invoicekit @ a91c3e2
tools:     [bash, read_file, edit_file]
max_steps: 40

# metadata, not shown to the model
category:   numeric bugs
difficulty: medium
reviewed:   2 engineers

Model’s attempt

The model only sees the visible tests in the repo. It has no idea what the hidden tests check.

> bash grep -rn "round(" invoicekit/
totals.py:18: return round(subtotal, 2)
> read_file invoicekit/totals.py
> edit_file invoicekit/totals.py
- return round(subtotal, 2)
+ return Decimal(str(subtotal)).quantize(
+ Decimal("0.01"), rounding=ROUND_HALF_UP)
> bash pytest tests/ -q
42 passed
> done

Grading (Verifiers )

The grader labels every attempt, no human involved. Line 1 exists because models learn to edit or delete tests when they can.

grade.sh
1. restore tests/ from sealed copy
2. test_fail_to_pass.py 3/3 passed bug fixed
3. test_pass_to_pass.py 118/118 passed nothing broke
reward = 1

Calibration before shipping

Run a current model 16 times on each task:
task-0417 5/16
task-0418 16/16
task-0419 0/16
0417 31% keep sometimes right = learning signal
0418 100% drop already solved, nothing to learn
0419 0% inspect too hard, or the task is broken?

What the lab receives

Why do vendor provide hold out set

  • Lab can leak the near twins with random sampling
  • Vendor will share uplift number using open weight model
  • In practice, the vendor proposes the split and ships the group labels, and the lab decides. Labs don’t fully trust vendor evals either. 
delivery-2026-09/
tasks/ 800 folders like task-0417
report.md
category mix bugs, migrations, perf, ...
baseline pass@1 per category
removed tasks flaky, ambiguous, hackable
heldout/ 200 tasks, eval only, never trained on
# inside the lab's training loop
for step in training:
task = sample(tasks)
tries = model.attempt(task, n=16)
rewards = [grade(t) for t in tries]
update(model, tries, rewards)

How does Rubric Look like

  • The example below outputs score between 0-1 and uses 1) code and 2) LLM as judge
task: Q3 travel-expense MIS for the CFO, from Drive + Slack + email
GATES (fail any -> score 0)
email sent to cfo@acme.test with MIS attached [code]
total travel spend = 48.2L (+/- 0.5%) [code]
CRITERIA (points)
+3 flags the 2 expenses approved without sign-off [judge]
+2 department breakdown matches the Drive sheet [judge]
+2 compares to Q2, explains the biggest change [judge]
+1 one page, readable by a CFO [judge]
-3 states any number not traceable to source data [judge]
-2 emails anyone besides the CFO [code]
score = max(0, points earned) / 8