LogoCookLLM Docs
LogoCookLLM Docs
HomeCookLLM

Principles

Tokenization
Tokenization BasicsBPE AlgorithmGPT TokenizersBPE Training Engineering
Model Architecture
Transformer LM
From token ids to logitsEmbedding and LM Head
Attention Mechanisms
From Self-Attention to GQAAttention Sink
Position Encoding
Position Encoding BasicsRoPE Math DerivationRoPE ImplementationLength Extrapolation
GPU Programming Basics
GPU Architecture BasicsTensor LayoutTriton Basics: Vector Add
FlashAttention
Flash Attention PrinciplesFrom Naive Implementation to Auto-TuningBlock Pointers and Multi-Dim SupportCausal Masking OptimizationGrouped Query AttentionBackward Pass Implementation
Distributed Training
Data ParallelismZeRO OptimizerFully Sharded Data ParallelTensor ParallelismPipeline ParallelismMulti-Dimensional Hybrid Parallelism

Hands-on Training

Overview
Pretraining
Pretraining DataTokenizer TrainingModel ArchitectureData PipelineTraining LoopMonitoring and Validation
X (Twitter)
SystemsFlashAttention

Backward Pass Implementation

Premium

Implement Flash Attention gradient computation, achieving memory-efficient training through recomputation.

Get code access

Log in to continue reading

This is premium content. Please log in to access the full article.

Grouped Query Attention

Add GQA/MQA support so multiple query heads share KV, reducing KV cache memory.

Distributed Training

From data parallelism to multi-dimensional hybrid parallelism — understanding the core parallel strategies of large model training

Table of Contents

Why Do We Need a Custom Backward Pass?
Limitations of PyTorch Autograd
The Recomputation Strategy
The Math of the Attention Backward Pass
Forward Pass Recap
Gradient Derivation
1. ∂L∂V\frac{\partial \mathcal{L}}{\partial \mathbf{V}}∂V∂L​ (the simplest)
2. ∂L∂P\frac{\partial \mathcal{L}}{\partial \mathbf{P}}∂P∂L​ (intermediate gradient)
3. ∂L∂S\frac{\partial \mathcal{L}}{\partial \mathbf{S}}∂S∂L​ (softmax backward pass)
4. ∂L∂Q\frac{\partial \mathcal{L}}{\partial \mathbf{Q}}∂Q∂L​ and ∂L∂K\frac{\partial \mathcal{L}}{\partial \mathbf{K}}∂K∂L​
The Complete Gradient Computation Flow
Code Implementation Walkthrough
Modifications to the Forward Kernel
Backward Kernel Implementation
Key Implementation Details
1. Reversal of the Loop Order
2. Atomic Add for dQ
3. Recompute P Rather Than Save It
Wrapping with torch.autograd.Function
Performance Validation
Numerical Correctness Test
Memory Footprint Comparison
Design Tradeoffs and Optimization Directions
The Cost of Recomputation
Further Optimization Directions
Summary