912581011438aba0b5e6f3fe942d81602df615e2
[culture.git] / grids.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import math, sys, tqdm, os, warnings
9
10 import torch, torchvision
11
12 from torch import nn
13 from torch.nn import functional as F
14
15 ######################################################################
16
17 import problem
18
19
20 class Grids(problem.Problem):
21     named_colors = [
22         ("white", [255, 255, 255]),
23         ("red", [255, 0, 0]),
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]),
33     ]
34
35     def __init__(self, device=torch.device("cpu")):
36         self.colors = torch.tensor([c for _, c in self.named_colors])
37         self.height = 10
38         self.width = 10
39         self.device = device
40
41     ######################################################################
42
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)
47         s = x.shape
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)
50
51         x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
52         x[:, :, torch.arange(0, x.size(2), scale), :] = 0
53         x = x[:, :, 1:, 1:]
54
55         for n in range(m.size(0)):
56             for i in range(m.size(1)):
57                 for j in range(m.size(2)):
58                     if m[n, i, j] == 0:
59                         for k in range(2, scale - 2):
60                             for l in [0, 1]:
61                                 x[n, :, i * scale + k, j * scale + k - l] = 0
62                                 x[
63                                     n, :, i * scale + scale - 1 - k, j * scale + k - l
64                                 ] = 0
65
66         return x
67
68     def save_image(
69         self,
70         result_dir,
71         filename,
72         prompts,
73         answers,
74         predicted_prompts=None,
75         predicted_answers=None,
76         nrow=4,
77     ):
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
82         )
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)
86
87         if predicted_prompts is None:
88             predicted_prompts = 255
89
90         if predicted_answers is None:
91             predicted_answers = 255
92
93         def add_frame(x, c, margin, bottom=False):
94             if bottom:
95                 h, w, di, dj = x.size(2) + margin, x.size(3), 0, 0
96             else:
97                 h, w, di, dj = (
98                     x.size(2) + 2 * margin,
99                     x.size(3) + 2 * margin,
100                     margin,
101                     margin,
102                 )
103
104             y = x.new_full((x.size(0), x.size(1), h, w), 0)
105
106             if type(c) is int:
107                 y[...] = c
108             else:
109                 c = c.long()[:, None]
110                 c = (
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)
116                 )
117                 y[...] = c[:, :, None, None]
118
119             y[:, :, di : di + x.size(2), dj : dj + x.size(3)] = x
120
121             return y
122
123         margin = 8
124
125         img_prompts = torch.cat(
126             [
127                 add_frame(
128                     add_frame(self.frame2img(x), c=0, margin=1),
129                     c=predicted_prompts,
130                     margin=margin,
131                 )
132                 for x in prompts.to("cpu").split(split_size=self.width, dim=2)
133             ],
134             dim=3,
135         )
136
137         h = img_prompts.size(2)
138         img_answers = add_frame(
139             add_frame(self.frame2img(answers.to("cpu")), c=0, margin=1),
140             c=predicted_answers,
141             margin=margin,
142         )
143
144         separator_size = 2 * margin
145
146         separator = img_prompts.new_full(
147             (
148                 img_prompts.size(0),
149                 img_prompts.size(1),
150                 img_prompts.size(2),
151                 separator_size,
152             ),
153             255,
154         )
155
156         marker = img_prompts.new_full(
157             (
158                 img_prompts.size(0),
159                 img_prompts.size(1),
160                 img_prompts.size(2),
161                 separator_size,
162             ),
163             255,
164         )
165
166         # marker[:, :, 0] = 0
167         # marker[:, :, h - 1] = 0
168
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
174
175         img = torch.cat(
176             [
177                 img_prompts,
178                 marker,
179                 img_answers,
180             ],
181             dim=3,
182         )
183
184         image_name = os.path.join(result_dir, filename)
185         torchvision.utils.save_image(
186             img.float() / 255.0,
187             image_name,
188             nrow=nrow,
189             padding=margin * 4,
190             pad_value=1.0,
191         )
192
193     ######################################################################
194
195     def nb_token_values(self):
196         return len(self.colors)
197
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
201     # with this one.
202     def rec_coo(self, nb_rec, min_height=3, min_width=3):
203         nb_trials = 200
204
205         while True:
206             v = (
207                 (
208                     torch.rand(nb_trials * nb_rec, self.height + 1, device=self.device)
209                     .sort(dim=-1)
210                     .indices
211                     < 2
212                 )
213                 .long()
214                 .cumsum(dim=1)
215                 == 1
216             ).long()
217
218             h = (
219                 (
220                     torch.rand(nb_trials * nb_rec, self.width + 1, device=self.device)
221                     .sort(dim=-1)
222                     .indices
223                     < 2
224                 )
225                 .long()
226                 .cumsum(dim=1)
227                 == 1
228             ).long()
229
230             i = torch.logical_and(
231                 v.sum(dim=-1) >= min_height, h.sum(dim=-1) >= min_width
232             )
233
234             v, h = v[i], h[i]
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)
239
240             r = v[:, :, :, None] * h[:, :, None, :]
241
242             valid = r.sum(dim=1).flatten(1).max(dim=-1).values == 1
243
244             v = v[valid]
245             h = h[valid]
246
247             if v.size(0) > 0:
248                 break
249
250         av = torch.arange(v.size(2), device=self.device)[None, :]
251         ah = torch.arange(h.size(2), device=self.device)[None, :]
252
253         return [
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,
260             )
261         ]
262
263     def rec_coo_(self, x, n, min_height=3, min_width=3):
264         collision = x.new(x.size())
265         while True:
266             collision[...] = 0
267             result = []
268             for _ in range(n):
269                 while True:
270                     i1, i2 = torch.randint(x.size(0), (2,))
271                     if i1 + min_height <= i2:
272                         break
273                 while True:
274                     j1, j2 = torch.randint(x.size(1), (2,))
275                     if j1 + min_width <= j2:
276                         break
277                 collision[i1:i2, j1:j2] += 1
278                 if collision.max() > 1:
279                     break
280                 result.append((i1, j1, i2, j2))
281             if collision.max() == 1:
282                 break
283         return result
284
285     ######################################################################
286
287     def task_replace_color(self, A, f_A, B, f_B):
288         nb_rec = 3
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]
296
297     def task_translate(self, A, f_A, B, f_B):
298         di, dj = torch.randint(3, (2,)) - 1
299         nb_rec = 3
300         c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
301         for X, f_X in [(A, f_A), (B, f_B)]:
302             while True:
303                 r = self.rec_coo(nb_rec)
304                 i1, j1, i2, j2 = r[nb_rec - 1]
305                 if (
306                     i1 + di >= 0
307                     and i2 + di < X.size(0)
308                     and j1 + dj >= 0
309                     and j2 + dj < X.size(1)
310                 ):
311                     break
312
313             for n in range(nb_rec):
314                 i1, j1, i2, j2 = r[n]
315                 X[i1:i2, j1:j2] = c[n]
316                 if n == nb_rec - 1:
317                     f_X[i1 + di : i2 + di, j1 + dj : j2 + dj] = c[n]
318                 else:
319                     f_X[i1:i2, j1:j2] = c[n]
320
321     def task_grow(self, A, f_A, B, f_B):
322         di, dj = torch.randint(2, (2,)) * 2 - 1
323         nb_rec = 3
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)]:
327             while True:
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:
331                     break
332
333             for n in range(nb_rec):
334                 i1, j1, i2, j2 = r[n]
335                 if n == nb_rec - 1:
336                     if direction == 0:
337                         X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
338                         f_X[i1:i2, j1:j2] = c[n]
339                     else:
340                         X[i1:i2, j1:j2] = c[n]
341                         f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c[n]
342                 else:
343                     X[i1:i2, j1:j2] = c[n]
344                     f_X[i1:i2, j1:j2] = c[n]
345
346     def task_color_grow(self, A, f_A, B, f_B):
347         di, dj = torch.randint(2, (2,)) * 2 - 1
348         nb_rec = 3
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
358                 if direction == 0:
359                     i = (i1 + i2) // 2
360                     X[i : i + 1, j1:j2] = c[2 * n + 1]
361                     if n == nb_rec - 1:
362                         f_X[i:i2, j1:j2] = c[2 * n + 1]
363                     else:
364                         f_X[i : i + 1, j1:j2] = c[2 * n + 1]
365                 elif direction == 1:
366                     i = (i1 + i2 - 1) // 2
367                     X[i : i + 1, j1:j2] = c[2 * n + 1]
368                     if n == nb_rec - 1:
369                         f_X[i1 : i + 1, j1:j2] = c[2 * n + 1]
370                     else:
371                         f_X[i : i + 1, j1:j2] = c[2 * n + 1]
372                 elif direction == 2:
373                     j = (j1 + j2) // 2
374                     X[i1:i2, j : j + 1] = c[2 * n + 1]
375                     if n == nb_rec - 1:
376                         f_X[i1:i2, j:j2] = c[2 * n + 1]
377                     else:
378                         f_X[i1:i2, j : j + 1] = c[2 * n + 1]
379                 elif direction == 3:
380                     j = (j1 + j2 - 1) // 2
381                     X[i1:i2, j : j + 1] = c[2 * n + 1]
382                     if n == nb_rec - 1:
383                         f_X[i1:i2, j1 : j + 1] = c[2 * n + 1]
384                     else:
385                         f_X[i1:i2, j : j + 1] = c[2 * n + 1]
386
387     def task_frame(self, A, f_A, B, f_B):
388         nb_rec = 3
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]
396                 if n == nb_rec - 1:
397                     f_X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = 0
398
399     def task_detect(self, A, f_A, B, f_B):
400         nb_rec = 3
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]
407                 if n < nb_rec - 1:
408                     f_X[i1, j1] = c[-1]
409
410     def contact(self, X, i, j, q):
411         nq, nq_diag = 0, 0
412         no = 0
413
414         for ii, jj in [
415             (i - 1, j - 1),
416             (i - 1, j),
417             (i - 1, j + 1),
418             (i, j - 1),
419             (i, j + 1),
420             (i + 1, j - 1),
421             (i + 1, j),
422             (i + 1, j + 1),
423         ]:
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:
426                     no += 1
427
428         for ii, jj in [
429             (i - 1, j - 1),
430             (i - 1, j + 1),
431             (i + 1, j - 1),
432             (i + 1, j + 1),
433         ]:
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:
436                     nq_diag += 1
437
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:
440                 if X[ii, jj] == q:
441                     nq += 1
442
443         return no, nq, nq_diag
444
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
448
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:
457                     if nq == 0:
458                         if nb[q[p]] < self.width:
459                             X[i, j] = c[q[p]]
460                             nb[q[p]] += 1
461                     if nq == 1:
462                         X[i, j] = c[q[p]]
463
464             for n in range(N):
465                 for j in range(nb[n]):
466                     f_X[n, j] = c[n]
467
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)]:
471             while True:
472                 di, dj = torch.randint(7, (2,)) - 3
473                 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
474                 if (
475                     abs(di) + abs(dj) > 0
476                     and i + 2 * di >= 0
477                     and i + 2 * di < self.height
478                     and j + 2 * dj >= 0
479                     and j + 2 * dj < self.width
480                 ):
481                     break
482
483             k = 0
484             while (
485                 i + k * di >= 0
486                 and i + k * di < self.height
487                 and j + k * dj >= 0
488                 and j + k * dj < self.width
489             ):
490                 if k < 2:
491                     X[i + k * di, j + k * dj] = c[k]
492                 f_X[i + k * di, j + k * dj] = c[min(k, 1)]
493                 k += 1
494
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)]:
498
499             def free(i, j):
500                 return (
501                     i >= 0
502                     and i < self.height
503                     and j >= 0
504                     and j < self.width
505                     and f_X[i, j] == 0
506                 )
507
508             while True:
509                 f_X[...] = 0
510                 X[...] = 0
511
512                 for _ in range((self.height * self.width) // 10):
513                     i, j = torch.randint(self.height, (1,)), torch.randint(
514                         self.width, (1,)
515                     )
516                     X[i, j] = c[0]
517                     f_X[i, j] = c[0]
518
519                 while True:
520                     di, dj = torch.randint(7, (2,)) - 3
521                     if abs(di) + abs(dj) == 1:
522                         break
523
524                 i, j = torch.randint(self.height, (1,)), torch.randint(self.width, (1,))
525
526                 X[i, j] = c[1]
527                 f_X[i, j] = c[1]
528                 l = 0
529
530                 while True:
531                     l += 1
532                     if free(i + di, j + dj):
533                         pass
534                     elif free(i - dj, j + di):
535                         di, dj = -dj, di
536                         if free(i + dj, j - di):
537                             if torch.rand(1) < 0.5:
538                                 di, dj = -di, -dj
539                     elif free(i + dj, j - di):
540                         di, dj = dj, -di
541                     else:
542                         break
543
544                     i, j = i + di, j + dj
545                     f_X[i, j] = c[2]
546                     if l <= 1:
547                         X[i, j] = c[2]
548
549                     if l >= self.width:
550                         break
551
552                 f_X[i, j] = c[1]
553                 X[i, j] = c[1]
554
555                 if l > 3:
556                     break
557
558     def task_scale(self, A, f_A, B, f_B):
559         c = torch.randperm(len(self.colors) - 1)[:2] + 1
560
561         i, j = torch.randint(self.height // 2, (1,)), torch.randint(
562             self.width // 2, (1,)
563         )
564
565         for X, f_X in [(A, f_A), (B, f_B)]:
566             for _ in range(3):
567                 while True:
568                     i1, j1 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
569                         self.width // 2 + 1, (1,)
570                     )
571                     i2, j2 = torch.randint(self.height // 2 + 1, (1,)), torch.randint(
572                         self.width // 2 + 1, (1,)
573                     )
574                     if i1 < i2 and j1 < j2 and min(i2 - i1, j2 - j1) <= 3:
575                         break
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]
578
579             X[i, j] = c[1]
580             f_X[0:2, 0:2] = c[1]
581
582     def task_symbols(self, A, f_A, B, f_B):
583         nb_rec = 4
584         c = torch.randperm(len(self.colors) - 1)[: nb_rec + 1] + 1
585         delta = 3
586         for X, f_X in [(A, f_A), (B, f_B)]:
587             while True:
588                 i, j = torch.randint(self.height - delta + 1, (nb_rec,)), torch.randint(
589                     self.width - delta + 1, (nb_rec,)
590                 )
591                 d = (i[None, :] - i[:, None]).abs().max((j[None, :] - j[:, None]).abs())
592                 d.fill_diagonal_(delta + 1)
593                 if d.min() > delta:
594                     break
595
596             for k in range(1, nb_rec):
597                 X[i[k] : i[k] + delta, j[k] : j[k] + delta] = c[k]
598
599             ai, aj = i.float().mean(), j.float().mean()
600
601             q = torch.randint(3, (1,)) + 1
602
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]
605             X[i[0] + delta // 2 + 1, j[0] + delta // 2 - 1] = c[0]
606             X[i[0] + delta // 2 + 1, j[0] + delta // 2 + 1] = c[0]
607
608             assert i[q] != ai and j[q] != aj
609
610             X[
611                 i[0] + delta // 2 + (i[q] - ai).sign().long(),
612                 j[0] + delta // 2 + (j[q] - aj).sign().long(),
613             ] = c[nb_rec]
614
615             f_X[i[0] : i[0] + delta, j[0] : j[0] + delta] = c[q]
616
617     def task_ortho(self, A, f_A, B, f_B):
618         nb_rec = 3
619         di, dj = torch.randint(3, (2,)) - 1
620         o = torch.tensor([[0.0, 1.0], [-1.0, 0.0]])
621         m = torch.eye(2)
622         for _ in range(torch.randint(4, (1,))):
623             m = m @ o
624         if torch.rand(1) < 0.5:
625             m[0, :] = -m[0, :]
626
627         ci, cj = (self.height - 1) / 2, (self.width - 1) / 2
628
629         for X, f_X in [(A, f_A), (B, f_B)]:
630             while True:
631                 X[...] = 0
632                 f_X[...] = 0
633
634                 c = torch.randperm(len(self.colors) - 1)[:nb_rec] + 1
635
636                 for r in range(nb_rec):
637                     while True:
638                         i1, i2 = torch.randint(self.height - 2, (2,)) + 1
639                         j1, j2 = torch.randint(self.width - 2, (2,)) + 1
640                         if (
641                             i2 >= i1
642                             and j2 >= j1
643                             and max(i2 - i1, j2 - j1) >= 2
644                             and min(i2 - i1, j2 - j1) <= 3
645                         ):
646                             break
647                     X[i1 : i2 + 1, j1 : j2 + 1] = c[r]
648
649                     i1, j1, i2, j2 = i1 - ci, j1 - cj, i2 - ci, j2 - cj
650
651                     i1, j1 = m[0, 0] * i1 + m[0, 1] * j1, m[1, 0] * i1 + m[1, 1] * j1
652                     i2, j2 = m[0, 0] * i2 + m[0, 1] * j2, m[1, 0] * i2 + m[1, 1] * j2
653
654                     i1, j1, i2, j2 = i1 + ci, j1 + cj, i2 + ci, j2 + cj
655                     i1, i2 = i1.long() + di, i2.long() + di
656                     j1, j2 = j1.long() + dj, j2.long() + dj
657                     if i1 > i2:
658                         i1, i2 = i2, i1
659                     if j1 > j2:
660                         j1, j2 = j2, j1
661
662                     f_X[i1 : i2 + 1, j1 : j2 + 1] = c[r]
663
664                 n = F.one_hot(X.flatten()).sum(dim=0)[1:]
665                 if (
666                     n.sum() > self.height * self.width // 4
667                     and (n > 0).long().sum() == nb_rec
668                 ):
669                     break
670
671     def task_islands(self, A, f_A, B, f_B):
672         pass
673
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)
677     # X[...]=-1
678     # for q in k:
679     # i,j=q%self.height,q//self.height
680     # if
681
682     ######################################################################
683
684     def all_tasks(self):
685         return [
686             self.task_replace_color,
687             self.task_translate,
688             self.task_grow,
689             self.task_color_grow,
690             self.task_frame,
691             self.task_detect,
692             self.task_count,
693             self.task_trajectory,
694             self.task_bounce,
695             self.task_scale,
696             self.task_symbols,
697             self.task_ortho,
698             # self.task_islands,
699         ]
700
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]
704         f_Bs = answers
705         return (Bs == f_Bs).long().min(dim=-1).values > 0
706
707     def generate_prompts_and_answers(self, nb, tasks=None, device="cpu"):
708         if tasks is None:
709             tasks = self.all_tasks()
710
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)
714
715         for prompt, answer in tqdm.tqdm(
716             zip(prompts, answers),
717             dynamic_ncols=True,
718             desc="world generation",
719             total=prompts.size(0),
720         ):
721             A = prompt[0 * (S + 1) : 0 * (S + 1) + S].view(self.height, self.width)
722             f_A = prompt[1 * (S + 1) : 1 * (S + 1) + S].view(self.height, self.width)
723             B = prompt[2 * (S + 1) : 2 * (S + 1) + S].view(self.height, self.width)
724             f_B = answer.view(self.height, self.width)
725             task = tasks[torch.randint(len(tasks), (1,))]
726             task(A, f_A, B, f_B)
727
728         return prompts.flatten(1), answers.flatten(1)
729
730     def save_quizzes(
731         self,
732         result_dir,
733         filename_prefix,
734         prompts,
735         answers,
736         predicted_prompts=None,
737         predicted_answers=None,
738         nrow=4,
739     ):
740         self.save_image(
741             result_dir,
742             filename_prefix + ".png",
743             prompts,
744             answers,
745             predicted_prompts,
746             predicted_answers,
747             nrow,
748         )
749
750
751 ######################################################################
752
753 if __name__ == "__main__":
754     import time
755
756     nb = 48
757
758     grids = Grids()
759
760     # for t in grids.all_tasks():
761     for t in [grids.task_ortho]:
762         print(t.__name__)
763         prompts, answers = grids.generate_prompts_and_answers(nb, tasks=[t])
764         grids.save_quizzes("/tmp", t.__name__, prompts[:nb], answers[:nb], nrow=4)
765
766     exit(0)
767
768     nb = 72
769
770     start_time = time.perf_counter()
771     prompts, answers = grids.generate_prompts_and_answers(nb)
772     delay = time.perf_counter() - start_time
773     print(f"{prompts.size(0)/delay:02f} seq/s")
774
775     m = torch.randint(2, (prompts.size(0),))
776     predicted_prompts = m * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
777     predicted_answers = (1 - m) * (torch.randint(2, (prompts.size(0),)) * 2 - 1)
778
779     grids.save_quizzes(
780         "/tmp",
781         "test",
782         prompts[:nb],
783         answers[:nb],
784         # You can add a bool to put a frame around the predicted parts
785         predicted_prompts[:nb],
786         predicted_answers[:nb],
787     )