Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

resampler.py 3.5 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  1. # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. # FFN
  6. def FeedForward(dim, mult=4):
  7. inner_dim = int(dim * mult)
  8. return nn.Sequential(
  9. nn.LayerNorm(dim),
  10. nn.Linear(dim, inner_dim, bias=False),
  11. nn.GELU(),
  12. nn.Linear(inner_dim, dim, bias=False),
  13. )
  14. def reshape_tensor(x, heads):
  15. bs, length, width = x.shape
  16. #(bs, length, width) --> (bs, length, n_heads, dim_per_head)
  17. x = x.view(bs, length, heads, -1)
  18. # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
  19. x = x.transpose(1, 2)
  20. # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
  21. x = x.reshape(bs, heads, length, -1)
  22. return x
  23. class PerceiverAttention(nn.Module):
  24. def __init__(self, *, dim, dim_head=64, heads=8):
  25. super().__init__()
  26. self.scale = dim_head**-0.5
  27. self.dim_head = dim_head
  28. self.heads = heads
  29. inner_dim = dim_head * heads
  30. self.norm1 = nn.LayerNorm(dim)
  31. self.norm2 = nn.LayerNorm(dim)
  32. self.to_q = nn.Linear(dim, inner_dim, bias=False)
  33. self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
  34. self.to_out = nn.Linear(inner_dim, dim, bias=False)
  35. def forward(self, x, latents):
  36. """
  37. Args:
  38. x (torch.Tensor): image features
  39. shape (b, n1, D)
  40. latent (torch.Tensor): latent features
  41. shape (b, n2, D)
  42. """
  43. x = self.norm1(x)
  44. latents = self.norm2(latents)
  45. b, l, _ = latents.shape
  46. q = self.to_q(latents)
  47. kv_input = torch.cat((x, latents), dim=-2)
  48. k, v = self.to_kv(kv_input).chunk(2, dim=-1)
  49. q = reshape_tensor(q, self.heads)
  50. k = reshape_tensor(k, self.heads)
  51. v = reshape_tensor(v, self.heads)
  52. # attention
  53. scale = 1 / math.sqrt(math.sqrt(self.dim_head))
  54. weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
  55. weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
  56. out = weight @ v
  57. out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
  58. return self.to_out(out)
  59. class Resampler(nn.Module):
  60. def __init__(
  61. self,
  62. dim=1024,
  63. depth=8,
  64. dim_head=64,
  65. heads=16,
  66. num_queries=8,
  67. embedding_dim=768,
  68. output_dim=1024,
  69. ff_mult=4,
  70. ):
  71. super().__init__()
  72. self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
  73. self.proj_in = nn.Linear(embedding_dim, dim)
  74. self.proj_out = nn.Linear(dim, output_dim)
  75. self.norm_out = nn.LayerNorm(output_dim)
  76. self.layers = nn.ModuleList([])
  77. for _ in range(depth):
  78. self.layers.append(
  79. nn.ModuleList(
  80. [
  81. PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
  82. FeedForward(dim=dim, mult=ff_mult),
  83. ]
  84. )
  85. )
  86. def forward(self, x):
  87. latents = self.latents.repeat(x.size(0), 1, 1).to(x)
  88. x = self.proj_in(x)
  89. for attn, ff in self.layers:
  90. latents = attn(x, latents) + latents
  91. latents = ff(latents) + latents
  92. latents = self.proj_out(latents)
  93. return self.norm_out(latents)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...