Great question! You have several options for where to place this command. Here are the most common approaches:
📍 Option 1: Inside the class (in a method)
class SelfAttention_v2(nn.Module):
def __init__(self, d_in, d_out, qkv_bias=False):
super().__init__()
self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
# Option 1a: Print right after initialization
print("Submodules:", list(self.named_children()))
def show_submodules(self):
# Option 1b: Create a method to call later
return list(self.named_children())
def forward(self, x):
# ... rest of forward pass
📍 Option 2: Outside the class (after instantiation)
# After defining the class, create an instance
model = SelfAttention_v2(d_in=512, d_out=64)
# Then inspect it
print(list(model.named_children()))
# Or more readable:
for name, module in model.named_children():
print(f"{name}: {module}")
📍 Option 3: In a Jupyter notebook or interactive session
# Create the model
attn = SelfAttention_v2(d_in=512, d_out=64)
# Inspect in multiple ways:
list(attn.named_children()) # Shows name-module pairs
# Alternative ways to inspect:
print(attn) # Shows the whole structure
attn.state_dict().keys() # Shows all parameter names
# See all parameters (including weights and biases)
for name, param in attention_layer.named_parameters():
print(f"{name}: {param.shape}")
# Count total parameters
total_params = sum(p.numel() for p in attention_layer.parameters())
print(f"Total parameters: {total_params}")
# Check if model has any submodules
print(f"Has submodules: {len(list(attention_layer.children())) > 0}")
The key point is: self only exists inside the class methods, so if you want to use it from outside, you need to reference the instance of your class (like model or attention_layer in the examples above).
User
If possible, I would like a visual diagram of the whole attention flow (e.g., including softmax, scaling, context vector).
Assistant
I'll create a visual diagram showing the complete attention flow in your SelfAttention_v2 implementation!
SELF-ATTENTION MECHANISM FLOW
================================
Input: x [batch_size, seq_len, d_in]
↓
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ PARALLEL PROJECTIONS │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ x ──→│ W_query │ x ──→│ W_key │ x ──→│ W_value │ │
│ │ (Linear) │ │ (Linear) │ │ (Linear) │ │
│ │ d_in → d_out│ │ d_in → d_out│ │ d_in → d_out│ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ ↓ ↓ ↓ │
│ queries keys values │
│ [batch, seq, d_out] [batch, seq, d_out] [batch, seq, d_out] │
└─────────────────────────────────────────────────────────────────────────────────────────┘
↓ ↓
└────────────┬───────────┘
↓
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ ATTENTION SCORES COMPUTATION │
│ │
│ queries @ keys.T │
│ [batch, seq, d_out] @ [batch, d_out, seq] │
│ ↓ │
│ attn_scores │
│ [batch, seq, seq] │
│ │
│ Each element (i,j) represents how much token i attends to token j │
└─────────────────────────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ SCALING │
│ │
│ attn_scores / sqrt(d_out) │
│ │
│ Scaling prevents values from becoming too large before softmax │
│ (which would lead to very peaked distributions) │
└─────────────────────────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ SOFTMAX │
│ │
│ softmax(scaled_scores, dim=-1) │
│ │
│ attn_weights │
│ [batch, seq, seq] │
│ │
│ Each row sums to 1.0 (probability distribution over keys) │
└─────────────────────────────────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ WEIGHTED AGGREGATION │
│ │
│ attn_weights @ values │
│ [batch, seq, seq] @ [batch, seq, d_out] │
│ ↓ │
│ context_vec │
│ [batch, seq, d_out] │
│ │
│ Each output position is a weighted sum of all value vectors │
└─────────────────────────────────────────────────────────────────────────────────────────┘
↓
OUTPUT
[batch, seq, d_out]
User
Could you draw the diagram again, labeling the dimensions of the matrices and tensors, taking as an example DeepSeek V3 or R1?
Assistant
I'll create a detailed diagram with actual dimensions from a large language model. Since DeepSeek V3/R1's exact architecture isn't publicly documented in detail, I'll use typical dimensions from similar-scale models (like LLaMA-70B or GPT-3 scale) which would be representative:
This shows how each output token is a weighted combination of all value vectors, where weights come from the attention mechanism!
📊 Typical LLM Architecture Parameters:
DeepSeek V3 / Large Model Scale (estimated)
Model Parameters: ~70B
Hidden Size (d_model): 8192
Num Attention Heads: 64
Head Dimension: 128 (8192 / 64)
Num Layers: 80
Max Sequence Length: 4096 or 8192
Vocabulary Size: ~100,000
For a single forward pass with batch_size=1, seq_len=2048:
Attention Scores per Layer:
- Shape: [64 heads, 2048, 2048]
- Memory: 64 × 2048 × 2048 × 4 bytes = 1 GB
Total for 80 layers:
- Just attention scores: 80 GB
- Full model activations: ~200-300 GB
This is why techniques like:
- Flash Attention (compute attention in blocks)
- Gradient checkpointing
- Model parallelism
are essential for large models!
🔧 Optimization Techniques Used:
Grouped Query Attention (GQA): Share keys/values across multiple query heads
Flash Attention: Fused kernels to avoid materializing full attention matrix
RoPE (Rotary Position Embeddings): Efficient position encoding
SwiGLU activation: Better than ReLU for large models
These optimizations allow models like DeepSeek V3 to handle long contexts efficiently despite the quadratic complexity of attention!