LLM/Model & Papers
Llama 3 implemented in pure NumPy
Curiosity: How can we understand LLM architectures at the most fundamental level?
๐ฆ Llama 3 Implemented in Pure NumPy: Understanding LLMs from First Principles
Curiosity: How can we understand LLM architectures at the most fundamental level? What insights can we retrieve by implementing complex models using only basic NumPy operations?
Implementing Llama 3 in pure NumPy offers a unique opportunity to understand transformer architectures from first principles. This educational implementation, inspired by Andrej Karpathyโs work, provides clarity and interpretability that high-level frameworks often obscure.
Why Pure NumPy Implementation?
graph LR
A[Understanding LLMs] --> B[High-Level Frameworks]
A --> C[Pure NumPy]
B --> B1[Fast Development]
B --> B2[Abstraction Layers]
B --> B3[Less Visibility]
C --> C1[Full Control]
C --> C2[Clear Operations]
C --> C3[Educational Value]
style A fill:#e1f5ff
style C fill:#fff3cd
style B3 fill:#f8d7da
style C3 fill:#d4edda
Llama 3 Training Scale
Retrieve: The scale of Llama 3 training reveals the computational resources required for state-of-the-art models.
| Resource | Quantity | Impact |
|---|---|---|
| GPUs | 24,000 | Massive parallel processing |
| Training Data | 15T tokens | Comprehensive knowledge base |
| Instruction Data | 10M samples | Fine-tuning for alignment |
| GPU Hours | 1.3M hours | Extensive compute investment |
Architecture Overview
Key Insight: Despite transitioning to GQA (Grouped Query Attention), the model structure remains unchanged from Llama 2, making it a familiar yet powerful framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import numpy as np
class Llama3Attention:
"""Simplified Llama 3 attention mechanism in NumPy"""
def __init__(self, dim, num_heads, head_dim):
self.dim = dim
self.num_heads = num_heads
self.head_dim = head_dim
# Weight matrices
self.q_proj = np.random.randn(dim, num_heads * head_dim) * 0.02
self.k_proj = np.random.randn(dim, num_heads * head_dim) * 0.02
self.v_proj = np.random.randn(dim, num_heads * head_dim) * 0.02
self.o_proj = np.random.randn(num_heads * head_dim, dim) * 0.02
def forward(self, x, mask=None):
"""Forward pass of attention"""
batch_size, seq_len, _ = x.shape
# Project to Q, K, V
Q = x @ self.q_proj # [batch, seq, num_heads * head_dim]
K = x @ self.k_proj
V = x @ v_proj
# Reshape for multi-head attention
Q = Q.reshape(batch_size, seq_len, self.num_heads, self.head_dim)
K = K.reshape(batch_size, seq_len, self.num_heads, self.head_dim)
V = V.reshape(batch_size, seq_len, self.num_heads, self.head_dim)
# Scaled dot-product attention
scores = np.einsum('bshd,bthd->bsht', Q, K) / np.sqrt(self.head_dim)
if mask is not None:
scores = np.where(mask, scores, -np.inf)
attn_weights = self.softmax(scores)
output = np.einsum('bsht,bthd->bshd', attn_weights, V)
# Reshape and project output
output = output.reshape(batch_size, seq_len, -1)
return output @ self.o_proj
def softmax(self, x):
"""Numerically stable softmax"""
exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
return exp_x / np.sum(exp_x, axis=-1, keepdims=True)
GQA (Grouped Query Attention) Implementation
Note: While GQA is incorporated into the code structure, itโs not applied to model behavior in this educational implementation, ensuring enhanced interpretability.
graph TB
A[Input Tokens] --> B[Embedding Layer]
B --> C[Transformer Blocks]
C --> D[Attention Layer]
D --> E[GQA Mechanism]
E --> F[Feed Forward]
F --> G[Output]
H[Positional Encoding] --> C
I[Layer Norm] --> D
I --> F
style A fill:#e1f5ff
style D fill:#fff3cd
style E fill:#d4edda
style G fill:#f8d7da
Implementation Benefits
| Aspect | Benefit | Impact |
|---|---|---|
| Educational | Clear understanding of operations | โฌ๏ธ Learning |
| Interpretability | See every computation step | โฌ๏ธ Debugging |
| Portability | No framework dependencies | โฌ๏ธ Accessibility |
| Clarity | Intuitive model structure | โฌ๏ธ Understanding |
Key Implementation Details
1. Model Conversion
- Leveraging stories15M model trained by Andrej Karpathy
- Converting to NumPy compressed format
- Maintaining clarity and precision
2. Architecture Preservation
- Llama 2 structure compatibility
- GQA integration (structural, not behavioral)
- Transformer block implementation
3. Educational Focus
- Step-by-step operations
- Clear mathematical formulations
- Practical examples
Comparison: Framework vs. Pure NumPy
| Feature | PyTorch/TensorFlow | Pure NumPy |
|---|---|---|
| Speed | โกโกโก Very Fast | โก Slower |
| GPU Support | โ Native | โ CPU only |
| Abstraction | High | Low |
| Understanding | โ ๏ธ Limited | โ Complete |
| Educational Value | โ ๏ธ Medium | โ High |
Use Cases
Retrieve: Pure NumPy implementations are valuable for:
- Educational purposes
- Understanding model internals
- Debugging and verification
- Research and experimentation
Innovate: By understanding the fundamentals, you can:
- Optimize implementations
- Create custom architectures
- Debug complex issues
- Build domain-specific models
Resources
๐งโ๐ป Code Repository: https://github.com/likejazz/llama3.np
Key Features:
- Pure NumPy implementation
- Educational focus
- Clear documentation
- Karpathy-inspired approach
Key Takeaways
Retrieve: Implementing Llama 3 in pure NumPy provides deep insights into transformer architectures, revealing the mathematical operations that power modern LLMs.
Innovate: By understanding these fundamentals, you can innovate on architectures, optimize implementations, and build custom solutions tailored to specific needs.
Curiosity โ Retrieve โ Innovation: Start with curiosity about how LLMs work, retrieve knowledge through hands-on implementation, and innovate by applying these insights to new problems.
Next Steps:
- Explore the GitHub repository
- Run the implementation
- Modify and experiment
- Build your own variations
Translate to Korean
๐ฆ ์์ NumPy๐ฉ ๐ฌ๋ก ๊ตฌํ๋ ๋ผ๋ง 3
๐ ํฅ๋ฏธ ์ง์งํ ๋ฐ๊ฒฌ! @Andrej Karpathy์์ ์๊ฐ์ ๋ฐ์ NumPy์์ ๊ตฌํ ๋ Llama 3 ๋ชจ๋ธ์ ๋ํ ํฅ๋ฏธ๋ก์ด ๊ธฐ์ฌ๋ฅผ ๋ฐ๊ฒฌํ์ต๋๋ค. AI at Meta ์ ๋ผ๋ง 3 ๋ชจ๋ธ์ ์ธ์์ ์ธ ๊ท๋ชจ์ ์ฑ๋ฅ์ผ๋ก ํ์ฅ์ ์ผ์ผํค๊ณ ์์ต๋๋ค. ๐
๐ง ์ฝ๋ : https://github.com/likejazz/llama3.np
๐ 24K GPU, 15T ํ๋ จ ๋ฐ์ดํฐ, 10M ๋ช ๋ น ๋ฐ์ดํฐ ๋ฐ 1.3M GPU ์๊ฐ์ ์ฌ์ฉํ๋ฉด ๊ทธ ์์น๋ ์ ๋ง ์๋์ ์ ๋๋ค. GQA๋ฅผ ์ฌ์ฉํ๊ธฐ๋ก ์ ํํ์์๋ ๋ถ๊ตฌํ๊ณ ๋ชจ๋ธ ๊ตฌ์กฐ๋ Llama 2์์ ๋ณ๊ฒฝ๋์ง ์์ ์น์ํ๋ฉด์๋ ๊ฐ๋ ฅํ ํ๋ ์์ํฌ๊ฐ ๋์์ต๋๋ค.
๐ง ์ดํด๋ฅผ ๋๊ธฐ ์ํด ์ ์๋ NumPy๋ฅผ ์ฌ์ฉํ์ฌ ์ ํํ๊ฒ ๊ตฌํํ๋ ๋ฐ ์ค์ ์ ๋๊ณ ์์ต๋๋ค. Andrej Karpathy๊ฐ ํ๋ จํ stories15M ๋ชจ๋ธ์ ํ์ฉํ์ฌ ๋ณด๋ค ์ง๊ด์ ์ธ ๋ชจ๋ธ ๊ตฌ์กฐ๋ฅผ ์ํด NumPy ์์ถ ํ์์ผ๋ก ๋ณํํ๊ณ ์์ต๋๋ค. Karpathy๊ฐ ํ๋ จํ Llama 2 ๋ชจ๋ธ์ ์คํ ๊ฐ๋ฅํ ์ฝ๋๋ก ๋ณํํ์ฌ ์ ๊ทผ ๋ฐฉ์์ ๋ช ํ์ฑ๊ณผ ์ ๋ฐ๋๋ฅผ ์ ์งํ๋ ๋์ ๊ณ์ ์ง์ผ๋ด ์ฃผ์ญ์์ค.
๐ GQA๋ฅผ ์ฝ๋์ ํตํฉํ๋ ๋์ ์์ฑ์๋ GQA๋ฅผ ๋ชจ๋ธ ๋์์ ์ ์ฉํ์ง ์์ผ๋ฏ๋ก ํด์ ๊ฐ๋ฅ์ฑ์ ๋์ด๊ธฐ ์ํด NumPy๋ฅผ ์ํํ๊ฒ ๊ตฌํํ ์ ์์ต๋๋ค. ์ด ํ์ ์ ์ธ ์ ๊ทผ ๋ฐฉ์์ ๋ํ ๋ ๋ง์ ํต์ฐฐ๋ ฅ์ ๊ณ์ ์ง์ผ๋ด ์ฃผ์ญ์์ค!
Working on something like this?
I take a small number of paid, scoped reviews: AI agent/RAG architecture diagnosis, Unity CI & build-automation audits, and multimodal QA design review. Each one ends in a written findings document.
Work with me