5 import torch, torchvision
8 from torch.nn import functional as F
13 def __init__(self, x, y, w, h, r, g, b):
22 def collision(self, scene):
26 and max(self.x, c.x) <= min(self.x + self.w, c.x + c.w)
27 and max(self.y, c.y) <= min(self.y + self.h, c.y + c.h)
33 def scene2tensor(xh, yh, scene, size):
34 width, height = size, size
35 pixel_map = torch.ByteTensor(width, height, 4).fill_(255)
36 data = pixel_map.numpy()
37 surface = cairo.ImageSurface.create_for_data(
38 data, cairo.FORMAT_ARGB32, width, height
41 ctx = cairo.Context(surface)
42 ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
45 ctx.move_to(b.x * size, b.y * size)
46 ctx.rel_line_to(b.w * size, 0)
47 ctx.rel_line_to(0, b.h * size)
48 ctx.rel_line_to(-b.w * size, 0)
50 ctx.set_source_rgba(b.r, b.g, b.b, 1.0)
54 ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0)
55 ctx.move_to(xh * size - hs / 2, yh * size - hs / 2)
56 ctx.rel_line_to(hs, 0)
57 ctx.rel_line_to(0, hs)
58 ctx.rel_line_to(-hs, 0)
62 return pixel_map[None, :, :, :3].flip(-1).permute(0, 3, 1, 2).float() / 255
76 wh = torch.rand(2) * 0.2 + 0.2
77 xy = torch.rand(2) * (1 - wh)
78 c = colors[torch.randint(len(colors), (1,))]
80 xy[0].item(), xy[1].item(), wh[0].item(), wh[1].item(), c[0], c[1], c[2]
82 if not b.collision(scene):
88 def generate_sequence(nb_steps=10, all_frames=False, size=64):
105 scene = random_scene()
106 xh, yh = tuple(x.item() for x in torch.rand(2))
108 frames.append(scene2tensor(xh, yh, scene, size=size))
110 actions = torch.randint(len(effects), (nb_steps,))
114 g, dx, dy = effects[a]
117 if b.x <= xh and b.x + b.w >= xh and b.y <= yh and b.y + b.h >= yh:
126 or b.collision(scene)
137 if xh < 0 or xh > 1 or yh < 0 or yh > 1:
141 frames.append(scene2tensor(xh, yh, scene, size=size))
144 frames.append(scene2tensor(xh, yh, scene, size=size))
149 return frames, actions
152 ######################################################################
155 # ||x_i - c_j||^2 = ||x_i||^2 + ||c_j||^2 - 2<x_i, c_j>
159 return nx[:, None] + nc[None, :] - 2 * x @ c.t()
162 def update_centroids(x, c, nb_min=1):
163 _, b = sq2matrix(x, c).min(1)
167 for k in range(0, c.size(0)):
168 i = b.eq(k).nonzero(as_tuple=False).squeeze()
169 if i.numel() >= nb_min:
170 c[k] = x.index_select(0, i).mean(0)
172 n = torch.randint(x.size(0), (1,))
176 return c, b, nb_resets
179 def kmeans(x, nb_centroids, nb_min=1):
180 if x.size(0) < nb_centroids * nb_min:
181 print("Not enough points!")
184 c = x[torch.randperm(x.size(0))[:nb_centroids]]
185 t = torch.full((x.size(0),), -1)
189 c, u, nb_resets = update_centroids(x, c, nb_min)
191 nb_changes = (u - t).sign().abs().sum() + nb_resets
199 ######################################################################
202 def patchify(x, factor, invert_size=None):
203 if invert_size is None:
209 x.size(2) // factor, # 3
211 x.size(3) // factor, # 5
213 .permute(0, 2, 4, 1, 3, 5)
214 .reshape(-1, x.size(1), x.size(2) // factor, x.size(3) // factor)
223 invert_size[2] // factor, # 4
224 invert_size[3] // factor, # 5
226 .permute(0, 3, 1, 4, 2, 5)
227 .reshape(invert_size)
231 class Normalizer(nn.Module):
232 def __init__(self, mu, std):
234 self.mu = nn.Parameter(mu)
235 self.log_var = nn.Parameter(2 * torch.log(std))
237 def forward(self, x):
238 return (x - self.mu) / torch.exp(self.log_var / 2.0)
241 class SignSTE(nn.Module):
245 def forward(self, x):
246 # torch.sign() takes three values
247 s = (x >= 0).float() * 2 - 1
250 return s + u - u.detach()
259 nb_bits_per_block=10,
264 device=torch.device("cpu"),
266 mu, std = train_input.mean(), train_input.std()
268 encoder = nn.Sequential(
270 nn.Conv2d(3, dim_hidden, kernel_size=5, stride=1, padding=2),
272 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
274 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
276 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
278 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
283 kernel_size=block_size,
290 decoder = nn.Sequential(
294 kernel_size=block_size,
299 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
301 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
303 nn.Conv2d(dim_hidden, dim_hidden, kernel_size=5, stride=1, padding=2),
305 nn.Conv2d(dim_hidden, 3, kernel_size=5, stride=1, padding=2),
308 model = nn.Sequential(encoder, decoder)
310 nb_parameters = sum(p.numel() for p in model.parameters())
312 print(f"nb_parameters {nb_parameters}")
316 for k in range(nb_epochs):
318 math.log(lr_start) + math.log(lr_end / lr_start) / (nb_epochs - 1) * k
321 optimizer = torch.optim.Adam(model.parameters(), lr=lr)
322 acc_loss, nb_samples = 0.0, 0
324 for input in tqdm.tqdm(
325 train_input.split(batch_size),
328 total=train_input.size(0) // batch_size,
330 output = model(input)
331 loss = F.mse_loss(output, input)
332 acc_loss += loss.item() * input.size(0)
333 nb_samples += input.size(0)
335 optimizer.zero_grad()
339 print(f"loss {k} {acc_loss/nb_samples}")
342 return encoder, decoder
345 ######################################################################
347 if __name__ == "__main__":
352 start_time = time.perf_counter()
358 frames, actions = generate_sequence(nb_steps=31)
360 end_time = time.perf_counter()
361 print(f"{nb / (end_time - start_time):.02f} samples per second")
363 input = torch.cat(all_frames, 0)
364 encoder, decoder = train_encoder(input)
366 # x = patchify(input, 8)
367 # y = x.reshape(x.size(0), -1)
368 # print(f"{x.size()=} {y.size()=}")
369 # centroids, t = kmeans(y, 4096)
370 # results = centroids[t]
371 # results = results.reshape(x.size())
372 # results = patchify(results, 8, input.size())
377 print(f"{input.size()=} {z.size()=} {results.size()=}")
379 torchvision.utils.save_image(input[:64], "orig.png", nrow=8)
381 torchvision.utils.save_image(results[:64], "qtiz.png", nrow=8)
383 # frames, actions = generate_sequence(nb_steps=31, all_frames=True)
384 # frames = torch.cat(frames, 0)
385 # torchvision.utils.save_image(frames, "seq.png", nrow=8)