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. #
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. #
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/>. #
16 # Written by and Copyright (C) Francois Fleuret #
17 # Contact <francois.fleuret@unige.ch> for comments & bug reports #
18 #########################################################################
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
25 # The agent "@" moves in a maze-like grid with random walls "#". There
26 # are five actions: move NESW or do not move.
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.
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
37 # The agent can carry "keys" ("a", "b", "c") that open "vaults" ("A",
38 # "B", "C"). The keys and vault can only be used in sequence:
39 # initially the agent can move only to free spaces, or to the "a", in
40 # which case the key is removed from the environment and the agent now
41 # carries it, and can move to free spaces or the "A". When it moves to
42 # the "A", it gets a reward, loses the "a", the "A" is removed from
43 # the environment, but can now move to the "b", etc. Rewards are 1 for
44 # "A" and "B" and 10 for "C".
46 ######################################################################
50 from torch.nn.functional import conv2d
52 ######################################################################
55 def add_ansi_coloring(s):
57 return [add_ansi_coloring(x) for x in s]
59 for u, c in [("#", 40), ("$", 31), ("@", 32)] + [(x, 36) for x in "aAbBcC"]:
60 s = s.replace(u, f"\u001b[{c}m{u}\u001b[0m")
65 def fusion_multi_lines(l, width_min=0):
66 l = [x if type(x) is list else [str(x)] for x in l]
69 w = max(width_min, max([len(r) for r in o]))
70 return [" " * w] * (h - len(o)) + [r + " " * (w - len(r)) for r in o]
72 h = max([len(x) for x in l])
73 l = [f(o, h) for o in l]
75 return "\n".join(["|".join([o[k] for o in l]) for k in range(h)])
78 class PicroCrafterEngine:
87 device=torch.device("cpu"),
89 assert (world_height - 2 * margin) % (view_height - 2 * margin) == 0
90 assert (world_width - 2 * margin) % (view_width - 2 * margin) == 0
94 self.world_height = world_height
95 self.world_width = world_width
97 self.view_height = view_height
98 self.view_width = view_width
99 self.nb_walls = nb_walls
100 self.life_level_max = 5
101 self.life_level_gain_100th = 5
102 self.reward_per_hit = -1
103 self.reward_death = -10
105 self.tiles = " +#@$aAbBcC-" + "".join(
106 [str(n) for n in range(self.life_level_max + 1)]
108 self.tile2id = dict([(t, n) for n, t in enumerate(self.tiles)])
109 self.id2tile = dict([(n, t) for n, t in enumerate(self.tiles)])
111 self.next_object = dict(
113 (self.tile2id[s], self.tile2id[t])
125 self.object_reward = dict(
139 self.accessible_object_to_inventory = dict(
141 (self.tile2id[s], self.tile2id[t])
154 def reset(self, nb_agents):
155 self.worlds = self.create_worlds(
156 nb_agents, self.world_height, self.world_width, self.nb_walls, self.margin
158 self.life_level_in_100th = torch.full(
159 (nb_agents,), self.life_level_max * 100 + 99, device=self.device
161 self.accessible_object = torch.full(
162 (nb_agents,), self.tile2id["a"], device=self.device
165 def create_mazes(self, nb, height, width, nb_walls):
166 m = torch.zeros(nb, height, width, dtype=torch.int64, device=self.device)
172 i = torch.arange(height, device=m.device)[None, :, None]
173 j = torch.arange(width, device=m.device)[None, None, :]
175 for _ in range(nb_walls):
176 q = torch.rand(m.size(), device=m.device).flatten(1).sort(-1).indices * (
177 (1 - m) * (i % 2 == 0) * (j % 2 == 0)
179 q = (q == q.max(dim=-1, keepdim=True).values).long().view(m.size())
180 a = q[:, None].expand(-1, 4, -1, -1).clone()
181 a[:, 0, :-1, :] += q[:, 1:, :]
182 a[:, 0, :-2, :] += q[:, 2:, :]
183 a[:, 1, 1:, :] += q[:, :-1, :]
184 a[:, 1, 2:, :] += q[:, :-2, :]
185 a[:, 2, :, :-1] += q[:, :, 1:]
186 a[:, 2, :, :-2] += q[:, :, 2:]
187 a[:, 3, :, 1:] += q[:, :, :-1]
188 a[:, 3, :, 2:] += q[:, :, :-2]
190 torch.arange(a.size(0), device=a.device),
191 torch.randint(4, (a.size(0),), device=a.device),
193 m = (m + q + a).clamp(max=1)
197 def create_worlds(self, nb, height, width, nb_walls, margin=2):
198 margin -= 1 # The maze adds a wall all around
199 m = self.create_mazes(nb, height - 2 * margin, width - 2 * margin, nb_walls)
201 z = "@aAbBcC$$$$$" # What to add to the maze
202 u = torch.rand(q.size(), device=q.device) * (1 - q)
203 r = u.sort(dim=-1, descending=True).indices[:, : len(z)]
205 q *= self.tile2id["#"]
207 torch.arange(q.size(0), device=q.device)[:, None].expand_as(r), r
208 ] = torch.tensor([self.tile2id[c] for c in z], device=q.device)[None, :]
212 (m.size(0), m.size(1) + margin * 2, m.size(2) + margin * 2),
215 r[:, margin:-margin, margin:-margin] = m
219 def nb_actions(self):
222 def action2str(self, n):
228 def nb_view_tiles(self):
229 return len(self.tiles)
231 def min_max_reward(self):
233 min(4 * self.reward_per_hit, self.reward_death),
234 max(self.object_reward.values()),
237 def step(self, actions):
238 a = (self.worlds == self.tile2id["@"]).nonzero()
239 self.worlds[a[:, 0], a[:, 1], a[:, 2]] = self.tile2id[" "]
240 s = torch.tensor([[0, 0], [-1, 0], [0, 1], [1, 0], [0, -1]], device=self.device)
242 b[:, 1:] = b[:, 1:] + s[actions[b[:, 0]]]
244 o = (self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.tile2id[" "]).long()
245 # or it is the next accessible object
247 self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.accessible_object[b[:, 0]]
249 o = (o + q).clamp(max=1)[:, None]
250 b = (1 - o) * a + o * b
251 self.worlds[b[:, 0], b[:, 1], b[:, 2]] = self.tile2id["@"]
254 q = qq.new_zeros((self.worlds.size(0),) + qq.size()[1:])
257 nb_hits = self.monster_moves()
259 alive_before = self.life_level_in_100th > 99
260 self.life_level_in_100th[alive_before] = (
261 self.life_level_in_100th[alive_before]
262 + self.life_level_gain_100th
263 - nb_hits[alive_before] * 100
264 ).clamp(max=self.life_level_max * 100 + 99)
265 alive_after = self.life_level_in_100th > 99
266 self.worlds[torch.logical_not(alive_after)] = self.tile2id["#"]
267 reward = nb_hits * self.reward_per_hit
269 for i in range(q.size(0)):
271 reward[i] += self.object_reward[self.accessible_object[i].item()]
272 self.accessible_object[i] = self.next_object[
273 self.accessible_object[i].item()
277 alive_after.long() * reward
278 + alive_before.long() * (1 - alive_after.long()) * self.reward_death
280 inventory = torch.tensor(
282 self.accessible_object_to_inventory[s.item()]
283 for s in self.accessible_object
287 self.life_level_in_100th = (
288 self.life_level_in_100th
289 * (self.accessible_object != self.tile2id["-"]).long()
292 reward[torch.logical_not(alive_before)] = 0
293 return reward, inventory, self.life_level_in_100th // 100
295 def monster_moves(self):
296 # Current positions of the monsters
297 m = (self.worlds == self.tile2id["$"]).long().flatten(1)
299 # Total number of monsters
302 # Create a tensor with one channel per monster
304 (torch.rand(m.size(), device=m.device) * m)
305 .sort(dim=-1, descending=True)
308 o = m.new_zeros((m.size(0), n) + m.size()[1:])
309 i = torch.arange(o.size(0), device=o.device)[:, None].expand(-1, o.size(1))
310 j = torch.arange(o.size(1), device=o.device)[None, :].expand(o.size(0), -1)
314 # Create the tensor of possible motions
315 o = o.view((self.worlds.size(0), n) + self.worlds.flatten(1).size()[1:])
316 move_kernel = torch.tensor(
317 [[[[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]]]], device=o.device
323 o.size(0) * o.size(1), 1, self.worlds.size(-2), self.worlds.size(-1)
331 # Let's do the moves per say
332 i = torch.arange(self.worlds.size(0), device=self.worlds.device)[
336 for n in range(p.size(1)):
337 u = o[:, n].sort(dim=-1, descending=True).indices[:, :1]
338 q = p[:, n] * (self.worlds.flatten(1) == self.tile2id[" "]) + o[:, n]
340 (q * torch.rand(q.size(), device=q.device))
341 .sort(dim=-1, descending=True)
344 self.worlds.flatten(1)[i, u] = self.tile2id[" "]
345 self.worlds.flatten(1)[i, r] = self.tile2id["$"]
350 (self.worlds == self.tile2id["$"]).float()[:, None],
356 * (self.worlds == self.tile2id["@"]).long()
365 i_height, i_width = (
366 self.view_height - 2 * self.margin,
367 self.view_width - 2 * self.margin,
369 a = (self.worlds == self.tile2id["@"]).nonzero()
370 y = i_height * ((a[:, 1] - self.margin) // i_height)
371 x = i_width * ((a[:, 2] - self.margin) // i_width)
372 n = a[:, 0][:, None, None].expand(-1, self.view_height, self.view_width)
374 torch.arange(self.view_height, device=a.device)[None, :, None]
378 torch.arange(self.view_width, device=a.device)[None, None, :]
381 v = self.worlds.new_full(
382 (self.worlds.size(0), self.view_height + 1, self.view_width),
386 v[a[:, 0], : self.view_height] = self.worlds[n, i, j]
388 v[:, self.view_height] = self.tile2id["-"]
389 v[:, self.view_height, 0] = self.tile2id["0"] + (
390 self.life_level_in_100th // 100
391 ).clamp(min=0, max=self.life_level_max)
392 v[:, self.view_height, 1] = torch.tensor(
394 self.accessible_object_to_inventory[o.item()]
395 for o in self.accessible_object
402 def seq2tilepic(self, t, width):
405 if n in self.id2tile:
406 return self.id2tile[n]
411 return [self.seq2tilepic(r, width) for r in t]
413 t = t.reshape(-1, width)
415 t = ["".join([tile(n) for n in r]) for r in t]
420 self, src=None, comments=[], width=None, printer=print, ansi_term=False
423 src = list(self.worlds)
425 height = max([x.size(0) if torch.is_tensor(x) else 1 for x in src])
429 if n in self.id2tile:
430 return self.id2tile[n]
434 for k in range(height):
437 if torch.is_tensor(x):
440 return " " * len(x) if k < height - 1 else x
442 s = "".join([tile(n) for n in x[k]])
444 for u, c in [("#", 40), ("$", 31), ("@", 32)] + [
445 (x, 36) for x in "aAbBcC"
447 s = s.replace(u, f"\u001b[{c}m{u}\u001b[0m")
450 return " " * len(x) if k < height - 1 else x
452 printer("|".join([f(x) for x in src]))
455 ######################################################################
457 if __name__ == "__main__":
460 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
462 # nb_agents, nb_iter, display = 10000, 100, False
464 nb_agents, nb_iter, display = 4, 10000, True
467 start_time = time.perf_counter()
468 engine = PicroCrafterEngine(
481 engine.reset(nb_agents)
483 print(f"timing {nb_agents/(time.perf_counter() - start_time)} init per s")
485 start_time = time.perf_counter()
488 coloring = add_ansi_coloring
490 coloring = lambda x: x
493 for k in range(nb_iter):
502 l = engine.seq2tilepic(engine.worlds.flatten(1), width=engine.world_width)
504 to_print += coloring(fusion_multi_lines(l)) + "\n\n"
506 views = engine.views()
507 action = torch.randint(engine.nb_actions(), (nb_agents,), device=device)
509 rewards, inventories, life_levels = engine.step(action)
512 l = engine.seq2tilepic(views.flatten(1), engine.view_width)
514 v + [f"{engine.action2str(a.item())}/{r: 3d}"]
515 for (v, a, r) in zip(l, action, rewards)
519 coloring(fusion_multi_lines(l, width_min=engine.world_width)) + "\n"
526 if (life_levels > 0).long().sum() == 0:
531 print(f"timing {(nb_agents*k)/(time.perf_counter() - start_time)} iteration per s")