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

Class CrossAttentionHead

astroclip/modules.py:10–56  ·  view source on GitHub ↗

Cross-attention head with dropout. This module is a single head of a cross-attention layer. It takes a query and a key tensor, computes the attention weights, and returns the weighted sum of the values tensor. The attention weights are also returned. :param embed_dim: dimensionalit

Source from the content-addressed store, hash-verified

8
9
10class CrossAttentionHead(nn.Module):
11 """Cross-attention head with dropout.
12
13 This module is a single head of a cross-attention layer. It takes a query and a key
14 tensor, computes the attention weights, and returns the weighted sum of the values
15 tensor. The attention weights are also returned.
16
17 :param embed_dim: dimensionality of the input tensors
18 :param n_head: number of heads
19 :param model_embed_dim: dimensionality of the model tensors
20 :param dropout: amount of dropout
21 """
22
23 embed_dim: int
24 n_head: int
25 model_embed_dim: int
26 dropout: float
27
28 def __init__(
29 self,
30 embed_dim: int,
31 n_head: int,
32 model_embed_dim: int,
33 dropout: float,
34 ):
35 super().__init__()
36 self.query = nn.Parameter(torch.randn(1, 1, embed_dim))
37 self.multihead_attn = nn.MultiheadAttention(
38 embed_dim=embed_dim,
39 num_heads=n_head,
40 batch_first=True,
41 kdim=model_embed_dim,
42 vdim=model_embed_dim,
43 )
44 self.layernorm = nn.LayerNorm(embed_dim)
45 self.dropout = nn.Dropout(dropout)
46
47 def forward(self, x: torch.tensor):
48 batch_size = x.shape[0]
49 attentions = self.multihead_attn(
50 query=self.query.repeat(batch_size, 1, 1),
51 key=x,
52 value=x,
53 average_attn_weights=False,
54 )[0]
55 x = self.layernorm(self.dropout(attentions))
56 return x, attentions[1]
57
58
59class MLP(nn.Module):

Callers 2

__init__Method · 0.85
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected