LLM Training Guide
A comprehensive guide for building and training large language models from scratch, based on the Manning book "Build a Large Language Model from Scratch".
Overview
This skill covers the complete LLM training pipeline:
- Tokenization - Converting text to token IDs
- Data Sampling - Preparing training data
- Token Embeddings - Vector representations
- Attention Mechanisms - Capturing word relationships
- LLM Architecture - Full model structure
- Pre-training - Training from scratch
- Fine-tuning - Adapting for specific tasks
Phase 1: Tokenization
Goal: Divide input text into tokens (IDs) in a meaningful way.
Key Concepts
- Tokens: The basic units the model processes (can be characters, words, or subwords)
- Vocabulary: The set of all unique tokens
- Token IDs: Numeric identifiers for each token in the vocabulary
Implementation Steps
- Build vocabulary from your training corpus
- Create token-to-ID mapping (tokenizer)
- Create ID-to-token mapping (for decoding)
- Encode text → convert to token IDs
- Decode IDs → convert back to text
Best Practices
- Use subword tokenization (like BPE or WordPiece) for better coverage
- Include special tokens:
<pad>, <unk>, <bos>, <eos>
- Keep vocabulary size reasonable (typically 50K-100K tokens)
- Consider your domain when building vocabulary
Phase 2: Data Sampling
Goal: Sample input data and prepare it for training by separating into sequences of specific length and generating expected responses.
Key Concepts
- Sequence length: Fixed number of tokens per training example
- Context window: How much history the model sees
- Target generation: What the model should predict (next token)
Implementation Steps
- Load and concatenate all training text
- Tokenize the entire corpus
- Split into sequences of fixed length (e.g., 1024 tokens)
- Create input/target pairs:
- Input: tokens [0, 1, 2, ..., n-1]
- Target: tokens [1, 2, 3, ..., n]
- Batch sequences for efficient training
Best Practices
- Use sequence lengths that fit your GPU memory
- Shuffle sequences between epochs
- Consider overlapping sequences for more training data
- Balance dataset across domains if using mixed data
Phase 3: Token Embeddings
Goal: Assign each token a vector representation of desired dimensions. Each word becomes a point in X-dimensional space.
Key Concepts
- Embedding dimension: Size of the vector (e.g., 512, 1024, 4096)
- Learnable parameters: Embeddings are initialized randomly and trained
- Position embeddings: Additional vectors encoding word position
Implementation Steps
- Initialize token embeddings randomly (vocab_size × embedding_dim)
- Initialize position embeddings randomly (max_seq_len × embedding_dim)
- Combine embeddings: token_embedding + position_embedding
- Train embeddings alongside model parameters
Position Embedding Types
- Absolute: Fixed position encoding (simple, effective)
- Relative: Encodes distance between tokens
- Rotary: Rotates embeddings based on position (RoPE)
Best Practices
- Embedding dimension should match model hidden size
- Use learned embeddings rather than fixed ones
- Consider sinusoidal position embeddings for extrapolation
Phase 4: Attention Mechanisms
Goal: Apply attention layers to capture relationships between words in the sentence.
Key Concepts
- Self-attention: Each token attends to all tokens in the sequence
- Query, Key, Value: Three projections for attention computation
- Multi-head attention: Multiple attention heads in parallel
- Causal masking: Prevents attending to future tokens (for training)
Implementation Steps
- Project embeddings to Q, K, V matrices
- Compute attention scores: Q × K^T / sqrt(d_k)
- Apply causal mask (for decoder-only models)
- Softmax to get attention weights
- Weighted sum: attention_weights × V
- Combine heads and project back
Attention Formula
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k))V
Best Practices
- Use multi-head attention (8-16 heads typical)
- Apply layer normalization before and after attention
- Use residual connections around attention blocks
- Consider flash attention for efficiency
Phase 5: LLM Architecture
Goal: Develop the full LLM architecture by combining all components.
Standard Transformer Decoder Architecture
Input → Token Embedding → Position Embedding → [N × (Attention → MLP)] → Output Projection → Logits
Components
- Embedding Layer: Token + Position embeddings
- N Transformer Blocks:
- Multi-head self-attention
- Layer normalization
- Feed-forward MLP (2-4x hidden size)
- Layer normalization
- Output Projection: Hidden size → vocabulary size
- Loss Function: Cross-entropy on next token prediction
Implementation Steps
- Define model class with all layers
- Implement forward pass through all components
- Implement training loop with loss computation
- Implement generation (sampling, beam search, etc.)
- Add saving/loading for model checkpoints
Best Practices
- Use pre-norm architecture (norm before attention/MLP)
- Initialize weights carefully (e.g., Xavier, He initialization)
- Use gradient clipping to prevent exploding gradients
- Implement mixed precision training for efficiency
Phase 6: Pre-training
Goal: Train the model from scratch using the defined architecture, loss functions, and optimizer.
Training Loop
for epoch in epochs:
for batch in dataloader:
# Forward pass
logits = model(input_tokens)
# Compute loss
loss = cross_entropy(logits, target_tokens)
# Backward pass
loss.backward()
# Update weights
optimizer.step()
optimizer.zero_grad()
Key Hyperparameters
- Learning rate: 1e-4 to 3e-4 (with warmup)
- Batch size: Depends on GPU memory (effective batch size 1024-4096)
- Optimizer: AdamW with weight decay (0.01-0.1)
- Learning rate schedule: Cosine decay or linear warmup + decay
- Gradient accumulation: For larger effective batch sizes
Best Practices
- Use learning rate warmup (first 10% of steps)
- Monitor training loss and perplexity
- Save checkpoints regularly
- Use gradient checkpointing for memory efficiency
- Consider distributed training for large models
Phase 7: Fine-tuning
7.0 LoRA (Low-Rank Adaptation)
Goal: Reduce computation needed for fine-tuning by training only small adapter matrices.
How LoRA Works
- Freeze pre-trained weights
- Add small rank-r matrices to attention layers
- Train only the LoRA parameters
- Merge LoRA weights with base model for inference
Implementation Steps
- Freeze base model parameters
- Add LoRA adapters to attention Q, V, (optionally K, O)
- Train only LoRA parameters
- Merge weights for deployment
Best Practices
- Rank r: 8-64 (higher for more capacity)
- Alpha: Scaling factor (typically 2× rank)
- Apply to attention layers primarily
- Use lower learning rate than pre-training
7.1 Fine-tuning for Classification
Goal: Adapt pre-trained model to classify text into categories.
Implementation Steps
- Load pre-trained model (frozen or partially unfrozen)
- Add classification head on top of embeddings
- Prepare labeled dataset with categories
- Train with cross-entropy loss on labels
- Evaluate with accuracy, F1, etc.
Best Practices
- Use mean pooling or [CLS] token for classification
- Fine-tune last 1-2 layers initially
- Use smaller learning rate than pre-training
- Consider few-shot learning for limited data
7.2 Fine-tuning for Instruction Following
Goal: Adapt pre-trained model to follow instructions (chat, tasks, etc.).
Implementation Steps
- Prepare instruction dataset (instruction, input, output format)
- Format examples with special tokens:
<instruction> {instruction} <input> {input} <output> {output}
- Train on formatted data with next-token prediction
- Evaluate on instruction following benchmarks
Best Practices
- Use diverse instruction templates
- Include both simple and complex instructions
- Consider supervised fine-tuning (SFT) before RLHF
- Use quality datasets (e.g., Alpaca, Dolly)
- Monitor for instruction following vs. memorization
Common Issues and Solutions
| Issue |
Solution |
| Training loss not decreasing |
Check learning rate, batch size, data quality |
| Model generates repetitive text |
Adjust temperature, use top-k/top-p sampling |
| Out of memory |
Reduce batch size, use gradient checkpointing |
| Slow training |
Use mixed precision, flash attention |
| Poor generalization |
More data, regularization, better architecture |
Next Steps
After completing these phases, you can:
- Deploy your model for inference
- Optimize with quantization, pruning
- Scale to larger datasets and models
- Experiment with different architectures
- Fine-tune for your specific use case
References
- Manning Book: "Build a Large Language Model from Scratch"
- Original Transformer Paper: "Attention Is All You Need"
- LoRA Paper: "LoRA: Low-Rank Adaptation of Large Language Models"
- Various implementation guides and tutorials
1---2name: llm-training-guide3description: Guide for building and training large language models from scratch. Use this skill whenever the user wants to understand LLM training concepts, implement tokenization, data sampling, embeddings, attention mechanisms, model architecture, pre-training, or fine-tuning workflows. Trigger on mentions of LLM training, building models from scratch, tokenization, embeddings, attention, pre-training, fine-tuning, LoRA, or any LLM development task.4---56# LLM Training Guide78A comprehensive guide for building and training large language models from scratch, based on the Manning book "Build a Large Language Model from Scratch".910## Overview1112This skill covers the complete LLM training pipeline:13141. **Tokenization** - Converting text to token IDs152. **Data Sampling** - Preparing training data163. **Token Embeddings** - Vector representations174. **Attention Mechanisms** - Capturing word relationships185. **LLM Architecture** - Full model structure196. **Pre-training** - Training from scratch207. **Fine-tuning** - Adapting for specific tasks2122## Phase 1: Tokenization2324**Goal**: Divide input text into tokens (IDs) in a meaningful way.2526### Key Concepts2728- **Tokens**: The basic units the model processes (can be characters, words, or subwords)29- **Vocabulary**: The set of all unique tokens30- **Token IDs**: Numeric identifiers for each token in the vocabulary3132### Implementation Steps33341. **Build vocabulary** from your training corpus352. **Create token-to-ID mapping** (tokenizer)363. **Create ID-to-token mapping** (for decoding)374. **Encode text** → convert to token IDs385. **Decode IDs** → convert back to text3940### Best Practices4142- Use subword tokenization (like BPE or WordPiece) for better coverage43- Include special tokens: `<pad>`, `<unk>`, `<bos>`, `<eos>`44- Keep vocabulary size reasonable (typically 50K-100K tokens)45- Consider your domain when building vocabulary4647## Phase 2: Data Sampling4849**Goal**: Sample input data and prepare it for training by separating into sequences of specific length and generating expected responses.5051### Key Concepts5253- **Sequence length**: Fixed number of tokens per training example54- **Context window**: How much history the model sees55- **Target generation**: What the model should predict (next token)5657### Implementation Steps58591. **Load and concatenate** all training text602. **Tokenize** the entire corpus613. **Split into sequences** of fixed length (e.g., 1024 tokens)624. **Create input/target pairs**:63 - Input: tokens [0, 1, 2, ..., n-1]64 - Target: tokens [1, 2, 3, ..., n]655. **Batch sequences** for efficient training6667### Best Practices6869- Use sequence lengths that fit your GPU memory70- Shuffle sequences between epochs71- Consider overlapping sequences for more training data72- Balance dataset across domains if using mixed data7374## Phase 3: Token Embeddings7576**Goal**: Assign each token a vector representation of desired dimensions. Each word becomes a point in X-dimensional space.7778### Key Concepts7980- **Embedding dimension**: Size of the vector (e.g., 512, 1024, 4096)81- **Learnable parameters**: Embeddings are initialized randomly and trained82- **Position embeddings**: Additional vectors encoding word position8384### Implementation Steps85861. **Initialize token embeddings** randomly (vocab_size × embedding_dim)872. **Initialize position embeddings** randomly (max_seq_len × embedding_dim)883. **Combine embeddings**: token_embedding + position_embedding894. **Train embeddings** alongside model parameters9091### Position Embedding Types9293- **Absolute**: Fixed position encoding (simple, effective)94- **Relative**: Encodes distance between tokens95- **Rotary**: Rotates embeddings based on position (RoPE)9697### Best Practices9899- Embedding dimension should match model hidden size100- Use learned embeddings rather than fixed ones101- Consider sinusoidal position embeddings for extrapolation102103## Phase 4: Attention Mechanisms104105**Goal**: Apply attention layers to capture relationships between words in the sentence.106107### Key Concepts108109- **Self-attention**: Each token attends to all tokens in the sequence110- **Query, Key, Value**: Three projections for attention computation111- **Multi-head attention**: Multiple attention heads in parallel112- **Causal masking**: Prevents attending to future tokens (for training)113114### Implementation Steps1151161. **Project embeddings** to Q, K, V matrices1172. **Compute attention scores**: Q × K^T / sqrt(d_k)1183. **Apply causal mask** (for decoder-only models)1194. **Softmax** to get attention weights1205. **Weighted sum**: attention_weights × V1216. **Combine heads** and project back122123### Attention Formula124125```126Attention(Q, K, V) = softmax(QK^T / sqrt(d_k))V127```128129### Best Practices130131- Use multi-head attention (8-16 heads typical)132- Apply layer normalization before and after attention133- Use residual connections around attention blocks134- Consider flash attention for efficiency135136## Phase 5: LLM Architecture137138**Goal**: Develop the full LLM architecture by combining all components.139140### Standard Transformer Decoder Architecture141142```143Input → Token Embedding → Position Embedding → [N × (Attention → MLP)] → Output Projection → Logits144```145146### Components1471481. **Embedding Layer**: Token + Position embeddings1492. **N Transformer Blocks**:150 - Multi-head self-attention151 - Layer normalization152 - Feed-forward MLP (2-4x hidden size)153 - Layer normalization1543. **Output Projection**: Hidden size → vocabulary size1554. **Loss Function**: Cross-entropy on next token prediction156157### Implementation Steps1581591. **Define model class** with all layers1602. **Implement forward pass** through all components1613. **Implement training loop** with loss computation1624. **Implement generation** (sampling, beam search, etc.)1635. **Add saving/loading** for model checkpoints164165### Best Practices166167- Use pre-norm architecture (norm before attention/MLP)168- Initialize weights carefully (e.g., Xavier, He initialization)169- Use gradient clipping to prevent exploding gradients170- Implement mixed precision training for efficiency171172## Phase 6: Pre-training173174**Goal**: Train the model from scratch using the defined architecture, loss functions, and optimizer.175176### Training Loop177178```python179for epoch in epochs:180 for batch in dataloader:181 # Forward pass182 logits = model(input_tokens)183 184 # Compute loss185 loss = cross_entropy(logits, target_tokens)186 187 # Backward pass188 loss.backward()189 190 # Update weights191 optimizer.step()192 optimizer.zero_grad()193```194195### Key Hyperparameters196197- **Learning rate**: 1e-4 to 3e-4 (with warmup)198- **Batch size**: Depends on GPU memory (effective batch size 1024-4096)199- **Optimizer**: AdamW with weight decay (0.01-0.1)200- **Learning rate schedule**: Cosine decay or linear warmup + decay201- **Gradient accumulation**: For larger effective batch sizes202203### Best Practices204205- Use learning rate warmup (first 10% of steps)206- Monitor training loss and perplexity207- Save checkpoints regularly208- Use gradient checkpointing for memory efficiency209- Consider distributed training for large models210211## Phase 7: Fine-tuning212213### 7.0 LoRA (Low-Rank Adaptation)214215**Goal**: Reduce computation needed for fine-tuning by training only small adapter matrices.216217### How LoRA Works218219- Freeze pre-trained weights220- Add small rank-r matrices to attention layers221- Train only the LoRA parameters222- Merge LoRA weights with base model for inference223224### Implementation Steps2252261. **Freeze base model** parameters2272. **Add LoRA adapters** to attention Q, V, (optionally K, O)2283. **Train only LoRA parameters**2294. **Merge weights** for deployment230231### Best Practices232233- Rank r: 8-64 (higher for more capacity)234- Alpha: Scaling factor (typically 2× rank)235- Apply to attention layers primarily236- Use lower learning rate than pre-training237238### 7.1 Fine-tuning for Classification239240**Goal**: Adapt pre-trained model to classify text into categories.241242### Implementation Steps2432441. **Load pre-trained model** (frozen or partially unfrozen)2452. **Add classification head** on top of embeddings2463. **Prepare labeled dataset** with categories2474. **Train with cross-entropy loss** on labels2485. **Evaluate** with accuracy, F1, etc.249250### Best Practices251252- Use mean pooling or [CLS] token for classification253- Fine-tune last 1-2 layers initially254- Use smaller learning rate than pre-training255- Consider few-shot learning for limited data256257### 7.2 Fine-tuning for Instruction Following258259**Goal**: Adapt pre-trained model to follow instructions (chat, tasks, etc.).260261### Implementation Steps2622631. **Prepare instruction dataset** (instruction, input, output format)2642. **Format examples** with special tokens:265 ```266 <instruction> {instruction} <input> {input} <output> {output}267 ```2683. **Train on formatted data** with next-token prediction2694. **Evaluate** on instruction following benchmarks270271### Best Practices272273- Use diverse instruction templates274- Include both simple and complex instructions275- Consider supervised fine-tuning (SFT) before RLHF276- Use quality datasets (e.g., Alpaca, Dolly)277- Monitor for instruction following vs. memorization278279## Common Issues and Solutions280281| Issue | Solution |282|-------|----------|283| Training loss not decreasing | Check learning rate, batch size, data quality |284| Model generates repetitive text | Adjust temperature, use top-k/top-p sampling |285| Out of memory | Reduce batch size, use gradient checkpointing |286| Slow training | Use mixed precision, flash attention |287| Poor generalization | More data, regularization, better architecture |288289## Next Steps290291After completing these phases, you can:2922931. **Deploy** your model for inference2942. **Optimize** with quantization, pruning2953. **Scale** to larger datasets and models2964. **Experiment** with different architectures2975. **Fine-tune** for your specific use case298299## References300301- Manning Book: "Build a Large Language Model from Scratch"302- Original Transformer Paper: "Attention Is All You Need"303- LoRA Paper: "LoRA: Low-Rank Adaptation of Large Language Models"304- Various implementation guides and tutorials