From Transformer Fundamentals to a Complete SafeTensors Inference Runtime
Introduction: How LLMs Actually Generate Text
Chapter 1: How LLMs Think: The Transformer Inference Journey
- The Inference Journey from Prompt to Response
- Why Inference Is Different from Training
- The Transformer Blueprint at a Glance
- What This Book Builds
- A First Look: Loading, Running and Generating
Chapter 2: Tokens, Vocabularies and the Language of Models
- What a Token Really Is
- Byte Pair Encoding and Subword Tokenization
- Loading and Interpreting Tokenizer Files
- Implementing Token Encoding in C
- Implementing Token Decoding and Special Tokens
Chapter 3: Tensors, Shapes and Memory Layouts
- The Tensor as a Multi-Dimensional Array
- Row-Major vs Column-Major and Why It Matters
- Shapes, Strides and Offsets
- Float16, BFloat16 and Float32 Representations
- Contiguous vs Strided vs Packed Tensors
Chapter 4: Building the Tensor Core Library
- Tensor Allocation and Lifetime Management
- Views, Reshaping and Slicing Without Copies
- Element-Wise Operations and Broadcasting
- Matrix Multiplication from First Principles
- Reductions, Sums and Normalization Primitives
Chapter 5: The Transformer Layer in Depth
- Layer Normalization and RMSNorm
- Multi-Head Self-Attention Mechanism
- Feed-Forward Networks and Activation Functions
- Residual Connections and Gate Linear Units
- Putting It All Together: One Transformer Block
Chapter 6: Positional Encodings and RoPE
- Why Positional Information Matters
- Learnable vs Absolute vs Rotary Encodings
- The Mathematics of RoPE
- Implementing RoPE in C
- RoPE Scaling and Long-Context Strategies
Chapter 7: Softmax, Logits and Sampling
- From Hidden States to Logits
- Numerically Stable Softmax
- Temperature Scaling and Exploration
- Top-K Filtering and Nucleus Sampling
- Deterministic and Reproducible Generation
Chapter 8: The KV Cache and Autoregressive Generation
- The Autoregressive Generation Loop
- Key-Value Caching: The Core Optimization
- KV Cache Layouts and Memory Planning
- Prefill vs Decode Phases
- Managing Cache Growth and Limits
Chapter 9: The SafeTensors File Format
- Why SafeTensors and What Problem It Solves
- Header Structure and Serialization
- Tensor Descriptors, Data Types and Offsets
- Endianness, Alignment and File Boundaries
- Supported Data Types and Shape Encoding
Chapter 10: Implementing the SafeTensors Loader in C
- Header Reading and Length Prefix Parsing
- JSON Metadata Parsing in C
- Tensor Descriptor Extraction and Validation
- Mapping and Reading Tensor Data Blocks
- Error Handling, Boundaries and Integrity Checks
Chapter 11: Model Configuration and Weight Mapping
- The config.json: Architecture Parameters
- Weight Naming Conventions and Patterns
- Mapping Transformer Layer Weights
- Handling Embeddings and Output Projections
- Validation: Checking Loaded Weight Shapes
Chapter 12: Building the Model Forward Pass
- Token Embedding Lookup
- The Layer Loop: Attention, FFN and Residuals
- Positional Encoding at Each Position
- Final Layer Normalization
- Computing Output Logits
- The Complete Attention Implementation
- Putting It All Together: The Forward Pass
Chapter 13: End-to-End Inference: From Prompt to Text
- Runtime State and Context Management
- The Generation Loop Implementation
- Integration: Tokenizer, Model and Sampler
- Streaming Output and Callbacks
- Command-Line Interface and First Run
Chapter 14: Verifying Correctness Before Optimizing
- Reference Implementations and Ground Truth
- Comparing Embeddings and Intermediate Activations
- Logit Comparison and Numerical Tolerance
- Generating Test Cases from Known Outputs
- Assertions, Sanitizers and Debugging Techniques
Chapter 15: Performance Profiling and Bottleneck Analysis
- Latency, Throughput and Tokens Per Second
- Profiling Tools: Perf, Valgrind and Flame Graphs
- Compute-Bound vs Memory-Bound Analysis
- Cache Misses, Branch Mispredictions and Latency
- Identifying the Critical Path
Chapter 16: SIMD and Vectorization
- Understanding SIMD Architectures: AVX2, AVX-512, NEON
- Autovectorization vs Hand-Written Intrinsics
- Vectorized Element-Wise Operations
- Vectorized Matrix Multiplication
- Cross-Platform SIMD Portability
Chapter 17: Memory and Threading Optimizations
- Cache Locality and Data Layout Optimization
- Loop Tiling and Blocking for MatMul
- Multithreading with OpenMP and Native Threads
- False Sharing, Synchronization and Contention
- NUMA Awareness and Large Memory Models
- Memory Bandwidth, Compute-Bound vs Memory-Bound Workloads
Chapter 18: Advanced Optimization Techniques
- Weight Quantization and Low-Bit Representations
- Packed Weights and Efficient Memory Use
- Batching and Continuous Batching
- Speculative Decoding and Draft Models
- Asynchronous Execution and Pipeline Parallelism
- Model-Size-Dependent Optimization Strategies
