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 environment is a rectangular area with walls "#" dispatched
26 # randomly. The agent "@" can perform five actions: move NESW or do
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.
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
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".
47 ######################################################################
51 from torch.nn.functional import conv2d
53 ######################################################################
58 return [to_ansi(x) for x in s]
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")
68 return [to_unicode(x) for x in s]
70 for u, c in [("#", "█"), ("+", "░"), ("|", "│")]:
76 def fusion_multi_lines(l, width_min=0):
77 l = [x if type(x) is list else [str(x)] for x in l]
81 return " " * (k // 2) + r + " " * (k - k // 2)
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]
87 h = max([len(x) for x in l])
88 l = [f(o, h) for o in l]
90 return "\n".join(["|".join([o[k] for o in l]) for k in range(h)])
93 class PicroCrafterEngine:
102 device=torch.device("cpu"),
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
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
120 self.tiles = " +#@$aAbBcC-" + "".join(
121 [str(n) for n in range(self.life_level_max + 1)]
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)])
126 self.next_object = dict(
128 (self.tile2id[s], self.tile2id[t])
140 self.object_reward = dict(
154 self.accessible_object_to_inventory = dict(
156 (self.tile2id[s], self.tile2id[t])
169 def reset(self, nb_agents):
170 self.worlds = self.create_worlds(
177 self.life_level_in_100th = torch.full(
178 (nb_agents,), self.life_level_max * 100 + 99, device=self.device
180 self.accessible_object = torch.full(
181 (nb_agents,), self.tile2id["a"], device=self.device
184 def create_mazes(self, nb, height, width, nb_walls):
185 m = torch.zeros(nb, height, width, dtype=torch.int64, device=self.device)
191 i = torch.arange(height, device=m.device)[None, :, None]
192 j = torch.arange(width, device=m.device)[None, None, :]
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)
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]
209 torch.arange(a.size(0), device=a.device),
210 torch.randint(4, (a.size(0),), device=a.device),
212 m = (m + q + a).clamp(max=1)
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
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)]
226 q *= self.tile2id["#"]
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, :]
233 (m.size(0), m.size(1) + world_margin * 2, m.size(2) + world_margin * 2),
236 r[:, world_margin:-world_margin, world_margin:-world_margin] = m
240 def nb_actions(self):
243 def action2str(self, n):
249 def nb_view_tiles(self):
250 return len(self.tiles)
252 def min_max_reward(self):
254 min(4 * self.reward_per_hit, self.reward_death),
255 max(self.object_reward.values()),
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)
263 b[:, 1:] = b[:, 1:] + s[actions[b[:, 0]]]
265 o = (self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.tile2id[" "]).long()
266 # or it is the next accessible object
268 self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.accessible_object[b[:, 0]]
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["@"]
275 q = qq.new_zeros((self.worlds.size(0),) + qq.size()[1:])
278 nb_hits = self.monster_moves()
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
290 for i in range(q.size(0)):
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()
298 alive_after.long() * reward
299 + alive_before.long() * (1 - alive_after.long()) * self.reward_death
301 inventory = torch.tensor(
303 self.accessible_object_to_inventory[s.item()]
304 for s in self.accessible_object
308 self.life_level_in_100th = (
309 self.life_level_in_100th
310 * (self.accessible_object != self.tile2id["-"]).long()
313 reward[torch.logical_not(alive_before)] = 0
314 return reward, inventory, self.life_level_in_100th // 100
316 def monster_moves(self):
317 # Current positions of the monsters
318 m = (self.worlds == self.tile2id["$"]).long().flatten(1)
320 # Total number of monsters
323 # Create a tensor with one channel per monster
325 (torch.rand(m.size(), device=m.device) * m)
326 .sort(dim=-1, descending=True)
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)
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
344 o.size(0) * o.size(1), 1, self.worlds.size(-2), self.worlds.size(-1)
352 # Let's do the moves per say
353 i = torch.arange(self.worlds.size(0), device=self.worlds.device)[
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]
361 (q * torch.rand(q.size(), device=q.device))
362 .sort(dim=-1, descending=True)
365 self.worlds.flatten(1)[i, u] = self.tile2id[" "]
366 self.worlds.flatten(1)[i, r] = self.tile2id["$"]
371 (self.worlds == self.tile2id["$"]).float()[:, None],
377 * (self.worlds == self.tile2id["@"]).long()
386 i_height, i_width = (
387 self.view_height - 2 * self.world_margin,
388 self.view_width - 2 * self.world_margin,
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)
395 torch.arange(self.view_height, device=a.device)[None, :, None]
399 torch.arange(self.view_width, device=a.device)[None, None, :]
402 v = self.worlds.new_full(
403 (self.worlds.size(0), self.view_height + 1, self.view_width),
407 v[a[:, 0], : self.view_height] = self.worlds[n, i, j]
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(
415 self.accessible_object_to_inventory[o.item()]
416 for o in self.accessible_object
423 def seq2tiles(self, t, width=None):
426 if n in self.id2tile:
427 return self.id2tile[n]
432 return [self.seq2tiles(r, width) for r in t]
435 width = self.view_width
437 t = t.reshape(-1, width)
439 t = ["".join([tile(n) for n in r]) for r in t]
444 ######################################################################
446 if __name__ == "__main__":
449 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
451 # char_conv = lambda x: x
452 char_conv = to_unicode
454 # nb_agents, nb_iter, display = 1000, 1000, False
457 nb_agents, nb_iter, display = 4, 10000, True
461 char_conv = lambda x: to_ansi(to_unicode(x))
463 start_time = time.perf_counter()
464 engine = PicroCrafterEngine(
474 engine.reset(nb_agents)
476 print(f"timing {nb_agents/(time.perf_counter() - start_time)} init per s")
478 start_time = time.perf_counter()
481 for k in range(nb_iter):
490 l = engine.seq2tiles(engine.worlds.flatten(1), width=engine.world_width)
492 to_print += char_conv(fusion_multi_lines(l)) + "\n\n"
494 views = engine.views()
495 action = torch.randint(engine.nb_actions(), (nb_agents,), device=device)
497 rewards, inventories, life_levels = engine.step(action)
500 l = engine.seq2tiles(views.flatten(1))
502 v + [f"{engine.action2str(a.item())}/{r: 3d}"]
503 for (v, a, r) in zip(l, action, rewards)
507 char_conv(fusion_multi_lines(l, width_min=engine.world_width)) + "\n"
514 if (life_levels > 0).long().sum() == 0:
519 print(f"timing {(nb_agents*k)/(time.perf_counter() - start_time)} iteration per s")