class CausalSelfAttention(nn.Module):
def __init__(self, n_embd, n_head, block_size=1024):
super().__init__()
if n_embd % n_head:
raise ValueError("n_embd must be divisible by n_head")
self.n_head = n_head
self.qkv = nn.Linear(n_embd, 3 * n_embd)
self.proj = nn.Linear(n_embd, n_embd)
ones = torch.ones(block_size, block_size, dtype=torch.bool)
self.register_buffer("mask", torch.tril(ones))
for n_head in (1, 12, 24):
m = CausalSelfAttention(768, n_head)
print(n_head, sum(p.numel() for p in m.parameters()))
1 2362368
12 2362368
24 2362368
Two layers, with biases:
H isn't in it. At GPT-2 small's width, C=768, that's 2,362,368 parameters (9.0 MiB in fp32), whether you use 1, 12 or 24 heads.
In the editor, write attn_params(C). The last line prints it next to PyTorch's own count for two real layers.