5 import torch, torchvision
8 from torch.nn import functional as F
11 ######################################################################
17 def __init__(self, x, y, w, h, r, g, b):
26 def collision(self, scene):
30 and max(self.x, c.x) <= min(self.x + self.w, c.x + c.w)
31 and max(self.y, c.y) <= min(self.y + self.h, c.y + c.h)
37 ######################################################################
40 class Normalizer(nn.Module):
41 def __init__(self, mu, std):
43 self.register_buffer("mu", mu)
44 self.register_buffer("log_var", 2 * torch.log(std))
47 return (x - self.mu) / torch.exp(self.log_var / 2.0)
50 class SignSTE(nn.Module):
55 # torch.sign() takes three values
56 s = (x >= 0).float() * 2 - 1
60 return s + u - u.detach()
75 device=torch.device("cpu"),
77 mu, std = train_input.float().mean(), train_input.float().std()
79 def encoder_core(depth, dim):
83 dim * 2**k, dim * 2**k, kernel_size=5, stride=1, padding=2
86 nn.Conv2d(dim * 2**k, dim * 2 ** (k + 1), kernel_size=2, stride=2),
92 return nn.Sequential(*[x for m in l for x in m])
94 def decoder_core(depth, dim):
98 dim * 2 ** (k + 1), dim * 2**k, kernel_size=2, stride=2
102 dim * 2**k, dim * 2**k, kernel_size=5, stride=1, padding=2
106 for k in range(depth - 1, -1, -1)
109 return nn.Sequential(*[x for m in l for x in m])
111 encoder = nn.Sequential(
113 nn.Conv2d(3, dim_hidden, kernel_size=1, stride=1),
116 encoder_core(depth=depth, dim=dim_hidden),
118 nn.Conv2d(dim_hidden * 2**depth, nb_bits_per_token, kernel_size=1, stride=1),
121 quantizer = SignSTE()
123 decoder = nn.Sequential(
124 nn.Conv2d(nb_bits_per_token, dim_hidden * 2**depth, kernel_size=1, stride=1),
126 decoder_core(depth=depth, dim=dim_hidden),
128 nn.ConvTranspose2d(dim_hidden, 3 * Box.nb_rgb_levels, kernel_size=1, stride=1),
131 model = nn.Sequential(encoder, decoder)
133 nb_parameters = sum(p.numel() for p in model.parameters())
135 print(f"nb_parameters {nb_parameters}")
139 for k in range(nb_epochs):
141 math.log(lr_start) + math.log(lr_end / lr_start) / (nb_epochs - 1) * k
143 optimizer = torch.optim.Adam(model.parameters(), lr=lr)
147 for input in tqdm.tqdm(train_input.split(batch_size), desc="vqae-train"):
149 zq = z if k < 2 else quantizer(z)
152 output = output.reshape(
153 output.size(0), -1, 3, output.size(2), output.size(3)
156 train_loss = F.cross_entropy(output, input)
158 acc_train_loss += train_loss.item() * input.size(0)
160 optimizer.zero_grad()
161 train_loss.backward()
166 for input in tqdm.tqdm(test_input.split(batch_size), desc="vqae-test"):
168 zq = z if k < 1 else quantizer(z)
171 output = output.reshape(
172 output.size(0), -1, 3, output.size(2), output.size(3)
175 test_loss = F.cross_entropy(output, input)
177 acc_test_loss += test_loss.item() * input.size(0)
179 train_loss = acc_train_loss / train_input.size(0)
180 test_loss = acc_test_loss / test_input.size(0)
182 print(f"train_ae {k} lr {lr} train_loss {train_loss} test_loss {test_loss}")
185 return encoder, quantizer, decoder
188 ######################################################################
191 def scene2tensor(xh, yh, scene, size):
192 width, height = size, size
193 pixel_map = torch.ByteTensor(width, height, 4).fill_(255)
194 data = pixel_map.numpy()
195 surface = cairo.ImageSurface.create_for_data(
196 data, cairo.FORMAT_ARGB32, width, height
199 ctx = cairo.Context(surface)
200 ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
203 ctx.move_to(b.x * size, b.y * size)
204 ctx.rel_line_to(b.w * size, 0)
205 ctx.rel_line_to(0, b.h * size)
206 ctx.rel_line_to(-b.w * size, 0)
209 b.r / (Box.nb_rgb_levels - 1),
210 b.g / (Box.nb_rgb_levels - 1),
211 b.b / (Box.nb_rgb_levels - 1),
217 ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0)
218 ctx.move_to(xh * size - hs / 2, yh * size - hs / 2)
219 ctx.rel_line_to(hs, 0)
220 ctx.rel_line_to(0, hs)
221 ctx.rel_line_to(-hs, 0)
226 pixel_map[None, :, :, :3]
230 .mul(Box.nb_rgb_levels)
238 ((Box.nb_rgb_levels - 1), 0, 0),
239 (0, (Box.nb_rgb_levels - 1), 0),
240 (0, 0, (Box.nb_rgb_levels - 1)),
241 ((Box.nb_rgb_levels - 1), (Box.nb_rgb_levels - 1), 0),
243 (Box.nb_rgb_levels * 2) // 3,
244 (Box.nb_rgb_levels * 2) // 3,
245 (Box.nb_rgb_levels * 2) // 3,
250 wh = torch.rand(2) * 0.2 + 0.2
251 xy = torch.rand(2) * (1 - wh)
252 c = colors[torch.randint(len(colors), (1,))]
254 xy[0].item(), xy[1].item(), wh[0].item(), wh[1].item(), c[0], c[1], c[2]
256 if not b.collision(scene):
262 def generate_episode(steps, size=64):
279 scene = random_scene()
280 xh, yh = tuple(x.item() for x in torch.rand(2))
282 actions = torch.randint(len(effects), (len(steps),))
285 for s, a in zip(steps, actions):
287 frames.append(scene2tensor(xh, yh, scene, size=size))
289 g, dx, dy = effects[a]
292 if b.x <= xh and b.x + b.w >= xh and b.y <= yh and b.y + b.h >= yh:
301 or b.collision(scene)
312 if xh < 0 or xh > 1 or yh < 0 or yh > 1:
318 return frames, actions
321 ######################################################################
324 def generate_episodes(nb, steps):
325 all_frames, all_actions = [], []
326 for n in tqdm.tqdm(range(nb), dynamic_ncols=True, desc="world-data"):
327 frames, actions = generate_episode(steps)
329 all_actions += [actions]
330 return torch.cat(all_frames, 0).contiguous(), torch.cat(all_actions, 0)
333 def create_data_and_processors(
334 nb_train_samples, nb_test_samples, mode, nb_steps, nb_epochs=10
336 assert mode in ["first_last"]
338 if mode == "first_last":
339 steps = [True] + [False] * (nb_steps + 1) + [True]
341 train_input, train_actions = generate_episodes(nb_train_samples, steps)
342 test_input, test_actions = generate_episodes(nb_test_samples, steps)
344 encoder, quantizer, decoder = train_encoder(
345 train_input, test_input, nb_epochs=nb_epochs
348 quantizer.train(False)
351 z = encoder(train_input[:1])
352 pow2 = (2 ** torch.arange(z.size(1), device=z.device))[None, None, :]
353 z_h, z_w = z.size(2), z.size(3)
355 def frame2seq(input, batch_size=25):
358 for x in input.split(batch_size):
360 ze_bool = (quantizer(z) >= 0).long()
362 ze_bool.permute(0, 2, 3, 1).reshape(
363 ze_bool.size(0), -1, ze_bool.size(1)
370 return torch.cat(seq, dim=0)
372 def seq2frame(input, batch_size=25, T=1e-2):
375 for seq in input.split(batch_size):
376 zd_bool = (seq[:, :, None] // pow2) % 2
377 zd_bool = zd_bool.reshape(zd_bool.size(0), z_h, z_w, -1).permute(0, 3, 1, 2)
378 logits = decoder(zd_bool * 2.0 - 1.0)
379 logits = logits.reshape(
380 logits.size(0), -1, 3, logits.size(2), logits.size(3)
381 ).permute(0, 2, 3, 4, 1)
382 output = torch.distributions.categorical.Categorical(
386 frames.append(output)
388 return torch.cat(frames, dim=0)
390 return train_input, train_actions, test_input, test_actions, frame2seq, seq2frame
393 ######################################################################
395 if __name__ == "__main__":
403 ) = create_data_and_processors(
412 input = test_input[:64]
414 seq = frame2seq(input)
416 print(f"{seq.size()=} {seq.dtype=} {seq.min()=} {seq.max()=}")
418 output = seq2frame(seq)
420 torchvision.utils.save_image(
421 input.float() / (Box.nb_rgb_levels - 1), "orig.png", nrow=8
424 torchvision.utils.save_image(
425 output.float() / (Box.nb_rgb_levels - 1), "qtiz.png", nrow=8