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
@@ -0,0 +1,1890 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """`BatchEnvironment`, the batch of environments on the GPU or the CPU, and `memory_estimate`."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import ctypes
11
+ import importlib
12
+ import importlib.util
13
+ import io
14
+ import numbers
15
+ import operator
16
+ import os
17
+ import pickle
18
+ import struct
19
+ import sys
20
+ import tempfile
21
+ import warnings
22
+ from typing import Any
23
+
24
+ import torch
25
+
26
+ from ..errors import (
27
+ ActionRangeError,
28
+ ArgumentError,
29
+ ChoiceError,
30
+ ClosedError,
31
+ ConfigurationError,
32
+ DeviceError,
33
+ EnvironmentIndexError,
34
+ LibraryError,
35
+ StateError,
36
+ _from_library,
37
+ )
38
+ from . import frame_stack as _frame_stack
39
+ from . import log as _log
40
+ from .assets import _DATA_DIRECTORY, _resolve_asset
41
+ from .library import (
42
+ _CONFIGURATION_VERSION,
43
+ _automatic,
44
+ _backend,
45
+ _Configuration,
46
+ _load_library,
47
+ _placement,
48
+ library_path,
49
+ )
50
+ from .memory import (
51
+ _LOCAL_MEMORY_HELD,
52
+ _free_device_memory,
53
+ _local_memory_bytes,
54
+ _MemoryEstimate,
55
+ _warn_memory,
56
+ )
57
+ from .state import _pickle_episode, _StateUnpickler
58
+
59
+ _REPRESENTATIONS = {'simple115': 1, 'simple115v2': 2, 'extracted': 4, 'raw': 8}
60
+ # GRF's frames, which the renderer draws, beside the cheapest representation of the library.
61
+ _PIXEL_REPRESENTATIONS = ('pixels', 'pixels_gray')
62
+ # By the type code of `cuju_environment_raw_field`.
63
+ _RAW_TYPES = (torch.float32, torch.int32, torch.bool, torch.uint8)
64
+ # `MAXIMUM_AGENTS` of the library.
65
+ _MAXIMUM_AGENTS = 22
66
+ _TYPE_STRINGS = {torch.float32: '<f4', torch.int32: '<i4', torch.bool: '|b1', torch.uint8: '|u1'}
67
+ _ACTION_SETS = {'default': 0, 'v2': 1, 'full': 2}
68
+ _ACTION_COUNTS = {'default': 19, 'v2': 20, 'full': 33}
69
+ # Whether this PyTorch has `torch.library.custom_op` (2.4 and later), which `torch.compile` traces
70
+ # a step through.
71
+ _CUSTOM_OPERATORS = hasattr(torch.library, 'custom_op')
72
+
73
+
74
+ class _Native:
75
+ """The library's handle of a batch and the files it built, which the views of its buffers keep.
76
+
77
+ A tensor that views a buffer holds this object through its storage, where Python's cycle
78
+ collector cannot see it, so this object never refers to the batch. The batch goes when the
79
+ caller drops it, and the memory when the last view of it goes.
80
+ """
81
+
82
+ def __init__(self, library, device):
83
+ self.library, self.device = library, device
84
+ self.environment = None
85
+ self.scenario_directory = None
86
+ # The allocator whose functions the library calls, kept until the batch is freed.
87
+ self.allocator = None
88
+ # The page-locked output buffers of a CPU batch, released before the batch.
89
+ self.pinned = None
90
+
91
+ def free(self):
92
+ """Frees the batch and its buffers and removes the bundles it built, at most once."""
93
+ if self.pinned:
94
+ from . import pinned as _pinned
95
+
96
+ _pinned.unregister(self.pinned)
97
+ self.pinned = None
98
+ if self.environment:
99
+ context = (
100
+ torch.cuda.device(self.device)
101
+ if self.device.type == 'cuda'
102
+ else contextlib.nullcontext()
103
+ )
104
+ with context:
105
+ self.library.cuju_environment_destroy(self.environment)
106
+ self.environment = None
107
+ # The library released its memory through the allocator inside the call.
108
+ self.allocator = None
109
+ if self.scenario_directory is not None:
110
+ self.scenario_directory.cleanup()
111
+ self.scenario_directory = None
112
+
113
+ def __del__(self, _finalizing=sys.is_finalizing):
114
+ # At interpreter exit the modules that `free` uses may already be torn down, and the
115
+ # process frees the batch with everything else. The default argument outlives them.
116
+ if _finalizing():
117
+ return
118
+ self.free()
119
+
120
+
121
+ class _CudaArray:
122
+ """A device buffer that `torch.as_tensor` reads through `__cuda_array_interface__`."""
123
+
124
+ def __init__(self, pointer, shape, dtype, owner):
125
+ # The tensor holds this object, and this object the owner of the memory it views.
126
+ self.owner = owner
127
+ self.__cuda_array_interface__ = {
128
+ 'data': (pointer, False),
129
+ 'shape': tuple(shape),
130
+ 'typestr': _TYPE_STRINGS[dtype],
131
+ 'version': 2,
132
+ 'strides': None,
133
+ }
134
+
135
+
136
+ def _view(pointer, shape, dtype, device, owner):
137
+ """Returns a tensor that views the batch memory at `pointer` on `device` without a copy.
138
+
139
+ The tensor keeps `owner`, the `_Native` of the batch, alive, so the memory outlives the batch
140
+ while a tensor views it. The owner must not refer to the batch, or the two form a cycle that
141
+ nothing collects.
142
+ """
143
+ shape = tuple(shape)
144
+ if not all(shape):
145
+ return torch.zeros(shape, dtype=dtype, device=device)
146
+ if device.type == 'cuda':
147
+ return torch.as_tensor(_CudaArray(pointer, shape, dtype, owner), device=device)
148
+ elements = 1
149
+ for size in shape:
150
+ elements *= size
151
+ memory = (ctypes.c_char * (elements * dtype.itemsize)).from_address(pointer)
152
+ memory.owner = owner
153
+ return torch.frombuffer(memory, dtype=dtype, count=elements).view(shape)
154
+
155
+
156
+ def _spaces():
157
+ """Returns the spaces of gymnasium, or of gym without it, and their `batch_space`."""
158
+ try:
159
+ import gymnasium as gym
160
+ except ImportError:
161
+ try:
162
+ import gym
163
+ except ImportError:
164
+ raise ModuleNotFoundError(
165
+ 'expected gymnasium or gym for the spaces of a batch'
166
+ ) from None
167
+ return gym.spaces, importlib.import_module(gym.__name__ + '.vector.utils').batch_space
168
+
169
+
170
+ def _host(values, dtype):
171
+ """Returns `values` as a contiguous CPU tensor of `dtype`, which the library reads."""
172
+ return torch.as_tensor(values, dtype=dtype).to('cpu').contiguous()
173
+
174
+
175
+ def _observer_failed(observer, error):
176
+ """Warns that a step observer raised and was removed, while the batch goes on."""
177
+ _log.LOGGER.warning(
178
+ 'cuju: removed the step observer %r, which raised %s: %s',
179
+ observer,
180
+ type(error).__name__,
181
+ error,
182
+ )
183
+
184
+
185
+ def _per_environment(values, dtype, name, count, error=ConfigurationError):
186
+ """Returns `values` as one host value per environment; a single value serves every one."""
187
+ array = _host(values, dtype)
188
+ if array.dim() == 0:
189
+ array = array.repeat(count)
190
+ if tuple(array.shape) != (count,):
191
+ raise error(
192
+ f'expected {name} with one value, or one for each of the {count} environments, '
193
+ f'found the shape {tuple(array.shape)}'
194
+ )
195
+ return array.contiguous()
196
+
197
+
198
+ def _integers(values, dtype, name, count, error):
199
+ """Returns integer `values` as one host value per environment, and refuses floating ones."""
200
+ array = torch.as_tensor(values)
201
+ # GRF: the seed of a scenario is a C++ `unsigned int`, which refuses a float, 5.0 included.
202
+ if array.is_floating_point() or array.is_complex():
203
+ raise TypeError(f'expected integer {name}, found {array.dtype}')
204
+ return _per_environment(array, dtype, name, count, error)
205
+
206
+
207
+ def _is_pair(value):
208
+ """Returns whether `value` is a `(left, right)` pair."""
209
+ return isinstance(value, (tuple, list)) and len(value) == 2
210
+
211
+
212
+ def _choice(kind, value, choices, hints=None):
213
+ """Returns `choices[value]`, or raises `ChoiceError` naming the valid values and any hint."""
214
+ if value in choices:
215
+ return choices[value]
216
+ hint = (hints or {}).get(value, '')
217
+ raise ChoiceError(
218
+ f'expected the {kind} {", ".join(map(repr, choices))}, found {value!r}'
219
+ + (f'; {hint}' if hint else '')
220
+ )
221
+
222
+
223
+ class BatchEnvironment:
224
+ """A batch of football environments on the GPU or the CPU.
225
+
226
+ Every tensor that a method returns views a buffer of the batch on its device, without a copy,
227
+ and the next `reset` or `step` overwrites it, so a caller clones what it keeps. The tensor
228
+ attributes live on the CPU.
229
+
230
+ Attributes:
231
+ device: `cuda` or `cpu`, the backend that runs the batch.
232
+ torch_device: The `torch.device` that holds the buffers of the batch, such as `cuda:0`, and
233
+ on which every call runs.
234
+ threads: The CPU threads that run the environments, the caller included, or 0 on the GPU.
235
+ environment_count: The number of environments.
236
+ left_agents: The agents of the left team of each environment, `[environment_count]` `int32`.
237
+ right_agents: The agents of the right team of each environment, `[environment_count]`
238
+ `int32`.
239
+ agents: The size of the agent axis, the largest number of agents of any bundle.
240
+ agent_mask: `[environment_count, agents]`, true for each agent that exists.
241
+ left_players: The players of the left team of each environment, `[environment_count]`
242
+ `int32`, as GRF's `len(observation['left_team'])` for a left agent.
243
+ right_players: The players of the right team of each environment, `[environment_count]`
244
+ `int32`. A right agent sees its own team as the left team, so its counts swap.
245
+ players: The size of each team array of `raw`, the largest team of any bundle; the array
246
+ holds the players of its team first and zeros after them.
247
+ single_observation_space, single_action_space, observation_space, action_space: The spaces
248
+ of one environment and of the batch, as gymnasium describes them.
249
+ squeeze, stacked, channel_dimensions, auto_reset, check_actions, debug: The options of
250
+ the batch.
251
+ action_count: The number of actions: 19 for `default`, 20 for `v2` and 33 for `full`.
252
+ difficulty: `[environment_count, 2]`, the difficulty of the left and of the right team of
253
+ each environment. It is the one that `difficulty` sets, else the scenario's, and for a
254
+ scenario whose difficulty follows the parity of the episode, that of its first episode.
255
+
256
+ Examples:
257
+ >>> import torch
258
+ >>> import cuju
259
+ >>> batch = cuju.BatchEnvironment('5_vs_5_l4_r0', environment_count=1024, device='cpu')
260
+ >>> observation = batch.reset()
261
+ >>> tuple(observation.shape)
262
+ (1024, 4, 115)
263
+ >>> actions = torch.zeros((1024, 4), dtype=torch.int32)
264
+ >>> observation, reward, done, information = batch.step(actions)
265
+ >>> tuple(reward.shape), tuple(done.shape)
266
+ ((1024, 4), (1024,))
267
+ """
268
+
269
+ # The step observers, in the order they were added. A batch without any pays one check per step.
270
+ _observers: tuple[Any, ...] = ()
271
+ # Whether `close` has begun, after which the batch takes no observer and removes none.
272
+ _closing = False
273
+ # The actions of the step in flight, which `step_wait` hands the observers.
274
+ _async_actions = None
275
+
276
+ def __init__(
277
+ self,
278
+ assets: str | list[str],
279
+ animations: str | None = None,
280
+ environment_count: int = 1024,
281
+ representation: str = 'simple115v2',
282
+ rewards: str = 'scoring',
283
+ action_set: str = 'default',
284
+ seed: int = 0,
285
+ numpy_legacy: bool = True,
286
+ auto_reset: bool = True,
287
+ library: str | None = None,
288
+ assignment: Any = None,
289
+ with_raw: bool = False,
290
+ difficulty: list[tuple[float | None, float | None]] | None = None,
291
+ device: str | torch.device = 'cuda',
292
+ threads: int = 0,
293
+ physics_steps_per_frame: int = 10,
294
+ channel_dimensions: tuple[int, int] = (96, 72),
295
+ stacked: bool = False,
296
+ game_engine_random_seed: Any = None,
297
+ squeeze: bool = False,
298
+ agent_counts: list[tuple[int | None, int | None]] | None = None,
299
+ episode_number: int = 0,
300
+ first_index: int = 0,
301
+ allocator: str = 'cuda',
302
+ pin_threads: bool = False,
303
+ numa: bool = False,
304
+ pin_memory: bool = False,
305
+ check_actions: bool = False,
306
+ debug: bool = False,
307
+ render_frames: bool = False,
308
+ render_resolution_x: int = 1280,
309
+ render_resolution_y: int = 720,
310
+ ) -> None:
311
+ """Creates the batch and allocates its buffers.
312
+
313
+ Args:
314
+ assets: A bundle or a list of bundles, each a bundle path, a shipped name
315
+ `<scenario>_l<left>_r<right>` with any agent counts, a bare shipped scenario such as
316
+ `5_vs_5`, or a GRF scenario file; the last two take one left agent, as in GRF.
317
+ animations: The path of `animations.bin`. `None` takes the shipped tables.
318
+ environment_count: The number of environments.
319
+ representation: `simple115`, `simple115v2`, `extracted` (the SMM), `raw` (a dictionary
320
+ of named tensors), or `pixels` and `pixels_gray`, GRF's frames shrunk to
321
+ `channel_dimensions`, `[environment_count, agents, height, width, 3]` and
322
+ `[..., 1]` `uint8`, which play every environment as a rendering GRF does and
323
+ draw each render with cuju's renderer.
324
+ rewards: `scoring`, or `scoring,checkpoints` to add the checkpoint reward.
325
+ action_set: `default`, `v2` or `full`.
326
+ seed: The seed of the batch, from 0 to 2**64 - 1. Environment `index` plays as GRF's
327
+ `create_environment` after `random.seed(seed * 2**32 + first_index + index)`.
328
+ numpy_legacy: Whether the checkpoint reward adds in the precision of numpy before 2, as
329
+ GRF does with such a numpy. `False` follows numpy 2.
330
+ auto_reset: Whether a step resets every environment whose episode ended. `False` leaves
331
+ each such environment at its end until `reset_done` or `reset`.
332
+ library: The path of the library of `device`. `None` takes `library_path(device)`.
333
+ assignment: The index into `assets` of the bundle of each environment,
334
+ `[environment_count]`. `None` gives every environment the first bundle.
335
+ with_raw: Whether the batch also writes the `raw` representation, which `raw` and
336
+ `final_raw` return.
337
+ difficulty: One `(left, right)` pair of team difficulties per bundle, each from 0 to 1
338
+ or `None` for the scenario's; every reset writes them. `None` keeps the scenarios'
339
+ own.
340
+ device: `cuda` for the current CUDA device through `libcuju_cuda.so`, `cuda:N` or a
341
+ `torch.device` for GPU N, or `cpu` for the CPU through `libcuju_cpu.so`. Both give
342
+ the same outputs bit for bit, and the device decides only where the batch runs.
343
+ `auto` takes PyTorch's current CUDA device where PyTorch sees a GPU and the CUDA
344
+ library is installed, else `cpu`, and `batch.torch_device` says which. Only an
345
+ explicit `auto` picks, never the default.
346
+ threads: The CPU threads, the caller included, or 0 for one per logical processor that
347
+ the process may run on. The GPU ignores it.
348
+ physics_steps_per_frame: The ticks of 10 milliseconds in a step, as GRF's option.
349
+ channel_dimensions: The width and the height of the SMM in cells, as GRF's option.
350
+ stacked: Whether the observation stacks the last 4 along its last axis, the oldest
351
+ first, as GRF's `stacked`; a reset fills the stack. `raw` has no stack.
352
+ game_engine_random_seed: The seed of every episode, as GRF's option: an integer for
353
+ every environment, or one per environment with -1 to draw. `None` draws every seed.
354
+ squeeze: Whether the observation (except `raw`) and the reward drop the agent axis and
355
+ `step` takes `[environment_count]` actions, as GRF for one agent. Needs one agent
356
+ each.
357
+ agent_counts: One `(left, right)` pair of agent counts per bundle, each `None` for what
358
+ the name or the bundle gives. `None` keeps the agents of every bundle.
359
+ episode_number: GRF's `episode_number`, the episode before the first; its parity picks
360
+ the even or the odd form of a scenario.
361
+ first_index: The index of environment 0 in the seed rule, so the batch plays the
362
+ environments `first_index` to `first_index + environment_count - 1` of `seed`, as a
363
+ larger batch plays them. Every index stays below 2**32.
364
+ allocator: Where the GPU buffers come from, `cuda` from `cudaMalloc`, or `torch` from
365
+ PyTorch's caching allocator, so that `torch.cuda.memory_allocated`, its statistics
366
+ and its limits count them. The outputs are the same bit for bit. The local memory
367
+ that the driver reserves for the kernels stays outside either. The CPU ignores it.
368
+ pin_threads: Whether each CPU thread that the batch starts stays on a processor of its
369
+ own, taken in order from those that `os.sched_setaffinity` allows. The calling
370
+ thread stays where it is. The GPU ignores it.
371
+ numa: Whether the CPU threads form a group per NUMA node, on that node's processors,
372
+ each stepping a fixed range of environments whose memory its threads touch first.
373
+ With one node it changes nothing. The GPU ignores it.
374
+ pin_memory: Whether the output buffers of a CPU batch are page-locked, so that
375
+ `tensor.to('cuda', non_blocking=True)` copies them without waiting. Needs CUDA. The
376
+ GPU ignores it.
377
+ check_actions: Whether a GPU batch also checks actions in GPU memory against
378
+ `[-action_count, action_count)`, as it checks actions in host memory, so that `step`
379
+ raises `ActionRangeError` before any environment steps. The check waits for the
380
+ device at every step. Without it, such an action steps as the idle action. The CPU
381
+ checks every action anyway.
382
+ debug: Whether every `step`, `step_async`, `reset_done` and masked `reset` of a GPU
383
+ batch waits for the device, so that a failure on the device raises at the call that
384
+ caused it. It checks the actions as `check_actions` does, and costs the waits. A
385
+ CUDA graph capture never waits. The CPU, which waits anyway, ignores it.
386
+ render_frames: Whether every environment plays as a rendering GRF does and `step`
387
+ adds GRF's frame of each to the information, `information['frame']`,
388
+ `[environment_count, render_resolution_y, render_resolution_x, 3]` `uint8` with
389
+ rows from the top, as GRF's observation `frame` holds them, and `final_frame` for
390
+ the ends of episodes.
391
+ render_resolution_x: The width of GRF's frames in pixels, as GRF's option, a multiple
392
+ of 4 up to 16384. `pixels` and `pixels_gray` shrink the whole frame, as GRF's
393
+ wrapper does. Only a batch that renders reads it.
394
+ render_resolution_y: The height of GRF's frames in pixels, as GRF's option, up to
395
+ 16384. GRF's `Config` sets it to 720 before it reads the caller's options, so it
396
+ stays 720 when only the width changes, here as there.
397
+
398
+ Raises:
399
+ TypeError: If `game_engine_random_seed` holds floating-point values, which GRF refuses.
400
+ ChoiceError: If `representation`, `action_set` or `device` names no known value. It is a
401
+ `ValueError` and a `KeyError`.
402
+ ConfigurationError: If `difficulty` or `agent_counts` lacks a pair per bundle,
403
+ `squeeze` meets an environment without exactly one agent, `stacked` meets `raw`,
404
+ `rewards` lacks `scoring`, `seed` lies outside `[0, 2**64)` or `first_index`
405
+ outside its range. It is a `ValueError`, and its subclass
406
+ `scenarios.ScenarioError` reports a refused scenario file.
407
+ MissingFileError: If an asset names no bundle or the library is missing. It is a
408
+ `FileNotFoundError`.
409
+ DeviceError: If `device` names a CUDA GPU and PyTorch sees none or fewer, or the CPU
410
+ lacks AVX2, BMI2 or FMA. It is a `RuntimeError`.
411
+ LibraryError: If the library fails to create the batch, for example on an `assignment`
412
+ outside `assets`, a team with fewer players than agents, a scenario with
413
+ `control_all_players` and agents that switch players, which GRF asserts against, or
414
+ if the library runs another backend. It is a `RuntimeError`.
415
+ """
416
+ device = _automatic(device)
417
+ backend = _backend(device)
418
+ pixel_kind = representation if representation in _PIXEL_REPRESENTATIONS else None
419
+ if pixel_kind and stacked:
420
+ raise ConfigurationError(f'expected no stack with {representation}, found stacked=True')
421
+ representation_flag = _choice(
422
+ 'representation',
423
+ 'simple115' if pixel_kind else representation,
424
+ _REPRESENTATIONS,
425
+ {
426
+ 'extracted_stacked': "pass representation='extracted' with stacked=True",
427
+ 'simple115_stacked': "pass representation='simple115' with stacked=True",
428
+ },
429
+ )
430
+ _choice('action set', action_set, _ACTION_SETS)
431
+ # GRF: an assertion requires `scoring` in the rewards.
432
+ if 'scoring' not in rewards.split(','):
433
+ raise ConfigurationError(
434
+ f'expected the rewards scoring or scoring,checkpoints, found {rewards!r}'
435
+ )
436
+ # GRF: the other parts are ignored, so a typo silently drops a reward.
437
+ unknown = [part for part in rewards.split(',') if part not in ('scoring', 'checkpoints')]
438
+ if unknown:
439
+ warnings.warn(
440
+ f'the rewards {rewards!r} hold {unknown}, which GRF ignores, as cuju does; '
441
+ "write them without spaces, as 'scoring,checkpoints'",
442
+ stacklevel=2,
443
+ )
444
+ if pixel_kind or render_frames:
445
+ for name, value in (('x', render_resolution_x), ('y', render_resolution_y)):
446
+ if isinstance(value, bool) or not isinstance(value, numbers.Integral):
447
+ raise ConfigurationError(
448
+ f'expected render_resolution_{name} to be a whole number, found {value!r}'
449
+ )
450
+ if not 0 < value <= 16384:
451
+ raise ConfigurationError(
452
+ f'expected render_resolution_{name} from 1 to 16384, found {value}'
453
+ )
454
+ # The renderer reads frames back in rows of whole words, as GRF's glReadPixels packs
455
+ # them for a width that is a multiple of 4.
456
+ if render_resolution_x % 4:
457
+ raise ConfigurationError(
458
+ 'expected render_resolution_x to be a multiple of 4, found '
459
+ f'{render_resolution_x}'
460
+ )
461
+ # The library holds the seed in 64 bits, where a larger or negative one would wrap.
462
+ if not 0 <= seed < 2**64:
463
+ raise ConfigurationError(f'expected a seed from 0 to 2**64 - 1, found {seed}')
464
+ if environment_count < 1:
465
+ raise ConfigurationError(
466
+ f'expected at least one environment, found {environment_count}'
467
+ )
468
+ # GRF: the index and the seed share one key, so an index of 2**32 would be another seed's.
469
+ if not 0 <= first_index <= 2**32 - environment_count:
470
+ raise ConfigurationError(
471
+ f'expected a first index from 0 to 2**32 - environment_count, found {first_index}'
472
+ )
473
+ if threads < 0:
474
+ raise ConfigurationError(
475
+ f'expected 0 threads for one per processor, or more, found {threads}'
476
+ )
477
+ if allocator not in ('cuda', 'torch'):
478
+ raise ChoiceError(f'expected the allocator cuda or torch, found {allocator!r}')
479
+ if pin_memory and backend == 'cpu' and not torch.cuda.is_available():
480
+ raise DeviceError(
481
+ 'expected a CUDA GPU for pin_memory=True, found none that PyTorch can use'
482
+ )
483
+ self.device = backend
484
+ # A GPU batch stays on its CUDA device, and every call runs there.
485
+ self._torch_device = _placement(device)
486
+ logged = _log.start(backend, self._torch_device)
487
+ self._library = _load_library(library, backend)
488
+ # What the views of the buffers keep alive, without the batch.
489
+ self._native = _Native(self._library, self._torch_device)
490
+ requested = [assets] if isinstance(assets, str) or callable(assets) else list(assets)
491
+ self._requested = requested
492
+ resolved = [_resolve_asset(asset) for asset in requested]
493
+ paths = [path for path, _ in resolved]
494
+ if animations is None:
495
+ animations = os.path.join(_DATA_DIRECTORY, 'animations.bin')
496
+ # A scenario file becomes a bundle without agents, which the batch reads at its creation,
497
+ # built with the batch's animation tables.
498
+ for index, path in enumerate(paths):
499
+ if path.endswith('.py'):
500
+ from .. import scenarios
501
+
502
+ # With `CUJU_BUNDLE_CACHE` set, a file builds once and later batches load it.
503
+ cached = scenarios._batch_bundle(path, backend, library, animations)
504
+ if cached is not None:
505
+ paths[index] = cached
506
+ continue
507
+ if self._native.scenario_directory is None:
508
+ self._native.scenario_directory = tempfile.TemporaryDirectory(prefix='cuju-')
509
+ name = os.path.splitext(os.path.basename(path))[0]
510
+ paths[index] = scenarios.build_bundle(
511
+ path,
512
+ os.path.join(self._native.scenario_directory.name, f'{index}_{name}_l0_r0.cjb'),
513
+ device=backend,
514
+ library=library,
515
+ animations=animations,
516
+ )
517
+ if agent_counts is not None and (
518
+ len(agent_counts) != len(paths) or not all(map(_is_pair, agent_counts))
519
+ ):
520
+ raise ConfigurationError(
521
+ f'expected a (left, right) pair of agent counts for each of the {len(paths)} '
522
+ f'bundles, such as [(4, 0)] for one, found {agent_counts!r}'
523
+ )
524
+ counts = [
525
+ [
526
+ named if given is None else given
527
+ for named, given in zip(named_pair, given_pair, strict=True)
528
+ ]
529
+ for (_, named_pair), given_pair in zip(
530
+ resolved, agent_counts or [(None, None)] * len(paths), strict=True
531
+ )
532
+ ]
533
+ counts_array = (ctypes.c_int * (2 * len(paths)))(
534
+ *(count for pair in counts for count in pair)
535
+ )
536
+ if difficulty is not None:
537
+ if len(difficulty) != len(paths) or not all(map(_is_pair, difficulty)):
538
+ raise ConfigurationError(
539
+ f'expected a (left, right) pair of difficulties for each of the {len(paths)} '
540
+ f'bundles, such as [(None, 0.5)] for one, found {difficulty!r}'
541
+ )
542
+ if any(
543
+ value is not None and not 0 <= value <= 1 for pair in difficulty for value in pair
544
+ ):
545
+ raise ConfigurationError(
546
+ f"expected difficulties from 0 to 1, or None for the scenario's, found "
547
+ f'{difficulty!r}'
548
+ )
549
+ if assignment is None and len(paths) > 1:
550
+ warnings.warn(
551
+ f'the batch has {len(paths)} bundles and no assignment, so every environment plays '
552
+ 'the first; pass assignment, the bundle index of each environment',
553
+ stacklevel=2,
554
+ )
555
+ if with_raw:
556
+ representation_flag |= _REPRESENTATIONS['raw']
557
+ if stacked and representation == 'raw':
558
+ raise ConfigurationError(
559
+ 'expected simple115, simple115v2 or extracted for a stack, found raw'
560
+ )
561
+ path_array = (ctypes.c_char_p * len(paths))(*(path.encode() for path in paths))
562
+ assignment_array = (
563
+ None
564
+ if assignment is None
565
+ else _per_environment(assignment, torch.int32, 'assignment', environment_count)
566
+ )
567
+ fixed_seeds = None
568
+ if game_engine_random_seed is not None:
569
+ fixed_seeds = _integers(
570
+ game_engine_random_seed,
571
+ torch.int64,
572
+ 'game_engine_random_seed',
573
+ environment_count,
574
+ ConfigurationError,
575
+ )
576
+ width, height = channel_dimensions
577
+ configuration = _Configuration(
578
+ version=_CONFIGURATION_VERSION,
579
+ assets=path_array,
580
+ asset_count=len(paths),
581
+ assignment=None if assignment_array is None else assignment_array.data_ptr(),
582
+ animations=animations.encode(),
583
+ environment_count=environment_count,
584
+ seed=seed,
585
+ action_set=_ACTION_SETS[action_set],
586
+ observation=representation_flag,
587
+ checkpoints=int('checkpoints' in rewards.split(',')),
588
+ numpy_legacy=int(numpy_legacy),
589
+ auto_reset=int(auto_reset),
590
+ threads=threads,
591
+ ticks_per_step=physics_steps_per_frame,
592
+ smm_width=width,
593
+ smm_height=height,
594
+ stack=4 if stacked else 1,
595
+ fixed_seeds=None if fixed_seeds is None else fixed_seeds.data_ptr(),
596
+ agent_counts=ctypes.addressof(counts_array),
597
+ episode_number=episode_number,
598
+ first_index=first_index,
599
+ pin_threads=int(pin_threads),
600
+ numa=int(numa),
601
+ page_aligned=int(pin_memory and backend == 'cpu'),
602
+ )
603
+ estimate_only = getattr(self, '_estimate_only', False)
604
+ # The functions must outlive the batch, which calls them until it is freed.
605
+ if allocator == 'torch' and backend == 'cuda' and not estimate_only:
606
+ from .allocator import TorchAllocator
607
+
608
+ self._native.allocator = TorchAllocator(self._torch_device)
609
+ configuration.allocate, configuration.release = self._native.allocator.pointers()
610
+ # The query loads the kernels, so the free memory that follows leaves their code out.
611
+ local_memory = _local_memory_bytes(self._library, self._torch_device)
612
+ free_memory = None
613
+ if backend == 'cuda' and not estimate_only:
614
+ free_memory = _free_device_memory(self._torch_device, allocator)
615
+ with self._on_device():
616
+ if estimate_only:
617
+ estimate = ctypes.c_ulonglong()
618
+ status = self._library.cuju_memory_estimate(
619
+ ctypes.byref(configuration), ctypes.byref(estimate)
620
+ )
621
+ environment = None if status != 0 else 1
622
+ else:
623
+ environment = self._library.cuju_environment_create(ctypes.byref(configuration))
624
+ if not environment:
625
+ message = self._library.cuju_last_error().decode()
626
+ # The library names the bundle it read; name what the caller passed instead.
627
+ for path, asset in zip(paths, requested, strict=True):
628
+ message = message.replace(path, repr(asset))
629
+ if self._native.allocator is not None and self._native.allocator.errors:
630
+ raise self._native.allocator.errors[0]
631
+ raise _from_library(message)
632
+ if estimate_only:
633
+ bundles = (
634
+ torch.zeros(environment_count, dtype=torch.int64)
635
+ if assignment_array is None
636
+ else assignment_array.long()
637
+ )
638
+ # The difficulty set below takes `[environment_count, 2]` floats of the library.
639
+ sets_difficulty = any(
640
+ value is not None and bool((bundles == bundle).any())
641
+ for bundle, pair in enumerate(difficulty or [])
642
+ for value in pair
643
+ )
644
+ self._estimated_bytes = _MemoryEstimate(
645
+ estimate.value + 8 * environment_count * sets_difficulty, local_memory
646
+ )
647
+ return
648
+ self._native.environment = environment
649
+ # The creation launched the kernels, and the driver holds their local memory from then on.
650
+ if backend == 'cuda':
651
+ _LOCAL_MEMORY_HELD.add(self._torch_device.index)
652
+ if free_memory is not None:
653
+ _warn_memory(
654
+ self.memory_bytes + local_memory, free_memory, self._torch_device, local_memory
655
+ )
656
+ self.threads = self._library.cuju_environment_threads(environment)
657
+ self.environment_count = environment_count
658
+ self.left_agents = torch.zeros(environment_count, dtype=torch.int32)
659
+ self.right_agents = torch.zeros(environment_count, dtype=torch.int32)
660
+ self.agents = self._library.cuju_environment_agents(
661
+ environment, self.left_agents.data_ptr(), self.right_agents.data_ptr()
662
+ )
663
+ self.left_players = torch.zeros(environment_count, dtype=torch.int32)
664
+ self.right_players = torch.zeros(environment_count, dtype=torch.int32)
665
+ self.players = self._library.cuju_environment_players(
666
+ environment, self.left_players.data_ptr(), self.right_players.data_ptr()
667
+ )
668
+ slots = torch.arange(self.agents)
669
+ self.agent_mask = slots < (self.left_agents + self.right_agents)[:, None]
670
+ self.action_count = _ACTION_COUNTS[action_set]
671
+ if squeeze and not bool(((self.left_agents + self.right_agents) == 1).all()):
672
+ self.close()
673
+ raise ConfigurationError(
674
+ 'expected one agent in every environment to squeeze the agent axis'
675
+ )
676
+ self.squeeze = squeeze
677
+ self.stacked = stacked
678
+ self.channel_dimensions = (width, height)
679
+ bundles = (
680
+ torch.zeros(environment_count, dtype=torch.int64)
681
+ if assignment_array is None
682
+ else assignment_array.long()
683
+ )
684
+ chosen = torch.full((environment_count, 2), float('nan'))
685
+ for bundle, pair in enumerate(difficulty or []):
686
+ for side, value in enumerate(pair):
687
+ if value is not None:
688
+ chosen[bundles == bundle, side] = value
689
+ if not torch.isnan(chosen).all():
690
+ # The library takes a negative difficulty for that of the scenario.
691
+ values = torch.nan_to_num(chosen, nan=-1.0).contiguous()
692
+ with self._on_device():
693
+ self._check(
694
+ self._library.cuju_environment_set_difficulty(self._handle(), values.data_ptr())
695
+ )
696
+ self.difficulty = torch.empty((environment_count, 2), dtype=torch.float32)
697
+ self._library.cuju_environment_difficulty(self._handle(), self.difficulty.data_ptr())
698
+ self.auto_reset = auto_reset
699
+ self.check_actions, self.debug = check_actions, debug
700
+ self._checks_device_actions = backend == 'cuda' and (check_actions or debug)
701
+ self._agent_mask_on_device = None
702
+ self._checkpoints = 'checkpoints' in rewards.split(',')
703
+ self._representation = representation
704
+ self._raw_fields = (
705
+ self._describe_raw() if representation_flag & _REPRESENTATIONS['raw'] else None
706
+ )
707
+ stack = 4 if stacked else 1
708
+ if representation == 'raw':
709
+ self._observation_name, self._observation_shape, self._observation_type = (
710
+ 'raw',
711
+ None,
712
+ None,
713
+ )
714
+ elif representation == 'extracted':
715
+ self._observation_name, self._observation_shape, self._observation_type = (
716
+ 'smm',
717
+ (environment_count, self.agents, height, width, 4 * stack),
718
+ torch.uint8,
719
+ )
720
+ else:
721
+ self._observation_name, self._observation_shape, self._observation_type = (
722
+ 'simple115',
723
+ (environment_count, self.agents, 115 * stack),
724
+ torch.float32,
725
+ )
726
+ # The tensors share the buffers, which never move, so they are made once.
727
+ self._cached_outputs = None
728
+ self._score_reward = None
729
+ _log.created(self, requested, library or library_path(backend), logged)
730
+ # The key of the batch for the operators of `torch.compile`, and the outputs they mutate.
731
+ self._operator_key = None
732
+ self._operator_outputs = None
733
+ self._operator_static = False
734
+ self._step_in_flight = False
735
+ if pin_memory and backend == 'cpu':
736
+ from . import pinned as _pinned
737
+
738
+ try:
739
+ self._native.pinned = _pinned.register(self._output_ranges())
740
+ except BaseException:
741
+ self.close()
742
+ raise
743
+ self._frames = None
744
+ self._render_frames = bool(render_frames)
745
+ if pixel_kind or render_frames:
746
+ from .pixels import Frames
747
+
748
+ # GRF: a rendering engine plays render mode and every reset with animations.
749
+ self._set_render(render_mode=1, referee_animations=True)
750
+ try:
751
+ self._frames = Frames(
752
+ self,
753
+ pixel_kind,
754
+ width,
755
+ height,
756
+ (int(render_resolution_x), int(render_resolution_y)),
757
+ )
758
+ except BaseException:
759
+ self.close()
760
+ raise
761
+ if os.environ.get('CUJU_BATCH_HOOKS'):
762
+ # The hooks read states and never write one, so every output stays as it is.
763
+ from .. import _plugins
764
+
765
+ _plugins.on_batch_created(self)
766
+
767
+ @property
768
+ def scenario_name(self) -> str:
769
+ """The scenarios that the batch was created with, as their names without folders or
770
+ suffixes, joined by commas, such as `5_vs_5_l4_r0` or `academy_corner, my_scenario`."""
771
+ names = []
772
+ for asset in self._requested:
773
+ name = os.path.basename(os.fspath(asset))
774
+ for suffix in ('.cjb', '.py'):
775
+ name = name.removesuffix(suffix)
776
+ if name not in names:
777
+ names.append(name)
778
+ return ', '.join(names)
779
+
780
+ @property
781
+ def observers(self) -> tuple[Any, ...]:
782
+ """The step observers of the batch, in the order that they are called."""
783
+ return self._observers
784
+
785
+ def add_observer(self, observer: Any) -> Any:
786
+ """Calls `observer` after every `reset` and step of the batch, and when the batch closes.
787
+
788
+ The batch calls `observer(batch, done, information)`. After `step` and `step_wait`, `done`
789
+ is the done flags that the step returns, and `information` holds the entries of the
790
+ dictionary that the step returns, the step's rewards under `reward`, the tensor that the
791
+ step returns, and the step's actions under `actions`, in a dictionary of its own, so the
792
+ step's own dictionary stays as it is. The actions are the `[environment_count, agents]`
793
+ `int32` indices that the step played, as the caller gave them, on the batch's device. They
794
+ are the caller's own tensor when it was already such a tensor, which the observer reads and
795
+ leaves as it is, and clones to keep past its call. After `step_async` they are a copy taken
796
+ when the step started, since the caller may change its tensor while the step runs. After
797
+ `reset` and `reset_done`, `done` is `None` and `information` maps `reset` to the
798
+ `[environment_count]` booleans of the environments that started an episode, or to `None`
799
+ when every environment did. When the batch closes, `done` is `None` and `information`
800
+ maps `close` to `True`, and the batch drops its observers after that call. Observers run
801
+ in the order that they were added, after the outputs are written, and they may read the
802
+ batch, such as its states, but must leave its outputs as they are. An observer that closes
803
+ the batch during a reset or a step makes that call raise `ClosedError`, since the outputs
804
+ view the freed buffers.
805
+
806
+ A batch dropped without `close` makes no close call. An observer that keeps the batch in an
807
+ attribute forms a cycle with it, which holds the batch's memory until Python collects the
808
+ cycle, so an observer that needs the batch between its calls holds it through a `weakref`.
809
+
810
+ An observer that raises an `Exception` is removed, with one warning through the logger
811
+ `cuju`, and the batch goes on. A step or reset captured into a CUDA graph, or run by a
812
+ function that `torch.compile` compiled, calls no observer, since it runs without Python.
813
+
814
+ Args:
815
+ observer: The callable.
816
+
817
+ Returns:
818
+ The observer, so that a call can add and keep it at once.
819
+
820
+ Raises:
821
+ ArgumentError: If the observer is not callable or was already added. It is a
822
+ `ValueError`.
823
+ ClosedError: If the batch is closed or closing. It is a `RuntimeError`.
824
+ """
825
+ self._handle()
826
+ if self._closing:
827
+ raise ClosedError('the batch is closing')
828
+ if not callable(observer):
829
+ raise ArgumentError(f'expected a callable observer, found {observer!r}')
830
+ if any(added is observer for added in self._observers):
831
+ raise ArgumentError(f'expected an observer that was not added yet, found {observer!r}')
832
+ self._observers = (*self._observers, observer)
833
+ return observer
834
+
835
+ def remove_observer(self, observer: Any) -> None:
836
+ """Stops calling an observer that `add_observer` added.
837
+
838
+ Once `close` begins the batch drops every observer, so the call then does nothing, as for
839
+ an observer that removes itself during its close call.
840
+
841
+ Raises:
842
+ ArgumentError: If the open batch has no such observer. It is a `ValueError`.
843
+ """
844
+ if not self._discard_observer(observer) and not self._closing:
845
+ raise ArgumentError(f'expected an observer of the batch, found {observer!r}')
846
+
847
+ def _discard_observer(self, observer):
848
+ """Removes an observer, and returns whether the batch had it."""
849
+ kept = tuple(added for added in self._observers if added is not observer)
850
+ found = len(kept) != len(self._observers)
851
+ self._observers = kept
852
+ return found
853
+
854
+ def _capturing(self):
855
+ """Returns whether the batch's stream is capturing a CUDA graph, which runs without Python
856
+ when it replays, so that a call under capture is not observed."""
857
+ if self.device == 'cpu':
858
+ return False
859
+ with self._on_device():
860
+ return torch.cuda.is_current_stream_capturing()
861
+
862
+ def _notify(self, done, information):
863
+ """Calls every observer, and removes one that raises with a warning, sparing the call."""
864
+ if self._capturing():
865
+ return
866
+ for observer in self._observers:
867
+ # An observer may remove another, which then misses the call.
868
+ if not any(added is observer for added in self._observers):
869
+ continue
870
+ try:
871
+ observer(self, done, information)
872
+ except Exception as error:
873
+ self._discard_observer(observer)
874
+ _observer_failed(observer, error)
875
+ # An observer that closed the batch freed the buffers that the outputs view, so the call
876
+ # raises rather than return them.
877
+ if self._closing:
878
+ raise ClosedError('an observer closed the batch during the call')
879
+
880
+ def _output_ranges(self):
881
+ """Returns the address and the size in bytes of every output buffer of the batch."""
882
+ count, agents = self.environment_count, self.agents
883
+ sizes = {'reward': count * agents * 4, 'done': count, 'score_reward': count * 4}
884
+ if self._observation_shape is not None:
885
+ elements = 1
886
+ for size in self._observation_shape:
887
+ elements *= size
888
+ observation = elements * self._observation_type.itemsize
889
+ sizes[self._observation_name] = sizes['final_' + self._observation_name] = observation
890
+ if self._raw_fields is not None:
891
+ raw = 0
892
+ for _, dtype, shape, offset in self._raw_fields:
893
+ elements = 1
894
+ for size in shape:
895
+ elements *= size
896
+ raw = max(raw, offset + elements * dtype.itemsize)
897
+ sizes['raw'] = sizes['final_raw'] = raw
898
+ return [
899
+ (self._library.cuju_environment_buffer(self._handle(), name.encode()), size)
900
+ for name, size in sizes.items()
901
+ ]
902
+
903
+ def close(self) -> None:
904
+ """Frees the batch and its buffers at once. A second call does nothing.
905
+
906
+ The tensors that the batch returned view those buffers, so none may be used after it, and
907
+ every later call on the batch raises `ClosedError`, a `RuntimeError`. A batch dropped
908
+ without `close` frees them once no tensor that it returned remains, and makes no close call
909
+ to its observers.
910
+
911
+ The observers receive their close call in order, and one may remove itself or another
912
+ during it. A call of `close` from an observer's close call returns at once, and the first
913
+ call frees the batch once every observer has had its call.
914
+ """
915
+ if self._closing:
916
+ return
917
+ self._closing = True
918
+ try:
919
+ for observer in self._observers:
920
+ # An observer may remove another, which then misses the call.
921
+ if not any(added is observer for added in self._observers):
922
+ continue
923
+ try:
924
+ observer(self, None, {'close': True})
925
+ except Exception as error:
926
+ _observer_failed(observer, error)
927
+ finally:
928
+ self._observers = ()
929
+ frames = getattr(self, '_frames', None)
930
+ if frames is not None:
931
+ frames.close()
932
+ native = getattr(self, '_native', None)
933
+ if native is not None:
934
+ native.free()
935
+
936
+ def __enter__(self) -> BatchEnvironment:
937
+ self._handle()
938
+ return self
939
+
940
+ def __exit__(self, *exception: object) -> None:
941
+ # `with` frees the batch at the end of its block, an exception included.
942
+ self.close()
943
+
944
+ def __reduce__(self):
945
+ # A batch owns device memory and threads, which no pickle can carry to another process.
946
+ raise TypeError(
947
+ 'a batch cannot be pickled; create it inside the worker process that uses it'
948
+ )
949
+
950
+ @property
951
+ def memory_bytes(self) -> int:
952
+ """The bytes of memory that the batch has requested so far, its tables included.
953
+
954
+ It counts device memory on the GPU and host memory on the CPU. The allocators round each
955
+ request up. The first batch of the process on a GPU also makes the driver reserve the local
956
+ memory of the kernels, which `memory_estimate` gives as `local_memory_bytes` and this count
957
+ leaves out. A few later calls add a small buffer each, on the GPU the first
958
+ `reset` with seeds, with a reverse flag or with a host mask, and on the CPU the first
959
+ `step_async`.
960
+ """
961
+ return int(self._library.cuju_environment_memory_bytes(self._handle()))
962
+
963
+ def _handle(self):
964
+ """Returns the library's handle of the batch, or raises `ClosedError` once it is closed."""
965
+ environment = getattr(getattr(self, '_native', None), 'environment', None)
966
+ if not environment:
967
+ raise ClosedError('the batch is closed')
968
+ return environment
969
+
970
+ def _check(self, status):
971
+ """Raises the error of the library if `status` reports a failure."""
972
+ if status != 0:
973
+ raise _from_library(self._library.cuju_last_error().decode())
974
+
975
+ def _set_render(self, mask=None, render_mode=0, referee_animations=False):
976
+ """Sets GRF's render mode and referee animations of later resets, for the renderer.
977
+
978
+ Args:
979
+ mask: A sequence of `environment_count` truth values that picks the environments, or
980
+ `None` for every environment.
981
+ render_mode: GRF's render mode, stored for the renderer.
982
+ referee_animations: GRF's `animations` flag of `GameEnv::reset`, which plays every
983
+ stoppage in full.
984
+ """
985
+ pointer = None
986
+ if mask is not None:
987
+ values = (ctypes.c_ubyte * self.environment_count)(*(1 if flag else 0 for flag in mask))
988
+ pointer = ctypes.cast(values, ctypes.c_void_p)
989
+ self._check(
990
+ self._library.cuju_environment_set_render(
991
+ self._handle(), pointer, int(render_mode), 1 if referee_animations else 0
992
+ )
993
+ )
994
+
995
+ def _render_states(self, indices):
996
+ """Returns the RenderState of each environment of `indices`, for the renderer.
997
+
998
+ Each environment carries its RenderState from call to call, as GRF's graphics side does,
999
+ so the renderer calls this after every step it draws.
1000
+
1001
+ Args:
1002
+ indices: A sequence of environment indices.
1003
+
1004
+ Returns:
1005
+ The bytes of the RenderStates, one after another in the layout of
1006
+ `include/cuju/render/render_state.h`, and a list of each environment's count of state
1007
+ saves and loads, after each of which GRF draws the nets afresh.
1008
+ """
1009
+ count = len(indices)
1010
+ size = self._library.cuju_engine_render_state_size()
1011
+ environments = (ctypes.c_int * max(count, 1))(*indices)
1012
+ states = ctypes.create_string_buffer(max(count * size, 1))
1013
+ processed = (ctypes.c_uint * max(count, 1))()
1014
+ self._check(
1015
+ self._library.cuju_environment_render_states(
1016
+ self._handle(),
1017
+ ctypes.cast(environments, ctypes.c_void_p),
1018
+ count,
1019
+ ctypes.cast(states, ctypes.c_void_p),
1020
+ count * size,
1021
+ ctypes.cast(processed, ctypes.c_void_p),
1022
+ )
1023
+ )
1024
+ return states.raw[: count * size], list(processed)[:count]
1025
+
1026
+ def _describe_raw(self):
1027
+ """Returns the name, the type, the shape and the offset of each raw array."""
1028
+ fields = []
1029
+ element_type, offset = ctypes.c_int(), ctypes.c_ulonglong()
1030
+ dimensions = (ctypes.c_int * 2)()
1031
+ for field in range(64):
1032
+ name = self._library.cuju_environment_raw_field(
1033
+ self._handle(),
1034
+ field,
1035
+ ctypes.byref(element_type),
1036
+ dimensions,
1037
+ ctypes.byref(offset),
1038
+ )
1039
+ if name is None:
1040
+ break
1041
+ shape = (
1042
+ self.environment_count,
1043
+ self.agents,
1044
+ *(dimension for dimension in dimensions if dimension),
1045
+ )
1046
+ fields.append((name.decode(), _RAW_TYPES[element_type.value], shape, offset.value))
1047
+ return fields
1048
+
1049
+ def _raw(self, name):
1050
+ """Returns the raw arrays of a buffer as tensors that share it."""
1051
+ pointer = self._library.cuju_environment_buffer(self._handle(), name.encode())
1052
+ return {
1053
+ field: _view(pointer + offset, shape, dtype, self._torch_device, self._native)
1054
+ for field, dtype, shape, offset in self._raw_fields
1055
+ }
1056
+
1057
+ def _buffer(self, name, shape, dtype):
1058
+ """Returns a named output buffer as a tensor that shares it."""
1059
+ pointer = self._library.cuju_environment_buffer(self._handle(), name.encode())
1060
+ return _view(pointer, shape, dtype, self._torch_device, self._native)
1061
+
1062
+ def _outputs(self):
1063
+ """Returns the observation, the reward, the done flags and the final observation."""
1064
+ # The cached tensors view the buffers, which a closed batch has freed.
1065
+ self._handle()
1066
+ if self._cached_outputs is None:
1067
+ reward = self._buffer('reward', (self.environment_count, self.agents), torch.float32)
1068
+ done = self._buffer('done', (self.environment_count,), torch.uint8)
1069
+ if self._representation == 'raw':
1070
+ observation, final = self._raw('raw'), self._raw('final_raw')
1071
+ else:
1072
+ observation = self._buffer(
1073
+ self._observation_name, self._observation_shape, self._observation_type
1074
+ )
1075
+ final = self._buffer(
1076
+ 'final_' + self._observation_name,
1077
+ self._observation_shape,
1078
+ self._observation_type,
1079
+ )
1080
+ if self.squeeze:
1081
+ # GRF: the raw observation of one agent keeps its agent axis.
1082
+ if self._representation != 'raw':
1083
+ observation, final = observation.squeeze(1), final.squeeze(1)
1084
+ reward = reward.squeeze(1)
1085
+ self._cached_outputs = observation, reward, done, final
1086
+ self._prepare_operators()
1087
+ # The buffers never move, so the compiler's CUDA graphs may write them in place. The
1088
+ # compiler takes seconds to load, so a batch marks them only once something else loaded it.
1089
+ if not self._operator_static and 'torch._dynamo' in sys.modules:
1090
+ for tensor in self._operator_outputs:
1091
+ torch._dynamo.mark_static_address(tensor)
1092
+ self._operator_static = True
1093
+ return self._cached_outputs
1094
+
1095
+ @property
1096
+ def torch_device(self) -> torch.device:
1097
+ """The `torch.device` of the buffers of the batch, such as `cuda:0` or `cpu`."""
1098
+ return self._torch_device
1099
+
1100
+ def _prepare_operators(self):
1101
+ """Registers the batch with the operators of `torch.compile` and lists what they mutate."""
1102
+ from . import operators as _operators
1103
+
1104
+ if self._score_reward is None:
1105
+ self._score_reward = self._buffer(
1106
+ 'score_reward', (self.environment_count,), torch.int32
1107
+ )
1108
+ self._operator_outputs = [
1109
+ tensor
1110
+ for output in (*self._cached_outputs, self._score_reward)
1111
+ for tensor in (output.values() if isinstance(output, dict) else (output,))
1112
+ ]
1113
+ self._operator_key = _operators.register(self)
1114
+
1115
+ def _operator_step(self, actions, outputs):
1116
+ """Runs `cuju::step`, then fills each of `outputs` that copies a tensor of the batch."""
1117
+ if self._checks_device_actions:
1118
+ self._check_device_actions(actions)
1119
+ with self._on_device():
1120
+ status = self._library.cuju_environment_step(
1121
+ self._handle(), actions.data_ptr(), 1, self._stream(), 0
1122
+ )
1123
+ if status == -2:
1124
+ raise ActionRangeError(self._library.cuju_last_error().decode())
1125
+ self._check(status)
1126
+ self._wait_in_debug()
1127
+ self._copy_operator_outputs(outputs)
1128
+
1129
+ def _operator_reset_done(self, outputs):
1130
+ """Runs `cuju::reset_done`, then fills `outputs` as `_operator_step` does."""
1131
+ with self._on_device():
1132
+ self._check(self._library.cuju_environment_reset_done(self._handle(), self._stream()))
1133
+ self._wait_in_debug()
1134
+ self._copy_operator_outputs(outputs)
1135
+
1136
+ def _copy_operator_outputs(self, outputs):
1137
+ """Copies each output into the tensor of `outputs` in its place, unless it is the same."""
1138
+ for given, own in zip(outputs, self._operator_outputs, strict=True):
1139
+ if given.data_ptr() != own.data_ptr():
1140
+ given.copy_(own)
1141
+
1142
+ def _compiled_step(self, actions):
1143
+ """`step` under `torch.compile`, through the operator `cuju::step`."""
1144
+ shape = (self.environment_count, self.agents)
1145
+ if not isinstance(actions, torch.Tensor):
1146
+ actions = torch.as_tensor(actions)
1147
+ if actions.is_floating_point() or actions.is_complex():
1148
+ raise TypeError(f'expected integer action indices, found {actions.dtype}')
1149
+ if tuple(actions.shape) != shape and not (
1150
+ self.agents == 1 and tuple(actions.shape) == (self.environment_count,)
1151
+ ):
1152
+ raise ArgumentError(
1153
+ f'expected actions of the shape {shape}, [environment_count, agents], found '
1154
+ f'{tuple(actions.shape)}'
1155
+ )
1156
+ actions = actions.to(self._torch_device, torch.int32).reshape(shape).contiguous()
1157
+ # Before the first reset this is a graph break, and the step then raises as `step` does.
1158
+ if self._operator_outputs is None:
1159
+ self._outputs()
1160
+ torch.ops.cuju.step(self._operator_key, actions, self._operator_outputs)
1161
+ observation, reward, done, final = self._cached_outputs
1162
+ return (
1163
+ observation,
1164
+ reward,
1165
+ done,
1166
+ {'final_observation': final, 'score_reward': self._score_reward},
1167
+ )
1168
+
1169
+ def _compiled_reset_done(self):
1170
+ """`reset_done` under `torch.compile`, through the operator `cuju::reset_done`."""
1171
+ if self._operator_outputs is None:
1172
+ self._outputs()
1173
+ torch.ops.cuju.reset_done(self._operator_key, self._operator_outputs)
1174
+
1175
+ def _stream(self):
1176
+ """Returns PyTorch's current CUDA stream on the batch's device, or `None` on the CPU."""
1177
+ if self.device == 'cpu':
1178
+ return None
1179
+ return torch.cuda.current_stream(self._torch_device).cuda_stream
1180
+
1181
+ def _on_device(self):
1182
+ """Returns a context that runs the calls of the library on the batch's CUDA device."""
1183
+ if self.device == 'cpu':
1184
+ return contextlib.nullcontext()
1185
+ return torch.cuda.device(self._torch_device)
1186
+
1187
+ def _per_environment(self, values, dtype, name):
1188
+ """Returns `values` as one host value per environment of the batch."""
1189
+ return _per_environment(values, dtype, name, self.environment_count, ArgumentError)
1190
+
1191
+ def _staged(self, array):
1192
+ """Returns a host input of a GPU batch that the caller may reuse once the call returns.
1193
+
1194
+ The library copies host inputs to the device with `cudaMemcpyAsync`, which reads pinned
1195
+ memory later, when the stream reaches the copy, and stages pageable memory before it
1196
+ returns. So a pinned input becomes a pageable clone, and any other stays as it is.
1197
+ """
1198
+ if array is not None and self.device == 'cuda' and array.is_pinned():
1199
+ return array.clone()
1200
+ return array
1201
+
1202
+ def reset(self, seeds: Any = None, reverse: Any = None, mask: Any = None) -> Any:
1203
+ """Starts the next episode of every environment, or of those that `mask` selects.
1204
+
1205
+ Args:
1206
+ seeds: One seed per environment for this episode, as `game_engine_random_seed` in the
1207
+ configuration of GRF, or one seed for every environment. A seed of -1 draws that
1208
+ environment's seed exactly as `None` does, the draws of its first reset included.
1209
+ `None` draws every seed.
1210
+ reverse: One `reverse_team_processing` flag per environment, or one for every
1211
+ environment. `None` follows the seeds, as GRF does. Only the first reset of an
1212
+ environment reads it.
1213
+ mask: `[environment_count]` booleans. Each environment where it is true starts its next
1214
+ episode as GRF's `reset()` does, with its seed draw, and the others keep their
1215
+ episode, outputs and done flags. A mask on the batch's device takes no copy, and
1216
+ the call then waits for nothing, so a CUDA graph can capture it once every
1217
+ environment has had its first reset. `None` resets every environment and waits.
1218
+ Host arguments, pinned or not, may be reused as soon as the call returns.
1219
+
1220
+ Returns:
1221
+ The observation of every agent: `[environment_count, agents, 115]` for `simple115` and
1222
+ `simple115v2`, `[environment_count, agents, height, width, 4]` for `extracted`, or a
1223
+ dictionary of `[environment_count, agents, ...]` tensors for `raw`. A stack multiplies
1224
+ the last axis by 4, and `squeeze` drops the agent axis except for `raw`.
1225
+
1226
+ Raises:
1227
+ TypeError: If `seeds`, `reverse` or `mask` holds floating-point values, which GRF
1228
+ refuses for a seed, 5.0 included.
1229
+ ArgumentError: If `seeds`, `reverse` or `mask` holds neither one value nor one per
1230
+ environment, a seed lies outside `[0, 4294967295]` and is not -1, or a reverse flag
1231
+ is neither 0 nor 1. It is a `ValueError`.
1232
+ LibraryError: If the library fails to reset the batch. It is a `RuntimeError`.
1233
+ UndefinedPathError: If an environment reaches a path that GRF leaves undefined. It is a
1234
+ `RuntimeError`.
1235
+ DeviceError: If the device fails in a `debug` batch. It is a `RuntimeError`.
1236
+ """
1237
+ seed_array = None
1238
+ if seeds is not None:
1239
+ seed_array = _integers(
1240
+ seeds, torch.int64, 'seeds', self.environment_count, ArgumentError
1241
+ )
1242
+ # GRF: the scenario holds its seed as a 32-bit `unsigned int`.
1243
+ if bool(((seed_array < -1) | (seed_array > 4294967295)).any()):
1244
+ raise ArgumentError(
1245
+ f'expected seeds from 0 to 4294967295, or -1 to draw, found '
1246
+ f'{seed_array.tolist()}'
1247
+ )
1248
+ reverse_array = None
1249
+ if reverse is not None:
1250
+ reverse_array = _integers(
1251
+ reverse, torch.int64, 'reverse', self.environment_count, ArgumentError
1252
+ )
1253
+ if bool(((reverse_array != 0) & (reverse_array != 1)).any()):
1254
+ raise ArgumentError(
1255
+ f'expected reverse flags of 0 or 1, found {reverse_array.tolist()}'
1256
+ )
1257
+ reverse_array = reverse_array.to(torch.int32)
1258
+ if mask is not None:
1259
+ return self._reset_masked(mask, seed_array, reverse_array)
1260
+ if seed_array is not None and bool((seed_array == -1).any()):
1261
+ # Only the masked entry takes seeds that draw.
1262
+ return self._reset_masked(None, seed_array, reverse_array, synchronize=True)
1263
+ if seed_array is not None:
1264
+ seed_array = seed_array.to(torch.int32)
1265
+ with self._on_device():
1266
+ self._check(
1267
+ self._library.cuju_environment_reset(
1268
+ self._handle(),
1269
+ None if seed_array is None else seed_array.data_ptr(),
1270
+ None if reverse_array is None else reverse_array.data_ptr(),
1271
+ self._stream(),
1272
+ )
1273
+ )
1274
+ self._draw()
1275
+ observation = self._observation_of(self._outputs()[0])
1276
+ if self._observers:
1277
+ self._notify(None, {'reset': None})
1278
+ return observation
1279
+
1280
+ def _reset_masked(self, mask, seed_array, reverse_array, synchronize=False):
1281
+ """Resets the environments of `mask`, or all for `None`, through the masked entry."""
1282
+ mask_array, on_device = None, 0
1283
+ if mask is not None:
1284
+ if not isinstance(mask, torch.Tensor):
1285
+ mask = torch.as_tensor(mask)
1286
+ if mask.is_floating_point() or mask.is_complex():
1287
+ raise TypeError(f'expected a boolean or integer mask, found {mask.dtype}')
1288
+ if mask.device == self._torch_device and mask.dim() == 1:
1289
+ if tuple(mask.shape) != (self.environment_count,):
1290
+ raise ArgumentError(
1291
+ f'expected a mask of the shape ({self.environment_count},), found '
1292
+ f'{tuple(mask.shape)}'
1293
+ )
1294
+ mask_array, on_device = mask.to(torch.uint8).contiguous(), 1
1295
+ else:
1296
+ mask_array = self._staged(self._per_environment(mask, torch.uint8, 'mask'))
1297
+ on_device = int(self.device == 'cpu')
1298
+ seed_array, reverse_array = self._staged(seed_array), self._staged(reverse_array)
1299
+ with self._on_device():
1300
+ self._check(
1301
+ self._library.cuju_environment_reset_masked(
1302
+ self._handle(),
1303
+ None if mask_array is None else mask_array.data_ptr(),
1304
+ on_device,
1305
+ None if seed_array is None else seed_array.data_ptr(),
1306
+ None if reverse_array is None else reverse_array.data_ptr(),
1307
+ self._stream(),
1308
+ int(synchronize),
1309
+ )
1310
+ )
1311
+ self._wait_in_debug()
1312
+ self._draw()
1313
+ observation = self._observation_of(self._outputs()[0])
1314
+ if self._observers and not self._capturing():
1315
+ self._notify(None, {'reset': None if mask_array is None else mask_array.bool()})
1316
+ return observation
1317
+
1318
+ def reset_done(self) -> None:
1319
+ """Starts the next episode of every environment whose episode ended.
1320
+
1321
+ A batch with `auto_reset=False` leaves such environments at their end. The reset reads the
1322
+ done flags in the batch's memory, so on the GPU it does not wait for the device; it writes
1323
+ the new observations and clears the done flags of the environments it resets.
1324
+
1325
+ Raises:
1326
+ LibraryError: If the library fails to run the reset. It is a `RuntimeError`.
1327
+ UndefinedPathError: If an environment reaches a path that GRF leaves undefined. It is a
1328
+ `RuntimeError`.
1329
+ DeviceError: If the device fails in a `debug` batch. It is a `RuntimeError`.
1330
+ """
1331
+ # Under `torch.compile` the call goes through the operator `cuju::reset_done`.
1332
+ if _CUSTOM_OPERATORS and torch.compiler.is_compiling():
1333
+ return self._compiled_reset_done()
1334
+ # The reset clears the done flags, so the observers receive a copy of them from before.
1335
+ ended = self._outputs()[2].bool() if self._observers and not self._capturing() else None
1336
+ with self._on_device():
1337
+ self._check(self._library.cuju_environment_reset_done(self._handle(), self._stream()))
1338
+ self._wait_in_debug()
1339
+ self._draw()
1340
+ if self._observers:
1341
+ self._notify(None, {'reset': ended})
1342
+
1343
+ def observation(self) -> Any:
1344
+ """Returns the observation of every agent that the last `reset` or `step` returned."""
1345
+ return self._observation_of(self._outputs()[0])
1346
+
1347
+ def frame(self) -> torch.Tensor:
1348
+ """Returns GRF's frame of every environment after the last `reset` or `step`.
1349
+
1350
+ Returns:
1351
+ `[environment_count, height, width, 3]` `uint8`, rows from the top, as GRF's observation
1352
+ `frame` holds them.
1353
+
1354
+ Raises:
1355
+ ConfigurationError: If the batch renders nothing, without `pixels`, `pixels_gray` or
1356
+ `render_frames`. It is a `ValueError`.
1357
+ """
1358
+ if self._frames is None:
1359
+ raise ConfigurationError(
1360
+ "expected a batch that renders, with representation='pixels' or render_frames=True"
1361
+ )
1362
+ return self._frames.frame.to(self._torch_device)
1363
+
1364
+ def _observation_of(self, native, final=False):
1365
+ """The observation that the batch returns: the frames' for pixels, else the library's."""
1366
+ frames = self._frames
1367
+ if frames is None or frames.kind is None:
1368
+ return native
1369
+ observation = frames.final_observation if final else frames.observation
1370
+ observation = observation.to(self._torch_device)
1371
+ return observation.squeeze(1) if self.squeeze else observation
1372
+
1373
+ def _draw(self):
1374
+ """Draws the renders of the last call, which the frames and pixels then show."""
1375
+ if self._frames is not None:
1376
+ self._frames.draw(range(self.environment_count))
1377
+
1378
+ @property
1379
+ def single_observation_space(self) -> Any:
1380
+ """The observation space of one environment, as GRF's with the same options, or `None` for
1381
+ `raw`, which has none in GRF. The spaces need gymnasium or gym."""
1382
+ if self._representation == 'raw':
1383
+ return None
1384
+ spaces, _ = _spaces()
1385
+ import numpy as np
1386
+
1387
+ shape = self._observation_shape[2 if self.squeeze else 1 :]
1388
+ if self._representation in _PIXEL_REPRESENTATIONS:
1389
+ shape = tuple(self._frames.observation.shape[2 if self.squeeze else 1 :])
1390
+ return spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8)
1391
+ if self._representation == 'extracted':
1392
+ return spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8)
1393
+ return spaces.Box(low=-np.inf, high=np.inf, shape=shape, dtype=np.float32)
1394
+
1395
+ @property
1396
+ def single_action_space(self) -> Any:
1397
+ """The action space of one environment, `Discrete` with `squeeze` and `MultiDiscrete` over
1398
+ the agents without, as in GRF for one agent and for several."""
1399
+ spaces, _ = _spaces()
1400
+ if self.squeeze:
1401
+ return spaces.Discrete(self.action_count)
1402
+ return spaces.MultiDiscrete([self.action_count] * self.agents)
1403
+
1404
+ @property
1405
+ def observation_space(self) -> Any:
1406
+ """The observation space of the batch, `single_observation_space` for each environment, or
1407
+ `None` for `raw`."""
1408
+ single = self.single_observation_space
1409
+ return None if single is None else _spaces()[1](single, self.environment_count)
1410
+
1411
+ @property
1412
+ def action_space(self) -> Any:
1413
+ """The action space of the batch, `single_action_space` for each environment."""
1414
+ return _spaces()[1](self.single_action_space, self.environment_count)
1415
+
1416
+ def _raw_of(self, name):
1417
+ """Returns the raw tensors of a buffer, as `raw` returns them."""
1418
+ if self._raw_fields is None:
1419
+ raise ConfigurationError('expected a batch with the raw representation or `with_raw`')
1420
+ return self._raw(name)
1421
+
1422
+ def raw(self) -> dict[str, torch.Tensor]:
1423
+ """Returns the `raw` representation of the last observation of every agent.
1424
+
1425
+ The tensors view buffers of the batch, which the next call to `reset` or `step` overwrites.
1426
+
1427
+ Raises:
1428
+ ConfigurationError: If the batch writes no raw representation. It is a `ValueError`.
1429
+ """
1430
+ return self._raw_of('raw')
1431
+
1432
+ def final_raw(self) -> dict[str, torch.Tensor]:
1433
+ """Returns the `raw` representation of the step that ended each episode, as `raw` does.
1434
+
1435
+ Raises:
1436
+ ConfigurationError: If the batch writes no raw representation. It is a `ValueError`.
1437
+ """
1438
+ return self._raw_of('final_raw')
1439
+
1440
+ def step(self, actions: Any) -> tuple[Any, Any, Any, dict[str, Any]]:
1441
+ """Runs one step of every environment.
1442
+
1443
+ On the GPU the step runs on the current stream of PyTorch and does not wait for the device.
1444
+ Under `torch.compile` it traces as the operator `cuju::step`, so a compiled function that
1445
+ steps the batch needs no graph break, and `mode='reduce-overhead'` may capture it.
1446
+
1447
+ Args:
1448
+ actions: `[environment_count, agents]` indices into the action set. As in GRF, an index
1449
+ from `-action_count` to `-1` counts from the end. A tensor on the batch's device
1450
+ takes no copy. Actions in host memory, pinned or not, may be reused as soon as
1451
+ the call returns, since a GPU batch copies pinned ones first.
1452
+
1453
+ Returns:
1454
+ The observation, the reward `[environment_count, agents]`, the done flags
1455
+ `[environment_count]` and the information, which maps `final_observation` to the
1456
+ observation of the step that ended each episode and `score_reward` to GRF's
1457
+ `info['score_reward']`, the left team's scoring reward, `[environment_count]` `int32`.
1458
+
1459
+ Raises:
1460
+ TypeError: If the actions are not integers.
1461
+ ArgumentError: If the actions are not `[environment_count, agents]`, or
1462
+ `[environment_count]` for one agent. It is a `ValueError`.
1463
+ ActionRangeError: If an action in host memory, or with `check_actions` or `debug` in
1464
+ GPU memory, lies outside `[-action_count, action_count)`, and then no environment
1465
+ steps. It is an `IndexError`.
1466
+ DeviceError: If the device fails in a `debug` batch. It is a `RuntimeError`.
1467
+ UndefinedPathError: If an environment reaches a path that GRF leaves undefined. It is a
1468
+ `RuntimeError`. On the GPU the device traps, which ends the CUDA context of the
1469
+ process, so the next CUDA call reports it and the process must restart.
1470
+ LibraryError: If the library fails to run the step. It is a `RuntimeError`.
1471
+ """
1472
+ # Under `torch.compile` the step goes through the operator `cuju::step`, without a break.
1473
+ if _CUSTOM_OPERATORS and torch.compiler.is_compiling():
1474
+ if self._frames is not None:
1475
+ raise ConfigurationError('a batch that renders steps outside torch.compile')
1476
+ return self._compiled_step(actions)
1477
+ shape = (self.environment_count, self.agents)
1478
+ if not isinstance(actions, torch.Tensor):
1479
+ actions = torch.as_tensor(actions)
1480
+ # An empty list, the actions of environments without agents, holds no type.
1481
+ if actions.numel() == 0:
1482
+ actions = actions.to(torch.int32)
1483
+ # GRF: an action must be an integer.
1484
+ if actions.is_floating_point() or actions.is_complex():
1485
+ raise TypeError(f'expected integer action indices, found {actions.dtype}')
1486
+ # With one agent, `[environment_count]` actions serve as well, as `squeeze` returns them.
1487
+ if tuple(actions.shape) != shape and not (
1488
+ self.agents == 1 and tuple(actions.shape) == (self.environment_count,)
1489
+ ):
1490
+ raise ArgumentError(
1491
+ f'expected actions of the shape {shape}, [environment_count, agents], found '
1492
+ f'{tuple(actions.shape)}'
1493
+ )
1494
+ if actions.device == self._torch_device:
1495
+ contiguous_actions = actions.to(torch.int32).reshape(shape).contiguous()
1496
+ on_device = 1
1497
+ if self._checks_device_actions:
1498
+ self._check_device_actions(contiguous_actions)
1499
+ else:
1500
+ contiguous_actions = self._staged(_host(actions, torch.int32).reshape(shape))
1501
+ on_device = int(self.device == 'cpu')
1502
+ # GRF: an action indexes a Python list, so one outside `[-action_count, action_count)`
1503
+ # raises. The library checks host actions only, since a check on the GPU would wait for it.
1504
+ with self._on_device():
1505
+ status = self._library.cuju_environment_step(
1506
+ self._handle(), contiguous_actions.data_ptr(), on_device, self._stream(), 0
1507
+ )
1508
+ if status == -2:
1509
+ raise ActionRangeError(self._library.cuju_last_error().decode())
1510
+ self._check(status)
1511
+ self._wait_in_debug()
1512
+ self._draw()
1513
+ observation, reward, done, final = self._outputs()
1514
+ observation, final = self._observation_of(observation), self._observation_of(final, True)
1515
+ if self._score_reward is None:
1516
+ self._score_reward = self._buffer(
1517
+ 'score_reward', (self.environment_count,), torch.int32
1518
+ )
1519
+ information = {'final_observation': final, 'score_reward': self._score_reward}
1520
+ if self._render_frames:
1521
+ information['frame'] = self._frames.frame.to(self._torch_device)
1522
+ information['final_frame'] = self._frames.final_frame.to(self._torch_device)
1523
+ if self._observers:
1524
+ actions = self._on_batch_device(contiguous_actions)
1525
+ self._notify(done, {**information, 'reward': reward, 'actions': actions})
1526
+ return observation, reward, done, information
1527
+
1528
+ def _on_batch_device(self, actions, copy=False):
1529
+ """Returns the actions of a step on the batch's device for the observers, a copy with
1530
+ `copy`, else the tensor itself where it already lies there."""
1531
+ if actions.device != self._torch_device:
1532
+ return actions.to(self._torch_device)
1533
+ return actions.clone() if copy else actions
1534
+
1535
+ def _check_device_actions(self, actions):
1536
+ """Raises `ActionRangeError` for an action in GPU memory outside the set, before a step."""
1537
+ with self._on_device():
1538
+ # The check reads its result on the host, which a CUDA graph capture cannot wait for.
1539
+ if torch.cuda.is_current_stream_capturing():
1540
+ return
1541
+ # As the library's check of host actions, the agent slots past an environment's agents
1542
+ # go unchecked.
1543
+ if self._agent_mask_on_device is None:
1544
+ self._agent_mask_on_device = self.agent_mask.to(self._torch_device)
1545
+ count = self.action_count
1546
+ outside = ((actions < -count) | (actions >= count)) & self._agent_mask_on_device
1547
+ if not bool(outside.any()):
1548
+ return
1549
+ environment, agent = (int(index) for index in outside.nonzero()[0])
1550
+ raise ActionRangeError(
1551
+ f'expected action indices from {-count} to {count - 1}, found '
1552
+ f'{int(actions[environment, agent])} on the device for agent {agent} of '
1553
+ f'environment {environment}'
1554
+ )
1555
+
1556
+ def _wait_in_debug(self):
1557
+ """Waits for the device in a `debug` GPU batch, so that a failure raises at its call."""
1558
+ if not self.debug or self.device == 'cpu':
1559
+ return
1560
+ with self._on_device():
1561
+ if torch.cuda.is_current_stream_capturing():
1562
+ return
1563
+ self._check(self._library.cuju_environment_synchronize(self._handle(), self._stream()))
1564
+
1565
+ def _environment_index(self, index):
1566
+ """Returns `index` as an integer, or raises `EnvironmentIndexError` outside the batch."""
1567
+ index = operator.index(index)
1568
+ if not 0 <= index < self.environment_count:
1569
+ raise EnvironmentIndexError(
1570
+ f'expected an environment from 0 to {self.environment_count - 1}, found {index}'
1571
+ )
1572
+ return index
1573
+
1574
+ def _check_stack(self, stacked):
1575
+ """Raises `StateError` unless `stacked` matches the batch, as GRF pickles its stack."""
1576
+ if self.stacked and not stacked:
1577
+ raise StateError(
1578
+ 'expected stacked=True for the state of a batch that stacks its observations, '
1579
+ "whose state holds GRF's FrameStack"
1580
+ )
1581
+ if stacked and not self.stacked:
1582
+ raise StateError('expected a batch with stacked=True for a stacked state')
1583
+
1584
+ def _frame_shape(self):
1585
+ """Returns the shape of one agent's frame of the stack and its type."""
1586
+ shape = self._observation_shape[2:]
1587
+ dtype = 'uint8' if self._observation_type == torch.uint8 else 'float32'
1588
+ return (*shape[:-1], shape[-1] // _frame_stack.FRAMES), dtype
1589
+
1590
+ def step_async(self, actions: Any) -> None:
1591
+ """Starts a step of every environment and returns at once. `step_wait` ends the step.
1592
+
1593
+ On the CPU the batch steps in a thread of its own, with a copy of the actions, while the
1594
+ caller goes on, for example to run a policy on the GPU. On the GPU the step runs on the
1595
+ current stream, as `step` does. Until `step_wait` returns, the outputs are not ready, and
1596
+ any other call on the batch waits for the step first.
1597
+
1598
+ Args:
1599
+ actions: As for `step`, and the caller may reuse them at once.
1600
+
1601
+ Raises:
1602
+ TypeError, ArgumentError, ActionRangeError: As `step` raises them, before the step
1603
+ starts.
1604
+ RuntimeError: If a step is already in flight, or the library fails to start the step.
1605
+ """
1606
+ if self._step_in_flight:
1607
+ raise RuntimeError('a step is in flight; call step_wait before the next step_async')
1608
+ if self._frames is not None:
1609
+ raise ConfigurationError('a batch that renders steps with step, not step_async')
1610
+ shape = (self.environment_count, self.agents)
1611
+ if not isinstance(actions, torch.Tensor):
1612
+ actions = torch.as_tensor(actions)
1613
+ if actions.is_floating_point() or actions.is_complex():
1614
+ raise TypeError(f'expected integer action indices, found {actions.dtype}')
1615
+ if tuple(actions.shape) != shape and not (
1616
+ self.agents == 1 and tuple(actions.shape) == (self.environment_count,)
1617
+ ):
1618
+ raise ArgumentError(
1619
+ f'expected actions of the shape {shape}, [environment_count, agents], found '
1620
+ f'{tuple(actions.shape)}'
1621
+ )
1622
+ if actions.device == self._torch_device:
1623
+ contiguous_actions = actions.to(torch.int32).reshape(shape).contiguous()
1624
+ on_device = 1
1625
+ if self._checks_device_actions:
1626
+ self._check_device_actions(contiguous_actions)
1627
+ else:
1628
+ contiguous_actions = self._staged(_host(actions, torch.int32).reshape(shape))
1629
+ on_device = int(self.device == 'cpu')
1630
+ with self._on_device():
1631
+ status = self._library.cuju_environment_step_async(
1632
+ self._handle(), contiguous_actions.data_ptr(), on_device, self._stream()
1633
+ )
1634
+ if status == -2:
1635
+ raise ActionRangeError(self._library.cuju_last_error().decode())
1636
+ self._check(status)
1637
+ self._wait_in_debug()
1638
+ # The caller may change its actions once this returns, so the observers of `step_wait`
1639
+ # read a copy taken now. Without observers the batch keeps the tensor alone, which costs
1640
+ # nothing.
1641
+ self._async_actions = (
1642
+ self._on_batch_device(contiguous_actions, copy=True)
1643
+ if self._observers
1644
+ else contiguous_actions
1645
+ )
1646
+ self._step_in_flight = True
1647
+
1648
+ def step_wait(self) -> tuple[Any, Any, Any, dict[str, Any]]:
1649
+ """Waits for the step that `step_async` started and returns what `step` returns.
1650
+
1651
+ Raises:
1652
+ RuntimeError: If no step is in flight, or the step failed as `step` would.
1653
+ """
1654
+ if not self._step_in_flight:
1655
+ raise RuntimeError('no step is in flight; call step_async first')
1656
+ self._step_in_flight = False
1657
+ actions, self._async_actions = self._async_actions, None
1658
+ self._check(self._library.cuju_environment_step_wait(self._handle()))
1659
+ observation, reward, done, final = self._outputs()
1660
+ information = {'final_observation': final, 'score_reward': self._score_reward}
1661
+ if self._observers:
1662
+ actions = self._on_batch_device(actions)
1663
+ self._notify(done, {**information, 'reward': reward, 'actions': actions})
1664
+ return observation, reward, done, information
1665
+
1666
+ def _wait_for_device(self):
1667
+ """Waits for every stream of the device, since state copies bypass PyTorch's streams."""
1668
+ if self.device == 'cuda':
1669
+ torch.cuda.synchronize(self._torch_device)
1670
+
1671
+ def get_state(self, index: int, stacked: bool = False) -> bytes:
1672
+ """Returns the state of one environment in the byte format of GRF.
1673
+
1674
+ The bytes hold the length of a pickle as `int32`, the pickle of the episode logic and the
1675
+ serialized match.
1676
+
1677
+ Args:
1678
+ index: The index of the environment.
1679
+ stacked: Whether the pickle also holds GRF's `FrameStack`, as the state of GRF with
1680
+ `stacked=True` does. It is a `deque` of the last four observations as numpy arrays,
1681
+ each as GRF's wrappers return it, such as `[agents, 115]` or `[115]` for one agent.
1682
+ It needs numpy, and a batch with `stacked=True`.
1683
+
1684
+ Returns:
1685
+ The bytes, which `set_state` here or in GRF reads.
1686
+
1687
+ Raises:
1688
+ EnvironmentIndexError: If the index is out of range. It is an `IndexError` and a
1689
+ `RuntimeError`.
1690
+ StateError: If `stacked` differs from the batch's `stacked`. It is a `ValueError` and a
1691
+ `RuntimeError`.
1692
+ """
1693
+ index = self._environment_index(index)
1694
+ self._check_stack(stacked)
1695
+ state = self._state(index, stacked)
1696
+ if self._frames is not None:
1697
+ self._frames.state_processed(index)
1698
+ return state
1699
+
1700
+ def _state(self, index, stacked=False):
1701
+ """Returns the state of a valid environment index, with the stack only when `stacked`.
1702
+
1703
+ The renderer reads states through this, so a batch that stacks its observations shows as
1704
+ well, since a match needs no stack.
1705
+ """
1706
+ episode = (ctypes.c_int * (3 + _MAXIMUM_AGENTS))()
1707
+ size = ctypes.c_ulonglong()
1708
+ self._wait_for_device()
1709
+ with self._on_device():
1710
+ pointer = self._library.cuju_environment_get_state(
1711
+ self._handle(), index, ctypes.byref(size), episode
1712
+ )
1713
+ if not pointer:
1714
+ raise _from_library(self._library.cuju_last_error().decode())
1715
+ match = ctypes.string_at(pointer, size.value)
1716
+ collected = list(episode[3 : 3 + self.agents]) if self._checkpoints else None
1717
+ frames = None
1718
+ if stacked:
1719
+ agents = int(self.left_agents[index] + self.right_agents[index])
1720
+ stack = self._buffer(
1721
+ self._observation_name, self._observation_shape, self._observation_type
1722
+ )[index, :agents].cpu()
1723
+ frames = _frame_stack.pickled_frames(_frame_stack.frames_of(stack, agents))
1724
+ data = _pickle_episode(list(episode[:3]), collected, frames)
1725
+ return struct.pack('<i', len(data)) + data + match
1726
+
1727
+ def set_state(self, index: int, state: bytes, stacked: bool = False) -> None:
1728
+ """Sets one environment to a state in the byte format of GRF.
1729
+
1730
+ The observation and the sticky actions follow from the state. The reward is 0 and the done
1731
+ flag is clear until the next step.
1732
+
1733
+ Args:
1734
+ index: The index of the environment.
1735
+ state: The bytes that `get_state` of this package or of GRF returned.
1736
+ stacked: Whether the state holds GRF's `FrameStack`, as `get_state(stacked=True)` here
1737
+ or a GRF with `stacked=True` writes it, and its four frames become the observation
1738
+ stack. It needs numpy, and a batch with `stacked=True`.
1739
+
1740
+ Raises:
1741
+ EnvironmentIndexError: If the index is out of range. It is an `IndexError` and a
1742
+ `RuntimeError`.
1743
+ StateError: If the bytes hold no pickle of the episode logic or do not load, the
1744
+ state belongs to another scenario or to other difficulties, `stacked` differs from
1745
+ the batch's, or a stacked state holds no four frames of the batch's observation.
1746
+ It is a `ValueError` and a `RuntimeError`.
1747
+ """
1748
+ index = self._environment_index(index)
1749
+ self._check_stack(stacked)
1750
+ if len(state) < 4 or not 0 < struct.unpack_from('<i', state)[0] <= len(state) - 4:
1751
+ raise StateError(
1752
+ f'expected the bytes of a state: a pickle length, the pickle and the match, '
1753
+ f'found {len(state)} bytes that hold none'
1754
+ )
1755
+ (length,) = struct.unpack_from('<i', state)
1756
+ try:
1757
+ unpickler = _StateUnpickler(io.BytesIO(state[4 : 4 + length]))
1758
+ unpickler.stacked = stacked
1759
+ unpickled = unpickler.load()
1760
+ logic = unpickled['FootballEnvCore'].__dict__
1761
+ except (pickle.UnpicklingError, KeyError, AttributeError, EOFError) as error:
1762
+ raise StateError(
1763
+ f'expected the pickle of the episode logic in the state, found {error}'
1764
+ ) from error
1765
+ episode = (ctypes.c_int * (3 + _MAXIMUM_AGENTS))(
1766
+ logic['previous_score_diff'], logic['previous_game_mode'], logic['prev_ball_owned_team']
1767
+ )
1768
+ # GRF: the checkpoint reward reads its counts from the state.
1769
+ if self._checkpoints and 'CheckpointRewardWrapper' not in unpickled:
1770
+ raise StateError('expected the checkpoints of the checkpoint reward in the state')
1771
+ for agent, count in unpickled.get('CheckpointRewardWrapper', {}).items():
1772
+ episode[3 + agent] = count
1773
+ stack = None
1774
+ if stacked and 0 <= index < self.environment_count:
1775
+ # GRF: `FrameStack.set_state` takes the deque of the state as its observations.
1776
+ if 'FrameStack' not in unpickled:
1777
+ raise StateError("expected GRF's FrameStack in the stacked state")
1778
+ shape, dtype = self._frame_shape()
1779
+ agents = int(self.left_agents[index] + self.right_agents[index])
1780
+ try:
1781
+ stack = _frame_stack.stack_bytes(unpickled['FrameStack'], agents, shape, dtype)
1782
+ except ValueError as error:
1783
+ raise StateError(str(error)) from error
1784
+ match = state[4 + length :]
1785
+ self._wait_for_device()
1786
+ with self._on_device():
1787
+ status = self._library.cuju_environment_set_state(
1788
+ self._handle(), index, match, len(match), episode
1789
+ )
1790
+ if status != 0:
1791
+ message = self._library.cuju_last_error().decode()
1792
+ if 'found another' in message:
1793
+ # GRF: a state loads only where the constant part of the scenario is the same.
1794
+ message += (
1795
+ '; a state loads only into an environment of the same scenario, agent counts, '
1796
+ 'episode end flags, duration, ball position, formation and difficulties'
1797
+ )
1798
+ error = _from_library(message)
1799
+ raise StateError(message) if type(error) is LibraryError else error
1800
+ if self._frames is not None:
1801
+ self._frames.state_processed(index)
1802
+ if stack is not None:
1803
+ with self._on_device():
1804
+ self._check(
1805
+ self._library.cuju_environment_set_stack(
1806
+ self._handle(), index, self._observation_name.encode(), stack, len(stack)
1807
+ )
1808
+ )
1809
+
1810
+ def roles(self, index: int) -> dict[str, torch.Tensor]:
1811
+ """Returns the role that each player of one environment plays now.
1812
+
1813
+ A role is GRF's `e_PlayerRole` as a number, from 0 for the goalkeeper to 9 for the centre
1814
+ forward, as the raw observation gives it. When a goalkeeper is sent off, GRF hands the
1815
+ keeper's formation entry, and with it the role of goalkeeper, to the first active player of
1816
+ the team. That hand-over lives in the team data of the environment rather than in its
1817
+ state, so `get_state` leaves it out, and the roles here follow it. A state loaded with
1818
+ `set_state` keeps the hand-over of the environment that loads it, as in GRF.
1819
+
1820
+ Args:
1821
+ index: The index of the environment.
1822
+
1823
+ Returns:
1824
+ `left_team_roles` and `right_team_roles`, each `[players]` `int32` on the CPU with one
1825
+ entry per player of the team, in the order of the raw observation of a left agent, so
1826
+ they equal the raw arrays of the same names without their padding.
1827
+
1828
+ Raises:
1829
+ EnvironmentIndexError: If the index is out of range. It is an `IndexError` and a
1830
+ `RuntimeError`.
1831
+ """
1832
+ index = self._environment_index(index)
1833
+ left = int(self.left_players[index])
1834
+ roles = torch.empty(left + int(self.right_players[index]), dtype=torch.int32)
1835
+ self._wait_for_device()
1836
+ with self._on_device():
1837
+ count = self._library.cuju_environment_roles(
1838
+ self._handle(), index, roles.data_ptr(), roles.numel()
1839
+ )
1840
+ if count < 0:
1841
+ raise _from_library(self._library.cuju_last_error().decode())
1842
+ return {'left_team_roles': roles[:left], 'right_team_roles': roles[left:]}
1843
+
1844
+
1845
+ def memory_estimate(assets: str | list[str], **options: Any) -> int:
1846
+ """Returns the bytes that `BatchEnvironment(assets, **options)` requests, without creating it.
1847
+
1848
+ The count is what `memory_bytes` of that batch reports right after its creation, its buffers,
1849
+ worlds and tables, in device memory on the GPU and in host memory on the CPU. On the GPU it
1850
+ includes the work area of 12 KB per environment that the kernels use for their large lists.
1851
+ The allocators
1852
+ round each request up. It reads the bundles and the animation tables, as the creation does, so
1853
+ it takes a fraction of a second, and it needs the library of the device, and on the GPU a CUDA
1854
+ device, as the creation does.
1855
+
1856
+ The first batch of the process on a GPU also makes the driver reserve the local memory of the
1857
+ kernels for every thread that the GPU runs at once, a few kilobytes each, and holds it until
1858
+ the process ends. The result is an `int` whose attribute `local_memory_bytes` gives that
1859
+ reservation, from the local memory of the kernels and the size of the device. It is 0 once a
1860
+ batch was created on the device, since every later batch of the process shares the
1861
+ reservation, and always 0 on the CPU, so that a batch created next takes the result plus
1862
+ `local_memory_bytes`.
1863
+
1864
+ Args:
1865
+ assets: As `BatchEnvironment` takes them.
1866
+ **options: Any other argument of `BatchEnvironment`, such as `environment_count`,
1867
+ `representation` or `device`.
1868
+
1869
+ Returns:
1870
+ The bytes of memory that the batch would request, with the attribute
1871
+ `local_memory_bytes`.
1872
+
1873
+ Raises:
1874
+ LibraryError: If the library refuses the configuration. The other errors are those that
1875
+ `BatchEnvironment` raises for the same arguments, except the check of `squeeze`
1876
+ against the agents, which follows the creation.
1877
+
1878
+ Examples:
1879
+ >>> import cuju
1880
+ >>> per_environment = cuju.memory_estimate(
1881
+ ... '5_vs_5_l4_r0', environment_count=2, device='cpu'
1882
+ ... ) - cuju.memory_estimate('5_vs_5_l4_r0', environment_count=1, device='cpu')
1883
+ """
1884
+ batch = BatchEnvironment.__new__(BatchEnvironment)
1885
+ batch._estimate_only = True
1886
+ try:
1887
+ batch.__init__(assets, **options)
1888
+ return batch._estimated_bytes
1889
+ finally:
1890
+ batch.close()