5 import torch, torchvision
8 from torch.nn import functional as F
15 def __init__(self, x, y, w, h, r, g, b):
24 def collision(self, scene):
28 and max(self.x, c.x) <= min(self.x + self.w, c.x + c.w)
29 and max(self.y, c.y) <= min(self.y + self.h, c.y + c.h)
35 def scene2tensor(xh, yh, scene, size):
36 width, height = size, size
37 pixel_map = torch.ByteTensor(width, height, 4).fill_(255)
38 data = pixel_map.numpy()
39 surface = cairo.ImageSurface.create_for_data(
40 data, cairo.FORMAT_ARGB32, width, height
43 ctx = cairo.Context(surface)
44 ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
47 ctx.move_to(b.x * size, b.y * size)
48 ctx.rel_line_to(b.w * size, 0)
49 ctx.rel_line_to(0, b.h * size)
50 ctx.rel_line_to(-b.w * size, 0)
53 b.r / (Box.nb_rgb_levels - 1),
54 b.g / (Box.nb_rgb_levels - 1),
55 b.b / (Box.nb_rgb_levels - 1),
61 ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0)
62 ctx.move_to(xh * size - hs / 2, yh * size - hs / 2)
63 ctx.rel_line_to(hs, 0)
64 ctx.rel_line_to(0, hs)
65 ctx.rel_line_to(-hs, 0)
70 pixel_map[None, :, :, :3]
74 .mul(Box.nb_rgb_levels)
82 ((Box.nb_rgb_levels - 1), 0, 0),
83 (0, (Box.nb_rgb_levels - 1), 0),
84 (0, 0, (Box.nb_rgb_levels - 1)),
85 ((Box.nb_rgb_levels - 1), (Box.nb_rgb_levels - 1), 0),
87 (Box.nb_rgb_levels * 2) // 3,
88 (Box.nb_rgb_levels * 2) // 3,
89 (Box.nb_rgb_levels * 2) // 3,
94 wh = torch.rand(2) * 0.2 + 0.2
95 xy = torch.rand(2) * (1 - wh)
96 c = colors[torch.randint(len(colors), (1,))]
98 xy[0].item(), xy[1].item(), wh[0].item(), wh[1].item(), c[0], c[1], c[2]
100 if not b.collision(scene):
106 def generate_episode(nb_steps=10, size=64):
123 scene = random_scene()
124 xh, yh = tuple(x.item() for x in torch.rand(2))
126 frames.append(scene2tensor(xh, yh, scene, size=size))
128 actions = torch.randint(len(effects), (nb_steps,))
132 g, dx, dy = effects[a]
135 if b.x <= xh and b.x + b.w >= xh and b.y <= yh and b.y + b.h >= yh:
144 or b.collision(scene)
155 if xh < 0 or xh > 1 or yh < 0 or yh > 1:
158 frames.append(scene2tensor(xh, yh, scene, size=size))
163 return frames, actions
166 ######################################################################
169 # ||x_i - c_j||^2 = ||x_i||^2 + ||c_j||^2 - 2<x_i, c_j>
173 return nx[:, None] + nc[None, :] - 2 * x @ c.t()
176 def update_centroids(x, c, nb_min=1):
177 _, b = sq2matrix(x, c).min(1)
181 for k in range(0, c.size(0)):
182 i = b.eq(k).nonzero(as_tuple=False).squeeze()
183 if i.numel() >= nb_min:
184 c[k] = x.index_select(0, i).mean(0)
186 n = torch.randint(x.size(0), (1,))
190 return c, b, nb_resets
193 def kmeans(x, nb_centroids, nb_min=1):
194 if x.size(0) < nb_centroids * nb_min:
195 print("Not enough points!")
198 c = x[torch.randperm(x.size(0))[:nb_centroids]]
199 t = torch.full((x.size(0),), -1)
203 c, u, nb_resets = update_centroids(x, c, nb_min)
205 nb_changes = (u - t).sign().abs().sum() + nb_resets
213 ######################################################################
216 def patchify(x, factor, invert_size=None):
217 if invert_size is None:
223 x.size(2) // factor, # 3
225 x.size(3) // factor, # 5
227 .permute(0, 2, 4, 1, 3, 5)
228 .reshape(-1, x.size(1), x.size(2) // factor, x.size(3) // factor)
237 invert_size[2] // factor, # 4
238 invert_size[3] // factor, # 5
240 .permute(0, 3, 1, 4, 2, 5)
241 .reshape(invert_size)
245 class Normalizer(nn.Module):
246 def __init__(self, mu, std):
248 self.register_buffer("mu", mu)
249 self.register_buffer("log_var", 2 * torch.log(std))
251 def forward(self, x):
252 return (x - self.mu) / torch.exp(self.log_var / 2.0)
255 class SignSTE(nn.Module):
259 def forward(self, x):
260 # torch.sign() takes three values
261 s = (x >= 0).float() * 2 - 1
264 return s + u - u.detach()
274 nb_bits_per_token=10,
279 device=torch.device("cpu"),
281 mu, std = train_input.float().mean(), train_input.float().std()
283 def encoder_core(depth, dim):
287 dim * 2**k, dim * 2**k, kernel_size=5, stride=1, padding=2
290 nn.Conv2d(dim * 2**k, dim * 2 ** (k + 1), kernel_size=2, stride=2),
293 for k in range(depth)
296 return nn.Sequential(*[x for m in l for x in m])
298 def decoder_core(depth, dim):
302 dim * 2 ** (k + 1), dim * 2**k, kernel_size=2, stride=2
306 dim * 2**k, dim * 2**k, kernel_size=5, stride=1, padding=2
310 for k in range(depth - 1, -1, -1)
313 return nn.Sequential(*[x for m in l for x in m])
315 encoder = nn.Sequential(
317 nn.Conv2d(3, dim_hidden, kernel_size=1, stride=1),
320 encoder_core(depth=depth, dim=dim_hidden),
322 nn.Conv2d(dim_hidden * 2**depth, nb_bits_per_token, kernel_size=1, stride=1),
325 quantizer = SignSTE()
327 decoder = nn.Sequential(
328 nn.Conv2d(nb_bits_per_token, dim_hidden * 2**depth, kernel_size=1, stride=1),
330 decoder_core(depth=depth, dim=dim_hidden),
332 nn.ConvTranspose2d(dim_hidden, 3 * Box.nb_rgb_levels, kernel_size=1, stride=1),
335 model = nn.Sequential(encoder, decoder)
337 nb_parameters = sum(p.numel() for p in model.parameters())
339 print(f"nb_parameters {nb_parameters}")
343 g5x5 = torch.exp(-torch.tensor([[-2.0, -1.0, 0.0, 1.0, 2.0]]) ** 2 / 2)
344 g5x5 = (g5x5.t() @ g5x5).view(1, 1, 5, 5)
345 g5x5 = g5x5 / g5x5.sum()
347 for k in range(nb_epochs):
349 math.log(lr_start) + math.log(lr_end / lr_start) / (nb_epochs - 1) * k
351 optimizer = torch.optim.Adam(model.parameters(), lr=lr)
355 for input in train_input.split(batch_size):
357 zq = z if k < 1 else quantizer(z)
360 output = output.reshape(
361 output.size(0), -1, 3, output.size(2), output.size(3)
364 train_loss = F.cross_entropy(output, input)
366 acc_train_loss += train_loss.item() * input.size(0)
368 optimizer.zero_grad()
369 train_loss.backward()
374 for input in test_input.split(batch_size):
376 zq = z if k < 1 else quantizer(z)
379 output = output.reshape(
380 output.size(0), -1, 3, output.size(2), output.size(3)
383 test_loss = F.cross_entropy(output, input)
385 acc_test_loss += test_loss.item() * input.size(0)
387 train_loss = acc_train_loss / train_input.size(0)
388 test_loss = acc_test_loss / test_input.size(0)
390 print(f"train_ae {k} lr {lr} train_loss {train_loss} test_loss {test_loss}")
393 return encoder, quantizer, decoder
395 def generate_episodes(nb):
397 for n in tqdm.tqdm(range(nb), dynamic_ncols=True, desc="world-data"):
398 frames, actions = generate_episode(nb_steps=31)
399 all_frames += [ frames[0], frames[-1] ]
400 return torch.cat(all_frames, 0).contiguous()
402 def create_data_and_processors(nb_train_samples, nb_test_samples):
403 train_input = generate_episodes(nb_train_samples)
404 test_input = generate_episodes(nb_test_samples)
405 encoder, quantizer, decoder = train_encoder(train_input, test_input, nb_epochs=2)
407 input = test_input[:64]
409 z = encoder(input.float())
410 height, width = z.size(2), z.size(3)
411 zq = quantizer(z).long()
412 pow2=(2**torch.arange(zq.size(1), device=zq.device))[None,None,:]
413 seq = (zq.permute(0,2,3,1).clamp(min=0).reshape(zq.size(0),-1,zq.size(1)) * pow2).sum(-1)
414 print(f"{seq.size()=}")
418 zq = ((seq[:,:,None] // pow2)%2)*2-1
419 zq = zq.reshape(zq.size(0), height, width, -1).permute(0,3,1,2)
424 print("CHECK", (ZZ-zq).abs().sum())
426 results = decoder(zq.float())
428 results = results.reshape(
429 results.size(0), -1, 3, results.size(2), results.size(3)
430 ).permute(0, 2, 3, 4, 1)
431 results = torch.distributions.categorical.Categorical(logits=results / T).sample()
434 torchvision.utils.save_image(
435 input.float() / (Box.nb_rgb_levels - 1), "orig.png", nrow=8
438 torchvision.utils.save_image(
439 results.float() / (Box.nb_rgb_levels - 1), "qtiz.png", nrow=8
443 ######################################################################
445 if __name__ == "__main__":
446 create_data_and_processors(250,100)
448 # train_input = generate_episodes(2500)
449 # test_input = generate_episodes(1000)
451 # encoder, quantizer, decoder = train_encoder(train_input, test_input)
453 # input = test_input[torch.randperm(test_input.size(0))[:64]]
454 # z = encoder(input.float())
456 # results = decoder(zq)
459 # results = torch.distributions.categorical.Categorical(logits=results / T).sample()