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         world_margin=2,
100         view_height=5,
101         view_width=5,
102         device=torch.device("cpu"),
103     ):
104         assert (world_height - 2 * world_margin) % (view_height - 2 * world_margin) == 0
105         assert (world_width - 2 * world_margin) % (view_width - 2 * world_margin) == 0
106
107         self.device = device
108
109         self.world_height = world_height
110         self.world_width = world_width
111         self.world_margin = world_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,
172             self.world_height,
173             self.world_width,
174             self.nb_walls,
175             self.world_margin,
176         ).to(self.device)
177         self.life_level_in_100th = torch.full(
178             (nb_agents,), self.life_level_max * 100 + 99, device=self.device
179         )
180         self.accessible_object = torch.full(
181             (nb_agents,), self.tile2id["a"], device=self.device
182         )
183
184     def create_mazes(self, nb, height, width, nb_walls):
185         m = torch.zeros(nb, height, width, dtype=torch.int64, device=self.device)
186         m[:, 0, :] = 1
187         m[:, -1, :] = 1
188         m[:, :, 0] = 1
189         m[:, :, -1] = 1
190
191         i = torch.arange(height, device=m.device)[None, :, None]
192         j = torch.arange(width, device=m.device)[None, None, :]
193
194         for _ in range(nb_walls):
195             q = torch.rand(m.size(), device=m.device).flatten(1).sort(-1).indices * (
196                 (1 - m) * (i % 2 == 0) * (j % 2 == 0)
197             ).flatten(1)
198             q = (q == q.max(dim=-1, keepdim=True).values).long().view(m.size())
199             a = q[:, None].expand(-1, 4, -1, -1).clone()
200             a[:, 0, :-1, :] += q[:, 1:, :]
201             a[:, 0, :-2, :] += q[:, 2:, :]
202             a[:, 1, 1:, :] += q[:, :-1, :]
203             a[:, 1, 2:, :] += q[:, :-2, :]
204             a[:, 2, :, :-1] += q[:, :, 1:]
205             a[:, 2, :, :-2] += q[:, :, 2:]
206             a[:, 3, :, 1:] += q[:, :, :-1]
207             a[:, 3, :, 2:] += q[:, :, :-2]
208             a = a[
209                 torch.arange(a.size(0), device=a.device),
210                 torch.randint(4, (a.size(0),), device=a.device),
211             ]
212             m = (m + q + a).clamp(max=1)
213
214         return m
215
216     def create_worlds(self, nb, height, width, nb_walls, world_margin=2):
217         world_margin -= 1  # The maze adds a wall all around
218         m = self.create_mazes(
219             nb, height - 2 * world_margin, width - 2 * world_margin, nb_walls
220         )
221         q = m.flatten(1)
222         z = "@aAbBcC$$$$$"  # What to add to the maze
223         u = torch.rand(q.size(), device=q.device) * (1 - q)
224         r = u.sort(dim=-1, descending=True).indices[:, : len(z)]
225
226         q *= self.tile2id["#"]
227         q[
228             torch.arange(q.size(0), device=q.device)[:, None].expand_as(r), r
229         ] = torch.tensor([self.tile2id[c] for c in z], device=q.device)[None, :]
230
231         if world_margin > 0:
232             r = m.new_full(
233                 (m.size(0), m.size(1) + world_margin * 2, m.size(2) + world_margin * 2),
234                 self.tile2id["+"],
235             )
236             r[:, world_margin:-world_margin, world_margin:-world_margin] = m
237             m = r
238         return m
239
240     def nb_actions(self):
241         return 5
242
243     def action2str(self, n):
244         if n >= 0 and n < 5:
245             return "XNESW"[n]
246         else:
247             return "?"
248
249     def nb_view_tiles(self):
250         return len(self.tiles)
251
252     def min_max_reward(self):
253         return (
254             min(4 * self.reward_per_hit, self.reward_death),
255             max(self.object_reward.values()),
256         )
257
258     def step(self, actions):
259         a = (self.worlds == self.tile2id["@"]).nonzero()
260         self.worlds[a[:, 0], a[:, 1], a[:, 2]] = self.tile2id[" "]
261         s = torch.tensor([[0, 0], [-1, 0], [0, 1], [1, 0], [0, -1]], device=self.device)
262         b = a.clone()
263         b[:, 1:] = b[:, 1:] + s[actions[b[:, 0]]]
264         # position is empty
265         o = (self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.tile2id[" "]).long()
266         # or it is the next accessible object
267         q = (
268             self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.accessible_object[b[:, 0]]
269         ).long()
270         o = (o + q).clamp(max=1)[:, None]
271         b = (1 - o) * a + o * b
272         self.worlds[b[:, 0], b[:, 1], b[:, 2]] = self.tile2id["@"]
273
274         qq = q
275         q = qq.new_zeros((self.worlds.size(0),) + qq.size()[1:])
276         q[b[:, 0]] = qq
277
278         nb_hits = self.monster_moves()
279
280         alive_before = self.life_level_in_100th > 99
281         self.life_level_in_100th[alive_before] = (
282             self.life_level_in_100th[alive_before]
283             + self.life_level_gain_100th
284             - nb_hits[alive_before] * 100
285         ).clamp(max=self.life_level_max * 100 + 99)
286         alive_after = self.life_level_in_100th > 99
287         self.worlds[torch.logical_not(alive_after)] = self.tile2id["#"]
288         reward = nb_hits * self.reward_per_hit
289
290         for i in range(q.size(0)):
291             if q[i] == 1:
292                 reward[i] += self.object_reward[self.accessible_object[i].item()]
293                 self.accessible_object[i] = self.next_object[
294                     self.accessible_object[i].item()
295                 ]
296
297         reward = (
298             alive_after.long() * reward
299             + alive_before.long() * (1 - alive_after.long()) * self.reward_death
300         )
301         inventory = torch.tensor(
302             [
303                 self.accessible_object_to_inventory[s.item()]
304                 for s in self.accessible_object
305             ]
306         )
307
308         self.life_level_in_100th = (
309             self.life_level_in_100th
310             * (self.accessible_object != self.tile2id["-"]).long()
311         )
312
313         reward[torch.logical_not(alive_before)] = 0
314         return reward, inventory, self.life_level_in_100th // 100
315
316     def monster_moves(self):
317         # Current positions of the monsters
318         m = (self.worlds == self.tile2id["$"]).long().flatten(1)
319
320         # Total number of monsters
321         n = m.sum(-1).max()
322
323         # Create a tensor with one channel per monster
324         r = (
325             (torch.rand(m.size(), device=m.device) * m)
326             .sort(dim=-1, descending=True)
327             .indices[:, :n]
328         )
329         o = m.new_zeros((m.size(0), n) + m.size()[1:])
330         i = torch.arange(o.size(0), device=o.device)[:, None].expand(-1, o.size(1))
331         j = torch.arange(o.size(1), device=o.device)[None, :].expand(o.size(0), -1)
332         o[i, j, r] = 1
333         o = o * m[:, None]
334
335         # Create the tensor of possible motions
336         o = o.view((self.worlds.size(0), n) + self.worlds.flatten(1).size()[1:])
337         move_kernel = torch.tensor(
338             [[[[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]]]], device=o.device
339         )
340
341         p = (
342             conv2d(
343                 o.view(
344                     o.size(0) * o.size(1), 1, self.worlds.size(-2), self.worlds.size(-1)
345                 ).float(),
346                 move_kernel,
347                 padding=1,
348             ).view(o.size())
349             == 1.0
350         ).long()
351
352         # Let's do the moves per say
353         i = torch.arange(self.worlds.size(0), device=self.worlds.device)[
354             :, None
355         ].expand_as(r)
356
357         for n in range(p.size(1)):
358             u = o[:, n].sort(dim=-1, descending=True).indices[:, :1]
359             q = p[:, n] * (self.worlds.flatten(1) == self.tile2id[" "]) + o[:, n]
360             r = (
361                 (q * torch.rand(q.size(), device=q.device))
362                 .sort(dim=-1, descending=True)
363                 .indices[:, :1]
364             )
365             self.worlds.flatten(1)[i, u] = self.tile2id[" "]
366             self.worlds.flatten(1)[i, r] = self.tile2id["$"]
367
368         nb_hits = (
369             (
370                 conv2d(
371                     (self.worlds == self.tile2id["$"]).float()[:, None],
372                     move_kernel,
373                     padding=1,
374                 )
375                 .long()
376                 .squeeze(1)
377                 * (self.worlds == self.tile2id["@"]).long()
378             )
379             .flatten(1)
380             .sum(-1)
381         )
382
383         return nb_hits
384
385     def views(self):
386         i_height, i_width = (
387             self.view_height - 2 * self.world_margin,
388             self.view_width - 2 * self.world_margin,
389         )
390         a = (self.worlds == self.tile2id["@"]).nonzero()
391         y = i_height * ((a[:, 1] - self.world_margin) // i_height)
392         x = i_width * ((a[:, 2] - self.world_margin) // i_width)
393         n = a[:, 0][:, None, None].expand(-1, self.view_height, self.view_width)
394         i = (
395             torch.arange(self.view_height, device=a.device)[None, :, None]
396             + y[:, None, None]
397         ).expand_as(n)
398         j = (
399             torch.arange(self.view_width, device=a.device)[None, None, :]
400             + x[:, None, None]
401         ).expand_as(n)
402         v = self.worlds.new_full(
403             (self.worlds.size(0), self.view_height + 1, self.view_width),
404             self.tile2id["#"],
405         )
406
407         v[a[:, 0], : self.view_height] = self.worlds[n, i, j]
408
409         v[:, self.view_height] = self.tile2id["-"]
410         v[:, self.view_height, 0] = self.tile2id["0"] + (
411             self.life_level_in_100th // 100
412         ).clamp(min=0, max=self.life_level_max)
413         v[:, self.view_height, 1] = torch.tensor(
414             [
415                 self.accessible_object_to_inventory[o.item()]
416                 for o in self.accessible_object
417             ],
418             device=v.device,
419         )
420
421         return v
422
423     def seq2tiles(self, t, width=None):
424         def tile(n):
425             n = n.item()
426             if n in self.id2tile:
427                 return self.id2tile[n]
428             else:
429                 return "?"
430
431         if t.dim() == 2:
432             return [self.seq2tiles(r, width) for r in t]
433
434         if width is None:
435             width = self.view_width
436
437         t = t.reshape(-1, width)
438
439         t = ["".join([tile(n) for n in r]) for r in t]
440
441         return t
442
443
444 ######################################################################
445
446 if __name__ == "__main__":
447     import os, time, sys
448
449     device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
450
451     # char_conv = lambda x: x
452     char_conv = to_unicode
453
454     # nb_agents, nb_iter, display = 1000, 1000, False
455     # ansi_term = False
456
457     nb_agents, nb_iter, display = 4, 10000, True
458     ansi_term = True
459
460     if ansi_term:
461         char_conv = lambda x: to_ansi(to_unicode(x))
462
463     start_time = time.perf_counter()
464     engine = PicroCrafterEngine(
465         world_height=27,
466         world_width=27,
467         nb_walls=35,
468         view_height=9,
469         view_width=9,
470         world_margin=4,
471         device=device,
472     )
473
474     engine.reset(nb_agents)
475
476     print(f"timing {nb_agents/(time.perf_counter() - start_time)} init per s")
477
478     start_time = time.perf_counter()
479
480     stop = 0
481     for k in range(nb_iter):
482         if display:
483             if ansi_term:
484                 to_print = "\u001bc"
485                 # print("\u001b[2J")
486             else:
487                 to_print = ""
488                 os.system("clear")
489
490             l = engine.seq2tiles(engine.worlds.flatten(1), width=engine.world_width)
491
492             to_print += char_conv(fusion_multi_lines(l)) + "\n\n"
493
494         views = engine.views()
495         action = torch.randint(engine.nb_actions(), (nb_agents,), device=device)
496
497         rewards, inventories, life_levels = engine.step(action)
498
499         if display:
500             l = engine.seq2tiles(views.flatten(1))
501             l = [
502                 v + [f"{engine.action2str(a.item())}/{r: 3d}"]
503                 for (v, a, r) in zip(l, action, rewards)
504             ]
505
506             to_print += (
507                 char_conv(fusion_multi_lines(l, width_min=engine.world_width)) + "\n"
508             )
509
510             print(to_print)
511             sys.stdout.flush()
512             time.sleep(0.25)
513
514         if (life_levels > 0).long().sum() == 0:
515             stop += 1
516             if stop == 10:
517                 break
518
519     print(f"timing {(nb_agents*k)/(time.perf_counter() - start_time)} iteration per s")