Where do I put the following command to find the submodules:
python
list(self.named_children())
✅ Answer: You can run list(self.named_children())inside your class methods, especially in the __init__ or forward method, or outside the class after instantiating the model.
Let’s explore both options:
🔹 Option 1: Inside the class (e.g., in __init__)
You can print or inspect the submodules right after defining them:
python
import torch.nn as nn
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)
# Print submodules
print("Submodules:")
for name, module in self.named_children():
print(f"{name}: {module}")
def forward(self, x):
...
When you create an instance of this class, it will print:
Could you draw the diagram again, labeling the dimensions of the matrices and tensors, taking as an example DeepSeek V3 or R1?
Assistant
Absolutely! Let's create a detailed visual diagram of self-attention, including tensor shapes (dimensions), using realistic values inspired by large models like DeepSeek V3 or R1.
🧠 Realistic Dimensions (Inspired by Models Like DeepSeek V3)
Let’s assume:
Parameter
Value
Description
batch_size
2
Number of input sequences in the batch
n_tokens
512
Max sequence length (context length)
d_in
4096
Input embedding dimension (hidden_size)
d_out
4096
Output dimension for Q, K, V projections
Note: These dimensions are similar to those used in large LLMs like DeepSeek V3/R1.
Would you like me to turn this into a code visualization notebook, or expand it to include multi-head attention, masking, or batch handling? I can also provide a diagram as an image if you'd prefer that!
In real LLMs like DeepSeek, this attention block is repeated across multiple heads (e.g., 32 or more), and then concatenated or projected back to original dimension.
You can stack multiple such attention layers (with residual connections and layer norms) to form a full Transformer block.
Would you like me to generate a PNG/SVG version of this diagram, or expand it into multi-head attention? I can also show how this integrates into a full Transformer encoder/decoder structure.