MCPcopy Create free account
hub / github.com/OpenDriveLab/ReSim / Attention

Class Attention

sat/sgm/modules/encoders/traj_encoder.py:45–77  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

43 return self.net(x)
44
45class Attention(nn.Module):
46 def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
47 super().__init__()
48 inner_dim = dim_head * heads
49 project_out = not (heads == 1 and dim_head == dim)
50
51 self.heads = heads
52 self.scale = dim_head ** -0.5
53
54 self.norm = nn.LayerNorm(dim)
55 self.attend = nn.Softmax(dim = -1)
56 self.dropout = nn.Dropout(dropout)
57
58 self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
59
60 self.to_out = nn.Sequential(
61 nn.Linear(inner_dim, dim),
62 nn.Dropout(dropout)
63 ) if project_out else nn.Identity()
64
65 def forward(self, x):
66 x = self.norm(x)
67 qkv = self.to_qkv(x).chunk(3, dim = -1)
68 q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
69
70 dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
71
72 attn = self.attend(dots)
73 attn = self.dropout(attn)
74
75 out = torch.matmul(attn, v)
76 out = rearrange(out, 'b h n d -> b n (h d)')
77 return self.to_out(out)
78
79class Transformer(nn.Module):
80 def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected