-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtrain_vq_e2e.py
284 lines (210 loc) · 7.7 KB
/
train_vq_e2e.py
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from shutil import rmtree
from pathlib import Path
import torch
from torch import tensor, nn
from torch.nn import Module
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam
from einops import rearrange, repeat, pack, unpack
from einops.layers.torch import Rearrange
import torchvision
import torchvision.transforms as T
from torchvision.utils import save_image
rmtree('./results', ignore_errors = True)
results_folder = Path('./results')
results_folder.mkdir(exist_ok = True, parents = True)
# functions
def divisible_by(num, den):
return (num % den) == 0
# e2e training encoder / decoder / transformer / vq
from x_transformers import Decoder
from vector_quantize_pytorch import VectorQuantize as VQ
from vector_quantize_pytorch.vector_quantize_pytorch import rotate_to
from genie2_pytorch.genie2 import (
gumbel_sample,
min_p_filter
)
class Lambda(Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x):
return self.fn(x)
class VQImageAutoregressiveAutoencoder(Module):
def __init__(
self,
image_size,
patch_size,
dim,
codebook_size,
decay = 0.9,
depth = 3,
dim_head = 16,
heads = 4,
recon_from_pred_codes_weight = 1., # whether to reconstruct from the predicted codes or from the quantized codes directly after vq. 1. means from entirely from predicted code and 0. means entirely right after VQ, so none of the transformer network receives any of the reconstruction gradients
recon_loss_weight = 1.,
vq_commit_loss_weight = 1.,
ar_commit_loss_weight = 1.
):
super().__init__()
assert divisible_by(image_size, patch_size)
self.seq_length = (image_size // patch_size) ** 2
self.encode = nn.Sequential(
Lambda(lambda x: x * 2 - 1),
Rearrange('... 1 (h p1) (w p2) -> ... (h w) (p1 p2)', p1 = patch_size, p2 = patch_size),
nn.Linear(patch_size ** 2, dim),
)
self.vq = VQ(
dim = dim,
codebook_size = codebook_size,
rotation_trick = True,
decay = decay
)
self.start_token = nn.Parameter(torch.zeros(dim))
self.decoder = nn.Sequential(
Decoder(
dim = dim,
heads = heads,
depth = depth,
attn_dim_head = dim_head,
rotary_pos_emb = True
),
nn.Linear(dim, dim)
)
self.decode = nn.Sequential(
nn.Linear(dim, patch_size ** 2),
Rearrange('... (h w) (p1 p2) -> ... 1 (h p1) (w p2)', p1 = patch_size, p2 = patch_size, h = image_size // patch_size),
Lambda(lambda x: (x + 1) * 0.5),
)
self.recon_from_pred_codes_weight = recon_from_pred_codes_weight
self.recon_loss_weight = recon_loss_weight
self.vq_commit_loss_weight = vq_commit_loss_weight
self.ar_commit_loss_weight = ar_commit_loss_weight
@property
def device(self):
return next(self.parameters()).device
@torch.no_grad()
def sample(
self,
num_samples = 64,
min_p = 0.25,
temperature = 1.5
):
self.eval()
out = torch.empty((num_samples, 0), dtype = torch.long, device = self.device)
codebook = self.vq.codebook
start_tokens = repeat(self.start_token, 'd -> b 1 d', b = num_samples)
for _ in range(self.seq_length):
codes = self.vq.get_codes_from_indices(out)
inp = torch.cat((start_tokens, codes), dim = -2)
embed = self.decoder(inp)
logits = -torch.cdist(embed, codebook)
logits = logits[:, -1]
logits = min_p_filter(logits, min_p)
sampled = gumbel_sample(logits, temperature = temperature)
out = torch.cat((out, sampled), dim = -1)
sampled_codes = self.vq.get_codes_from_indices(out)
images = self.decode(sampled_codes)
return images.clamp(0., 1.)
def forward(
self,
image
):
self.train()
encoded = self.encode(image)
quantized, codes, commit_loss = self.vq(encoded)
# setup autoregressive, patches as tokens scanned from each row left to right
start_tokens = repeat(self.start_token, '... -> b 1 ...', b = encoded.shape[0])
tokens = torch.cat((start_tokens, quantized[:, :-1]), dim = -2)
pred_codes = self.decoder(tokens)
logits = -torch.cdist(pred_codes, self.vq.codebook)
ce_loss = F.cross_entropy(
rearrange(logits, 'b n l -> b l n'),
codes
)
# recon loss, learning autoencoder end to end
recon_image_from_pred_codes = 0.
recon_image_from_vq = 0.
if self.recon_from_pred_codes_weight > 0.:
rotated_pred_codes = rotate_to(pred_codes, self.vq.get_codes_from_indices(codes))
recon_image_from_pred_codes = self.decode(rotated_pred_codes)
if self.recon_from_pred_codes_weight < 1.:
recon_image_from_vq = self.decode(quantized)
# weighted combine
recon_image = (
recon_image_from_pred_codes * self.recon_from_pred_codes_weight +
recon_image_from_vq * (1. - self.recon_from_pred_codes_weight)
)
# mse loss
recon_loss = F.mse_loss(
recon_image,
image
)
# ar commit loss
ar_commit_loss = F.mse_loss(pred_codes, quantized)
# total loss and breakdown
total_loss = (
ce_loss +
recon_loss * self.recon_loss_weight +
commit_loss * self.vq_commit_loss_weight +
ar_commit_loss * self.ar_commit_loss_weight
)
return total_loss, (image, recon_image), (ce_loss, recon_loss, commit_loss, ar_commit_loss)
# model
model = VQImageAutoregressiveAutoencoder(
dim = 256,
depth = 4,
codebook_size = 64,
decay = 0.95,
image_size = 28,
patch_size = 4,
recon_from_pred_codes_weight = 0.5
)
# data related + optimizer
class MnistDataset(Dataset):
def __init__(self):
self.mnist = torchvision.datasets.MNIST(
'./data',
download = True
)
def __len__(self):
return len(self.mnist)
def __getitem__(self, idx):
pil, labels = self.mnist[idx]
digit_tensor = T.PILToTensor()(pil)
return (digit_tensor / 255).float()
def cycle(iter_dl):
while True:
for batch in iter_dl:
yield batch
dataset = MnistDataset()
dataloader = DataLoader(dataset, batch_size = 32, shuffle = True)
iter_dl = cycle(dataloader)
optimizer = Adam(model.parameters(), lr = 3e-4)
# train loop
for step in range(1, 100_000 + 1):
loss, (image, recon_image), (ce_loss, recon_loss, vq_commit_loss, ar_commit_loss) = model(next(iter_dl))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
optimizer.zero_grad()
loss_str = "\t".join([f"{loss_name}: {loss.item():.3f}"
for loss_name, loss in (
('recon', recon_loss),
('ce', ce_loss),
('vq commit', vq_commit_loss),
('ar commit', ar_commit_loss)
)
])
print(f'{step}: {loss_str}')
if divisible_by(step, 500):
save_image(
rearrange([image, recon_image], 'ir b 1 h w -> 1 (b h) (ir w)'),
str(results_folder / f'{step}.train.recon.png')
)
image = model.sample(num_samples = 64)
save_image(
rearrange(image, '(gh gw) 1 h w -> 1 (gh h) (gw w)', gh = 8).detach().cpu(),
str(results_folder / f'{step}.png')
)