cuju-engine 0.3.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. cuju/__init__.py +217 -0
  2. cuju/__main__.py +262 -0
  3. cuju/_batch/__init__.py +4 -0
  4. cuju/_batch/allocator.py +52 -0
  5. cuju/_batch/assets.py +68 -0
  6. cuju/_batch/environment.py +1890 -0
  7. cuju/_batch/frame_stack.py +114 -0
  8. cuju/_batch/library.py +190 -0
  9. cuju/_batch/log.py +103 -0
  10. cuju/_batch/memory.py +70 -0
  11. cuju/_batch/operators.py +55 -0
  12. cuju/_batch/pinned.py +39 -0
  13. cuju/_batch/pixels.py +207 -0
  14. cuju/_batch/state.py +77 -0
  15. cuju/_checksums.py +60 -0
  16. cuju/_cli_contract.py +244 -0
  17. cuju/_cli_parsers.py +191 -0
  18. cuju/_completion.py +277 -0
  19. cuju/_dump_to_txt.py +66 -0
  20. cuju/_grf_config.py +331 -0
  21. cuju/_library_path.py +141 -0
  22. cuju/_media.py +113 -0
  23. cuju/_pixels.py +276 -0
  24. cuju/_plugins.py +106 -0
  25. cuju/_python_players.py +224 -0
  26. cuju/_replay_command.py +109 -0
  27. cuju/_replay_player.py +42 -0
  28. cuju/_replays.py +414 -0
  29. cuju/_script_helpers.py +109 -0
  30. cuju/_version.py +6 -0
  31. cuju/action_log.py +371 -0
  32. cuju/check.py +596 -0
  33. cuju/cuju_cpu.dll +0 -0
  34. cuju/cuju_cuda.dll +0 -0
  35. cuju/cuju_render.dll +0 -0
  36. cuju/data/SHA256SUMS +20 -0
  37. cuju/data/animations.bin +0 -0
  38. cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
  39. cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
  40. cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
  41. cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
  42. cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
  43. cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
  44. cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
  45. cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
  46. cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
  47. cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
  48. cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
  49. cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
  50. cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
  51. cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  52. cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  53. cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
  54. cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
  55. cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
  56. cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
  57. cuju/data/digests.json +186 -0
  58. cuju/data/render_digests.json.z +0 -0
  59. cuju/data/scenarios/11_vs_11_competition.py +45 -0
  60. cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
  61. cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
  62. cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
  63. cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
  64. cuju/data/scenarios/1_vs_1_easy.py +25 -0
  65. cuju/data/scenarios/5_vs_5.py +33 -0
  66. cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
  67. cuju/data/scenarios/academy_corner.py +45 -0
  68. cuju/data/scenarios/academy_counterattack_easy.py +45 -0
  69. cuju/data/scenarios/academy_counterattack_hard.py +45 -0
  70. cuju/data/scenarios/academy_empty_goal.py +25 -0
  71. cuju/data/scenarios/academy_empty_goal_close.py +25 -0
  72. cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
  73. cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
  74. cuju/data/scenarios/academy_run_to_score.py +30 -0
  75. cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
  76. cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
  77. cuju/data/scenarios/test_example_multiagent.py +28 -0
  78. cuju/dumps.py +942 -0
  79. cuju/engine_status.py +106 -0
  80. cuju/env.py +1168 -0
  81. cuju/errors.py +108 -0
  82. cuju/gfootball/GRF_SOURCES +86 -0
  83. cuju/gfootball/__init__.py +60 -0
  84. cuju/gfootball/_cv2.py +43 -0
  85. cuju/gfootball/_gym/__init__.py +88 -0
  86. cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
  87. cuju/gfootball/_gym/_vendored/__init__.py +43 -0
  88. cuju/gfootball/_gym/_vendored/core.py +361 -0
  89. cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
  90. cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
  91. cuju/gfootball/_gym/_vendored/error.py +230 -0
  92. cuju/gfootball/_gym/_vendored/logger.py +56 -0
  93. cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
  94. cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
  95. cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
  96. cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
  97. cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
  98. cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
  99. cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
  100. cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
  101. cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
  102. cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
  103. cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
  104. cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
  105. cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
  106. cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
  107. cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
  108. cuju/gfootball/_gym/_vendored/version.py +5 -0
  109. cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
  110. cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
  111. cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
  112. cuju/gfootball/dump_to_txt.py +49 -0
  113. cuju/gfootball/dump_to_video.py +33 -0
  114. cuju/gfootball/env/__init__.py +271 -0
  115. cuju/gfootball/env/config.py +163 -0
  116. cuju/gfootball/env/constants.py +33 -0
  117. cuju/gfootball/env/controller_base.py +114 -0
  118. cuju/gfootball/env/event_queue.py +54 -0
  119. cuju/gfootball/env/football_action_set.py +220 -0
  120. cuju/gfootball/env/football_action_set_test.py +76 -0
  121. cuju/gfootball/env/football_env.py +225 -0
  122. cuju/gfootball/env/football_env_core.py +447 -0
  123. cuju/gfootball/env/football_env_test.py +692 -0
  124. cuju/gfootball/env/gym_test.py +47 -0
  125. cuju/gfootball/env/observation_preprocessing.py +94 -0
  126. cuju/gfootball/env/observation_processor.py +526 -0
  127. cuju/gfootball/env/observation_rotation.py +163 -0
  128. cuju/gfootball/env/observation_rotation_test.py +84 -0
  129. cuju/gfootball/env/player_base.py +46 -0
  130. cuju/gfootball/env/players/__init__.py +16 -0
  131. cuju/gfootball/env/players/agent.py +39 -0
  132. cuju/gfootball/env/players/bot.py +217 -0
  133. cuju/gfootball/env/players/gamepad.py +81 -0
  134. cuju/gfootball/env/players/keyboard.py +72 -0
  135. cuju/gfootball/env/players/lazy.py +31 -0
  136. cuju/gfootball/env/players/ppo2_cnn.py +119 -0
  137. cuju/gfootball/env/players/replay.py +40 -0
  138. cuju/gfootball/env/remote_football_env.py +189 -0
  139. cuju/gfootball/env/scenario_builder.py +125 -0
  140. cuju/gfootball/env/script_helpers.py +130 -0
  141. cuju/gfootball/env/script_helpers_test.py +107 -0
  142. cuju/gfootball/env/wrappers.py +440 -0
  143. cuju/gfootball/env/wrappers_test.py +150 -0
  144. cuju/gfootball/eval_server/__init__.py +17 -0
  145. cuju/gfootball/eval_server/config.py +30 -0
  146. cuju/gfootball/eval_server/example_client.py +107 -0
  147. cuju/gfootball/eval_server/proto/game_server.proto +62 -0
  148. cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
  149. cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
  150. cuju/gfootball/eval_server/proto/master.proto +25 -0
  151. cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
  152. cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
  153. cuju/gfootball/eval_server/utils.py +52 -0
  154. cuju/gfootball/examples/__init__.py +16 -0
  155. cuju/gfootball/examples/models.py +66 -0
  156. cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
  157. cuju/gfootball/examples/run_ppo2.py +123 -0
  158. cuju/gfootball/play_game.py +73 -0
  159. cuju/gfootball/replay.py +43 -0
  160. cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
  161. cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
  162. cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
  163. cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
  164. cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
  165. cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
  166. cuju/gfootball/scenarios/5_vs_5.py +46 -0
  167. cuju/gfootball/scenarios/__init__.py +31 -0
  168. cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
  169. cuju/gfootball/scenarios/academy_corner.py +59 -0
  170. cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
  171. cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
  172. cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
  173. cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
  174. cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
  175. cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
  176. cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
  177. cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
  178. cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
  179. cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
  180. cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
  181. cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
  182. cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
  183. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
  184. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
  185. cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
  186. cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
  187. cuju/gfootball/scenarios/tests/__init__.py +31 -0
  188. cuju/gfootball/scenarios/tests/corner_test.py +38 -0
  189. cuju/gfootball/scenarios/tests/goal_test.py +35 -0
  190. cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
  191. cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
  192. cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
  193. cuju/gfootball/scenarios/tests/offside_test.py +39 -0
  194. cuju/gfootball/scenarios/tests/penalty.py +34 -0
  195. cuju/gfootball/scenarios/tests/second_half.py +33 -0
  196. cuju/gfootball/scenarios/tests/symmetric.py +53 -0
  197. cuju/gfootball_engine/__init__.py +31 -0
  198. cuju/gfootball_engine/_gameplayfootball.py +1624 -0
  199. cuju/gfootball_engine/_native.py +193 -0
  200. cuju/gfootball_engine/_pickle_names.py +114 -0
  201. cuju/gfootball_engine/_render_hooks.py +156 -0
  202. cuju/kaggle.py +425 -0
  203. cuju/multi_device.py +401 -0
  204. cuju/players.py +260 -0
  205. cuju/raw.py +93 -0
  206. cuju/scenarios.py +661 -0
  207. cuju/state.py +211 -0
  208. cuju/wrappers.py +325 -0
  209. cuju_engine-0.3.0.dist-info/METADATA +325 -0
  210. cuju_engine-0.3.0.dist-info/RECORD +222 -0
  211. cuju_engine-0.3.0.dist-info/WHEEL +5 -0
  212. cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
  213. cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
  214. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
  215. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
  216. cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
  217. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
  218. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
  219. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
  220. cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
  221. cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
  222. cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/multi_device.py ADDED
@@ -0,0 +1,401 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """One batch of environments over several devices, each device stepping a contiguous range.
4
+
5
+ The guide is in the repository's `docs/backends.md`, under Several GPUs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ import torch
13
+
14
+ from . import BatchEnvironment
15
+ from .errors import (
16
+ ActionRangeError,
17
+ ArgumentError,
18
+ ChoiceError,
19
+ ClosedError,
20
+ ConfigurationError,
21
+ EnvironmentIndexError,
22
+ )
23
+
24
+ __all__ = ['MultiDeviceBatch']
25
+
26
+
27
+ def _device(device):
28
+ """Returns a name, an index or a `torch.device` as a `torch.device` with an index."""
29
+ device = torch.device('cuda', device) if isinstance(device, int) else torch.device(device)
30
+ if device.type == 'cuda' and device.index is None:
31
+ device = torch.device('cuda', torch.cuda.current_device())
32
+ if device.type not in ('cuda', 'cpu'):
33
+ raise ChoiceError(f'expected a CUDA device or the CPU, found {device}')
34
+ return device
35
+
36
+
37
+ def _per_environment(values, start, end, count, error=ConfigurationError):
38
+ """Returns the values of environments `start` to `end - 1`, or the one value for every one."""
39
+ array = torch.as_tensor(values)
40
+ if array.dim() == 0:
41
+ return array.item()
42
+ if array.shape[0] != count:
43
+ raise error(
44
+ f'expected one value, or one for each of the {count} environments, found the shape '
45
+ f'{tuple(array.shape)}'
46
+ )
47
+ return array[start:end]
48
+
49
+
50
+ class MultiDeviceBatch:
51
+ """A batch whose environments run on several devices, each a `BatchEnvironment` of its own.
52
+
53
+ The part on device k plays environments `start` to `end - 1` of the seed rule, through
54
+ `first_index`, so environment `i` plays as environment `i` of one `BatchEnvironment` of
55
+ `environment_count` environments and the same options. A step starts on every device before it
56
+ waits for any, so the GPUs step at once, and a CPU part steps in its own thread.
57
+
58
+ The outputs of `reset` and `step` are tensors on `output_device`, which the next call
59
+ overwrites, as a `BatchEnvironment`'s are. Gathering them copies each part's outputs, and
60
+ `parts` gives each part's own outputs without the copy.
61
+
62
+ Attributes:
63
+ parts: The `BatchEnvironment` of each device, in the order of `devices`.
64
+ ranges: The `(start, end)` environments of each part.
65
+ devices: The device of each part.
66
+ output_device: The device of the outputs.
67
+ environment_count, agents, players, action_count, squeeze, stacked, auto_reset,
68
+ scenario_name: As in `BatchEnvironment`.
69
+ left_agents, right_agents, left_players, right_players, agent_mask, difficulty: As in
70
+ `BatchEnvironment`, over every environment.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ assets: str | list[str],
76
+ devices: list[Any],
77
+ environment_count: int = 1024,
78
+ split: list[int] | None = None,
79
+ output_device: Any = None,
80
+ assignment: Any = None,
81
+ game_engine_random_seed: Any = None,
82
+ **options: Any,
83
+ ) -> None:
84
+ """Creates a part of the batch on each device.
85
+
86
+ Args:
87
+ assets: As for `BatchEnvironment`.
88
+ devices: The devices, each `cpu`, `cuda`, `cuda:N`, an index N or a `torch.device`,
89
+ and a device may repeat.
90
+ environment_count: The number of environments over every device.
91
+ split: The number of environments of each device. `None` splits them evenly, the first
92
+ devices taking one more where they do not divide.
93
+ output_device: Where the outputs of `reset` and `step` live. `None` takes the first
94
+ device.
95
+ assignment, game_engine_random_seed: As for `BatchEnvironment`, over every
96
+ environment, and each part takes its range.
97
+ **options: The other options of `BatchEnvironment`, the same for every part, except
98
+ `device` and `first_index`, which the parts take from `devices` and `split`.
99
+
100
+ Raises:
101
+ ConfigurationError: If `devices` is empty, `split` does not add up to
102
+ `environment_count` or holds a part of no environment, `options` names `device` or
103
+ `first_index`, or `assignment` or `game_engine_random_seed` holds neither one value
104
+ nor one per environment. It is a `ValueError`.
105
+ ChoiceError: If a device is neither a CUDA device nor the CPU. It is a `ValueError`.
106
+ """
107
+ self.devices = [_device(device) for device in devices]
108
+ if not self.devices:
109
+ raise ConfigurationError('expected at least one device')
110
+ for name in ('device', 'first_index'):
111
+ if name in options:
112
+ raise ConfigurationError(
113
+ f'expected no {name}, which MultiDeviceBatch sets for each part'
114
+ )
115
+ count = len(self.devices)
116
+ if split is None:
117
+ split = [
118
+ environment_count // count + (part < environment_count % count)
119
+ for part in range(count)
120
+ ]
121
+ if len(split) != count or sum(split) != environment_count or min(split) < 1:
122
+ raise ConfigurationError(
123
+ f'expected a split of the {environment_count} environments into {count} parts of '
124
+ f'at least one, found {split}'
125
+ )
126
+ self.ranges = []
127
+ start = 0
128
+ for size in split:
129
+ self.ranges.append((start, start + size))
130
+ start += size
131
+ self.output_device = self.devices[0] if output_device is None else _device(output_device)
132
+ self.environment_count = environment_count
133
+ self.parts = []
134
+ try:
135
+ for device, (start, end) in zip(self.devices, self.ranges, strict=True):
136
+ part_options = dict(options)
137
+ if assignment is not None:
138
+ part_options['assignment'] = _per_environment(
139
+ assignment, start, end, environment_count
140
+ )
141
+ if game_engine_random_seed is not None:
142
+ part_options['game_engine_random_seed'] = _per_environment(
143
+ game_engine_random_seed, start, end, environment_count
144
+ )
145
+ # Environment 0 of a part keeps the seed rule's index of its range.
146
+ if start:
147
+ part_options['first_index'] = start
148
+ if device.type == 'cuda':
149
+ with torch.cuda.device(device):
150
+ part = BatchEnvironment(
151
+ assets, environment_count=end - start, device='cuda', **part_options
152
+ )
153
+ else:
154
+ part = BatchEnvironment(
155
+ assets, environment_count=end - start, device='cpu', **part_options
156
+ )
157
+ self.parts.append(part)
158
+ except BaseException:
159
+ self.close()
160
+ raise
161
+ first = self.parts[0]
162
+ for name in (
163
+ 'agents',
164
+ 'players',
165
+ 'action_count',
166
+ 'squeeze',
167
+ 'stacked',
168
+ 'auto_reset',
169
+ 'scenario_name',
170
+ ):
171
+ setattr(self, name, getattr(first, name))
172
+ for name in (
173
+ 'left_agents',
174
+ 'right_agents',
175
+ 'left_players',
176
+ 'right_players',
177
+ 'agent_mask',
178
+ 'difficulty',
179
+ ):
180
+ setattr(self, name, torch.cat([getattr(part, name) for part in self.parts]))
181
+ self._gathered = {}
182
+ # The event after the last gather from the page-locked outputs of a CPU part, which a copy
183
+ # to the GPU reads only when its stream gets there, and the event itself, made once.
184
+ self._copied = self._copy_event = None
185
+
186
+ def close(self) -> None:
187
+ """Closes every part. A second call does nothing.
188
+
189
+ Every later call of another method raises `ClosedError`, a `RuntimeError`, as on a closed
190
+ `BatchEnvironment`.
191
+ """
192
+ for part in getattr(self, 'parts', []):
193
+ part.close()
194
+ self.parts = []
195
+ self._copied = None
196
+
197
+ def _open_parts(self):
198
+ """Returns the parts, or raises `ClosedError` once the batch is closed."""
199
+ if not getattr(self, 'parts', None):
200
+ raise ClosedError('the batch is closed')
201
+ return self.parts
202
+
203
+ def _before_write(self, part):
204
+ """Waits, before a call rewrites the outputs of `part`, for the copies that read them.
205
+
206
+ A step, a reset or a state of a CPU part with page-locked outputs rewrites them, which a
207
+ copy of the last gather that the GPU has not yet run would then read. Other parts need no
208
+ wait, since a GPU part's next call runs after the copies on the same stream, and the copy
209
+ of pageable memory reads it before it returns.
210
+ """
211
+ if self._copied is not None and part.device == 'cpu' and part._native.pinned:
212
+ self._copied.synchronize()
213
+ self._copied = None
214
+
215
+ def __reduce__(self):
216
+ raise TypeError(
217
+ 'a batch cannot be pickled; create it inside the worker process that uses it'
218
+ )
219
+
220
+ def _gather(self, key, outputs):
221
+ """Gathers the parts' outputs on `output_device` into tensors that `key` reuses."""
222
+ if isinstance(outputs[0], dict):
223
+ return {
224
+ name: self._gather((key, name), [output[name] for output in outputs])
225
+ for name in outputs[0]
226
+ }
227
+ gathered = self._gathered.get(key)
228
+ if gathered is None:
229
+ shape = (self.environment_count, *outputs[0].shape[1:])
230
+ gathered = torch.empty(shape, dtype=outputs[0].dtype, device=self.output_device)
231
+ self._gathered[key] = gathered
232
+ # A copy into the host's pageable memory must wait, else it may land after the return.
233
+ non_blocking = self.output_device.type == 'cuda'
234
+ pinned = False
235
+ for part, (start, end), output in zip(self.parts, self.ranges, outputs, strict=True):
236
+ gathered[start:end].copy_(output, non_blocking=non_blocking)
237
+ pinned |= part.device == 'cpu' and bool(part._native.pinned)
238
+ if non_blocking and pinned:
239
+ if self._copy_event is None:
240
+ self._copy_event = torch.cuda.Event()
241
+ self._copy_event.record(torch.cuda.current_stream(self.output_device))
242
+ self._copied = self._copy_event
243
+ return gathered
244
+
245
+ def _split(self, values):
246
+ """Returns `values` per part, a slice of one value per environment or the one value."""
247
+ if values is None:
248
+ return [None] * len(self.parts)
249
+ return [
250
+ _per_environment(values, start, end, self.environment_count, ArgumentError)
251
+ for start, end in self.ranges
252
+ ]
253
+
254
+ def _step_outputs(self, results):
255
+ observation, reward, done, information = zip(*results, strict=True)
256
+ return (
257
+ self._gather('observation', observation),
258
+ self._gather('reward', reward),
259
+ self._gather('done', done),
260
+ {
261
+ name: self._gather(name, [part[name] for part in information])
262
+ for name in information[0]
263
+ },
264
+ )
265
+
266
+ def reset(self, seeds: Any = None, reverse: Any = None) -> Any:
267
+ """Starts the next episode of every environment, as `BatchEnvironment.reset` does.
268
+
269
+ Args:
270
+ seeds, reverse: As for `BatchEnvironment.reset`, over every environment.
271
+
272
+ Returns:
273
+ The observation of every environment on `output_device`.
274
+
275
+ Raises:
276
+ ArgumentError: If `seeds` or `reverse` holds neither one value nor one per environment,
277
+ or as `BatchEnvironment.reset` raises it. It is a `ValueError`.
278
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
279
+ """
280
+ parts = self._open_parts()
281
+ observations = []
282
+ for part, part_seeds, part_reverse in zip(
283
+ parts, self._split(seeds), self._split(reverse), strict=True
284
+ ):
285
+ self._before_write(part)
286
+ observations.append(part.reset(seeds=part_seeds, reverse=part_reverse))
287
+ return self._gather('observation', observations)
288
+
289
+ def reset_done(self) -> None:
290
+ """Starts the next episode of every environment whose episode ended.
291
+
292
+ Raises:
293
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
294
+ """
295
+ for part in self._open_parts():
296
+ self._before_write(part)
297
+ part.reset_done()
298
+
299
+ def step(self, actions: Any) -> tuple[Any, Any, Any, dict[str, Any]]:
300
+ """Runs one step of every environment, as `BatchEnvironment.step` does.
301
+
302
+ Args:
303
+ actions: `[environment_count, agents]` action indices, or `[environment_count]` for
304
+ one agent, on any device. Each part takes its rows on its own device.
305
+
306
+ Returns:
307
+ The observation, the reward, the done flags and the information of every environment,
308
+ on `output_device`.
309
+
310
+ Raises:
311
+ ActionRangeError: If a part on the CPU meets an action outside the action set, before
312
+ any part steps. It is an `IndexError`.
313
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
314
+ """
315
+ self._open_parts()
316
+ actions = torch.as_tensor(actions)
317
+ # A CUDA copy to the host could return before it lands, so only CUDA to CUDA skips the wait.
318
+ rows = [
319
+ actions[start:end].to(device, non_blocking=device.type == 'cuda' and actions.is_cuda)
320
+ for device, (start, end) in zip(self.devices, self.ranges, strict=True)
321
+ ]
322
+ # GRF: an action outside `[-action_count, action_count)` raises. A part checks its host
323
+ # actions too, but only once the parts before it stepped, so every part's are checked here
324
+ # first.
325
+ count = self.action_count
326
+ for part, part_rows in zip(self.parts, rows, strict=True):
327
+ # The part itself raises for a wrong shape or type.
328
+ if (
329
+ part.device == 'cpu'
330
+ and not part_rows.is_floating_point()
331
+ and part_rows.numel() == part.agent_mask.numel()
332
+ ):
333
+ values = part_rows.reshape(part.agent_mask.shape)[part.agent_mask]
334
+ if bool(((values < -count) | (values >= count)).any()):
335
+ raise ActionRangeError(
336
+ f'expected action indices from {-count} to {count - 1}, found '
337
+ f'{values[(values < -count) | (values >= count)][0].item()}'
338
+ )
339
+ # The CPU parts step in threads of their own, so every device steps at once.
340
+ started = []
341
+ try:
342
+ for part, part_rows in zip(self.parts, rows, strict=True):
343
+ self._before_write(part)
344
+ part.step_async(part_rows)
345
+ started.append(part)
346
+ except BaseException:
347
+ for part in started:
348
+ part.step_wait()
349
+ raise
350
+ return self._step_outputs([part.step_wait() for part in self.parts])
351
+
352
+ def observation(self) -> Any:
353
+ """Returns the observation of every environment of the last `reset` or `step`.
354
+
355
+ Raises:
356
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
357
+ """
358
+ return self._gather('observation', [part.observation() for part in self._open_parts()])
359
+
360
+ def _part(self, index):
361
+ """Returns the part of environment `index` and the index there."""
362
+ for part, (start, end) in zip(self._open_parts(), self.ranges, strict=True):
363
+ if start <= index < end:
364
+ return part, index - start
365
+ raise EnvironmentIndexError(
366
+ f'expected an environment from 0 to {self.environment_count - 1}, found {index}'
367
+ )
368
+
369
+ def get_state(self, index: int) -> bytes:
370
+ """Returns the state of environment `index`, as `BatchEnvironment.get_state` does.
371
+
372
+ Raises:
373
+ EnvironmentIndexError: If `index` lies outside the batch. It is an `IndexError` and a
374
+ `RuntimeError`.
375
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
376
+ """
377
+ part, local = self._part(index)
378
+ return part.get_state(local)
379
+
380
+ def roles(self, index: int) -> dict[str, torch.Tensor]:
381
+ """Returns the role of each player of environment `index`, as `BatchEnvironment.roles` does.
382
+
383
+ Raises:
384
+ EnvironmentIndexError: If `index` lies outside the batch. It is an `IndexError` and a
385
+ `RuntimeError`.
386
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
387
+ """
388
+ part, local = self._part(index)
389
+ return part.roles(local)
390
+
391
+ def set_state(self, index: int, state: bytes) -> None:
392
+ """Sets environment `index` to a state, as `BatchEnvironment.set_state` does.
393
+
394
+ Raises:
395
+ EnvironmentIndexError: If `index` lies outside the batch. It is an `IndexError` and a
396
+ `RuntimeError`.
397
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
398
+ """
399
+ part, local = self._part(index)
400
+ self._before_write(part)
401
+ part.set_state(local, state)
cuju/players.py ADDED
@@ -0,0 +1,260 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """GRF's scripted players `bot` and `lazy`, for one agent of every environment of a batch.
6
+
7
+ `Bot` is an exact port of `gfootball/env/players/bot.py` and `Lazy` of `lazy.py`. Their actions are
8
+ indices into the batch's action set, and the bot needs the `full` set. The guide is in the
9
+ repository's `docs/migrating-from-grf.md`, under Scripted players and `control_all_players`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ from typing import Any
16
+
17
+ import torch
18
+
19
+ __all__ = ['Bot', 'Lazy']
20
+
21
+ # GRF: the indices of the bot's actions in the `full` set.
22
+ _IDLE, _LONG_PASS, _SHORT_PASS, _SHOT, _SPRINT = 0, 9, 11, 12, 13
23
+ _PRESSURE, _RELEASE_PRESSURE = 21, 30
24
+ # GRF: `_direction_action` scores the eight directions in the order top, top_left, left,
25
+ # bottom_left, bottom, bottom_right, right, top_right.
26
+ _DIRECTIONS = (3, 2, 1, 8, 7, 6, 5, 4)
27
+ # GRF: each direction vector divided by its norm, `np.linalg.norm`, which is `sqrt(2.0)` for a
28
+ # diagonal.
29
+ _DIAGONAL = 1 / math.sqrt(2.0)
30
+ _DIRECTION_VECTORS = (
31
+ (0.0, -1.0),
32
+ (-_DIAGONAL, -_DIAGONAL),
33
+ (-1.0, 0.0),
34
+ (-_DIAGONAL, _DIAGONAL),
35
+ (0.0, 1.0),
36
+ (_DIAGONAL, _DIAGONAL),
37
+ (1.0, 0.0),
38
+ (_DIAGONAL, -_DIAGONAL),
39
+ )
40
+ _FULL_ACTIONS = 33
41
+ _TARGET_X = 0.85
42
+ _SHOOT_DISTANCE = 0.15
43
+
44
+
45
+ def _norm(x, y):
46
+ """Returns `np.linalg.norm` of the vectors `(x, y)`, the square root of their dot product."""
47
+ # Exact: numpy's dot of two numbers adds `x * x` and `y * y` in this order, each rounded, with
48
+ # no fused multiply-add, under the OpenBLAS kernels of x86-64 without AVX-512.
49
+ return torch.sqrt(x * x + y * y)
50
+
51
+
52
+ def _dot(x, y, u, v):
53
+ """Returns `np.dot` of the vectors `(x, y)` and `(u, v)`."""
54
+ # Exact: numpy's dot starts from 0.0, which only turns a negative zero positive, and no
55
+ # comparison of the bot tells the zeros apart.
56
+ return x * u + y * v
57
+
58
+
59
+ def _first(values, maximum):
60
+ """Returns the first index of the maximum or minimum on the last axis, as numpy's `argmax`.
61
+
62
+ GRF: the bot's strict comparisons pick the first as well.
63
+ """
64
+ best = values.amax(-1, keepdim=True) if maximum else values.amin(-1, keepdim=True)
65
+ positions = torch.arange(values.shape[-1], device=values.device).expand_as(values)
66
+ return torch.where(values == best, positions, values.shape[-1]).amin(-1)
67
+
68
+
69
+ def _direction_action(x, y):
70
+ """Returns, for each movement `(x, y)`, the direction action closest to it."""
71
+ scores = torch.stack([_dot(x, y, u, v) for u, v in _DIRECTION_VECTORS], -1)
72
+ return torch.tensor(_DIRECTIONS, device=x.device)[_first(scores, True)]
73
+
74
+
75
+ class Bot:
76
+ """GRF's `bot` player for one agent of every environment of a batch.
77
+
78
+ Each call of `act` reads the agent's current raw observation and returns GRF's bot's action.
79
+ It reads the observation in `float64`, as GRF's bot reads numpy arrays, and decides in tensors
80
+ over every environment at once on the batch's device.
81
+ Like GRF's, the bot remembers its last action and whether it presses, and keeps both across
82
+ episodes, since GRF's environment never resets its players' memory.
83
+
84
+ Attributes:
85
+ batch: The batch.
86
+ agent: The agent that the bot plays.
87
+ """
88
+
89
+ def __init__(self, batch: Any, agent: int) -> None:
90
+ """Binds a bot to an agent of a batch.
91
+
92
+ Args:
93
+ batch: A batch with the `full` action set and with `with_raw=True` or the raw
94
+ representation.
95
+ agent: The index of the agent, which must exist in every environment.
96
+
97
+ Raises:
98
+ ValueError: If the batch has another action set or no raw arrays, or if the agent is
99
+ missing in an environment.
100
+ """
101
+ # GRF: the bot asserts the `full` action set.
102
+ if batch.action_count != _FULL_ACTIONS:
103
+ raise ValueError("expected a batch with action_set='full', which GRF's bot needs")
104
+ if getattr(batch, '_raw_fields', None) is None:
105
+ raise ValueError('expected a batch with the raw representation or with_raw=True')
106
+ if not 0 <= agent < batch.agents or not bool(batch.agent_mask[:, agent].all()):
107
+ raise ValueError(f'expected an agent of every environment, found {agent}')
108
+ self.batch = batch
109
+ self.agent = agent
110
+ device = batch._torch_device
111
+ right = agent >= batch.left_agents
112
+ # A right agent sees its own team as the left team.
113
+ self._own = torch.where(right, batch.right_players, batch.left_players).to(device)
114
+ self._other = torch.where(right, batch.left_players, batch.right_players).to(device)
115
+ self._last_action = torch.full((batch.environment_count,), _IDLE, device=device)
116
+ self._pressure = torch.zeros(batch.environment_count, dtype=torch.bool, device=device)
117
+
118
+ def reset(self, mask: Any = None) -> None:
119
+ """Forgets the last action and the pressing, as a newly created GRF bot.
120
+
121
+ GRF never does this between episodes, and it serves a bot that starts with a new
122
+ environment.
123
+
124
+ Args:
125
+ mask: `[environment_count]` flags of the environments to reset, or `None` for all.
126
+ """
127
+ if mask is None:
128
+ self._last_action.fill_(_IDLE)
129
+ self._pressure.fill_(False)
130
+ else:
131
+ mask = torch.as_tensor(mask, dtype=torch.bool).to(self._pressure.device)
132
+ self._last_action[mask] = _IDLE
133
+ self._pressure[mask] = False
134
+
135
+ def act(self, raw: dict[str, torch.Tensor] | None = None) -> torch.Tensor:
136
+ """Returns the bot's actions, `[environment_count]` `int32` indices into the `full` set.
137
+
138
+ The bot remembers them for its next decision.
139
+
140
+ Args:
141
+ raw: The raw observation to act on, `batch.raw()` by default.
142
+ """
143
+ raw = self.batch.raw() if raw is None else raw
144
+ action, pressure = self._decide(raw)
145
+ self._last_action = action
146
+ self._pressure = pressure
147
+ return action.to(torch.int32)
148
+
149
+ def _decide(self, raw):
150
+ """Returns the action and the pressing of `bot.Player._get_action` for every environment."""
151
+ agent = self.agent
152
+ own = raw['left_team'][:, agent].double()
153
+ other = raw['right_team'][:, agent].double()
154
+ count = own.shape[1]
155
+ slots = torch.arange(count, device=own.device)
156
+ own_valid = slots < self._own[:, None]
157
+ other_valid = slots < self._other[:, None]
158
+ # GRF: `left_team[active]` with Python's indexing, where -1 is the last player.
159
+ active = raw['active'][:, agent].long()
160
+ active = torch.where(active < 0, active + self._own, active)
161
+ rows = torch.arange(own.shape[0], device=own.device)
162
+ position = own[rows, active]
163
+ x, y = position[:, 0], position[:, 1]
164
+ infinity = torch.tensor(math.inf, dtype=torch.float64, device=own.device)
165
+ other_x, other_y = other[:, None, :, 0], other[:, None, :, 1]
166
+
167
+ def distances(px, py):
168
+ """`_object_distance` from points `[N, M]` to opponents, `[N, M, players]`, or inf."""
169
+ distance = _norm(px[..., None] - other_x, py[..., None] - other_y)
170
+ return torch.where(other_valid[:, None], distance, infinity)
171
+
172
+ # The run to the goal, and the closest opponent in front, who may be missing.
173
+ target_x, target_y = _TARGET_X - x, 0.0 - y
174
+ move_action = _direction_action(target_x, target_y)
175
+ ahead = _dot(
176
+ target_x[:, None],
177
+ target_y[:, None],
178
+ other[..., 0] - x[:, None],
179
+ other[..., 1] - y[:, None],
180
+ )
181
+ front = torch.where(ahead > 0, distances(x[:, None], y[:, None])[:, 0], infinity)
182
+ front_index = _first(front, False)
183
+ front_distance = front[rows, front_index]
184
+ has_front = torch.isfinite(front_distance)
185
+ front_distance = torch.where(has_front, front_distance, 2.0)
186
+ # The best pass, where each teammate within 0.3 scores the closest approach of an
187
+ # opponent to ten points along the pass.
188
+ trajectory_x, trajectory_y = own[..., 0] - x[:, None], own[..., 1] - y[:, None]
189
+ reach = _norm(trajectory_x, trajectory_y)
190
+ closest = None
191
+ for step in range(10):
192
+ fraction = (step + 1) / 10.0
193
+ px = x[:, None] + fraction * trajectory_x
194
+ py = y[:, None] + fraction * trajectory_y
195
+ distance = distances(px, py).amin(-1)
196
+ closest = distance if closest is None else torch.minimum(closest, distance)
197
+ score = torch.where(own_valid & ~(reach > 0.3), -closest, -infinity)
198
+ best = own[rows, _first(score, True)]
199
+ pass_x, pass_y = best[:, 0] - x, best[:, 1] - y
200
+ pass_action = _direction_action(pass_x, pass_y)
201
+ # Around the opponent in front, perpendicular to it and toward the goal.
202
+ opponent = other[rows, front_index]
203
+ delta_x, delta_y = opponent[:, 0] - x, opponent[:, 1] - y
204
+ turn_x, turn_y = delta_y, -delta_x
205
+ flip = target_x * turn_x < 0
206
+ avoid_action = _direction_action(
207
+ torch.where(flip, -turn_x, turn_x), torch.where(flip, -turn_y, turn_y)
208
+ )
209
+ alone = (best[:, 0] == x) & (best[:, 1] == y)
210
+ blocked = front_distance < 0.08
211
+ run = torch.where(
212
+ blocked & alone,
213
+ avoid_action,
214
+ torch.where(
215
+ blocked,
216
+ torch.where(self._last_action == pass_action, _SHORT_PASS, pass_action),
217
+ move_action,
218
+ ),
219
+ )
220
+ ball = raw['ball'][:, agent].double()
221
+ shoot = _SHOOT_DISTANCE > _norm(ball[:, 0] - _TARGET_X, ball[:, 1] - 0.0)
222
+ action = torch.where(shoot, _SHOT, run)
223
+ # The rules before the play, from the last to the first, as GRF checks them first to last.
224
+ # Pressing ends wherever the play or its release is reached.
225
+ action = torch.where(self._pressure, _RELEASE_PRESSURE, action)
226
+ pressure = torch.zeros_like(self._pressure)
227
+ defending = raw['ball_owned_team'][:, agent] == 1
228
+ pressing = self._last_action == _PRESSURE
229
+ action = torch.where(defending, torch.where(pressing, _SPRINT, _PRESSURE), action)
230
+ pressure = torch.where(defending, pressing.logical_not() | self._pressure, pressure)
231
+ set_piece = raw['game_mode'][:, agent] != 0
232
+ action = torch.where(set_piece, _LONG_PASS, action)
233
+ pressure = torch.where(set_piece, self._pressure, pressure)
234
+ return action, pressure
235
+
236
+
237
+ class Lazy:
238
+ """GRF's `lazy` player, which stands still with `idle` for its agents in every environment.
239
+
240
+ Attributes:
241
+ batch: The batch.
242
+ agents: The agents that the player plays.
243
+ """
244
+
245
+ def __init__(self, batch: Any, agents: int | list[int]) -> None:
246
+ """Binds a lazy player to agents of a batch.
247
+
248
+ Args:
249
+ batch: Any batch, since `idle` is index 0 of every action set.
250
+ agents: An agent index or a list of them.
251
+ """
252
+ self.batch = batch
253
+ self.agents = [agents] if isinstance(agents, int) else list(agents)
254
+
255
+ def act(self, raw: dict[str, torch.Tensor] | None = None) -> torch.Tensor:
256
+ """Returns `idle`, `[environment_count, agents]`, or `[environment_count]` for one agent."""
257
+
258
+ shape = (self.batch.environment_count, len(self.agents))
259
+ actions = torch.full(shape, _IDLE, dtype=torch.int32, device=self.batch._torch_device)
260
+ return actions[:, 0] if len(self.agents) == 1 else actions