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 agent "@" moves in a maze-like grid with random walls "#". There
26 # are five actions: move NESW or do not move.
27 #
28 # There are monsters "$" moving randomly. The agent gets hit by every
29 # monster present in one of the 4 direct neighborhoods at the end of
30 # the moves, each hit results in a rewards of -1.
31 #
32 # The agent starts with 5 life points, each hit costs it 1pt, when it
33 # gets to 0 it dies, gets a reward of -10 and the episode is over. At
34 # every step it recovers 1/20th of a life point, with a maximum of
35 # 5pt.
36 #
37 # The agent can carry "keys" ("a", "b", "c") that open "vaults" ("A",
38 # "B", "C"). They keys can only be used in sequence: initially the
39 # agent can move only to free spaces, or to the "a", in which case it
40 # now carries it, and can move to free spaces or the "A". When it
41 # moves to the "A", it gets a reward and loses the "a", but can now
42 # move to the "b", etc. Rewards are 1 for "A" and "B" and 10 for "C".
43
44 ######################################################################
45
46 import torch
47
48 from torch.nn.functional import conv2d
49
50 ######################################################################
51
52
53 class PicroCrafterEngine:
54     def __init__(
55         self,
56         world_height=27,
57         world_width=27,
58         nb_walls=27,
59         margin=2,
60         view_height=5,
61         view_width=5,
62         device=torch.device("cpu"),
63     ):
64         assert (world_height - 2 * margin) % (view_height - 2 * margin) == 0
65         assert (world_width - 2 * margin) % (view_width - 2 * margin) == 0
66
67         self.device = device
68
69         self.world_height = world_height
70         self.world_width = world_width
71         self.margin = margin
72         self.view_height = view_height
73         self.view_width = view_width
74         self.nb_walls = nb_walls
75         self.life_level_max = 5
76         self.life_level_gain_100th = 5
77         self.reward_per_hit = -1
78         self.reward_death = -10
79
80         self.tokens = " +#@$aAbBcC"
81         self.token2id = dict([(t, n) for n, t in enumerate(self.tokens)])
82         self.id2token = dict([(n, t) for n, t in enumerate(self.tokens)])
83
84         self.next_object = dict(
85             [
86                 (self.token2id[s], self.token2id[t])
87                 for (s, t) in [
88                     ("a", "A"),
89                     ("A", "b"),
90                     ("b", "B"),
91                     ("B", "c"),
92                     ("c", "C"),
93                 ]
94             ]
95         )
96
97         self.object_reward = dict(
98             [
99                 (self.token2id[t], r)
100                 for (t, r) in [
101                     ("a", 0),
102                     ("A", 1),
103                     ("b", 0),
104                     ("B", 1),
105                     ("c", 0),
106                     ("C", 10),
107                 ]
108             ]
109         )
110
111         self.acessible_object_to_inventory = dict(
112             [
113                 (self.token2id[s], self.token2id[t])
114                 for (s, t) in [
115                     ("a", " "),
116                     ("A", "a"),
117                     ("b", " "),
118                     ("B", "b"),
119                     ("c", " "),
120                     ("C", " "),
121                 ]
122             ]
123         )
124
125     def reset(self, nb_agents):
126         self.worlds = self.create_worlds(
127             nb_agents, self.world_height, self.world_width, self.nb_walls, self.margin
128         ).to(self.device)
129         self.life_level_in_100th = torch.full(
130             (nb_agents,), self.life_level_max * 100, device=self.device
131         )
132         self.accessible_object = torch.full(
133             (nb_agents,), self.token2id["a"], device=self.device
134         )
135
136     def create_mazes(self, nb, height, width, nb_walls):
137         m = torch.zeros(nb, height, width, dtype=torch.int64, device=self.device)
138         m[:, 0, :] = 1
139         m[:, -1, :] = 1
140         m[:, :, 0] = 1
141         m[:, :, -1] = 1
142
143         i = torch.arange(height, device=m.device)[None, :, None]
144         j = torch.arange(width, device=m.device)[None, None, :]
145
146         for _ in range(nb_walls):
147             q = torch.rand(m.size(), device=m.device).flatten(1).sort(-1).indices * (
148                 (1 - m) * (i % 2 == 0) * (j % 2 == 0)
149             ).flatten(1)
150             q = (q == q.max(dim=-1, keepdim=True).values).long().view(m.size())
151             a = q[:, None].expand(-1, 4, -1, -1).clone()
152             a[:, 0, :-1, :] += q[:, 1:, :]
153             a[:, 0, :-2, :] += q[:, 2:, :]
154             a[:, 1, 1:, :] += q[:, :-1, :]
155             a[:, 1, 2:, :] += q[:, :-2, :]
156             a[:, 2, :, :-1] += q[:, :, 1:]
157             a[:, 2, :, :-2] += q[:, :, 2:]
158             a[:, 3, :, 1:] += q[:, :, :-1]
159             a[:, 3, :, 2:] += q[:, :, :-2]
160             a = a[
161                 torch.arange(a.size(0), device=a.device),
162                 torch.randint(4, (a.size(0),), device=a.device),
163             ]
164             m = (m + q + a).clamp(max=1)
165
166         return m
167
168     def create_worlds(self, nb, height, width, nb_walls, margin=2):
169         margin -= 1  # The maze adds a wall all around
170         m = self.create_mazes(nb, height - 2 * margin, width - 2 * margin, nb_walls)
171         q = m.flatten(1)
172         z = "@aAbBcC$$$$$"  # What to add to the maze
173         u = torch.rand(q.size(), device=q.device) * (1 - q)
174         r = u.sort(dim=-1, descending=True).indices[:, : len(z)]
175
176         q *= self.token2id["#"]
177         q[
178             torch.arange(q.size(0), device=q.device)[:, None].expand_as(r), r
179         ] = torch.tensor([self.token2id[c] for c in z], device=q.device)[None, :]
180
181         if margin > 0:
182             r = m.new_full(
183                 (m.size(0), m.size(1) + margin * 2, m.size(2) + margin * 2),
184                 self.token2id["+"],
185             )
186             r[:, margin:-margin, margin:-margin] = m
187             m = r
188         return m
189
190     def nb_actions(self):
191         return 5
192
193     def nb_view_tokens(self):
194         return len(self.tokens)
195
196     def min_max_reward(self):
197         return (
198             min(4 * self.reward_per_hit, self.reward_death),
199             max(self.object_reward.values()),
200         )
201
202     def step(self, actions):
203         a = (self.worlds == self.token2id["@"]).nonzero()
204         self.worlds[a[:, 0], a[:, 1], a[:, 2]] = self.token2id[" "]
205         s = torch.tensor([[0, 0], [-1, 0], [0, 1], [1, 0], [0, -1]], device=self.device)
206         b = a.clone()
207         b[:, 1:] = b[:, 1:] + s[actions[b[:, 0]]]
208
209         # position is empty
210         o = (self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.token2id[" "]).long()
211         # or it is the next accessible object
212         q = (
213             self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.accessible_object[b[:, 0]]
214         ).long()
215         o = (o + q).clamp(max=1)[:, None]
216         b = (1 - o) * a + o * b
217         self.worlds[b[:, 0], b[:, 1], b[:, 2]] = self.token2id["@"]
218
219         nb_hits = self.monster_moves()
220
221         alive_before = self.life_level_in_100th > 0
222         self.life_level_in_100th[alive_before] = (
223             self.life_level_in_100th[alive_before]
224             + self.life_level_gain_100th
225             - nb_hits[alive_before] * 100
226         ).clamp(max=self.life_level_max * 100)
227         alive_after = self.life_level_in_100th > 0
228         self.worlds[torch.logical_not(alive_after)] = self.token2id["#"]
229         reward = nb_hits * self.reward_per_hit
230
231         for i in range(q.size(0)):
232             if q[i] == 1:
233                 reward[i] += self.object_reward[self.accessible_object[i].item()]
234                 self.accessible_object[i] = self.next_object[
235                     self.accessible_object[i].item()
236                 ]
237
238         reward = (
239             reward + alive_before.long() * (1 - alive_after.long()) * self.reward_death
240         )
241         inventory = torch.tensor(
242             [
243                 self.acessible_object_to_inventory[s.item()]
244                 for s in self.accessible_object
245             ]
246         )
247
248         reward[torch.logical_not(alive_before)] = 0
249         return reward, inventory, self.life_level_in_100th // 100
250
251     def monster_moves(self):
252         # Current positions of the monsters
253         m = (self.worlds == self.token2id["$"]).long().flatten(1)
254
255         # Total number of monsters
256         n = m.sum(-1).max()
257
258         # Create a tensor with one channel per monster
259         r = (
260             (torch.rand(m.size(), device=m.device) * m)
261             .sort(dim=-1, descending=True)
262             .indices[:, :n]
263         )
264         o = m.new_zeros((m.size(0), n) + m.size()[1:])
265         i = torch.arange(o.size(0), device=o.device)[:, None].expand(-1, o.size(1))
266         j = torch.arange(o.size(1), device=o.device)[None, :].expand(o.size(0), -1)
267         o[i, j, r] = 1
268         o = o * m[:, None]
269
270         # Create the tensor of possible motions
271         o = o.view((self.worlds.size(0), n) + self.worlds.flatten(1).size()[1:])
272         move_kernel = torch.tensor(
273             [[[[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]]]], device=o.device
274         )
275
276         p = (
277             conv2d(
278                 o.view(
279                     o.size(0) * o.size(1), 1, self.worlds.size(-2), self.worlds.size(-1)
280                 ).float(),
281                 move_kernel,
282                 padding=1,
283             ).view(o.size())
284             == 1.0
285         ).long()
286
287         # Let's do the moves per say
288         i = torch.arange(self.worlds.size(0), device=self.worlds.device)[
289             :, None
290         ].expand_as(r)
291
292         for n in range(p.size(1)):
293             u = o[:, n].sort(dim=-1, descending=True).indices[:, :1]
294             q = p[:, n] * (self.worlds.flatten(1) == self.token2id[" "]) + o[:, n]
295             r = (
296                 (q * torch.rand(q.size(), device=q.device))
297                 .sort(dim=-1, descending=True)
298                 .indices[:, :1]
299             )
300             self.worlds.flatten(1)[i, u] = self.token2id[" "]
301             self.worlds.flatten(1)[i, r] = self.token2id["$"]
302
303         nb_hits = (
304             (
305                 conv2d(
306                     (self.worlds == self.token2id["$"]).float()[:, None],
307                     move_kernel,
308                     padding=1,
309                 )
310                 .long()
311                 .squeeze(1)
312                 * (self.worlds == self.token2id["@"]).long()
313             )
314             .flatten(1)
315             .sum(-1)
316         )
317
318         return nb_hits
319
320     def views(self):
321         i_height, i_width = (
322             self.view_height - 2 * self.margin,
323             self.view_width - 2 * self.margin,
324         )
325         a = (self.worlds == self.token2id["@"]).nonzero()
326         y = i_height * ((a[:, 1] - self.margin) // i_height)
327         x = i_width * ((a[:, 2] - self.margin) // i_width)
328         n = a[:, 0][:, None, None].expand(-1, self.view_height, self.view_width)
329         i = (
330             torch.arange(self.view_height, device=a.device)[None, :, None]
331             + y[:, None, None]
332         ).expand_as(n)
333         j = (
334             torch.arange(self.view_width, device=a.device)[None, None, :]
335             + x[:, None, None]
336         ).expand_as(n)
337         v = self.worlds.new_full(
338             (self.worlds.size(0), self.view_height, self.view_width), self.token2id["#"]
339         )
340
341         v[a[:, 0]] = self.worlds[n, i, j]
342
343         return v
344
345     def print_worlds(
346         self, src=None, comments=[], width=None, printer=print, ansi_term=False
347     ):
348         if src is None:
349             src = self.worlds
350
351         if width is None:
352             width = src.size(2)
353
354         def token(n):
355             n = n.item()
356             if n in self.id2token:
357                 return self.id2token[n]
358             else:
359                 return "?"
360
361         for k in range(src.size(1)):
362             s = ["".join([token(n) for n in m[k]]) for m in src]
363             s = [r + " " * (width - len(r)) for r in s]
364             if ansi_term:
365
366                 def colorize(x):
367                     for u, c in [("#", 40), ("$", 31), ("@", 32)] + [
368                         (x, 36) for x in "aAbBcC"
369                     ]:
370                         x = x.replace(u, f"\u001b[{c}m{u}\u001b[0m")
371                     return x
372
373                 s = [colorize(x) for x in s]
374             printer(" | ".join(s))
375
376         s = [c + " " * (width - len(c)) for c in comments]
377         printer(" | ".join(s))
378
379
380 ######################################################################
381
382 if __name__ == "__main__":
383     import os, time
384
385     device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
386
387     ansi_term = False
388     # nb_agents, nb_iter, display = 1000, 100, False
389     nb_agents, nb_iter, display = 3, 10000, True
390     ansi_term = True
391
392     start_time = time.perf_counter()
393     engine = PicroCrafterEngine(
394         world_height=27,
395         world_width=27,
396         nb_walls=35,
397         view_height=9,
398         view_width=9,
399         margin=4,
400         device=device,
401     )
402
403     engine.reset(nb_agents)
404
405     print(f"timing {nb_agents/(time.perf_counter() - start_time)} init per s")
406
407     start_time = time.perf_counter()
408
409     for k in range(nb_iter):
410         action = torch.randint(engine.nb_actions(), (nb_agents,), device=device)
411         rewards, inventories, life_levels = engine.step(
412             torch.randint(engine.nb_actions(), (nb_agents,), device=device)
413         )
414
415         if display:
416             os.system("clear")
417             engine.print_worlds(
418                 ansi_term=ansi_term,
419             )
420             print()
421             engine.print_worlds(
422                 src=engine.views(),
423                 comments=[
424                     f"L{p}I{engine.id2token[s.item()]}R{r}"
425                     for p, s, r in zip(life_levels, inventories, rewards)
426                 ],
427                 width=engine.world_width,
428                 ansi_term=ansi_term,
429             )
430             time.sleep(0.5)
431
432         if (life_levels > 0).long().sum() == 0:
433             break
434
435     print(
436         f"timing {(nb_agents*nb_iter)/(time.perf_counter() - start_time)} iteration per s"
437     )