MCPcopy Create free account
hub / github.com/PolymathicAI/AstroCLIP / SelfAttention

Class SelfAttention

astroclip/modules.py:108–207  ·  view source on GitHub ↗

Collection of self-attention heads. :param embedding_dim: total dimensionality of the model (equal to `head_size * num_heads`) :param num_heads: number of heads :param bias: whether to include bias terms :param dropout: amount of dropout; used both for the attention and for

Source from the content-addressed store, hash-verified

106
107
108class SelfAttention(nn.Module):
109 """Collection of self-attention heads.
110
111 :param embedding_dim: total dimensionality of the model (equal to
112 `head_size * num_heads`)
113 :param num_heads: number of heads
114 :param bias: whether to include bias terms
115 :param dropout: amount of dropout; used both for the attention and for the residual
116 pathways
117 :param causal: if true, use causal self-attention
118 """
119
120 embedding_dim: int
121 num_heads: int
122 dropout: float
123 uses_flash: bool
124
125 def __init__(
126 self,
127 embedding_dim: int,
128 num_heads: int,
129 causal: bool,
130 dropout: float,
131 bias: bool = True,
132 ):
133 super().__init__()
134 if embedding_dim % num_heads != 0:
135 raise ValueError("embedding_dim should be divisible by num_heads")
136
137 self.embedding_dim = embedding_dim
138 self.num_heads = num_heads
139 self.dropout = dropout
140 self.causal = causal
141
142 # key, query, value projections for all heads, but in a batch
143 self.attention = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
144
145 # output projection
146 self.projection = nn.Linear(embedding_dim, embedding_dim, bias=bias)
147
148 # regularization
149 self.attention_dropout = nn.Dropout(dropout)
150 self.residual_dropout = nn.Dropout(dropout)
151
152 # flash attention makes GPU go brrrrr but support is only in PyTorch >= 2.0
153 self.uses_flash = hasattr(F, "scaled_dot_product_attention")
154 if not self.uses_flash:
155 print("Using slow attention. Flash Attention requires PyTorch >= 2.0.")
156
157 if self.causal:
158 self.register_buffer("mask", torch.empty((1, 1, 0, 0), dtype=bool))
159
160 def forward(self, x: torch.Tensor) -> torch.Tensor:
161 # batch size, sequence length, embedding dimensionality
162 B, T, C = x.shape
163 if C != self.embedding_dim:
164 raise ValueError(
165 f"Expected input shape (..., {self.embedding_dim}, got {x.shape})"

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected