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 super().__init__(max_nb_cached_chunks, chunk_size, nb_threads)
46 ######################################################################
48 def frame2img(self, x, scale=15):
49 x = x.reshape(x.size(0), self.height, -1)
50 m = torch.logical_and(x >= 0, x < self.nb_token_values()).long()
51 x = self.colors[x * m].permute(0, 3, 1, 2)
53 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
54 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
56 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
57 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
60 for n in range(m.size(0)):
61 for i in range(m.size(1)):
62 for j in range(m.size(2)):
64 for k in range(2, scale - 2):
66 x[n, :, i * scale + k, j * scale + k - l] = 0
68 n, :, i * scale + scale - 1 - k, j * scale + k - l
79 predicted_prompts=None,
80 predicted_answers=None,
84 S = self.height * self.width
85 As = prompts[:, 0 * (S + 1) : 0 * (S + 1) + S].view(-1, self.height, self.width)
86 f_As = prompts[:, 1 * (S + 1) : 1 * (S + 1) + S].view(
87 -1, self.height, self.width
89 Bs = prompts[:, 2 * (S + 1) : 2 * (S + 1) + S].view(-1, self.height, self.width)
90 prompts = torch.cat([As, f_As, Bs], dim=2)
91 answers = answers.reshape(answers.size(0), self.height, self.width)
93 if predicted_prompts is None:
94 predicted_prompts = 255
96 if predicted_answers is None:
97 predicted_answers = 255
99 def add_frame(x, c, margin, bottom=False):
101 h, w, di, dj = x.size(2) + margin, x.size(3), 0, 0
104 x.size(2) + 2 * margin,
105 x.size(3) + 2 * margin,
110 y = x.new_full((x.size(0), x.size(1), h, w), 0)
115 c = c.long()[:, None]
117 (1 - ((c == 1).long() + (c == 0).long() + (c == -1).long()))
118 * torch.tensor([64, 64, 64])
119 + (c == 1).long() * torch.tensor([0, 255, 0])
120 + (c == 0).long() * torch.tensor([255, 255, 255])
121 + (c == -1).long() * torch.tensor([255, 0, 0])
123 y[...] = c[:, :, None, None]
125 y[:, :, di : di + x.size(2), dj : dj + x.size(3)] = x
129 img_prompts = torch.cat(
132 add_frame(self.frame2img(x), c=0, margin=1),
136 for x in prompts.to("cpu").split(split_size=self.width, dim=2)
141 h = img_prompts.size(2)
142 img_answers = add_frame(
143 add_frame(self.frame2img(answers.to("cpu")), c=0, margin=1),
148 separator_size = 2 * margin
150 separator = img_prompts.new_full(
160 marker = img_prompts.new_full(
170 # marker[:, :, 0] = 0
171 # marker[:, :, h - 1] = 0
173 for k in range(1, 2 * separator_size - 8):
174 i = k - (separator_size - 4)
175 j = separator_size - 5 - abs(i)
176 marker[:, :, h // 2 - 1 + i, 2 + j] = 0
177 marker[:, :, h // 2 - 1 + i + 1, 2 + j] = 0
188 image_name = os.path.join(result_dir, filename)
189 torchvision.utils.save_image(
197 ######################################################################
199 def nb_token_values(self):
200 return len(self.colors)
202 def rec_coo(self, nb_rec, min_height=3, min_width=3):
205 i = torch.randint(self.height, (N, nb_rec, 2)).sort(dim=-1).values
206 j = torch.randint(self.width, (N, nb_rec, 2)).sort(dim=-1).values
208 A_i1, A_i2, A_j1, A_j2 = i[:, 0, 0], i[:, 0, 1], j[:, 0, 0], j[:, 0, 1]
209 B_i1, B_i2, B_j1, B_j2 = i[:, 1, 0], i[:, 1, 1], j[:, 1, 0], j[:, 1, 1]
210 no_overlap = torch.logical_not(
211 (A_i1 > B_i2) & (A_i2 < B_i1) & (A_j1 > B_j1) & (A_j2 < B_j1)
213 i, j = i[no_overlap], j[no_overlap]
215 A_i1, A_i2, A_j1, A_j2 = i[:, 0, 0], i[:, 0, 1], j[:, 0, 0], j[:, 0, 1]
216 B_i1, B_i2, B_j1, B_j2 = i[:, 1, 0], i[:, 1, 1], j[:, 1, 0], j[:, 1, 1]
217 C_i1, C_i2, C_j1, C_j2 = i[:, 2, 0], i[:, 2, 1], j[:, 2, 0], j[:, 2, 1]
220 (A_i1 > B_i2) & (A_i2 < B_i1) & (A_j1 > B_j1) & (A_j2 < B_j1)
223 (A_i1 > C_i2) & (A_i2 < C_i1) & (A_j1 > C_j1) & (A_j2 < C_j1)
226 (B_i1 > C_i2) & (B_i2 < C_i1) & (B_j1 > C_j1) & (B_j2 < C_j1)
229 i, j = (i[no_overlap], j[no_overlap])
236 return [(i[0, k, 0], j[0, k, 0], i[0, k, 1], j[0, k, 1]) for k in range(nb_rec)]
238 ######################################################################
241 def task_replace_color(self, A, f_A, B, f_B):
243 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
244 for X, f_X in [(A, f_A), (B, f_B)]:
245 r = self.rec_coo(nb_rec)
246 for n in range(nb_rec):
247 i1, j1, i2, j2 = r[n]
248 X[i1:i2, j1:j2] = c[n]
249 f_X[i1:i2, j1:j2] = c[n if n > 0 else -1]
252 def task_translate(self, A, f_A, B, f_B):
253 di, dj = torch.randint(3, (2,)) - 1
255 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
256 for X, f_X in [(A, f_A), (B, f_B)]:
258 r = self.rec_coo(nb_rec)
259 i1, j1, i2, j2 = r[nb_rec - 1]
262 and i2 + di < X.size(0)
264 and j2 + dj < X.size(1)
268 for n in range(nb_rec):
269 i1, j1, i2, j2 = r[n]
270 X[i1:i2, j1:j2] = c[n]
272 f_X[i1 + di : i2 + di, j1 + dj : j2 + dj] = c[n]
274 f_X[i1:i2, j1:j2] = c[n]
277 def task_grow(self, A, f_A, B, f_B):
278 di, dj = torch.randint(2, (2,)) * 2 - 1
280 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
281 direction = torch.randint(2, (1,))
282 for X, f_X in [(A, f_A), (B, f_B)]:
284 r = self.rec_coo(nb_rec)
285 i1, j1, i2, j2 = r[nb_rec - 1]
286 if i1 + 3 < i2 and j1 + 3 < j2:
289 for n in range(nb_rec):
290 i1, j1, i2, j2 = r[n]
293 X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
294 f_X[i1:i2, j1:j2] = c[n]
296 X[i1:i2, j1:j2] = c[n]
297 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
299 X[i1:i2, j1:j2] = c[n]
300 f_X[i1:i2, j1:j2] = c[n]
303 def task_color_grow(self, A, f_A, B, f_B):
304 di, dj = torch.randint(2, (2,)) * 2 - 1
306 c = torch.randperm(len(self.colors) - 1)[: 2 * nb_rec] + 1
307 direction = torch.randint(4, (1,))
308 for X, f_X in [(A, f_A), (B, f_B)]:
309 r = self.rec_coo(nb_rec)
310 for n in range(nb_rec):
311 i1, j1, i2, j2 = r[n]
312 X[i1:i2, j1:j2] = c[2 * n]
313 f_X[i1:i2, j1:j2] = c[2 * n]
314 # Not my proudest moment
317 X[i : i + 1, j1:j2] = c[2 * n + 1]
319 f_X[i:i2, j1:j2] = c[2 * n + 1]
321 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
323 i = (i1 + i2 - 1) // 2
324 X[i : i + 1, j1:j2] = c[2 * n + 1]
326 f_X[i1 : i + 1, j1:j2] = c[2 * n + 1]
328 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
331 X[i1:i2, j : j + 1] = c[2 * n + 1]
333 f_X[i1:i2, j:j2] = c[2 * n + 1]
335 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
337 j = (j1 + j2 - 1) // 2
338 X[i1:i2, j : j + 1] = c[2 * n + 1]
340 f_X[i1:i2, j1 : j + 1] = c[2 * n + 1]
342 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
345 def task_frame(self, A, f_A, B, f_B):
347 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
348 for X, f_X in [(A, f_A), (B, f_B)]:
349 r = self.rec_coo(nb_rec)
350 for n in range(nb_rec):
351 i1, j1, i2, j2 = r[n]
352 X[i1:i2, j1:j2] = c[n]
353 f_X[i1:i2, j1:j2] = c[n]
355 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = 0
358 def task_detect(self, A, f_A, B, f_B):
360 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
361 for X, f_X in [(A, f_A), (B, f_B)]:
362 r = self.rec_coo(nb_rec)
363 for n in range(nb_rec):
364 i1, j1, i2, j2 = r[n]
365 X[i1:i2, j1:j2] = c[n]
370 def contact(self, X, i, j, q):
384 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
385 if X[ii, jj] != 0 and X[ii, jj] != q:
394 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
395 if X[ii, jj] == q and X[i, jj] != q and X[ii, j] != q:
398 for ii, jj in [(i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)]:
399 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
403 return no, nq, nq_diag
405 def task_count(self, A, f_A, B, f_B):
406 N = (torch.randint(4, (1,)) + 2).item()
407 c = torch.randperm(len(self.colors) - 1)[:N] + 1
409 for X, f_X in [(A, f_A), (B, f_B)]:
410 l_q = torch.randperm(self.height * self.width)[
411 : self.height * self.width // 20
413 l_d = torch.randint(N, l_q.size())
414 nb = torch.zeros(N, dtype=torch.int64)
416 for q, e in zip(l_q, l_d):
418 i, j = q % self.height, q // self.height
421 and X[max(0, i - 1) : i + 2, max(0, j - 1) : j + 2] == 0
426 l_q = torch.randperm((self.height - 2) * (self.width - 2))[
427 : self.height * self.width // 2
429 l_d = torch.randint(N, l_q.size())
430 for q, e in zip(l_q, l_d):
432 i, j = q % (self.height - 2) + 1, q // (self.height - 2) + 1
433 a1, a2, a3 = X[i - 1, j - 1 : j + 2]
434 a8, a4 = X[i, j - 1], X[i, j + 1]
435 a7, a6, a5 = X[i + 1, j - 1 : j + 2]
438 and nb[e] < self.width
439 and (a2 == 0 or a2 == d)
440 and (a4 == 0 or a4 == d)
441 and (a6 == 0 or a6 == d)
442 and (a8 == 0 or a8 == d)
443 and (a1 == 0 or a2 == d or a8 == d)
444 and (a3 == 0 or a4 == d or a2 == d)
445 and (a5 == 0 or a6 == d or a4 == d)
446 and (a7 == 0 or a8 == d or a6 == d)
459 for j in range(nb[e]):
463 def task_trajectory(self, A, f_A, B, f_B):
464 c = torch.randperm(len(self.colors) - 1)[:2] + 1
465 for X, f_X in [(A, f_A), (B, f_B)]:
467 di, dj = torch.randint(7, (2,)) - 3
468 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
470 abs(di) + abs(dj) > 0
472 and i + 2 * di < self.height
474 and j + 2 * dj < self.width
481 and i + k * di < self.height
483 and j + k * dj < self.width
486 X[i + k * di, j + k * dj] = c[k]
487 f_X[i + k * di, j + k * dj] = c[min(k, 1)]
491 def task_bounce(self, A, f_A, B, f_B):
492 c = torch.randperm(len(self.colors) - 1)[:3] + 1
493 for X, f_X in [(A, f_A), (B, f_B)]:
508 for _ in range((self.height * self.width) // 10):
509 i, j = torch.randint(self.height, (1,)), torch.randint(
516 di, dj = torch.randint(7, (2,)) - 3
517 if abs(di) + abs(dj) == 1:
520 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
528 if free(i + di, j + dj):
530 elif free(i - dj, j + di):
532 if free(i + dj, j - di):
533 if torch.rand(1) < 0.5:
535 elif free(i + dj, j - di):
540 i, j = i + di, j + dj
555 def task_scale(self, A, f_A, B, f_B):
556 c = torch.randperm(len(self.colors) - 1)[:2] + 1
558 i, j = torch.randint(self.height // 2, (1,)), torch.randint(
559 self.width // 2, (1,)
562 for X, f_X in [(A, f_A), (B, f_B)]:
565 i1, j1 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
566 self.width // 2 + 1, (1,)
568 i2, j2 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
569 self.width // 2 + 1, (1,)
571 if i1 < i2 and j1 < j2 and min(i2 - i1, j2 - j1) <= 3:
573 X[i + i1 : i + i2, j + j1 : j + j2] = c[0]
574 f_X[2 * i1 : 2 * i2, 2 * j1 : 2 * j2] = c[0]
580 def task_symbols(self, A, f_A, B, f_B):
582 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
584 for X, f_X in [(A, f_A), (B, f_B)]:
586 i, j = torch.randint(self.height - delta + 1, (nb_rec,)), torch.randint(
587 self.width - delta + 1, (nb_rec,)
589 d = (i[None, :] - i[:, None]).abs().max((j[None, :] - j[:, None]).abs())
590 d.fill_diagonal_(delta + 1)
594 for k in range(1, nb_rec):
595 X[i[k] : i[k] + delta, j[k] : j[k] + delta] = c[k]
597 ai, aj = i.float().mean(), j.float().mean()
599 q = torch.randint(3, (1,)) + 1
601 X[i[0] + delta // 2 - 1, j[0] + delta // 2 - 1] = c[0]
602 X[i[0] + delta // 2 - 1, j[0] + delta // 2 + 1] = c[0]
603 X[i[0] + delta // 2 + 1, j[0] + delta // 2 - 1] = c[0]
604 X[i[0] + delta // 2 + 1, j[0] + delta // 2 + 1] = c[0]
606 assert i[q] != ai and j[q] != aj
609 i[0] + delta // 2 + (i[q] - ai).sign().long(),
610 j[0] + delta // 2 + (j[q] - aj).sign().long(),
613 f_X[i[0] : i[0] + delta, j[0] : j[0] + delta] = c[q]
616 def task_ortho(self, A, f_A, B, f_B):
618 di, dj = torch.randint(3, (2,)) - 1
619 o = torch.tensor([[0.0, 1.0], [-1.0, 0.0]])
621 for _ in range(torch.randint(4, (1,))):
623 if torch.rand(1) < 0.5:
626 ci, cj = (self.height - 1) / 2, (self.width - 1) / 2
628 for X, f_X in [(A, f_A), (B, f_B)]:
633 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
635 for r in range(nb_rec):
637 i1, i2 = torch.randint(self.height - 2, (2,)) + 1
638 j1, j2 = torch.randint(self.width - 2, (2,)) + 1
642 and max(i2 - i1, j2 - j1) >= 2
643 and min(i2 - i1, j2 - j1) <= 3
646 X[i1 : i2 + 1, j1 : j2 + 1] = c[r]
648 i1, j1, i2, j2 = i1 - ci, j1 - cj, i2 - ci, j2 - cj
650 i1, j1 = m[0, 0] * i1 + m[0, 1] * j1, m[1, 0] * i1 + m[1, 1] * j1
651 i2, j2 = m[0, 0] * i2 + m[0, 1] * j2, m[1, 0] * i2 + m[1, 1] * j2
653 i1, j1, i2, j2 = i1 + ci, j1 + cj, i2 + ci, j2 + cj
654 i1, i2 = i1.long() + di, i2.long() + di
655 j1, j2 = j1.long() + dj, j2.long() + dj
661 f_X[i1 : i2 + 1, j1 : j2 + 1] = c[r]
663 n = F.one_hot(X.flatten()).sum(dim=0)[1:]
665 n.sum() > self.height * self.width // 4
666 and (n > 0).long().sum() == nb_rec
671 def task_islands(self, A, f_A, B, f_B):
674 # for X, f_X in [(A, f_A), (B, f_B)]:
675 # n = torch.arange(self.height * self.width).reshape(self.height, self.width)
676 # k = torch.randperm(self.height * self.width)
679 # i,j=q%self.height,q//self.height
682 ######################################################################
686 self.task_replace_color,
689 self.task_color_grow,
693 self.task_trajectory,
701 def trivial_prompts_and_answers(self, prompts, answers):
702 S = self.height * self.width
703 Bs = prompts[:, 2 * (S + 1) : 2 * (S + 1) + S]
705 return (Bs == f_Bs).long().min(dim=-1).values > 0
707 def generate_prompts_and_answers_(self, nb, tasks=None, progress_bar=False):
709 tasks = self.all_tasks()
711 S = self.height * self.width
712 prompts = torch.zeros(nb, 3 * S + 2, dtype=torch.int64)
713 answers = torch.zeros(nb, S, dtype=torch.int64)
715 bunch = zip(prompts, answers)
721 desc="world generation",
722 total=prompts.size(0),
725 for prompt, answer in bunch:
726 A = prompt[0 * (S + 1) : 0 * (S + 1) + S].view(self.height, self.width)
727 f_A = prompt[1 * (S + 1) : 1 * (S + 1) + S].view(self.height, self.width)
728 B = prompt[2 * (S + 1) : 2 * (S + 1) + S].view(self.height, self.width)
729 f_B = answer.view(self.height, self.width)
730 task = tasks[torch.randint(len(tasks), (1,))]
733 return prompts.flatten(1), answers.flatten(1)
741 predicted_prompts=None,
742 predicted_answers=None,
747 filename_prefix + ".png",
756 ######################################################################
758 if __name__ == "__main__":
761 # grids = Grids(max_nb_cached_chunks=5, chunk_size=100, nb_threads=4)
765 # grids = problem.MultiThreadProblem(
766 # grids, max_nb_cached_chunks=50, chunk_size=100, nb_threads=1
769 # start_time = time.perf_counter()
770 # prompts, answers = grids.generate_prompts_and_answers(nb)
771 # delay = time.perf_counter() - start_time
772 # print(f"{prompts.size(0)/delay:02f} seq/s")
778 # for t in grids.all_tasks():
779 # for t in [grids.task_count]:
781 # prompts, answers = grids.generate_prompts_and_answers_(nb, tasks=[t])
782 # grids.save_quizzes("/tmp", t.__name__, prompts[:nb], answers[:nb], nrow=4)
788 for t in grids.all_tasks():
789 start_time = time.perf_counter()
790 prompts, answers = grids.generate_prompts_and_answers_(nb, tasks=[t])
791 delay = time.perf_counter() - start_time
792 print(f"{t.__name__} {prompts.size(0)/delay:02f} seq/s")
796 m = torch.randint(2, (prompts.size(0),))
797 predicted_prompts = m * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
798 predicted_answers = (1 - m) * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
805 # You can add a bool to put a frame around the predicted parts
806 predicted_prompts[:nb],
807 predicted_answers[:nb],