3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
8 import math, sys, tqdm, os, warnings
10 import torch, torchvision
13 from torch.nn import functional as F
15 ######################################################################
20 class Grids(problem.Problem):
22 ("white", [255, 255, 255]),
24 ("green", [0, 192, 0]),
25 ("blue", [0, 0, 255]),
26 ("yellow", [255, 224, 0]),
27 ("cyan", [0, 255, 255]),
28 ("violet", [224, 128, 255]),
29 ("lightgreen", [192, 255, 192]),
30 ("brown", [165, 42, 42]),
31 ("lightblue", [192, 192, 255]),
32 ("gray", [128, 128, 128]),
35 def __init__(self, device=torch.device("cpu")):
36 self.colors = torch.tensor([c for _, c in self.named_colors])
41 ######################################################################
43 def frame2img(self, x, scale=15):
44 x = x.reshape(x.size(0), self.height, -1)
45 m = torch.logical_and(x >= 0, x < self.nb_token_values()).long()
46 x = self.colors[x * m].permute(0, 3, 1, 2)
48 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
49 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
51 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
52 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
55 for n in range(m.size(0)):
56 for i in range(m.size(1)):
57 for j in range(m.size(2)):
59 for k in range(2, scale - 2):
61 x[n, :, i * scale + k, j * scale + k - l] = 0
63 n, :, i * scale + scale - 1 - k, j * scale + k - l
74 predicted_prompts=None,
75 predicted_answers=None,
78 S = self.height * self.width
79 As = prompts[:, 0 * (S + 1) : 0 * (S + 1) + S].view(-1, self.height, self.width)
80 f_As = prompts[:, 1 * (S + 1) : 1 * (S + 1) + S].view(
81 -1, self.height, self.width
83 Bs = prompts[:, 2 * (S + 1) : 2 * (S + 1) + S].view(-1, self.height, self.width)
84 prompts = torch.cat([As, f_As, Bs], dim=2)
85 answers = answers.reshape(answers.size(0), self.height, self.width)
87 if predicted_prompts is None:
88 predicted_prompts = 255
90 if predicted_answers is None:
91 predicted_answers = 255
93 def add_frame(x, c, margin, bottom=False):
95 h, w, di, dj = x.size(2) + margin, x.size(3), 0, 0
98 x.size(2) + 2 * margin,
99 x.size(3) + 2 * margin,
104 y = x.new_full((x.size(0), x.size(1), h, w), 0)
109 c = c.long()[:, None]
111 (1 - ((c == 1).long() + (c == 0).long() + (c == -1).long()))
112 * torch.tensor([64, 64, 64], device=c.device)
113 + (c == 1).long() * torch.tensor([0, 255, 0], device=c.device)
114 + (c == 0).long() * torch.tensor([255, 255, 255], device=c.device)
115 + (c == -1).long() * torch.tensor([255, 0, 0], device=c.device)
117 y[...] = c[:, :, None, None]
119 y[:, :, di : di + x.size(2), dj : dj + x.size(3)] = x
125 img_prompts = torch.cat(
128 add_frame(self.frame2img(x), c=0, margin=1),
132 for x in prompts.to("cpu").split(split_size=self.width, dim=2)
137 h = img_prompts.size(2)
138 img_answers = add_frame(
139 add_frame(self.frame2img(answers.to("cpu")), c=0, margin=1),
144 separator_size = 2 * margin
146 separator = img_prompts.new_full(
156 marker = img_prompts.new_full(
166 # marker[:, :, 0] = 0
167 # marker[:, :, h - 1] = 0
169 for k in range(1, 2 * separator_size - 8):
170 i = k - (separator_size - 4)
171 j = separator_size - 5 - abs(i)
172 marker[:, :, h // 2 - 1 + i, 2 + j] = 0
173 marker[:, :, h // 2 - 1 + i + 1, 2 + j] = 0
184 image_name = os.path.join(result_dir, filename)
185 torchvision.utils.save_image(
193 ######################################################################
195 def nb_token_values(self):
196 return len(self.colors)
198 # That's quite a tensorial spaghetti mess to sample
199 # non-overlapping rectangles quickly, but made the generation of
200 # 100k samples go from 1h50 with a lame pure python code to 3min30s
202 def rec_coo(self, nb_rec, min_height=3, min_width=3):
208 torch.rand(nb_trials * nb_rec, self.height + 1, device=self.device)
220 torch.rand(nb_trials * nb_rec, self.width + 1, device=self.device)
230 i = torch.logical_and(
231 v.sum(dim=-1) >= min_height, h.sum(dim=-1) >= min_width
235 v = v[: v.size(0) - v.size(0) % nb_rec]
236 h = h[: h.size(0) - h.size(0) % nb_rec]
237 v = v.reshape(v.size(0) // nb_rec, nb_rec, -1)
238 h = h.reshape(h.size(0) // nb_rec, nb_rec, -1)
240 r = v[:, :, :, None] * h[:, :, None, :]
242 valid = r.sum(dim=1).flatten(1).max(dim=-1).values == 1
250 av = torch.arange(v.size(2), device=self.device)[None, :]
251 ah = torch.arange(h.size(2), device=self.device)[None, :]
254 (i1.item(), j1.item(), i2.item() + 1, j2.item() + 1)
255 for i1, j1, i2, j2 in zip(
256 v.size(2) - (v[0] * (v.size(2) - av)).max(dim=-1).values,
257 h.size(2) - (h[0] * (h.size(2) - ah)).max(dim=-1).values,
258 (v[0] * av).max(dim=-1).values,
259 (h[0] * ah).max(dim=-1).values,
263 def rec_coo_(self, x, n, min_height=3, min_width=3):
264 collision = x.new(x.size())
270 i1, i2 = torch.randint(x.size(0), (2,))
271 if i1 + min_height <= i2:
274 j1, j2 = torch.randint(x.size(1), (2,))
275 if j1 + min_width <= j2:
277 collision[i1:i2, j1:j2] += 1
278 if collision.max() > 1:
280 result.append((i1, j1, i2, j2))
281 if collision.max() == 1:
285 ######################################################################
287 def task_replace_color(self, A, f_A, B, f_B):
289 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
290 for X, f_X in [(A, f_A), (B, f_B)]:
291 r = self.rec_coo(nb_rec)
292 for n in range(nb_rec):
293 i1, j1, i2, j2 = r[n]
294 X[i1:i2, j1:j2] = c[n]
295 f_X[i1:i2, j1:j2] = c[n if n > 0 else -1]
297 def task_translate(self, A, f_A, B, f_B):
298 di, dj = torch.randint(3, (2,)) - 1
300 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
301 for X, f_X in [(A, f_A), (B, f_B)]:
303 r = self.rec_coo(nb_rec)
304 i1, j1, i2, j2 = r[nb_rec - 1]
307 and i2 + di < X.size(0)
309 and j2 + dj < X.size(1)
313 for n in range(nb_rec):
314 i1, j1, i2, j2 = r[n]
315 X[i1:i2, j1:j2] = c[n]
317 f_X[i1 + di : i2 + di, j1 + dj : j2 + dj] = c[n]
319 f_X[i1:i2, j1:j2] = c[n]
321 def task_grow(self, A, f_A, B, f_B):
322 di, dj = torch.randint(2, (2,)) * 2 - 1
324 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
325 direction = torch.randint(2, (1,))
326 for X, f_X in [(A, f_A), (B, f_B)]:
328 r = self.rec_coo(nb_rec)
329 i1, j1, i2, j2 = r[nb_rec - 1]
330 if i1 + 3 < i2 and j1 + 3 < j2:
333 for n in range(nb_rec):
334 i1, j1, i2, j2 = r[n]
337 X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
338 f_X[i1:i2, j1:j2] = c[n]
340 X[i1:i2, j1:j2] = c[n]
341 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
343 X[i1:i2, j1:j2] = c[n]
344 f_X[i1:i2, j1:j2] = c[n]
346 def task_color_grow(self, A, f_A, B, f_B):
347 di, dj = torch.randint(2, (2,)) * 2 - 1
349 c = torch.randperm(len(self.colors) - 1)[: 2 * nb_rec] + 1
350 direction = torch.randint(4, (1,))
351 for X, f_X in [(A, f_A), (B, f_B)]:
352 r = self.rec_coo(nb_rec)
353 for n in range(nb_rec):
354 i1, j1, i2, j2 = r[n]
355 X[i1:i2, j1:j2] = c[2 * n]
356 f_X[i1:i2, j1:j2] = c[2 * n]
357 # Not my proudest moment
360 X[i : i + 1, j1:j2] = c[2 * n + 1]
362 f_X[i:i2, j1:j2] = c[2 * n + 1]
364 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
366 i = (i1 + i2 - 1) // 2
367 X[i : i + 1, j1:j2] = c[2 * n + 1]
369 f_X[i1 : i + 1, j1:j2] = c[2 * n + 1]
371 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
374 X[i1:i2, j : j + 1] = c[2 * n + 1]
376 f_X[i1:i2, j:j2] = c[2 * n + 1]
378 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
380 j = (j1 + j2 - 1) // 2
381 X[i1:i2, j : j + 1] = c[2 * n + 1]
383 f_X[i1:i2, j1 : j + 1] = c[2 * n + 1]
385 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
387 def task_frame(self, A, f_A, B, f_B):
389 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
390 for X, f_X in [(A, f_A), (B, f_B)]:
391 r = self.rec_coo(nb_rec)
392 for n in range(nb_rec):
393 i1, j1, i2, j2 = r[n]
394 X[i1:i2, j1:j2] = c[n]
395 f_X[i1:i2, j1:j2] = c[n]
397 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = 0
399 def task_detect(self, A, f_A, B, f_B):
401 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
402 for X, f_X in [(A, f_A), (B, f_B)]:
403 r = self.rec_coo(nb_rec)
404 for n in range(nb_rec):
405 i1, j1, i2, j2 = r[n]
406 X[i1:i2, j1:j2] = c[n]
410 def contact(self, X, i, j, q):
424 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
425 if X[ii, jj] != 0 and X[ii, jj] != q:
434 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
435 if X[ii, jj] == q and X[i, jj] != q and X[ii, j] != q:
438 for ii, jj in [(i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)]:
439 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
443 return no, nq, nq_diag
445 def task_count(self, A, f_A, B, f_B):
446 N = torch.randint(4, (1,)) + 2
447 c = torch.randperm(len(self.colors) - 1)[:N] + 1
449 for X, f_X in [(A, f_A), (B, f_B)]:
450 nb = torch.zeros(N, dtype=torch.int64)
451 q = torch.randint(N, (self.height * self.width,))
452 k = torch.randperm(self.height * self.width)
453 for p in range(self.height * self.width):
454 i, j = k[p] % self.height, k[p] // self.height
455 no, nq, nq_diag = self.contact(X, i, j, c[q[p]])
456 if no == 0 and nq_diag == 0:
458 if nb[q[p]] < self.width:
465 for j in range(nb[n]):
468 def task_trajectory(self, A, f_A, B, f_B):
469 c = torch.randperm(len(self.colors) - 1)[:2] + 1
470 for X, f_X in [(A, f_A), (B, f_B)]:
472 di, dj = torch.randint(7, (2,)) - 3
473 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
475 abs(di) + abs(dj) > 0
477 and i + 2 * di < self.height
479 and j + 2 * dj < self.width
486 and i + k * di < self.height
488 and j + k * dj < self.width
491 X[i + k * di, j + k * dj] = c[k]
492 f_X[i + k * di, j + k * dj] = c[min(k, 1)]
495 def task_bounce(self, A, f_A, B, f_B):
496 c = torch.randperm(len(self.colors) - 1)[:3] + 1
497 for X, f_X in [(A, f_A), (B, f_B)]:
512 for _ in range((self.height * self.width) // 10):
513 i, j = torch.randint(self.height, (1,)), torch.randint(
520 di, dj = torch.randint(7, (2,)) - 3
521 if abs(di) + abs(dj) == 1:
524 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
532 if free(i + di, j + dj):
534 elif free(i - dj, j + di):
536 if free(i + dj, j - di):
537 if torch.rand(1) < 0.5:
539 elif free(i + dj, j - di):
544 i, j = i + di, j + dj
558 def task_scale(self, A, f_A, B, f_B):
559 c = torch.randperm(len(self.colors) - 1)[:2] + 1
561 i, j = torch.randint(self.height // 2, (1,)), torch.randint(
562 self.width // 2, (1,)
565 for X, f_X in [(A, f_A), (B, f_B)]:
568 i1, j1 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
569 self.width // 2 + 1, (1,)
571 i2, j2 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
572 self.width // 2 + 1, (1,)
574 if i1 < i2 and j1 < j2 and min(i2 - i1, j2 - j1) <= 3:
576 X[i + i1 : i + i2, j + j1 : j + j2] = c[0]
577 f_X[2 * i1 : 2 * i2, 2 * j1 : 2 * j2] = c[0]
582 def task_islands(self, A, f_A, B, f_B):
583 for X, f_X in [(A, f_A), (B, f_B)]:
586 for k in torch.randperm(self.height * self.width):
587 i, j = k % self.height, k // self.height
589 i == 0 or i == self.height - 1 or j == 0 or j == self.width - 1
591 no, nq, nq_diag = self.contact(X, i, j, 1)
594 (nq > 0 and not border)
595 or (nq == 0 and border and nb_on_border < 4)
603 for i in range(1, self.height - 1):
604 for j in range(1, self.width - 1):
607 and X[i - 1, j] + X[i + 1, j] + X[i, j - 1] + X[i, j + 1]
616 ######################################################################
620 self.task_replace_color,
623 self.task_color_grow,
627 self.task_trajectory,
633 def generate_prompts_and_answers(self, nb, tasks=None, device="cpu"):
635 tasks = self.all_tasks()
637 S = self.height * self.width
638 prompts = torch.zeros(nb, 3 * S + 2, dtype=torch.int64)
639 answers = torch.zeros(nb, S, dtype=torch.int64)
641 for prompt, answer in tqdm.tqdm(
642 zip(prompts, answers),
644 desc="world generation",
645 total=prompts.size(0),
647 A = prompt[0 * (S + 1) : 0 * (S + 1) + S].view(self.height, self.width)
648 f_A = prompt[1 * (S + 1) : 1 * (S + 1) + S].view(self.height, self.width)
649 B = prompt[2 * (S + 1) : 2 * (S + 1) + S].view(self.height, self.width)
650 f_B = answer.view(self.height, self.width)
651 task = tasks[torch.randint(len(tasks), (1,))]
654 return prompts.flatten(1), answers.flatten(1)
662 predicted_prompts=None,
663 predicted_answers=None,
668 filename_prefix + ".png",
677 ######################################################################
679 if __name__ == "__main__":
686 # for t in grids.all_tasks():
687 for t in [grids.task_islands]:
689 prompts, answers = grids.generate_prompts_and_answers(nb, tasks=[t])
690 grids.save_quizzes("/tmp", t.__name__, prompts[:nb], answers[:nb], nrow=4)
696 start_time = time.perf_counter()
697 prompts, answers = grids.generate_prompts_and_answers(nb)
698 delay = time.perf_counter() - start_time
699 print(f"{prompts.size(0)/delay:02f} seq/s")
701 m = torch.randint(2, (prompts.size(0),))
702 predicted_prompts = m * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
703 predicted_answers = (1 - m) * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
710 # You can add a bool to put a frame around the predicted parts
711 predicted_prompts[:nb],
712 predicted_answers[:nb],