Update.
[pytorch.git] / picocrafter.py
1 #!/usr/bin/env python
2
3 #########################################################################
4 # This program is free software: you can redistribute it and/or modify  #
5 # it under the terms of the version 3 of the GNU General Public License #
6 # as published by the Free Software Foundation.                         #
7 #                                                                       #
8 # This program is distributed in the hope that it will be useful, but   #
9 # WITHOUT ANY WARRANTY; without even the implied warranty of            #
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
11 # General Public License for more details.                              #
12 #                                                                       #
13 # You should have received a copy of the GNU General Public License     #
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.  #
15 #                                                                       #
16 # Written by and Copyright (C) Francois Fleuret                         #
17 # Contact <francois.fleuret@unige.ch> for comments & bug reports        #
18 #########################################################################
19
20 # This is a tiny rogue-like environment implemented with tensor
21 # operations, that runs in batches efficiently on a GPU. On a RTX4090
22 # it can initialize ~20k environments per second and run ~40k
23 # iterations.
24 #
25 # The environment is a rectangular area with walls "#" dispatched
26 # randomly. The agent "@" can perform five actions: move NESW or do
27 # not move.
28 #
29 # There are monsters "$" moving randomly. The agent gets hit by every
30 # monster present in one of the 4 direct neighborhoods at the end of
31 # the moves, each hit results in a rewards of -1.
32 #
33 # The agent starts with 5 life points, each hit costs it 1pt, when it
34 # gets to 0 it dies, gets a reward of -10 and the episode is over. At
35 # every step it recovers 1/20th of a life point, with a maximum of
36 # 5pt.
37 #
38 # The agent can carry "keys" ("a", "b", "c") that open "vaults" ("A",
39 # "B", "C"). The keys and vault can only be used in sequence:
40 # initially the agent can move only to free spaces, or to the "a", in
41 # which case the key is removed from the environment and the agent now
42 # carries it, and can move to free spaces or the "A". When it moves to
43 # the "A", it gets a reward, loses the "a", the "A" is removed from
44 # the environment, but the agent can now move to the "b", etc. Rewards
45 # are 1 for "A" and "B" and 10 for "C".
46
47 ######################################################################
48
49 import torch
50
51 from torch.nn.functional import conv2d
52
53 ######################################################################
54
55
56 def to_ansi(s):
57     if type(s) is list:
58         return [to_ansi(x) for x in s]
59
60     for u, c in [("$", 31), ("@", 32)] + [(x, 36) for x in "aAbBcC"]:
61         s = s.replace(u, f"\u001b[{c}m{u}\u001b[0m")
62
63     return s
64
65
66 def to_unicode(s):
67     if type(s) is list:
68         return [to_unicode(x) for x in s]
69
70     for u, c in [("#", "█"), ("+", "░"), ("|", "│")]:
71         s = s.replace(u, c)
72
73     return s
74
75
76 def fusion_multi_lines(l, width_min=0):
77     l = [x if type(x) is list else [str(x)] for x in l]
78
79     def center(r, w):
80         k = w - len(r)
81         return " " * (k // 2) + r + " " * (k - k // 2)
82
83     def f(o, h):
84         w = max(width_min, max([len(r) for r in o]))
85         return [" " * w] * (h - len(o)) + [center(r, w) for r in o]
86
87     h = max([len(x) for x in l])
88     l = [f(o, h) for o in l]
89
90     return "\n".join(["|".join([o[k] for o in l]) for k in range(h)])
91
92
93 class PicroCrafterEngine:
94     def __init__(
95         self,
96         world_height=27,
97         world_width=27,
98         nb_walls=27,
99         margin=2,
100         view_height=5,
101         view_width=5,
102         device=torch.device("cpu"),
103     ):
104         assert (world_height - 2 * margin) % (view_height - 2 * margin) == 0
105         assert (world_width - 2 * margin) % (view_width - 2 * margin) == 0
106
107         self.device = device
108
109         self.world_height = world_height
110         self.world_width = world_width
111         self.margin = margin
112         self.view_height = view_height
113         self.view_width = view_width
114         self.nb_walls = nb_walls
115         self.life_level_max = 5
116         self.life_level_gain_100th = 5
117         self.reward_per_hit = -1
118         self.reward_death = -10
119
120         self.tiles = " +#@$aAbBcC-" + "".join(
121             [str(n) for n in range(self.life_level_max + 1)]
122         )
123         self.tile2id = dict([(t, n) for n, t in enumerate(self.tiles)])
124         self.id2tile = dict([(n, t) for n, t in enumerate(self.tiles)])
125
126         self.next_object = dict(
127             [
128                 (self.tile2id[s], self.tile2id[t])
129                 for (s, t) in [
130                     ("a", "A"),
131                     ("A", "b"),
132                     ("b", "B"),
133                     ("B", "c"),
134                     ("c", "C"),
135                     ("C", "-"),
136                 ]
137             ]
138         )
139
140         self.object_reward = dict(
141             [
142                 (self.tile2id[t], r)
143                 for (t, r) in [
144                     ("a", 0),
145                     ("A", 1),
146                     ("b", 0),
147                     ("B", 1),
148                     ("c", 0),
149                     ("C", 10),
150                 ]
151             ]
152         )
153
154         self.accessible_object_to_inventory = dict(
155             [
156                 (self.tile2id[s], self.tile2id[t])
157                 for (s, t) in [
158                     ("a", " "),
159                     ("A", "a"),
160                     ("b", " "),
161                     ("B", "b"),
162                     ("c", " "),
163                     ("C", "c"),
164                     ("-", " "),
165                 ]
166             ]
167         )
168
169     def reset(self, nb_agents):
170         self.worlds = self.create_worlds(
171             nb_agents, self.world_height, self.world_width, self.nb_walls, self.margin
172         ).to(self.device)
173         self.life_level_in_100th = torch.full(
174             (nb_agents,), self.life_level_max * 100 + 99, device=self.device
175         )
176         self.accessible_object = torch.full(
177             (nb_agents,), self.tile2id["a"], device=self.device
178         )
179
180     def create_mazes(self, nb, height, width, nb_walls):
181         m = torch.zeros(nb, height, width, dtype=torch.int64, device=self.device)
182         m[:, 0, :] = 1
183         m[:, -1, :] = 1
184         m[:, :, 0] = 1
185         m[:, :, -1] = 1
186
187         i = torch.arange(height, device=m.device)[None, :, None]
188         j = torch.arange(width, device=m.device)[None, None, :]
189
190         for _ in range(nb_walls):
191             q = torch.rand(m.size(), device=m.device).flatten(1).sort(-1).indices * (
192                 (1 - m) * (i % 2 == 0) * (j % 2 == 0)
193             ).flatten(1)
194             q = (q == q.max(dim=-1, keepdim=True).values).long().view(m.size())
195             a = q[:, None].expand(-1, 4, -1, -1).clone()
196             a[:, 0, :-1, :] += q[:, 1:, :]
197             a[:, 0, :-2, :] += q[:, 2:, :]
198             a[:, 1, 1:, :] += q[:, :-1, :]
199             a[:, 1, 2:, :] += q[:, :-2, :]
200             a[:, 2, :, :-1] += q[:, :, 1:]
201             a[:, 2, :, :-2] += q[:, :, 2:]
202             a[:, 3, :, 1:] += q[:, :, :-1]
203             a[:, 3, :, 2:] += q[:, :, :-2]
204             a = a[
205                 torch.arange(a.size(0), device=a.device),
206                 torch.randint(4, (a.size(0),), device=a.device),
207             ]
208             m = (m + q + a).clamp(max=1)
209
210         return m
211
212     def create_worlds(self, nb, height, width, nb_walls, margin=2):
213         margin -= 1  # The maze adds a wall all around
214         m = self.create_mazes(nb, height - 2 * margin, width - 2 * margin, nb_walls)
215         q = m.flatten(1)
216         z = "@aAbBcC$$$$$"  # What to add to the maze
217         u = torch.rand(q.size(), device=q.device) * (1 - q)
218         r = u.sort(dim=-1, descending=True).indices[:, : len(z)]
219
220         q *= self.tile2id["#"]
221         q[
222             torch.arange(q.size(0), device=q.device)[:, None].expand_as(r), r
223         ] = torch.tensor([self.tile2id[c] for c in z], device=q.device)[None, :]
224
225         if margin > 0:
226             r = m.new_full(
227                 (m.size(0), m.size(1) + margin * 2, m.size(2) + margin * 2),
228                 self.tile2id["+"],
229             )
230             r[:, margin:-margin, margin:-margin] = m
231             m = r
232         return m
233
234     def nb_actions(self):
235         return 5
236
237     def action2str(self, n):
238         if n >= 0 and n < 5:
239             return "XNESW"[n]
240         else:
241             return "?"
242
243     def nb_view_tiles(self):
244         return len(self.tiles)
245
246     def min_max_reward(self):
247         return (
248             min(4 * self.reward_per_hit, self.reward_death),
249             max(self.object_reward.values()),
250         )
251
252     def step(self, actions):
253         a = (self.worlds == self.tile2id["@"]).nonzero()
254         self.worlds[a[:, 0], a[:, 1], a[:, 2]] = self.tile2id[" "]
255         s = torch.tensor([[0, 0], [-1, 0], [0, 1], [1, 0], [0, -1]], device=self.device)
256         b = a.clone()
257         b[:, 1:] = b[:, 1:] + s[actions[b[:, 0]]]
258         # position is empty
259         o = (self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.tile2id[" "]).long()
260         # or it is the next accessible object
261         q = (
262             self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.accessible_object[b[:, 0]]
263         ).long()
264         o = (o + q).clamp(max=1)[:, None]
265         b = (1 - o) * a + o * b
266         self.worlds[b[:, 0], b[:, 1], b[:, 2]] = self.tile2id["@"]
267
268         qq = q
269         q = qq.new_zeros((self.worlds.size(0),) + qq.size()[1:])
270         q[b[:, 0]] = qq
271
272         nb_hits = self.monster_moves()
273
274         alive_before = self.life_level_in_100th > 99
275         self.life_level_in_100th[alive_before] = (
276             self.life_level_in_100th[alive_before]
277             + self.life_level_gain_100th
278             - nb_hits[alive_before] * 100
279         ).clamp(max=self.life_level_max * 100 + 99)
280         alive_after = self.life_level_in_100th > 99
281         self.worlds[torch.logical_not(alive_after)] = self.tile2id["#"]
282         reward = nb_hits * self.reward_per_hit
283
284         for i in range(q.size(0)):
285             if q[i] == 1:
286                 reward[i] += self.object_reward[self.accessible_object[i].item()]
287                 self.accessible_object[i] = self.next_object[
288                     self.accessible_object[i].item()
289                 ]
290
291         reward = (
292             alive_after.long() * reward
293             + alive_before.long() * (1 - alive_after.long()) * self.reward_death
294         )
295         inventory = torch.tensor(
296             [
297                 self.accessible_object_to_inventory[s.item()]
298                 for s in self.accessible_object
299             ]
300         )
301
302         self.life_level_in_100th = (
303             self.life_level_in_100th
304             * (self.accessible_object != self.tile2id["-"]).long()
305         )
306
307         reward[torch.logical_not(alive_before)] = 0
308         return reward, inventory, self.life_level_in_100th // 100
309
310     def monster_moves(self):
311         # Current positions of the monsters
312         m = (self.worlds == self.tile2id["$"]).long().flatten(1)
313
314         # Total number of monsters
315         n = m.sum(-1).max()
316
317         # Create a tensor with one channel per monster
318         r = (
319             (torch.rand(m.size(), device=m.device) * m)
320             .sort(dim=-1, descending=True)
321             .indices[:, :n]
322         )
323         o = m.new_zeros((m.size(0), n) + m.size()[1:])
324         i = torch.arange(o.size(0), device=o.device)[:, None].expand(-1, o.size(1))
325         j = torch.arange(o.size(1), device=o.device)[None, :].expand(o.size(0), -1)
326         o[i, j, r] = 1
327         o = o * m[:, None]
328
329         # Create the tensor of possible motions
330         o = o.view((self.worlds.size(0), n) + self.worlds.flatten(1).size()[1:])
331         move_kernel = torch.tensor(
332             [[[[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]]]], device=o.device
333         )
334
335         p = (
336             conv2d(
337                 o.view(
338                     o.size(0) * o.size(1), 1, self.worlds.size(-2), self.worlds.size(-1)
339                 ).float(),
340                 move_kernel,
341                 padding=1,
342             ).view(o.size())
343             == 1.0
344         ).long()
345
346         # Let's do the moves per say
347         i = torch.arange(self.worlds.size(0), device=self.worlds.device)[
348             :, None
349         ].expand_as(r)
350
351         for n in range(p.size(1)):
352             u = o[:, n].sort(dim=-1, descending=True).indices[:, :1]
353             q = p[:, n] * (self.worlds.flatten(1) == self.tile2id[" "]) + o[:, n]
354             r = (
355                 (q * torch.rand(q.size(), device=q.device))
356                 .sort(dim=-1, descending=True)
357                 .indices[:, :1]
358             )
359             self.worlds.flatten(1)[i, u] = self.tile2id[" "]
360             self.worlds.flatten(1)[i, r] = self.tile2id["$"]
361
362         nb_hits = (
363             (
364                 conv2d(
365                     (self.worlds == self.tile2id["$"]).float()[:, None],
366                     move_kernel,
367                     padding=1,
368                 )
369                 .long()
370                 .squeeze(1)
371                 * (self.worlds == self.tile2id["@"]).long()
372             )
373             .flatten(1)
374             .sum(-1)
375         )
376
377         return nb_hits
378
379     def views(self):
380         i_height, i_width = (
381             self.view_height - 2 * self.margin,
382             self.view_width - 2 * self.margin,
383         )
384         a = (self.worlds == self.tile2id["@"]).nonzero()
385         y = i_height * ((a[:, 1] - self.margin) // i_height)
386         x = i_width * ((a[:, 2] - self.margin) // i_width)
387         n = a[:, 0][:, None, None].expand(-1, self.view_height, self.view_width)
388         i = (
389             torch.arange(self.view_height, device=a.device)[None, :, None]
390             + y[:, None, None]
391         ).expand_as(n)
392         j = (
393             torch.arange(self.view_width, device=a.device)[None, None, :]
394             + x[:, None, None]
395         ).expand_as(n)
396         v = self.worlds.new_full(
397             (self.worlds.size(0), self.view_height + 1, self.view_width),
398             self.tile2id["#"],
399         )
400
401         v[a[:, 0], : self.view_height] = self.worlds[n, i, j]
402
403         v[:, self.view_height] = self.tile2id["-"]
404         v[:, self.view_height, 0] = self.tile2id["0"] + (
405             self.life_level_in_100th // 100
406         ).clamp(min=0, max=self.life_level_max)
407         v[:, self.view_height, 1] = torch.tensor(
408             [
409                 self.accessible_object_to_inventory[o.item()]
410                 for o in self.accessible_object
411             ],
412             device=v.device,
413         )
414
415         return v
416
417     def seq2tilepic(self, t, width):
418         def tile(n):
419             n = n.item()
420             if n in self.id2tile:
421                 return self.id2tile[n]
422             else:
423                 return "?"
424
425         if t.dim() == 2:
426             return [self.seq2tilepic(r, width) for r in t]
427
428         t = t.reshape(-1, width)
429
430         t = ["".join([tile(n) for n in r]) for r in t]
431
432         return t
433
434
435 ######################################################################
436
437 if __name__ == "__main__":
438     import os, time, sys
439
440     device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
441
442     # char_conv = lambda x: x
443     char_conv = to_unicode
444
445     # nb_agents, nb_iter, display = 1000, 1000, False
446     # ansi_term = False
447
448     nb_agents, nb_iter, display = 4, 10000, True
449     ansi_term = True
450
451     if ansi_term:
452         char_conv = lambda x: to_ansi(to_unicode(x))
453
454     start_time = time.perf_counter()
455     engine = PicroCrafterEngine(
456         world_height=27,
457         world_width=27,
458         nb_walls=35,
459         view_height=9,
460         view_width=9,
461         margin=4,
462         device=device,
463     )
464
465     engine.reset(nb_agents)
466
467     print(f"timing {nb_agents/(time.perf_counter() - start_time)} init per s")
468
469     start_time = time.perf_counter()
470
471     stop = 0
472     for k in range(nb_iter):
473         if display:
474             if ansi_term:
475                 to_print = "\u001bc"
476                 # print("\u001b[2J")
477             else:
478                 to_print = ""
479                 os.system("clear")
480
481             l = engine.seq2tilepic(engine.worlds.flatten(1), width=engine.world_width)
482
483             to_print += char_conv(fusion_multi_lines(l)) + "\n\n"
484
485         views = engine.views()
486         action = torch.randint(engine.nb_actions(), (nb_agents,), device=device)
487
488         rewards, inventories, life_levels = engine.step(action)
489
490         if display:
491             l = engine.seq2tilepic(views.flatten(1), engine.view_width)
492             l = [
493                 v + [f"{engine.action2str(a.item())}/{r: 3d}"]
494                 for (v, a, r) in zip(l, action, rewards)
495             ]
496
497             to_print += (
498                 char_conv(fusion_multi_lines(l, width_min=engine.world_width)) + "\n"
499             )
500
501             print(to_print)
502             sys.stdout.flush()
503             time.sleep(0.25)
504
505         if (life_levels > 0).long().sum() == 0:
506             stop += 1
507             if stop == 10:
508                 break
509
510     print(f"timing {(nb_agents*k)/(time.perf_counter() - start_time)} iteration per s")