Leanpub Header

Skip to main content

How Transformers Actually Work

From First Principles to Production Inference

How Transformers Actually Work
This book is 100% completeLast updated on 2026-09-22

Go beyond calling transformer libraries and learn what actually happens under the hood. Starting from first principles, this book builds transformers from scratch with NumPy and PyTorch, then takes you through training, optimization and production inference. Along the way, you’ll work through the math, code and practical techniques behind modern transformer systems.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
174
Pages
About

About

About the Book

This book takes you from the ground up through everything you need to know about transformer architectures. We will start with the minimal math required, then build a transformer component by component using NumPy and PyTorch, trace the complete training lifecycle from data preparation to checkpoint saving, and scale up to modern production techniques including distributed training, FlashAttention, KV caching, quantization, and serving systems. Every chapter includes complete, runnable code, concrete numerical examples, and rigorous derivations of the key equations. The goal is not to teach you how to call a library but to give you a genuine understanding of what happens inside a transformer and the ability to implement, inspect, optimize, and deploy one yourself.

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 420 engineers and researchers. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

From First Principles to Production Inference

Chapter 1: What Problem Are We Solving?

  1. The Sequence Modeling Problem
  2. What Came Before: RNNs, LSTMs, and Their Limits
  3. Why Parallelism Matters
  4. The Attention Insight
  5. A Map of This Book

Chapter 2: Tensors, Shapes, and Matrix Multiplication

  1. Tensors as n-Dimensional Arrays
  2. Element-Wise Operations
  3. Matrix Multiplication and Broadcasting
  4. Batch Dimensions and the Last-Dimension Convention
  5. A Running Example of Shape Tracking

Chapter 3: Neural Networks From First Principles

  1. Linear Layers and Affine Transformations
  2. Activation Functions: Why Non-Linearity Is Necessary
  3. Loss Functions: Cross-Entropy and What It Measures
  4. Backpropagation: The Chain Rule in Practice
  5. Optimizers: Gradient Descent and Its Variants

Chapter 4: From Text to Numbers: Tokenization and Embeddings

  1. Character-Level versus Token-Level Representations
  2. Byte-Pair Encoding and Subword Tokenization
  3. Building a Vocabulary and Handling Unknown Tokens
  4. The Embedding Layer as a Lookup Table
  5. Embeddings as Learned Vector Representations

Chapter 5: The Attention Mechanism

  1. What Is Attention, Intuitively?
  2. Query, Key, and Value: The Retrieval Analogy
  3. Dot-Product Similarity and the Scaling Problem
  4. Softmax as a Probability Distribution Over Positions
  5. Computing Attention: A Step-by-Step Numerical Example

Chapter 6: Multi-Head Attention

  1. Why One Head Is Not Enough
  2. Projecting Into Subspaces
  3. Concatenating and Mixing Head Outputs
  4. The Tensor Algebra of Multi-Head Attention
  5. What Different Heads Learn

Chapter 7: Positional Information

  1. The Permutation Invariance Problem
  2. Sinusoidal Positional Encodings: Derivation and Properties
  3. Learned Positional Embeddings
  4. Relative Position and Distance-Aware Attention
  5. Masking: Why and When to Zero Out Positions

Chapter 8: Feed-Forward Networks

  1. The Position-Wise Feed-Forward Network
  2. Why We Need a Separate Transformation After Attention
  3. Activation Functions: ReLU, GELU, and SwiGLU
  4. Width, Depth, and Computational Trade-Offs
  5. The Complete Transformer Block

Chapter 9: Implementing a Transformer in NumPy

  1. Designing the Data Structures
  2. The Embedding and Positional Encoding Layer
  3. Implementing Scaled Dot-Product Attention From Scratch
  4. Building Multi-Head Attention
  5. The Complete Encoder Stack
  6. Testing and Verification

Chapter 10: Building a Decoder and Encoder-Decoder Architecture

  1. Causal Masking and Autoregressive Generation
  2. The Decoder Self-Attention Layer
  3. Cross-Attention: Attending to the Encoder
  4. Output Projection and Logits
  5. Generating Text One Token at a Time

Chapter 11: Automatic Differentiation and Backpropagation Through a Transformer

  1. Gradients of Matrix Multiplication
  2. Gradients Through Softmax and Attention
  3. Gradients of the Feed-Forward Network
  4. The Residual Connection and Gradient Flow
  5. Verification Against Numerical Gradients

Chapter 12: Training a Transformer From Scratch With PyTorch

  1. Why PyTorch: Autograd and Dynamic Graphs
  2. Preparing a Tiny Training Dataset
  3. The Complete Training Loop
  4. Monitoring Loss and Generating Samples
  5. Saving, Loading, and Resuming Checkpoints

Chapter 13: GPT-Style Decoder-Only Models

  1. Why Decoder-Only Works for Language Generation
  2. Architectural Choices in the GPT Family
  3. Layer Normalization Placement and RMSNorm
  4. RoPE: Rotary Positional Embeddings
  5. SwiGLU and the Modern Feed-Forward Design

Chapter 14: BERT and Encoder-Only Models

  1. Bidirectional Attention and Pretraining Objectives
  2. Masked Language Modeling in Detail
  3. Next Sentence Prediction
  4. Fine-Tuning for Downstream Tasks
  5. The Encoder-Only Limitations

Chapter 15: Encoder-Decoder and Instruction-Tuned Models

  1. The T5 Architecture and Text-to-Text Pretraining
  2. Prefix-LM and Hybrid Designs
  3. Instruction Tuning and Alignment
  4. Parameter-Efficient Fine-Tuning: LoRA and Friends
  5. Architectural Trade-Offs in Practice

Chapter 16: Scaling Techniques and Mixture of Experts

  1. The Scaling Laws: Data, Parameters, and Compute
  2. Sparse Expert Routing
  3. Mixture-of-Experts Training Dynamics
  4. Load Balancing and Expert Capacity
  5. MoE in Production Models

Chapter 17: Long-Context Techniques

  1. The O(n²) Attention Bottleneck
  2. Grouped-Query and Multi-Query Attention
  3. Sliding Window Attention
  4. Memory Compression and Token Pruning
  5. Extending Context Through Data and Training

Chapter 18: Initialization, Optimization, and Scheduling

  1. Initialization Strategies and Variance Control
  2. AdamW and Why It Works for Transformers
  3. Learning Rate Warmup and Cosine Decay
  4. Gradient Clipping and Stability
  5. Hyperparameter Recipes That Work

Chapter 19: Distributed Training: Parallelism Strategies

  1. Data Parallelism and Gradient Synchronization
  2. Model Parallelism: Tensor and Pipeline
  3. ZeRO and Optimizer State Sharding
  4. Communication Overhead and Topology
  5. Real-World Training Runs

Chapter 20: Memory and Precision

  1. The Memory Budget of a Transformer Training Run
  2. Mixed Precision: FP16, BF16, and Loss Scaling
  3. Gradient Accumulation for Effective Batching
  4. Activation Checkpointing
  5. Memory Profiling and Debugging

Chapter 21: Inference Optimization

  1. Pre-Fill Versus Decode: Two Different Regimes
  2. KV Caching: Why and How
  3. Continuous Batching and Scheduling
  4. Speculative Decoding
  5. Speculative Decoding Correctness and Sampling

Chapter 22: Quantization and Efficient Formats

  1. Why Quantization Works for Neural Networks
  2. Post-Training Quantization: INT8 and Below
  3. Quantization-Aware Training
  4. Grouped Quantization and Outlier Handling
  5. GGUF, GGML, and the Open-Source Ecosystem

Chapter 23: FlashAttention and GPU Hardware

  1. GPU Memory Hierarchy and Tensor Cores
  2. The Attention Kernel: Why It Is Slow
  3. FlashAttention: IO-Aware Recomputation
  4. FlashAttention-2 and Beyond
  5. Measuring and Profiling GPU Utilization

Chapter 24: Serving Architectures

  1. Throughput Versus Latency Trade-Offs
  2. Model Serving Frameworks
  3. Multi-GPU Inference and Expert Parallelism
  4. Caching, Load Balancing, and Autoscaling
  5. Cost Modeling and Efficiency

Chapter 25: What Transformers Can and Cannot Do

  1. What Attention Can Represent
  2. Transformers as Approximate Algorithm Implementers
  3. Inductive Biases: What the Architecture Assumes
  4. Positional Encoding Limits and Extrapolation
  5. Failure Modes and Systematic Errors

Chapter 26: The History and Future of Attention

  1. The Pre-Transformer Landscape: 2014-2017
  2. “Attention Is All You Need”: Context and Impact
  3. The Architecture Arms Race: 2018-Present
  4. Post-Transformer Alternatives
  5. Open Questions and Where to Look Next

Conclusion

  1. The Transformer in One Page
  2. What You Can Do Now
  3. The Next Decade of Sequence Modeling

References

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub