Muinez commited on
Commit
72772a5
·
verified ·
1 Parent(s): e7fc0f6

Upload stae.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. stae.py +266 -0
stae.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ class RMSNorm2d(nn.Module):
6
+ def __init__(self, channels, eps=1e-8, affine=True):
7
+ super().__init__()
8
+ self.eps = eps
9
+ self.affine = affine
10
+ if affine:
11
+ self.weight = nn.Parameter(torch.ones(channels))
12
+ else:
13
+ self.register_parameter("weight", None)
14
+
15
+ def forward(self, x):
16
+ norm = x.pow(2).mean(dim=1, keepdim=True).add(self.eps).rsqrt()
17
+ x = x * norm
18
+ if self.affine:
19
+ x = x * self.weight[:, None, None]
20
+ return x
21
+
22
+ class ConvMlp(nn.Module):
23
+ def __init__(self, in_features, hidden_features=None, out_features=None):
24
+ super().__init__()
25
+ self.model = nn.Sequential(
26
+ nn.Conv2d(in_channels=in_features, out_channels=hidden_features, kernel_size=1),
27
+ nn.GELU(),
28
+ nn.Conv2d(in_channels=hidden_features, out_channels=out_features, kernel_size=1),
29
+ )
30
+
31
+ def forward(self, x):
32
+ return self.model(x)
33
+
34
+ import torch
35
+ import torch.nn as nn
36
+ class GegluMlp(nn.Module):
37
+ def __init__(self, hidden_dim, out_dim=None):
38
+ super().__init__()
39
+
40
+ if(out_dim is None):
41
+ out_dim = hidden_dim
42
+ self.conv_up = nn.Conv2d(hidden_dim, hidden_dim * 4, kernel_size=1)
43
+ self.conv_down = nn.Conv2d(hidden_dim * 2, out_dim, kernel_size=1)
44
+ self.activation = nn.GELU(approximate="tanh")
45
+
46
+ def forward(self, x):
47
+ x = self.conv_up(x)
48
+ x_gate, x_act = torch.chunk(x, 2, dim=1)
49
+ x = self.activation(x_act) * x_gate
50
+ x = self.conv_down(x)
51
+
52
+ return x
53
+
54
+ class EncoderBlock(nn.Module):
55
+ def __init__(self, channels):
56
+ super().__init__()
57
+ self.norm = RMSNorm2d(channels)
58
+ hidden_dim = channels
59
+
60
+ self.mlp = GegluMlp(hidden_dim)
61
+
62
+ def forward(self, x):
63
+ norm = self.norm(x)
64
+ mlp_out = self.mlp(norm)
65
+ x = x + mlp_out
66
+
67
+ return x
68
+
69
+ class DecoderBlock(nn.Module):
70
+ def __init__(self, channels):
71
+ super().__init__()
72
+ self.norm = RMSNorm2d(channels)
73
+
74
+ self.mlp = nn.Sequential(
75
+ nn.Conv2d(channels, channels, kernel_size=1),
76
+ nn.GELU(approximate="tanh"),
77
+ nn.Conv2d(channels, channels, kernel_size=3, padding=1),
78
+ )
79
+
80
+ def forward(self, x):
81
+ norm = self.norm(x)
82
+ mlp_out = self.mlp(norm)
83
+ x = x + mlp_out
84
+
85
+ return x
86
+
87
+ class StupidEncoder(nn.Module):
88
+ def __init__(self,
89
+ hidden_dim,
90
+ in_channels,
91
+ out_channels,
92
+ patch_size,
93
+ num_blocks):
94
+ super().__init__()
95
+
96
+ self.initial = nn.Sequential(
97
+ nn.Conv2d(in_channels, hidden_dim, patch_size, padding=0, stride=patch_size),
98
+ )
99
+
100
+ self.blocks = nn.ModuleList(EncoderBlock(hidden_dim) for _ in range(num_blocks))
101
+ self.out = ConvMlp(hidden_dim, hidden_dim, out_channels)
102
+
103
+ def forward(self, x):
104
+ x = self.initial(x)
105
+
106
+ for block in self.blocks:
107
+ x = block(x)
108
+
109
+ x = self.out(x)
110
+ return x
111
+
112
+ class NerfHead(nn.Module):
113
+ def __init__(self, patch_dim, mlp_dim):
114
+ super().__init__()
115
+ self.mlp_dim = mlp_dim
116
+ self.param_gen = nn.Linear(patch_dim, self.mlp_dim*self.mlp_dim*2)
117
+ self.norm = nn.RMSNorm(self.mlp_dim)
118
+
119
+ def forward(self, pixels, patches):
120
+ bs = pixels.shape[0]
121
+ params = self.param_gen(patches)
122
+ layer1, layer2 = params.chunk(2, dim=-1)
123
+ layer1 = layer1.view(bs, self.mlp_dim, self.mlp_dim)
124
+ layer2 = layer2.view(bs, self.mlp_dim, self.mlp_dim)
125
+
126
+ layer1 = torch.nn.functional.normalize(layer1, dim=-2)
127
+
128
+ res_x = pixels
129
+ pixels = self.norm(pixels)
130
+ pixels = torch.bmm(pixels, layer1)
131
+ pixels = torch.nn.functional.silu(pixels)
132
+ pixels = torch.bmm(pixels, layer2)
133
+ pixels = pixels + res_x
134
+ return pixels
135
+
136
+ class StupidDecoder(nn.Module):
137
+ def __init__(self,
138
+ hidden_dim,
139
+ in_channels,
140
+ out_channels,
141
+ patch_size,
142
+ num_blocks,
143
+ nerf_blocks,
144
+ mlp_dim):
145
+ super().__init__()
146
+
147
+ self.out_channels = out_channels
148
+
149
+ self.patch_size = patch_size
150
+ self.conv_in = ConvMlp(in_channels, hidden_dim, hidden_dim)
151
+ self.blocks = []
152
+ for _ in range(num_blocks):
153
+ self.blocks.append(DecoderBlock(hidden_dim))
154
+ self.blocks.append(EncoderBlock(hidden_dim))
155
+ self.blocks = nn.ModuleList(self.blocks)
156
+
157
+ self.nerf = nn.ModuleList(NerfHead(hidden_dim, mlp_dim) for _ in range(nerf_blocks))
158
+ self.positions = nn.Parameter(torch.randn(1, self.patch_size**2, mlp_dim))
159
+ self.last = nn.Linear(mlp_dim, self.out_channels)
160
+
161
+ def forward(self, x):
162
+ B, C, H, W = x.shape
163
+ x = self.conv_in(x)
164
+ for block in self.blocks:
165
+ x = block(x)
166
+
167
+ patches = x.flatten(2).transpose(1,2) # B C H W -> B (HW) C
168
+ patch_count = H*W
169
+ total_len = x.shape[0] * patch_count
170
+ patches = patches.reshape(total_len, -1)
171
+ x = self.positions.repeat(total_len, 1, 1)
172
+
173
+ for block in self.nerf:
174
+ x = block(x, patches) # B * patch_count, ps*ps, C
175
+ x = self.last(x)
176
+ x = x.transpose(1,2) # [B * patch_count, ps*ps, C] -> [B*patch_count, C, ps*ps]
177
+ x = x.reshape(B, patch_count, -1) # [B*patch_count, C, ps*ps] -> [B, patch_count, ps*ps*3]
178
+ x = x.transpose(1,2) # [B, patch_count, ps*ps*3] -> [B, ps*ps*3, patch_count]
179
+ x = torch.nn.functional.fold(x.contiguous(),
180
+ (H*self.patch_size, W*self.patch_size),
181
+ kernel_size=self.patch_size,
182
+ stride=self.patch_size)
183
+
184
+ return x
185
+
186
+ class SimpleStupidDecoder(nn.Module):
187
+ def __init__(self,
188
+ hidden_dim,
189
+ in_channels,
190
+ out_channels,
191
+ patch_size,
192
+ num_blocks):
193
+ super().__init__()
194
+
195
+ self.out_channels = out_channels
196
+ self.patch_size = patch_size
197
+
198
+ self.conv_in = ConvMlp(in_channels, hidden_dim, hidden_dim)
199
+ self.blocks = nn.ModuleList(DecoderBlock(hidden_dim) for _ in range(num_blocks))
200
+
201
+ self.last = nn.Sequential(
202
+ ConvMlp(hidden_dim, hidden_dim, out_channels * patch_size * patch_size),
203
+ nn.PixelShuffle(patch_size)
204
+ )
205
+
206
+ def forward(self, x):
207
+ x = self.conv_in(x)
208
+ for block in self.blocks:
209
+ x = block(x)
210
+
211
+ return self.last(x)
212
+
213
+ class StupidAE(nn.Module):
214
+ def __init__(self):
215
+ super().__init__()
216
+
217
+ self.encoder = nn.Sequential(
218
+ StupidEncoder(in_channels=3, out_channels=32, hidden_dim=512, patch_size=8, num_blocks=2),
219
+ StupidEncoder(in_channels=32, out_channels=256, hidden_dim=1024, patch_size=4, num_blocks=2),
220
+ )
221
+
222
+ self.decoder = nn.Sequential(
223
+ StupidDecoder(in_channels=256, out_channels=32, hidden_dim=1024, patch_size=8, num_blocks=2, nerf_blocks=1, mlp_dim=128),
224
+ StupidDecoder(in_channels=32, out_channels=3, hidden_dim=512, patch_size=4, num_blocks=2, nerf_blocks=1, mlp_dim=32)
225
+ )
226
+
227
+ self.semantic_decoder = GegluMlp(256, 768)
228
+
229
+ @torch.compile(mode="default")
230
+ def encode(self, x):
231
+ return self.encoder(x)
232
+
233
+ @torch.compile(mode="default")
234
+ def decode(self, x):
235
+ return self.decoder(x)
236
+
237
+ def decode_from_tokens(self, tokens, H, W):
238
+ tokens = tokens * 1.28
239
+ results = []
240
+ downsample_factor = 32
241
+ batch_size = tokens.shape[0]
242
+
243
+ for i in range(batch_size):
244
+ h = int(H[i])
245
+ w = int(W[i])
246
+
247
+ h_lat = h // downsample_factor
248
+ w_lat = w // downsample_factor
249
+ num_tokens = h_lat * w_lat
250
+
251
+ # Достаем токены для текущей картинки: [Num_Tokens, C]
252
+ t = tokens[i, :num_tokens]
253
+
254
+ # Решейп в формат сверток [1, C, H_lat, W_lat]
255
+ t = t.transpose(0, 1).view(1, -1, h_lat, w_lat)
256
+
257
+ # Декодируем
258
+ img = self.decoder(t).squeeze(0) * 0.5 + 0.5
259
+ results.append(img)
260
+
261
+ return results
262
+
263
+ def forward(self, x):
264
+ x = self.encode(x)
265
+ x = self.decode(x)
266
+ return x