Update.
[culture.git] / lang.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 Lang(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         ("orange", [255, 192, 0]),
27         ("cyan", [0, 255, 255]),
28         ("violet", [255, 0, 255]),
29         ("lightgreen", [192, 255, 192]),
30         ("pink", [255, 192, 192]),
31         ("lightblue", [192, 192, 255]),
32         ("gray", [192, 192, 192]),
33     ]
34
35     def __init__(
36         self,
37         nb_iterations=2,
38     ):
39         self.colors = torch.tensor([c for _, c in self.named_colors])
40         self.name2color = dict([(p[0], i) for i, p in enumerate(self.named_colors)])
41         self.height = 10
42         self.width = 10
43         self.nb_iterations = nb_iterations
44
45     ######################################################################
46
47     def frame2img(self, x, scale=15):
48         x = x.reshape(x.size(0), self.height, -1)
49         x = self.colors[x].permute(0, 3, 1, 2)
50         s = x.shape
51         x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
52         x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
53
54         x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
55         x[:, :, torch.arange(0, x.size(2), scale), :] = 0
56         x = x[:, :, 1:, 1:]
57
58         return x
59
60     def save_image(
61         self,
62         result_dir,
63         filename,
64         prompts,
65         answers,
66         predicted_prompts=None,
67         predicted_answers=None,
68     ):
69         prompts = prompts.reshape(prompts.size(0), self.height, -1)
70         answers = answers.reshape(answers.size(0), self.height, -1)
71
72         if predicted_prompts is None:
73             predicted_prompts = 255
74
75         if predicted_answers is None:
76             predicted_answers = 255
77
78         def add_frame(x, c, margin, bottom=False):
79             if bottom:
80                 h, w, di, dj = x.size(2) + margin, x.size(3), 0, 0
81             else:
82                 h, w, di, dj = (
83                     x.size(2) + 2 * margin,
84                     x.size(3) + 2 * margin,
85                     margin,
86                     margin,
87                 )
88
89             y = x.new_full((x.size(0), x.size(1), h, w), 0)
90
91             if type(c) is int:
92                 y[...] = c
93             else:
94                 c = c.long()[:, None]
95                 c = c * torch.tensor([192, 192, 192], device=c.device) + (
96                     1 - c
97                 ) * torch.tensor([255, 255, 255], device=c.device)
98                 y[...] = c[:, :, None, None]
99
100             y[:, :, di : di + x.size(2), dj : dj + x.size(3)] = x
101
102             return y
103
104         margin = 8
105
106         img_prompts = torch.cat(
107             [
108                 add_frame(
109                     add_frame(self.frame2img(x), c=0, margin=1),
110                     c=predicted_prompts,
111                     margin=margin,
112                 )
113                 for x in prompts.to("cpu").split(split_size=self.width, dim=2)
114             ],
115             dim=3,
116         )
117
118         h = img_prompts.size(2)
119         img_answers = add_frame(
120             add_frame(self.frame2img(answers.to("cpu")), c=0, margin=1),
121             c=predicted_answers,
122             margin=margin,
123         )
124
125         separator_size = 2 * margin
126
127         separator = img_prompts.new_full(
128             (
129                 img_prompts.size(0),
130                 img_prompts.size(1),
131                 img_prompts.size(2),
132                 separator_size,
133             ),
134             255,
135         )
136
137         marker = img_prompts.new_full(
138             (
139                 img_prompts.size(0),
140                 img_prompts.size(1),
141                 img_prompts.size(2),
142                 separator_size,
143             ),
144             255,
145         )
146
147         # marker[:, :, 0] = 0
148         # marker[:, :, h - 1] = 0
149
150         for k in range(1, 2 * separator_size - 8):
151             i = k - (separator_size - 4)
152             j = separator_size - 5 - abs(i)
153             marker[:, :, h // 2 - 1 + i, 2 + j] = 0
154             marker[:, :, h // 2 - 1 + i + 1, 2 + j] = 0
155
156         img = torch.cat(
157             [
158                 img_prompts,
159                 marker,
160                 img_answers,
161             ],
162             dim=3,
163         )
164
165         image_name = os.path.join(result_dir, filename)
166         torchvision.utils.save_image(
167             img.float() / 255.0, image_name, nrow=4, padding=margin * 4, pad_value=1.0
168         )
169
170     ######################################################################
171
172     def nb_token_values(self):
173         return len(self.colors)
174
175     def rec_coo(self, x):
176         while True:
177             i1, i2 = torch.randint(x.size(0), (2,))
178             if i1 < i2 - 1:
179                 break
180         while True:
181             j1, j2 = torch.randint(x.size(1), (2,))
182             if j1 < j2 - 1:
183                 break
184         return i1, j1, i2, j2
185
186     def task_replace_color(self, A, f_A, B, f_B):
187         c1, c2 = torch.randperm(len(self.colors) - 1)[:2] + 1
188         for n, X, f_X in [(1, A, f_A), (3, B, f_B)]:
189             for _ in range(torch.randint(n, (1,)) + 1):
190                 i1, j1, i2, j2 = self.rec_coo(X)
191                 X[i1:i2, j1:j2] = c1
192                 f_X[i1:i2, j1:j2] = c2
193
194     def task_move(self, A, f_A, B, f_B):
195         c = torch.randperm(len(self.colors) - 1)[:1] + 1
196         di, dj = torch.randint(2, (2,)) * 2 - 1
197         for n, X, f_X in [(1, A, f_A), (3, B, f_B)]:
198             for _ in range(torch.randint(n, (1,)) + 1):
199                 while True:
200                     i1, j1, i2, j2 = self.rec_coo(X)
201                     if (
202                         i1 + di >= 0
203                         and i2 + di < X.size(0)
204                         and j1 + dj >= 0
205                         and j2 + dj < X.size(1)
206                     ):
207                         break
208
209                 X[i1:i2, j1:j2] = c
210                 f_X[i1 + di : i2 + di, j1 + dj : j2 + dj] = c
211
212     def task_grow(self, A, f_A, B, f_B):
213         c = torch.randperm(len(self.colors) - 1)[:1] + 1
214
215         for n, X, f_X in [(1, A, f_A), (3, B, f_B)]:
216             for _ in range(torch.randint(n, (1,)) + 1):
217                 while True:
218                     i1, j1, i2, j2 = self.rec_coo(X)
219                     if i1 + 3 < i2 and j1 + 3 < j2:
220                         break
221
222                 X[i1 + 1 : i2 - 1, j1 + 1 : j2 - 1] = c
223                 f_X[i1:i2, j1:j2] = c
224
225     def generate_prompts_and_answers(self, nb):
226         tasks = [self.task_replace_color, self.task_move, self.task_grow]
227         prompts = torch.zeros(nb, self.height, self.width * 3, dtype=torch.int64)
228         answers = torch.zeros(nb, self.height, self.width, dtype=torch.int64)
229         w = self.width
230         for prompt, answer in zip(prompts, answers):
231             A = prompt[:, 0 * w : 1 * w]
232             f_A = prompt[:, 1 * w : 2 * w]
233             B = prompt[:, 2 * w : 3 * w]
234             f_B = answer
235             tasks[torch.randint(len(tasks), (1,))](A, f_A, B, f_B)
236         return prompts.flatten(1), answers.flatten(1)
237
238     def save_quizzes(
239         self,
240         result_dir,
241         filename_prefix,
242         prompts,
243         answers,
244         predicted_prompts=None,
245         predicted_answers=None,
246     ):
247         self.save_image(
248             result_dir,
249             filename_prefix + ".png",
250             prompts,
251             answers,
252             predicted_prompts,
253             predicted_answers,
254         )
255
256
257 ######################################################################
258
259 if __name__ == "__main__":
260     import time
261
262     lang = Lang(nb_iterations=4)
263
264     prompts, answers = lang.generate_prompts_and_answers(36)
265
266     predicted_prompts = torch.rand(prompts.size(0)) < 0.5
267     predicted_answers = torch.logical_not(predicted_prompts)
268
269     lang.save_quizzes(
270         "/tmp",
271         "test",
272         prompts,
273         answers,  # predicted_prompts, predicted_answers
274     )
275
276     # start_time = time.perf_counter()
277     # token_sequences = lang.generate_token_sequences(nb=64)
278     # delay = time.perf_counter() - start_time
279     # print(f"{token_sequences.size(0)/delay:02f} seq/s")
280
281     # print(lang.seq2str(seq[:4]))
282
283     # for t in range(len(it[0])):
284     # img = torch.cat([lang.frame2img(f[t]) for f in it], dim=0)
285     # torchvision.utils.save_image(
286     # img.float() / 255.0,
287     # f"/tmp/frame_{t:03d}.png",
288     # nrow=8,
289     # padding=6,
290     # pad_value=0,
291     # )
292
293     # m = (torch.rand(seq.size()) < 0.05).long()
294     # seq = (1 - m) * seq + m * 23
295
296     # print(seq.size())
297     # img = lang.seq2img(token_sequences)
298     # print(img.size())
299
300     # torchvision.utils.save_image(
301     # img.float() / 255.0, "/tmp/world.png", nrow=6, padding=6, pad_value=0
302     # )