llm

1. What a Transformer Actually Computes

A decoder-only transformer (the backbone of most LLMs) is a stack of identical blocks. Each block does:

1. LayerNorm/RMSNorm → Multi-Head Self-Attention (MHSA)
For tokens \(x \in \mathbb{R}^{T \times d_{model}}\), project to queries/keys/values:

Q = xW_Q, K = xW_K, V = xW_V

Attn(Q,K,V) = softmax( (Q Kᵀ) / √d_h + mask ) V

For each head h (head dim \(d_h = d_{model}/H\)). Heads are concatenated and projected by \(W_O\).

2. Residual connection (pre/post-norm depending on variant).

3. MLP (a gated feed-forward network)
Classic: \( \text{GELU}(xW_1 + b_1)W_2 + b_2 \).
Modern LLMs often use SwiGLU: \(\text{SwiGLU}(x) = ((xW_{up}) \odot \sigma(xW_{gate})) W_{down}\).

4. Positional encoding (where RoPE/ALiBi live; see §5).

Key scaling features

2. Weights: What They Encode and How They’re Organized

Weights are the learned parameters of projections (Q/K/V/O), MLP matrices, embed tables, and norm scales. They encode:

Common choices

Practical memory math (float16)

3. Embeddings: From Tokens to Geometry

Token embeddings map discrete IDs to vectors \(e_t \in \mathbb{R}^{d}\). Positional embeddings inject order (see §5). Output embeddings (tied) convert hidden states back to vocabulary logits.

Semantic embeddings (for search/RAG) map arbitrary text to vectors where cosine/dot distance correlates with semantic similarity. They are trained with contrastive/ranking losses (positive pairs close, negatives far).

Vector geometry & similarity

Dimensionality trade-offs:

4. Vectors in Systems: Indexing, Search, and Reranking

Chunking: 256–800 tokens typical. Aim for semantic boundaries (paragraphs/sections). Maintain overlap (e.g., 20–30%) to handle query drift across chunk edges.

Indexing algorithms (ANN)

Hybrid search: BM25 (lexical) + dense cosine often beats either alone; use late fusion (reciprocal rank fusion) or learned fusion.

Reranking: Use a cross-encoder (bi-directional attention over [query, candidate]) on top-k ANN results for precision@k. It’s the single highest-ROI step in many RAG stacks.

Evaluation: report Recall@k, MRR, nDCG, and Answer faithfulness when generation is involved. Track coverage (how often gold can be retrieved) to separate retriever from generator errors.

5. Positional Representations and Long Context

Extending context

6. Training: Objectives and Signals

Compute budgeting: FLOPs for decoder-only roughly \(6 \times \text{tokens} \times \text{params}\). Data quality dominates once you scale; synthetic data helps if diverse, verified, and de-duplicated.

7. Inference: Latency, Throughput, and Memory

8. Quantization & Distillation (What Works Today)

· Weight-only quantization:
- INT8 (LLM.int8): safe default with minimal quality loss.
- NF4/INT4 (QLoRA/AWQ/GPTQ): 4-bit weights; add per-channel scales for stability.

9. Retrieval-Augmented Generation (RAG) That Holds Up

A robust RAG loop is a contract between retriever and generator:

5. Query planning (optionally multi-hop).

6. Retriever (hybrid dense+lexical), filters, and reranker.

7. Grounding: pass citations/snippets; require attribution.

8. Generator constrained to cite; verifier checks claims against sources.

9. Feedback: failure cases become hard negatives for retriever and counter-examples for the generator.

Common pitfalls: over-chunking, no reranker, mixing vector spaces (don’t index cosine-normalized vectors and then use dot without renorm), ignoring temporal freshness in embeddings.

10. Security, Safety, and Governance

11. Practical Tuning Playbook

12. Mental Models for Builders

Conclusion

Transformers give us a programmable bias for compositional reasoning; weights encode the priors; embeddings turn knowledge into geometry; vector indexes make it searchable at scale. Shipping systems means balancing all four: efficient attention and KV memory, disciplined vector pipelines (indexing + reranking), quantization that preserves quality, and verification that converts plausible text into contract-satisfying outcomes. Build with those constraints in mind and you’ll get models that are not just impressive—but reliable, fast, and cost-effective in the real world.