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 Reasoning(problem.Problem):
22 ("white", [255, 255, 255]),
24 ("green", [0, 192, 0]),
25 ("blue", [0, 0, 255]),
26 ("orange", [255, 192, 0]),
27 ("cyan", [0, 255, 255]),
28 ("violet", [255, 0, 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])
37 self.name2color = dict([(p[0], i) for i, p in enumerate(self.named_colors)])
42 ######################################################################
44 def frame2img(self, x, scale=15):
45 x = x.reshape(x.size(0), self.height, -1)
46 m = torch.logical_and(x >= 0, x < self.nb_token_values()).long()
47 x = self.colors[x * m].permute(0, 3, 1, 2)
49 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
50 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
52 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
53 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
56 for n in range(m.size(0)):
57 for i in range(m.size(1)):
58 for j in range(m.size(2)):
60 for k in range(2, scale - 2):
62 x[n, :, i * scale + k, j * scale + k - l] = 0
64 n, :, i * scale + scale - 1 - k, j * scale + k - l
69 def frame2img_(self, x, scale=15):
70 x = x.reshape(x.size(0), self.height, -1)
71 x = self.colors[x].permute(0, 3, 1, 2)
73 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
74 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
76 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
77 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
88 predicted_prompts=None,
89 predicted_answers=None,
92 prompts = prompts.reshape(prompts.size(0), self.height, -1)
93 answers = answers.reshape(answers.size(0), self.height, -1)
95 if predicted_prompts is None:
96 predicted_prompts = 255
98 if predicted_answers is None:
99 predicted_answers = 255
101 def add_frame(x, c, margin, bottom=False):
103 h, w, di, dj = x.size(2) + margin, x.size(3), 0, 0
106 x.size(2) + 2 * margin,
107 x.size(3) + 2 * margin,
112 y = x.new_full((x.size(0), x.size(1), h, w), 0)
117 c = c.long()[:, None]
119 (1 - ((c == 1).long() + (c == 0).long() + (c == -1).long()))
120 * torch.tensor([64, 64, 64], device=c.device)
121 + (c == 1).long() * torch.tensor([0, 255, 0], device=c.device)
122 + (c == 0).long() * torch.tensor([255, 255, 255], device=c.device)
123 + (c == -1).long() * torch.tensor([255, 0, 0], device=c.device)
125 y[...] = c[:, :, None, None]
127 y[:, :, di : di + x.size(2), dj : dj + x.size(3)] = x
133 img_prompts = torch.cat(
136 add_frame(self.frame2img(x), c=0, margin=1),
140 for x in prompts.to("cpu").split(split_size=self.width, dim=2)
145 h = img_prompts.size(2)
146 img_answers = add_frame(
147 add_frame(self.frame2img(answers.to("cpu")), c=0, margin=1),
152 separator_size = 2 * margin
154 separator = img_prompts.new_full(
164 marker = img_prompts.new_full(
174 # marker[:, :, 0] = 0
175 # marker[:, :, h - 1] = 0
177 for k in range(1, 2 * separator_size - 8):
178 i = k - (separator_size - 4)
179 j = separator_size - 5 - abs(i)
180 marker[:, :, h // 2 - 1 + i, 2 + j] = 0
181 marker[:, :, h // 2 - 1 + i + 1, 2 + j] = 0
192 image_name = os.path.join(result_dir, filename)
193 torchvision.utils.save_image(
201 ######################################################################
203 def nb_token_values(self):
204 return len(self.colors)
206 # That's quite a tensorial spaghetti mess to sample
207 # non-overlapping rectangles quickly, but made the generation of
208 # 100k samples go from 1h50 with a lame pure python code to 3min30s
210 def rec_coo(self, nb_rec, min_height=3, min_width=3):
216 torch.rand(nb_trials * nb_rec, self.height + 1, device=self.device)
228 torch.rand(nb_trials * nb_rec, self.width + 1, device=self.device)
238 i = torch.logical_and(
239 v.sum(dim=-1) >= min_height, h.sum(dim=-1) >= min_width
243 v = v[: v.size(0) - v.size(0) % nb_rec]
244 h = h[: h.size(0) - h.size(0) % nb_rec]
245 v = v.reshape(v.size(0) // nb_rec, nb_rec, -1)
246 h = h.reshape(h.size(0) // nb_rec, nb_rec, -1)
248 r = v[:, :, :, None] * h[:, :, None, :]
250 valid = r.sum(dim=1).flatten(1).max(dim=-1).values == 1
258 av = torch.arange(v.size(2), device=self.device)[None, :]
259 ah = torch.arange(h.size(2), device=self.device)[None, :]
262 (i1.item(), j1.item(), i2.item() + 1, j2.item() + 1)
263 for i1, j1, i2, j2 in zip(
264 v.size(2) - (v[0] * (v.size(2) - av)).max(dim=-1).values,
265 h.size(2) - (h[0] * (h.size(2) - ah)).max(dim=-1).values,
266 (v[0] * av).max(dim=-1).values,
267 (h[0] * ah).max(dim=-1).values,
271 def rec_coo_(self, x, n, min_height=3, min_width=3):
272 collision = x.new(x.size())
278 i1, i2 = torch.randint(x.size(0), (2,))
279 if i1 + min_height <= i2:
282 j1, j2 = torch.randint(x.size(1), (2,))
283 if j1 + min_width <= j2:
285 collision[i1:i2, j1:j2] += 1
286 if collision.max() > 1:
288 result.append((i1, j1, i2, j2))
289 if collision.max() == 1:
293 ######################################################################
295 def task_replace_color(self, A, f_A, B, f_B):
297 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
298 for X, f_X in [(A, f_A), (B, f_B)]:
299 r = self.rec_coo(nb_rec)
300 for n in range(nb_rec):
301 i1, j1, i2, j2 = r[n]
302 X[i1:i2, j1:j2] = c[n]
303 f_X[i1:i2, j1:j2] = c[n if n > 0 else -1]
305 def task_translate(self, A, f_A, B, f_B):
306 di, dj = torch.randint(3, (2,)) - 1
308 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
309 for X, f_X in [(A, f_A), (B, f_B)]:
311 r = self.rec_coo(nb_rec)
312 i1, j1, i2, j2 = r[nb_rec - 1]
315 and i2 + di < X.size(0)
317 and j2 + dj < X.size(1)
321 for n in range(nb_rec):
322 i1, j1, i2, j2 = r[n]
323 X[i1:i2, j1:j2] = c[n]
325 f_X[i1 + di : i2 + di, j1 + dj : j2 + dj] = c[n]
327 f_X[i1:i2, j1:j2] = c[n]
329 def task_grow(self, A, f_A, B, f_B):
330 di, dj = torch.randint(2, (2,)) * 2 - 1
332 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
333 direction = torch.randint(2, (1,))
334 for X, f_X in [(A, f_A), (B, f_B)]:
336 r = self.rec_coo(nb_rec)
337 i1, j1, i2, j2 = r[nb_rec - 1]
338 if i1 + 3 < i2 and j1 + 3 < j2:
341 for n in range(nb_rec):
342 i1, j1, i2, j2 = r[n]
345 X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
346 f_X[i1:i2, j1:j2] = c[n]
348 X[i1:i2, j1:j2] = c[n]
349 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
351 X[i1:i2, j1:j2] = c[n]
352 f_X[i1:i2, j1:j2] = c[n]
354 def task_color_grow(self, A, f_A, B, f_B):
355 di, dj = torch.randint(2, (2,)) * 2 - 1
357 c = torch.randperm(len(self.colors) - 1)[: 2 * nb_rec] + 1
358 direction = torch.randint(4, (1,))
359 for X, f_X in [(A, f_A), (B, f_B)]:
360 r = self.rec_coo(nb_rec)
361 for n in range(nb_rec):
362 i1, j1, i2, j2 = r[n]
363 X[i1:i2, j1:j2] = c[2 * n]
364 f_X[i1:i2, j1:j2] = c[2 * n]
365 # Not my proudest moment
368 X[i : i + 1, j1:j2] = c[2 * n + 1]
370 f_X[i:i2, j1:j2] = c[2 * n + 1]
372 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
374 i = (i1 + i2 - 1) // 2
375 X[i : i + 1, j1:j2] = c[2 * n + 1]
377 f_X[i1 : i + 1, j1:j2] = c[2 * n + 1]
379 f_X[i : i + 1, j1:j2] = c[2 * n + 1]
382 X[i1:i2, j : j + 1] = c[2 * n + 1]
384 f_X[i1:i2, j:j2] = c[2 * n + 1]
386 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
388 j = (j1 + j2 - 1) // 2
389 X[i1:i2, j : j + 1] = c[2 * n + 1]
391 f_X[i1:i2, j1 : j + 1] = c[2 * n + 1]
393 f_X[i1:i2, j : j + 1] = c[2 * n + 1]
395 def task_frame(self, A, f_A, B, f_B):
397 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
398 for X, f_X in [(A, f_A), (B, f_B)]:
399 r = self.rec_coo(nb_rec)
400 for n in range(nb_rec):
401 i1, j1, i2, j2 = r[n]
402 X[i1:i2, j1:j2] = c[n]
403 f_X[i1:i2, j1:j2] = c[n]
405 f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = 0
407 def task_detect(self, A, f_A, B, f_B):
409 c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
410 for X, f_X in [(A, f_A), (B, f_B)]:
411 r = self.rec_coo(nb_rec)
412 for n in range(nb_rec):
413 i1, j1, i2, j2 = r[n]
414 X[i1:i2, j1:j2] = c[n]
418 def task_count(self, A, f_A, B, f_B):
419 N = torch.randint(4, (1,)) + 2
420 c = torch.randperm(len(self.colors) - 1)[:N] + 1
422 for X, f_X in [(A, f_A), (B, f_B)]:
424 def contact(i, j, q):
438 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
439 if X[ii, jj] != 0 and X[ii, jj] != q:
448 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
449 if X[ii, jj] == q and X[i, jj] != q and X[ii, j] != q:
452 for ii, jj in [(i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)]:
453 if ii >= 0 and ii < self.height and jj >= 0 and jj < self.width:
457 return no, nq, nq_diag
459 nb = torch.zeros(N, dtype=torch.int64)
460 q = torch.randint(N, (self.height * self.width,))
461 k = torch.randperm(self.height * self.width)
462 for p in range(self.height * self.width):
463 i, j = k[p] % self.height, k[p] // self.height
464 no, nq, nq_diag = contact(i, j, c[q[p]])
465 if no == 0 and nq_diag == 0:
467 if nb[q[p]] < self.width:
474 for j in range(nb[n]):
477 def task_trajectory(self, A, f_A, B, f_B):
478 c = torch.randperm(len(self.colors) - 1)[:2] + 1
479 for X, f_X in [(A, f_A), (B, f_B)]:
481 di, dj = torch.randint(7, (2,)) - 3
482 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
484 abs(di) + abs(dj) > 0
486 and i + 2 * di < self.height
488 and j + 2 * dj < self.width
495 and i + k * di < self.height
497 and j + k * dj < self.width
500 X[i + k * di, j + k * dj] = c[k]
501 f_X[i + k * di, j + k * dj] = c[min(k, 1)]
504 def task_bounce(self, A, f_A, B, f_B):
505 c = torch.randperm(len(self.colors) - 1)[:3] + 1
506 for X, f_X in [(A, f_A), (B, f_B)]:
521 for _ in range((self.height * self.width) // 10):
522 i, j = torch.randint(self.height, (1,)), torch.randint(
529 di, dj = torch.randint(7, (2,)) - 3
530 if abs(di) + abs(dj) == 1:
533 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
541 if free(i + di, j + dj):
543 elif free(i - dj, j + di):
545 if free(i + dj, j - di):
546 if torch.rand(1) < 0.5:
548 elif free(i + dj, j - di):
553 i, j = i + di, j + dj
567 def task_scale(self, A, f_A, B, f_B):
568 c = torch.randperm(len(self.colors) - 1)[:2] + 1
570 i, j = torch.randint(self.height // 2, (1,)), torch.randint(
571 self.width // 2, (1,)
574 for X, f_X in [(A, f_A), (B, f_B)]:
577 i1, j1 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
578 self.width // 2 + 1, (1,)
580 i2, j2 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
581 self.width // 2 + 1, (1,)
583 if i1 < i2 and j1 < j2 and min(i2 - i1, j2 - j1) <= 3:
585 X[i + i1 : i + i2, j + j1 : j + j2] = c[0]
586 f_X[2 * i1 : 2 * i2, 2 * j1 : 2 * j2] = c[0]
591 def task_islands(self, A, f_A, B, f_B):
592 for X, f_X in [(A, f_A), (B, f_B)]:
594 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
597 or i == self.height - 1
599 or j == self.width - 1
604 di, dj = torch.randint(3, (2,)) - 1
605 if abs(di) + abs(dj) > 0:
609 i, j = i + di, j + dj
610 if i < 0 or i >= self.height or j < 0 or j >= self.width:
614 or i == self.height - 1
616 or j == self.width - 1
623 ######################################################################
627 self.task_replace_color,
630 self.task_color_grow,
634 self.task_trajectory,
640 def generate_prompts_and_answers(self, nb, tasks=None, device="cpu"):
642 tasks = self.all_tasks()
644 prompts = torch.zeros(nb, self.height, self.width * 3, dtype=torch.int64)
645 answers = torch.zeros(nb, self.height, self.width, dtype=torch.int64)
648 for prompt, answer in tqdm.tqdm(
649 zip(prompts, answers),
651 desc="world generation",
652 total=prompts.size(0),
654 A = prompt[:, 0 * w : 1 * w]
655 f_A = prompt[:, 1 * w : 2 * w]
656 B = prompt[:, 2 * w : 3 * w]
658 task = tasks[torch.randint(len(tasks), (1,))]
661 return prompts.flatten(1), answers.flatten(1)
669 predicted_prompts=None,
670 predicted_answers=None,
675 filename_prefix + ".png",
684 ######################################################################
686 if __name__ == "__main__":
691 reasoning = Reasoning()
693 for t in [reasoning.task_islands]: # reasoning.all_tasks():
695 prompts, answers = reasoning.generate_prompts_and_answers(nb, tasks=[t])
696 reasoning.save_quizzes("/tmp", t.__name__, prompts[:nb], answers[:nb], nrow=1)
702 start_time = time.perf_counter()
703 prompts, answers = reasoning.generate_prompts_and_answers(nb)
704 delay = time.perf_counter() - start_time
705 print(f"{prompts.size(0)/delay:02f} seq/s")
707 m = torch.randint(2, (prompts.size(0),))
708 predicted_prompts = m * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
709 predicted_answers = (1 - m) * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
711 reasoning.save_quizzes(
716 # You can add a bool to put a frame around the predicted parts
717 predicted_prompts[:nb],
718 predicted_answers[:nb],