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]),
37 max_nb_cached_chunks=None,
41 self.colors = torch.tensor([c for _, c in self.named_colors])
44 self.cache_rec_coo = {}
45 super().__init__(max_nb_cached_chunks, chunk_size, nb_threads)
47 ######################################################################
49 def frame2img(self, x, scale=15):
50 x = x.reshape(x.size(0), self.height, -1)
51 m = torch.logical_and(x >= 0, x < self.nb_token_values()).long()
52 x = self.colors[x * m].permute(0, 3, 1, 2)
54 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
55 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
57 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
58 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
61 for n in range(m.size(0)):
62 for i in range(m.size(1)):
63 for j in range(m.size(2)):
65 for k in range(2, scale - 2):
67 x[n, :, i * scale + k, j * scale + k - l] = 0
69 n, :, i * scale + scale - 1 - k, j * scale + k - l
80 predicted_prompts=None,
81 predicted_answers=None,
85 S = self.height * self.width
86 As = prompts[:, 0 * (S + 1) : 0 * (S + 1) + S].view(-1, self.height, self.width)
87 f_As = prompts[:, 1 * (S + 1) : 1 * (S + 1) + S].view(
88 -1, self.height, self.width
90 Bs = prompts[:, 2 * (S + 1) : 2 * (S + 1) + S].view(-1, self.height, self.width)
91 prompts = torch.cat([As, f_As, Bs], dim=2)
92 answers = answers.reshape(answers.size(0), self.height, self.width)
94 if predicted_prompts is None:
95 predicted_prompts = 255
97 if predicted_answers is None:
98 predicted_answers = 255
100 def add_frame(x, c, margin, bottom=False):
102 h, w, di, dj = x.size(2) + margin, x.size(3), 0, 0
105 x.size(2) + 2 * margin,
106 x.size(3) + 2 * margin,
111 y = x.new_full((x.size(0), x.size(1), h, w), 0)
116 c = c.long()[:, None]
118 (1 - ((c == 1).long() + (c == 0).long() + (c == -1).long()))
119 * torch.tensor([64, 64, 64])
120 + (c == 1).long() * torch.tensor([0, 255, 0])
121 + (c == 0).long() * torch.tensor([255, 255, 255])
122 + (c == -1).long() * torch.tensor([255, 0, 0])
124 y[...] = c[:, :, None, None]
126 y[:, :, di : di + x.size(2), dj : dj + x.size(3)] = x
130 img_prompts = torch.cat(
133 add_frame(self.frame2img(x), c=0, margin=1),
137 for x in prompts.to("cpu").split(split_size=self.width, dim=2)
142 h = img_prompts.size(2)
143 img_answers = add_frame(
144 add_frame(self.frame2img(answers.to("cpu")), c=0, margin=1),
149 separator_size = 2 * margin
151 separator = img_prompts.new_full(
161 marker = img_prompts.new_full(
171 # marker[:, :, 0] = 0
172 # marker[:, :, h - 1] = 0
174 for k in range(1, 2 * separator_size - 8):
175 i = k - (separator_size - 4)
176 j = separator_size - 5 - abs(i)
177 marker[:, :, h // 2 - 1 + i, 2 + j] = 0
178 marker[:, :, h // 2 - 1 + i + 1, 2 + j] = 0
189 image_name = os.path.join(result_dir, filename)
190 torchvision.utils.save_image(
198 ######################################################################
200 def nb_token_values(self):
201 return len(self.colors)
210 prevent_overlap=False,
212 if surface_max is None:
213 surface_max = self.height * self.width // 2
215 signature = (nb_rec, min_height, min_width, surface_max)
218 return self.cache_rec_coo[signature].pop()
227 i = torch.randint(self.height, (N * nb_rec, 2)).sort(dim=-1).values
228 j = torch.randint(self.width, (N * nb_rec, 2)).sort(dim=-1).values
231 (i[:, 1] >= i[:, 0] + min_height)
232 & (j[:, 1] >= j[:, 0] + min_height)
233 & ((i[:, 1] - i[:, 0]) * (j[:, 1] - j[:, 0]) <= surface_max)
236 i, j = i[big_enough], j[big_enough]
238 n = i.size(0) - i.size(0) % nb_rec
243 i = i[:n].reshape(n // nb_rec, nb_rec, -1)
244 j = j[:n].reshape(n // nb_rec, nb_rec, -1)
247 can_fit = ((i[:, :, 1] - i[:, :, 0]) * (j[:, :, 1] - j[:, :, 0])).sum(
249 ) <= self.height * self.width
250 i, j = i[can_fit], j[can_fit]
252 A_i1, A_i2, A_j1, A_j2 = (
258 B_i1, B_i2, B_j1, B_j2 = (
264 no_overlap = torch.logical_not(
270 i, j = i[no_overlap], j[no_overlap]
272 A_i1, A_i2, A_j1, A_j2 = (
278 B_i1, B_i2, B_j1, B_j2 = (
284 C_i1, C_i2, C_j1, C_j2 = (
310 i, j = (i[no_overlap], j[no_overlap])
317 self.cache_rec_coo[signature] = [
325 for k in range(nb_rec)
327 for n in range(i.size(0))
330 return self.cache_rec_coo[signature].pop()
332 ######################################################################
335 def task_replace_color(self, A, f_A, B, f_B):
337 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
338 for X, f_X in [(A, f_A), (B, f_B)]:
339 r = self.rec_coo(nb_rec, prevent_overlap=True)
340 for n in range(nb_rec):
341 i1, j1, i2, j2 = r[n]
342 X[i1:i2, j1:j2] = c[n]
343 f_X[i1:i2, j1:j2] = c[n if n > 0 else -1]
346 def task_translate(self, A, f_A, B, f_B):
347 di, dj = torch.randint(3, (2,)) - 1
349 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
350 for X, f_X in [(A, f_A), (B, f_B)]:
352 r = self.rec_coo(nb_rec, prevent_overlap=True)
353 i1, j1, i2, j2 = r[nb_rec - 1]
356 and i2 + di < X.size(0)
358 and j2 + dj < X.size(1)
362 for n in range(nb_rec):
363 i1, j1, i2, j2 = r[n]
364 X[i1:i2, j1:j2] = c[n]
366 f_X[i1 + di : i2 + di, j1 + dj : j2 + dj] = c[n]
368 f_X[i1:i2, j1:j2] = c[n]
371 def task_grow(self, A, f_A, B, f_B):
372 di, dj = torch.randint(2, (2,)) * 2 - 1
374 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
375 direction = torch.randint(2, (1,))
376 for X, f_X in [(A, f_A), (B, f_B)]:
378 r = self.rec_coo(nb_rec, prevent_overlap=True)
379 i1, j1, i2, j2 = r[nb_rec - 1]
380 if i1 + 3 < i2 and j1 + 3 < j2:
383 for n in range(nb_rec):
384 i1, j1, i2, j2 = r[n]
387 X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
388 f_X[i1:i2, j1:j2] = c[n]
390 X[i1:i2, j1:j2] = c[n]
391 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
393 X[i1:i2, j1:j2] = c[n]
394 f_X[i1:i2, j1:j2] = c[n]
397 def task_color_grow(self, A, f_A, B, f_B):
398 di, dj = torch.randint(2, (2,)) * 2 - 1
400 c = torch.randperm(len(self.colors) - 1)[: 2 * nb_rec] + 1
401 direction = torch.randint(4, (1,))
402 for X, f_X in [(A, f_A), (B, f_B)]:
403 r = self.rec_coo(nb_rec, prevent_overlap=True)
404 for n in range(nb_rec):
405 i1, j1, i2, j2 = r[n]
406 X[i1:i2, j1:j2] = c[2 * n]
407 f_X[i1:i2, j1:j2] = c[2 * n]
408 # Not my proudest moment
411 X[i : i + 1, j1:j2] = c[2 * n + 1]
413 f_X[i:i2, j1:j2] = c[2 * n + 1]
415 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
417 i = (i1 + i2 - 1) // 2
418 X[i : i + 1, j1:j2] = c[2 * n + 1]
420 f_X[i1 : i + 1, j1:j2] = c[2 * n + 1]
422 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
425 X[i1:i2, j : j + 1] = c[2 * n + 1]
427 f_X[i1:i2, j:j2] = c[2 * n + 1]
429 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
431 j = (j1 + j2 - 1) // 2
432 X[i1:i2, j : j + 1] = c[2 * n + 1]
434 f_X[i1:i2, j1 : j + 1] = c[2 * n + 1]
436 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
439 def task_frame(self, A, f_A, B, f_B):
441 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
442 for X, f_X in [(A, f_A), (B, f_B)]:
443 r = self.rec_coo(nb_rec, prevent_overlap=True)
444 for n in range(nb_rec):
445 i1, j1, i2, j2 = r[n]
446 X[i1:i2, j1:j2] = c[n]
448 f_X[i1:i2, j1] = c[n]
449 f_X[i1:i2, j2 - 1] = c[n]
450 f_X[i1, j1:j2] = c[n]
451 f_X[i2 - 1, j1:j2] = c[n]
453 f_X[i1:i2, j1:j2] = c[n]
456 def task_detect(self, A, f_A, B, f_B):
458 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
459 for X, f_X in [(A, f_A), (B, f_B)]:
460 r = self.rec_coo(nb_rec, prevent_overlap=True)
461 for n in range(nb_rec):
462 i1, j1, i2, j2 = r[n]
463 X[i1:i2, j1:j2] = c[n]
468 def contact(self, X, i, j, q):
482 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
483 if X[ii, jj] != 0 and X[ii, jj] != q:
492 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
493 if X[ii, jj] == q and X[i, jj] != q and X[ii, j] != q:
496 for ii, jj in [(i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)]:
497 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
501 return no, nq, nq_diag
503 def task_count(self, A, f_A, B, f_B):
504 N = (torch.randint(4, (1,)) + 2).item()
505 c = torch.randperm(len(self.colors) - 1)[:N] + 1
507 for X, f_X in [(A, f_A), (B, f_B)]:
508 l_q = torch.randperm(self.height * self.width)[
509 : self.height * self.width // 20
511 l_d = torch.randint(N, l_q.size())
512 nb = torch.zeros(N, dtype=torch.int64)
514 for q, e in zip(l_q, l_d):
516 i, j = q % self.height, q // self.height
519 and X[max(0, i - 1) : i + 2, max(0, j - 1) : j + 2] == 0
524 l_q = torch.randperm((self.height - 2) * (self.width - 2))[
525 : self.height * self.width // 2
527 l_d = torch.randint(N, l_q.size())
528 for q, e in zip(l_q, l_d):
530 i, j = q % (self.height - 2) + 1, q // (self.height - 2) + 1
531 a1, a2, a3 = X[i - 1, j - 1 : j + 2]
532 a8, a4 = X[i, j - 1], X[i, j + 1]
533 a7, a6, a5 = X[i + 1, j - 1 : j + 2]
536 and nb[e] < self.width
537 and (a2 == 0 or a2 == d)
538 and (a4 == 0 or a4 == d)
539 and (a6 == 0 or a6 == d)
540 and (a8 == 0 or a8 == d)
541 and (a1 == 0 or a2 == d or a8 == d)
542 and (a3 == 0 or a4 == d or a2 == d)
543 and (a5 == 0 or a6 == d or a4 == d)
544 and (a7 == 0 or a8 == d or a6 == d)
557 for j in range(nb[e]):
561 def task_trajectory(self, A, f_A, B, f_B):
562 c = torch.randperm(len(self.colors) - 1)[:2] + 1
563 for X, f_X in [(A, f_A), (B, f_B)]:
565 di, dj = torch.randint(7, (2,)) - 3
566 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
568 abs(di) + abs(dj) > 0
570 and i + 2 * di < self.height
572 and j + 2 * dj < self.width
579 and i + k * di < self.height
581 and j + k * dj < self.width
584 X[i + k * di, j + k * dj] = c[k]
585 f_X[i + k * di, j + k * dj] = c[min(k, 1)]
589 def task_bounce(self, A, f_A, B, f_B):
590 c = torch.randperm(len(self.colors) - 1)[:3] + 1
591 for X, f_X in [(A, f_A), (B, f_B)]:
606 for _ in range((self.height * self.width) // 10):
607 i, j = torch.randint(self.height, (1,)), torch.randint(
614 di, dj = torch.randint(7, (2,)) - 3
615 if abs(di) + abs(dj) == 1:
618 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
626 if free(i + di, j + dj):
628 elif free(i - dj, j + di):
630 if free(i + dj, j - di):
631 if torch.rand(1) < 0.5:
633 elif free(i + dj, j - di):
638 i, j = i + di, j + dj
653 def task_scale(self, A, f_A, B, f_B):
654 c = torch.randperm(len(self.colors) - 1)[:2] + 1
656 i, j = torch.randint(self.height // 2, (1,)), torch.randint(
657 self.width // 2, (1,)
660 for X, f_X in [(A, f_A), (B, f_B)]:
663 i1, j1 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
664 self.width // 2 + 1, (1,)
666 i2, j2 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
667 self.width // 2 + 1, (1,)
669 if i1 < i2 and j1 < j2 and min(i2 - i1, j2 - j1) <= 3:
671 X[i + i1 : i + i2, j + j1 : j + j2] = c[0]
672 f_X[2 * i1 : 2 * i2, 2 * j1 : 2 * j2] = c[0]
678 def task_symbols(self, A, f_A, B, f_B):
680 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
682 for X, f_X in [(A, f_A), (B, f_B)]:
684 i, j = torch.randint(self.height - delta + 1, (nb_rec,)), torch.randint(
685 self.width - delta + 1, (nb_rec,)
687 d = (i[None, :] - i[:, None]).abs().max((j[None, :] - j[:, None]).abs())
688 d.fill_diagonal_(delta + 1)
692 for k in range(1, nb_rec):
693 X[i[k] : i[k] + delta, j[k] : j[k] + delta] = c[k]
695 ai, aj = i.float().mean(), j.float().mean()
697 q = torch.randint(3, (1,)) + 1
699 X[i[0] + delta // 2 - 1, j[0] + delta // 2 - 1] = c[0]
700 X[i[0] + delta // 2 - 1, j[0] + delta // 2 + 1] = c[0]
701 X[i[0] + delta // 2 + 1, j[0] + delta // 2 - 1] = c[0]
702 X[i[0] + delta // 2 + 1, j[0] + delta // 2 + 1] = c[0]
704 assert i[q] != ai and j[q] != aj
707 i[0] + delta // 2 + (i[q] - ai).sign().long(),
708 j[0] + delta // 2 + (j[q] - aj).sign().long(),
711 f_X[i[0] : i[0] + delta, j[0] : j[0] + delta] = c[q]
714 def task_ortho(self, A, f_A, B, f_B):
716 di, dj = torch.randint(3, (2,)) - 1
717 o = torch.tensor([[0.0, 1.0], [-1.0, 0.0]])
719 for _ in range(torch.randint(4, (1,))):
721 if torch.rand(1) < 0.5:
724 ci, cj = (self.height - 1) / 2, (self.width - 1) / 2
726 for X, f_X in [(A, f_A), (B, f_B)]:
731 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
733 for r in range(nb_rec):
735 i1, i2 = torch.randint(self.height - 2, (2,)) + 1
736 j1, j2 = torch.randint(self.width - 2, (2,)) + 1
740 and max(i2 - i1, j2 - j1) >= 2
741 and min(i2 - i1, j2 - j1) <= 3
744 X[i1 : i2 + 1, j1 : j2 + 1] = c[r]
746 i1, j1, i2, j2 = i1 - ci, j1 - cj, i2 - ci, j2 - cj
748 i1, j1 = m[0, 0] * i1 + m[0, 1] * j1, m[1, 0] * i1 + m[1, 1] * j1
749 i2, j2 = m[0, 0] * i2 + m[0, 1] * j2, m[1, 0] * i2 + m[1, 1] * j2
751 i1, j1, i2, j2 = i1 + ci, j1 + cj, i2 + ci, j2 + cj
752 i1, i2 = i1.long() + di, i2.long() + di
753 j1, j2 = j1.long() + dj, j2.long() + dj
759 f_X[i1 : i2 + 1, j1 : j2 + 1] = c[r]
761 n = F.one_hot(X.flatten()).sum(dim=0)[1:]
763 n.sum() > self.height * self.width // 4
764 and (n > 0).long().sum() == nb_rec
769 def task_islands(self, A, f_A, B, f_B):
772 # for X, f_X in [(A, f_A), (B, f_B)]:
773 # n = torch.arange(self.height * self.width).reshape(self.height, self.width)
774 # k = torch.randperm(self.height * self.width)
777 # i,j=q%self.height,q//self.height
780 ######################################################################
784 self.task_replace_color,
787 self.task_color_grow,
791 self.task_trajectory,
799 def trivial_prompts_and_answers(self, prompts, answers):
800 S = self.height * self.width
801 Bs = prompts[:, 2 * (S + 1) : 2 * (S + 1) + S]
803 return (Bs == f_Bs).long().min(dim=-1).values > 0
805 def generate_prompts_and_answers_(self, nb, tasks=None, progress_bar=False):
807 tasks = self.all_tasks()
809 S = self.height * self.width
810 prompts = torch.zeros(nb, 3 * S + 2, dtype=torch.int64)
811 answers = torch.zeros(nb, S, dtype=torch.int64)
813 bunch = zip(prompts, answers)
819 desc="world generation",
820 total=prompts.size(0),
823 for prompt, answer in bunch:
824 A = prompt[0 * (S + 1) : 0 * (S + 1) + S].view(self.height, self.width)
825 f_A = prompt[1 * (S + 1) : 1 * (S + 1) + S].view(self.height, self.width)
826 B = prompt[2 * (S + 1) : 2 * (S + 1) + S].view(self.height, self.width)
827 f_B = answer.view(self.height, self.width)
828 task = tasks[torch.randint(len(tasks), (1,))]
831 return prompts.flatten(1), answers.flatten(1)
839 predicted_prompts=None,
840 predicted_answers=None,
845 filename_prefix + ".png",
854 ######################################################################
856 if __name__ == "__main__":
859 # grids = Grids(max_nb_cached_chunks=5, chunk_size=100, nb_threads=4)
863 # grids = problem.MultiThreadProblem(
864 # grids, max_nb_cached_chunks=50, chunk_size=100, nb_threads=1
867 # start_time = time.perf_counter()
868 # prompts, answers = grids.generate_prompts_and_answers(nb)
869 # delay = time.perf_counter() - start_time
870 # print(f"{prompts.size(0)/delay:02f} seq/s")
876 for t in grids.all_tasks():
877 # for t in [grids.task_replace_color]:
879 prompts, answers = grids.generate_prompts_and_answers_(nb, tasks=[t])
880 grids.save_quizzes("/tmp", t.__name__, prompts[:nb], answers[:nb], nrow=4)
884 for t in grids.all_tasks():
885 # for t in [ grids.task_replace_color ]: #grids.all_tasks():
886 start_time = time.perf_counter()
887 prompts, answers = grids.generate_prompts_and_answers_(nb, tasks=[t])
888 delay = time.perf_counter() - start_time
889 print(f"{t.__name__} {prompts.size(0)/delay:02f} seq/s")
893 m = torch.randint(2, (prompts.size(0),))
894 predicted_prompts = m * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
895 predicted_answers = (1 - m) * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
902 # You can add a bool to put a frame around the predicted parts
903 predicted_prompts[:nb],
904 predicted_answers[:nb],