1+ """
2+ class to create Multi-head self-attention with Rotary Position Embeddings (RoPE),
3+ using pytorch SDPA class.
14
5+ """
26import torch
3- import torch .nn as nn
7+
8+ from torch import nn
49from torch .nn .functional import scaled_dot_product_attention
510
6- from src .models .positional_embeddings import RoPESplitHalf
7- from configs .model import BetterGPTConfig as ModelConfig
811from src .utils .logger import get_logger
9- from src .utils .rope_helper import rotate_half , apply_rotary_pos_emb
12+ from src .utils .rope_helper import apply_rotary_pos_emb
1013
1114logger = get_logger (__name__ )
1215
@@ -19,9 +22,9 @@ class MHAttention(nn.Module):
1922 """
2023
2124 def __init__ (
22- self ,
23- emb_dim : int ,
24- head_count : int ,
25+ self ,
26+ emb_dim : int ,
27+ head_count : int ,
2528 head_dim : int
2629 ):
2730 """
@@ -38,7 +41,6 @@ def __init__(
3841 self .qkv_proj = nn .Linear (emb_dim , 3 * emb_dim , bias = False )
3942 self .out_proj = nn .Linear (emb_dim , emb_dim , bias = False )
4043
41-
4244 def forward (self , x , sin , cos , attention_mask = None ):
4345 """Apply multi-head attention with RoPE and an optional padding mask.
4446
@@ -62,7 +64,9 @@ def forward(self, x, sin, cos, attention_mask=None):
6264
6365 logger .debug (f"q shape: { q .shape } , k shape: { k .shape } , v shape: { v .shape } " )
6466 logger .debug (f"sin shape: { sin .shape } , cos shape: { cos .shape } " )
65- logger .debug (f"attention_mask shape: { attention_mask .shape if attention_mask is not None else 'None' } " )
67+ logger .debug (f"attention_mask shape: {
68+ attention_mask .shape if attention_mask is not None else 'None' } "
69+ )
6670
6771 rotated_q , rotated_k = apply_rotary_pos_emb (q , k , cos , sin )
6872
@@ -77,7 +81,7 @@ def forward(self, x, sin, cos, attention_mask=None):
7781 # Combine: mask positions that are padding OR in the future
7882 # causal_mask: [seq_len, seq_len] -> [1, 1, seq_len, seq_len]
7983 combined_mask = causal_mask .unsqueeze (0 ).unsqueeze (0 ) | (~ padding_mask )
80- # combined_mask is True where attention should be BLOCKED
84+ #combined_mask is True where attention should be BLOCKED
8185
8286 attn_bias = torch .zeros (batch , 1 , seq_length , seq_length , device = x .device , dtype = q .dtype )
8387 attn_bias .masked_fill_ (combined_mask , torch .finfo (q .dtype ).min )
0 commit comments