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

Upload stae_pixel.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. stae_pixel.py +314 -0
stae_pixel.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, cond=None):
104
+ x = self.initial(x)
105
+
106
+ if(cond is None):
107
+ for block in self.blocks:
108
+ x = block(x)
109
+ else:
110
+ cond = cond.chunk(len(self.blocks), dim=1)
111
+ for block, cond in zip(self.blocks, cond):
112
+ x = block(x) + cond
113
+
114
+ x = self.out(x)
115
+ return x
116
+
117
+ class NerfHead(nn.Module):
118
+ def __init__(self, patch_dim, mlp_dim):
119
+ super().__init__()
120
+ self.mlp_dim = mlp_dim
121
+ self.param_gen = nn.Linear(patch_dim, self.mlp_dim*self.mlp_dim*2)
122
+ self.norm = nn.RMSNorm(self.mlp_dim)
123
+
124
+ def forward(self, pixels, patches):
125
+ bs = pixels.shape[0]
126
+ params = self.param_gen(patches)
127
+ layer1, layer2 = params.chunk(2, dim=-1)
128
+ layer1 = layer1.view(bs, self.mlp_dim, self.mlp_dim)
129
+ layer2 = layer2.view(bs, self.mlp_dim, self.mlp_dim)
130
+
131
+ layer1 = torch.nn.functional.normalize(layer1, dim=-2)
132
+
133
+ res_x = pixels
134
+ pixels = self.norm(pixels)
135
+ pixels = torch.bmm(pixels, layer1)
136
+ pixels = torch.nn.functional.silu(pixels)
137
+ pixels = torch.bmm(pixels, layer2)
138
+ pixels = pixels + res_x
139
+ return pixels
140
+
141
+ class NerfEmbedder(nn.Module):
142
+ def __init__(self, in_channels, hidden_size_input, max_freqs):
143
+ super().__init__()
144
+ self.max_freqs = max_freqs
145
+ self.hidden_size_input = hidden_size_input
146
+ self.embedder = nn.Sequential(
147
+ nn.Linear(in_channels+max_freqs**2, hidden_size_input, bias=True),
148
+ )
149
+ self.positions = nn.Parameter(torch.randn(1, 16**2, max_freqs**2))
150
+
151
+
152
+ def forward(self, inputs):
153
+ B, P2, C = inputs.shape
154
+
155
+ dct = self.positions
156
+ dct = dct.repeat(B, 1, 1)
157
+ inputs = torch.cat([inputs, dct], dim=-1)
158
+ inputs = self.embedder(inputs)
159
+ return inputs
160
+
161
+
162
+ class StupidDecoder(nn.Module):
163
+ def __init__(self,
164
+ hidden_dim,
165
+ in_channels,
166
+ out_channels,
167
+ patch_size,
168
+ num_blocks,
169
+ nerf_blocks,
170
+ mlp_dim):
171
+ super().__init__()
172
+
173
+ self.out_channels = out_channels
174
+
175
+ self.patch_size = patch_size
176
+ self.conv_in = ConvMlp(in_channels, hidden_dim, hidden_dim)
177
+ self.blocks = []
178
+ for _ in range(num_blocks):
179
+ self.blocks.append(DecoderBlock(hidden_dim))
180
+ self.blocks.append(EncoderBlock(hidden_dim))
181
+ self.blocks = nn.ModuleList(self.blocks)
182
+
183
+ self.nerf = nn.ModuleList(NerfHead(hidden_dim, mlp_dim) for _ in range(nerf_blocks))
184
+ self.last = nn.Linear(mlp_dim, self.out_channels)
185
+ self.x_embedder = NerfEmbedder(3, mlp_dim, 8)
186
+
187
+ def forward(self, x, x_orig, cond=None):
188
+ B, C, H, W = x.shape
189
+ x = self.conv_in(x)
190
+ if(cond is None):
191
+ for block in self.blocks:
192
+ x = block(x)
193
+ else:
194
+ cond = cond.chunk(len(self.blocks), dim=1)
195
+ for block, cond in zip(self.blocks, cond):
196
+ add, scale = cond.chunk(2, dim=1)
197
+ x = (block(x) + add) * (1 + scale)
198
+
199
+ patches = x.flatten(2).transpose(1,2) # B C H W -> B (HW) C
200
+ patch_count = H*W
201
+ total_len = x.shape[0] * patch_count
202
+ patches = patches.reshape(total_len, -1)
203
+
204
+ x = torch.nn.functional.unfold(x_orig, kernel_size=self.patch_size, stride=self.patch_size).transpose(1, 2)
205
+ x = x.reshape(total_len, 3, self.patch_size ** 2 )
206
+ x = x.transpose(1, 2)
207
+ x = self.x_embedder(x)
208
+
209
+ for block in self.nerf:
210
+ x = block(x, patches) # B * patch_count, ps*ps, C
211
+ x = self.last(x)
212
+ x = x.transpose(1,2) # [B * patch_count, ps*ps, C] -> [B*patch_count, C, ps*ps]
213
+ x = x.reshape(B, patch_count, -1) # [B*patch_count, C, ps*ps] -> [B, patch_count, ps*ps*3]
214
+ x = x.transpose(1,2) # [B, patch_count, ps*ps*3] -> [B, ps*ps*3, patch_count]
215
+ x = torch.nn.functional.fold(x.contiguous(),
216
+ (H*self.patch_size, W*self.patch_size),
217
+ kernel_size=self.patch_size,
218
+ stride=self.patch_size)
219
+
220
+ return x
221
+
222
+ class Upsampler(nn.Module):
223
+ def __init__(self,
224
+ hidden_dim,
225
+ nerf_blocks,
226
+ mlp_dim,
227
+ patch_size,
228
+ out_channels):
229
+ super().__init__()
230
+
231
+ self.patch_size = patch_size
232
+ self.nerf = nn.ModuleList(NerfHead(hidden_dim, mlp_dim) for _ in range(nerf_blocks))
233
+ self.positions = nn.Parameter(torch.randn(1, self.patch_size**2, mlp_dim))
234
+ self.last = nn.Linear(mlp_dim, out_channels)
235
+
236
+ def forward(self, x):
237
+ B, C, H, W = x.shape
238
+
239
+ patches = x.flatten(2).transpose(1,2) # B C H W -> B (HW) C
240
+ patch_count = H*W
241
+ total_len = x.shape[0] * patch_count
242
+ patches = patches.reshape(total_len, -1)
243
+ x = self.positions.repeat(total_len, 1, 1)
244
+
245
+ for block in self.nerf:
246
+ x = block(x, patches) # B * patch_count, ps*ps, C
247
+ x = self.last(x)
248
+ x = x.transpose(1,2) # [B * patch_count, ps*ps, C] -> [B*patch_count, C, ps*ps]
249
+ x = x.reshape(B, patch_count, -1) # [B*patch_count, C, ps*ps] -> [B, patch_count, ps*ps*3]
250
+ x = x.transpose(1,2) # [B, patch_count, ps*ps*3] -> [B, ps*ps*3, patch_count]
251
+ x = torch.nn.functional.fold(x.contiguous(),
252
+ (H*self.patch_size, W*self.patch_size),
253
+ kernel_size=self.patch_size,
254
+ stride=self.patch_size)
255
+
256
+ return x
257
+
258
+ def weights_init_zeros(m):
259
+ if hasattr(m, 'weight') and m.weight is not None:
260
+ nn.init.constant_(m.weight, 0)
261
+ if hasattr(m, 'bias') and m.bias is not None:
262
+ nn.init.constant_(m.bias, 0)
263
+
264
+ class StupidAE(nn.Module):
265
+ def __init__(self):
266
+ super().__init__()
267
+
268
+ self.real_encoder = nn.Sequential(
269
+ StupidEncoder(in_channels=3, out_channels=32, hidden_dim=512, patch_size=8, num_blocks=1),
270
+ StupidEncoder(in_channels=32, out_channels=256, hidden_dim=1024, patch_size=4, num_blocks=2),
271
+ StupidEncoder(in_channels=256, out_channels=1024, hidden_dim=1024, patch_size=2, num_blocks=2),
272
+ Upsampler(1024, 1, 128, 4, 16)
273
+ )
274
+
275
+ encoder_dim = 1024
276
+ num_encoder_blocks = 1
277
+ self.encoder_proj = nn.Sequential(
278
+ nn.Conv2d(16, 1024, kernel_size=3, stride=1, padding=1),
279
+ nn.GELU(),
280
+ nn.Conv2d(1024, 24 * 1024, kernel_size=1, stride=1)
281
+ )
282
+
283
+ self.encoder_proj[2].apply(weights_init_zeros)
284
+
285
+ self.encoder = nn.Sequential(
286
+ StupidEncoder(in_channels=3, out_channels=512, hidden_dim=512, patch_size=8, num_blocks=1),
287
+ StupidEncoder(in_channels=512, out_channels=1024, hidden_dim=encoder_dim, patch_size=2, num_blocks=num_encoder_blocks),
288
+ )
289
+
290
+ self.decoder = StupidDecoder(in_channels=1024, out_channels=3, hidden_dim=1024, patch_size=16, num_blocks=6, nerf_blocks=2, mlp_dim=96)
291
+
292
+ # self.encoder.requires_grad_(False)
293
+ # self.decoder.requires_grad_(False)
294
+
295
+ # self.real_encoder.requires_grad_(False)
296
+
297
+ @torch.compile(mode="default")
298
+ def encode(self, x):
299
+ return self.real_encoder(x)
300
+
301
+ @torch.compile(mode="default")
302
+ def forward(self, x, cond=None):
303
+ x_orig = x
304
+
305
+ x = self.encoder(x)
306
+
307
+ if(cond is not None):
308
+ projected = self.encoder_proj(cond)
309
+ x = self.decoder(x, x_orig, projected)
310
+ else:
311
+ x = self.decoder(x, x_orig)
312
+
313
+
314
+ return x