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 * margin) % (view_height - 2 * margin) == 0
105 assert (world_width - 2 * margin) % (view_width - 2 * margin) == 0
109 self.world_height = world_height
110 self.world_width = world_width
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(
171 nb_agents, self.world_height, self.world_width, self.nb_walls, self.margin
173 self.life_level_in_100th = torch.full(
174 (nb_agents,), self.life_level_max * 100 + 99, device=self.device
176 self.accessible_object = torch.full(
177 (nb_agents,), self.tile2id["a"], device=self.device
180 def create_mazes(self, nb, height, width, nb_walls):
181 m = torch.zeros(nb, height, width, dtype=torch.int64, device=self.device)
187 i = torch.arange(height, device=m.device)[None, :, None]
188 j = torch.arange(width, device=m.device)[None, None, :]
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)
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]
205 torch.arange(a.size(0), device=a.device),
206 torch.randint(4, (a.size(0),), device=a.device),
208 m = (m + q + a).clamp(max=1)
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)
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)]
220 q *= self.tile2id["#"]
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, :]
227 (m.size(0), m.size(1) + margin * 2, m.size(2) + margin * 2),
230 r[:, margin:-margin, margin:-margin] = m
234 def nb_actions(self):
237 def action2str(self, n):
243 def nb_view_tiles(self):
244 return len(self.tiles)
246 def min_max_reward(self):
248 min(4 * self.reward_per_hit, self.reward_death),
249 max(self.object_reward.values()),
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)
257 b[:, 1:] = b[:, 1:] + s[actions[b[:, 0]]]
259 o = (self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.tile2id[" "]).long()
260 # or it is the next accessible object
262 self.worlds[b[:, 0], b[:, 1], b[:, 2]] == self.accessible_object[b[:, 0]]
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["@"]
269 q = qq.new_zeros((self.worlds.size(0),) + qq.size()[1:])
272 nb_hits = self.monster_moves()
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
284 for i in range(q.size(0)):
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()
292 alive_after.long() * reward
293 + alive_before.long() * (1 - alive_after.long()) * self.reward_death
295 inventory = torch.tensor(
297 self.accessible_object_to_inventory[s.item()]
298 for s in self.accessible_object
302 self.life_level_in_100th = (
303 self.life_level_in_100th
304 * (self.accessible_object != self.tile2id["-"]).long()
307 reward[torch.logical_not(alive_before)] = 0
308 return reward, inventory, self.life_level_in_100th // 100
310 def monster_moves(self):
311 # Current positions of the monsters
312 m = (self.worlds == self.tile2id["$"]).long().flatten(1)
314 # Total number of monsters
317 # Create a tensor with one channel per monster
319 (torch.rand(m.size(), device=m.device) * m)
320 .sort(dim=-1, descending=True)
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)
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
338 o.size(0) * o.size(1), 1, self.worlds.size(-2), self.worlds.size(-1)
346 # Let's do the moves per say
347 i = torch.arange(self.worlds.size(0), device=self.worlds.device)[
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]
355 (q * torch.rand(q.size(), device=q.device))
356 .sort(dim=-1, descending=True)
359 self.worlds.flatten(1)[i, u] = self.tile2id[" "]
360 self.worlds.flatten(1)[i, r] = self.tile2id["$"]
365 (self.worlds == self.tile2id["$"]).float()[:, None],
371 * (self.worlds == self.tile2id["@"]).long()
380 i_height, i_width = (
381 self.view_height - 2 * self.margin,
382 self.view_width - 2 * self.margin,
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)
389 torch.arange(self.view_height, device=a.device)[None, :, None]
393 torch.arange(self.view_width, device=a.device)[None, None, :]
396 v = self.worlds.new_full(
397 (self.worlds.size(0), self.view_height + 1, self.view_width),
401 v[a[:, 0], : self.view_height] = self.worlds[n, i, j]
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(
409 self.accessible_object_to_inventory[o.item()]
410 for o in self.accessible_object
417 def seq2tilepic(self, t, width):
420 if n in self.id2tile:
421 return self.id2tile[n]
426 return [self.seq2tilepic(r, width) for r in t]
428 t = t.reshape(-1, width)
430 t = ["".join([tile(n) for n in r]) for r in t]
435 ######################################################################
437 if __name__ == "__main__":
440 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
442 # char_conv = lambda x: x
443 char_conv = to_unicode
445 # nb_agents, nb_iter, display = 1000, 1000, False
448 nb_agents, nb_iter, display = 4, 10000, True
452 char_conv = lambda x: to_ansi(to_unicode(x))
454 start_time = time.perf_counter()
455 engine = PicroCrafterEngine(
465 engine.reset(nb_agents)
467 print(f"timing {nb_agents/(time.perf_counter() - start_time)} init per s")
469 start_time = time.perf_counter()
472 for k in range(nb_iter):
481 l = engine.seq2tilepic(engine.worlds.flatten(1), width=engine.world_width)
483 to_print += char_conv(fusion_multi_lines(l)) + "\n\n"
485 views = engine.views()
486 action = torch.randint(engine.nb_actions(), (nb_agents,), device=device)
488 rewards, inventories, life_levels = engine.step(action)
491 l = engine.seq2tilepic(views.flatten(1), engine.view_width)
493 v + [f"{engine.action2str(a.item())}/{r: 3d}"]
494 for (v, a, r) in zip(l, action, rewards)
498 char_conv(fusion_multi_lines(l, width_min=engine.world_width)) + "\n"
505 if (life_levels > 0).long().sum() == 0:
510 print(f"timing {(nb_agents*k)/(time.perf_counter() - start_time)} iteration per s")