Yes, changing the number of heads in a transformer layer does change the number of parameters.
In a transformer layer, the multi-head self-attention mechanism splits the input into multiple "heads" where each head performs scaled dot-product attention independently. The results from all the heads are then concatenated and linearly transformed to produce the final output.
Here’s how the number of heads affects the number of parameters:
1. Linear Layers for Query, Key, and Value
For each attention head, there are three linear layers that project the input into query, key, and value vectors. If the input has a dimension of ( d_{\text{model}} ) and there are ( h ) heads, each head will have a dimension of ( d_{\text{head}} = \frac{d_{\text{model}}}{h} ).
- For each head, the query, key, and value projections each have a weight matrix of size ( d_{\text{model}} \times d_{\text{head}} ).
- Therefore, the total number of parameters for these projections across all heads is ( 3 \times d_{\text{model}} \times d_{\text{model}} ). This part is independent of the number of heads ( h ), because ( d_{\text{head}} ) scales inversely with ( h ).
2. Output Projection
After the attention mechanism, the outputs of all heads are concatenated, resulting in a vector of size ( d_{\text{model}} ). This concatenated vector is then passed through another linear layer, which maps it back to ( d_{\text{model}} ) dimensions.
- The weight matrix for this linear layer has size ( d_{\text{model}} \times d_{\text{model}} ), and again, this is independent of the number of heads.
3. Total Parameters
The total number of parameters in the attention mechanism is primarily determined by the size of the projection matrices (query, key, value) and the output projection matrix. While the individual dimensions of the query, key, and value matrices change with the number of heads, the total number of parameters remains the same because the product ( d_{\text{model}} \times d_{\text{head}} ) adjusts according to the number of heads.
However, in practice, more heads can lead to changes in other parts of the model, such as the feedforward network or normalization layers, and might necessitate changes in hyperparameters or require adjustments to maintain overall model performance.
Summary:
- The core number of parameters in the multi-head attention mechanism itself does not increase with more heads, because the projection dimensions are adjusted accordingly.
- However, changing the number of heads can impact the overall architecture and might require changes elsewhere in the model, which could indirectly lead to an increase or decrease in total parameters depending on the specific implementation.