How LLMs work: Transformers, generation and efficiency

How LLMs work: Transformers, generation and efficiency

Learning materials

Transformer: from tokens to probabilities

  1. Tokenization: text becomes token identifiers (IDs). BPE (Byte Pair Encoding) builds a vocabulary during tokenizer training by merging the most frequent pairs of adjacent units. For example, merging “p” + “r” produces the token “pr”. New text is tokenized using the learned merge rules.
  2. Embedding: each ID becomes a feature vector. A larger vocabulary can shorten sequences but increases the embedding table at the same vector width.
  3. Positional information: lets the model account for token order. Token embeddings alone are insufficient.
  4. Transformer layers: attention mixes information across positions; other transformations process the resulting representations.
  5. Output: logits become a probability distribution for the next token.
How LLMs work: Transformers, generation and efficiency: mechanism diagram with an example

What Q, K and V do

VectorRole
Query, QThe current position's representation used to match available positions.
Key, KA position's representation used to calculate compatibility with a query.
Value, VA position's information contributing to the weighted sum.

Attention(Q,K,V) = softmax(QKᵀ / √d_k)V. With q·k = 12 and d_k = 9, the logit is 4. After softmax, weights 0.4 and 0.6 over scalar values 1 and 3 give 0.4 × 1 + 0.6 × 3 = 2.2.

Multi-head attention performs several such transformations. A standard split of d_model = 384 across 6 heads gives a width of 64 per head.

Training and generation

Decoder trainingGeneration
Teacher forcing supplies correct preceding tokens.The next token is chosen from the model's output and appended to its input.
A causal mask blocks future tokens; known positions can be computed in parallel.The next unknown token depends on previous choices; ordinary decoding is sequential.

Prefill, decode and KV cache

  • Prefill processes prompt tokens.
  • Decode generates the continuation one token at a time.
  • KV (Key–Value) cache stores previously computed keys and values for reuse at the next step. It does not replace weights or retain all answers forever.
  • GQA (Grouped-Query Attention) lets multiple query heads share fewer KV heads, reducing KV-cache size.
  • Length bucketing groups similarly sized sequences, reducing padding computation while preserving correct masks.

KV-cache bytes for one sequence: 2 × layers × tokens × KV_heads × head_dim × bytes_per_number. The 2 counts K and V. A batch of B equally long sequences adds a factor B.

Example: 1 layer × 50 tokens × 2 KV heads × 4 numbers × 2 bytes × 2 = 1600 bytes before metadata.

Choosing the next token

MethodRule
GreedySelect the highest-probability token.
Top-kKeep the k highest-probability tokens, renormalize and sample.
Top-pKeep the smallest sorted prefix whose sum is ≥ p, then renormalize and sample.
Temperature TDivide logits by T before softmax. A lower positive T strengthens preference for leading tokens.
Beam searchRetain a limited number of partial continuations. A pruned path may eventually have been best.

For [0.4, 0.35, 0.25] with top-p = 0.7, keep the first two tokens: 0.4 is insufficient; 0.75 is sufficient. max_new_tokens limits new tokens only, not prompt length.

Reducing model cost

  • LoRA (Low-Rank Adaptation) trains an update ΔW = BA with intermediate dimension r. For an m × n matrix, it uses mr + rn trainable elements and rank(ΔW) ≤ r. With 600 × 400 and r = 2, that is 1200 + 800 = 2000 elements without biases.
  • Quantization reduces numerical bit width. P weights at b bits theoretically occupy Pb / 8 bytes: 2 million 4-bit weights occupy 1 million bytes. Scales, zero-points and other metadata need additional memory.
  • Distillation trains a student to reproduce a teacher's behavior. Soft targets convey relative probabilities of alternatives instead of only one correct label.

If quantization hurts rare long queries, compare original and quantized models on identical queries, broken down by length and type. A single overall average can conceal the loss.

Calibration data are representative examples used to set quantization parameters, such as activation ranges in methods that use such calibration. A set containing only short, simple queries may poorly represent production workloads; include long and rare cases in the checks. This is separate from calibrating a classifier’s predicted probabilities.