cuju-engine 0.3.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. cuju/__init__.py +217 -0
  2. cuju/__main__.py +262 -0
  3. cuju/_batch/__init__.py +4 -0
  4. cuju/_batch/allocator.py +52 -0
  5. cuju/_batch/assets.py +68 -0
  6. cuju/_batch/environment.py +1890 -0
  7. cuju/_batch/frame_stack.py +114 -0
  8. cuju/_batch/library.py +190 -0
  9. cuju/_batch/log.py +103 -0
  10. cuju/_batch/memory.py +70 -0
  11. cuju/_batch/operators.py +55 -0
  12. cuju/_batch/pinned.py +39 -0
  13. cuju/_batch/pixels.py +207 -0
  14. cuju/_batch/state.py +77 -0
  15. cuju/_checksums.py +60 -0
  16. cuju/_cli_contract.py +244 -0
  17. cuju/_cli_parsers.py +191 -0
  18. cuju/_completion.py +277 -0
  19. cuju/_dump_to_txt.py +66 -0
  20. cuju/_grf_config.py +331 -0
  21. cuju/_library_path.py +141 -0
  22. cuju/_media.py +113 -0
  23. cuju/_pixels.py +276 -0
  24. cuju/_plugins.py +106 -0
  25. cuju/_python_players.py +224 -0
  26. cuju/_replay_command.py +109 -0
  27. cuju/_replay_player.py +42 -0
  28. cuju/_replays.py +414 -0
  29. cuju/_script_helpers.py +109 -0
  30. cuju/_version.py +6 -0
  31. cuju/action_log.py +371 -0
  32. cuju/check.py +596 -0
  33. cuju/cuju_cpu.dll +0 -0
  34. cuju/cuju_cuda.dll +0 -0
  35. cuju/cuju_render.dll +0 -0
  36. cuju/data/SHA256SUMS +20 -0
  37. cuju/data/animations.bin +0 -0
  38. cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
  39. cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
  40. cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
  41. cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
  42. cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
  43. cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
  44. cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
  45. cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
  46. cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
  47. cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
  48. cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
  49. cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
  50. cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
  51. cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  52. cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  53. cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
  54. cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
  55. cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
  56. cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
  57. cuju/data/digests.json +186 -0
  58. cuju/data/render_digests.json.z +0 -0
  59. cuju/data/scenarios/11_vs_11_competition.py +45 -0
  60. cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
  61. cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
  62. cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
  63. cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
  64. cuju/data/scenarios/1_vs_1_easy.py +25 -0
  65. cuju/data/scenarios/5_vs_5.py +33 -0
  66. cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
  67. cuju/data/scenarios/academy_corner.py +45 -0
  68. cuju/data/scenarios/academy_counterattack_easy.py +45 -0
  69. cuju/data/scenarios/academy_counterattack_hard.py +45 -0
  70. cuju/data/scenarios/academy_empty_goal.py +25 -0
  71. cuju/data/scenarios/academy_empty_goal_close.py +25 -0
  72. cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
  73. cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
  74. cuju/data/scenarios/academy_run_to_score.py +30 -0
  75. cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
  76. cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
  77. cuju/data/scenarios/test_example_multiagent.py +28 -0
  78. cuju/dumps.py +942 -0
  79. cuju/engine_status.py +106 -0
  80. cuju/env.py +1168 -0
  81. cuju/errors.py +108 -0
  82. cuju/gfootball/GRF_SOURCES +86 -0
  83. cuju/gfootball/__init__.py +60 -0
  84. cuju/gfootball/_cv2.py +43 -0
  85. cuju/gfootball/_gym/__init__.py +88 -0
  86. cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
  87. cuju/gfootball/_gym/_vendored/__init__.py +43 -0
  88. cuju/gfootball/_gym/_vendored/core.py +361 -0
  89. cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
  90. cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
  91. cuju/gfootball/_gym/_vendored/error.py +230 -0
  92. cuju/gfootball/_gym/_vendored/logger.py +56 -0
  93. cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
  94. cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
  95. cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
  96. cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
  97. cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
  98. cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
  99. cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
  100. cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
  101. cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
  102. cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
  103. cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
  104. cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
  105. cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
  106. cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
  107. cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
  108. cuju/gfootball/_gym/_vendored/version.py +5 -0
  109. cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
  110. cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
  111. cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
  112. cuju/gfootball/dump_to_txt.py +49 -0
  113. cuju/gfootball/dump_to_video.py +33 -0
  114. cuju/gfootball/env/__init__.py +271 -0
  115. cuju/gfootball/env/config.py +163 -0
  116. cuju/gfootball/env/constants.py +33 -0
  117. cuju/gfootball/env/controller_base.py +114 -0
  118. cuju/gfootball/env/event_queue.py +54 -0
  119. cuju/gfootball/env/football_action_set.py +220 -0
  120. cuju/gfootball/env/football_action_set_test.py +76 -0
  121. cuju/gfootball/env/football_env.py +225 -0
  122. cuju/gfootball/env/football_env_core.py +447 -0
  123. cuju/gfootball/env/football_env_test.py +692 -0
  124. cuju/gfootball/env/gym_test.py +47 -0
  125. cuju/gfootball/env/observation_preprocessing.py +94 -0
  126. cuju/gfootball/env/observation_processor.py +526 -0
  127. cuju/gfootball/env/observation_rotation.py +163 -0
  128. cuju/gfootball/env/observation_rotation_test.py +84 -0
  129. cuju/gfootball/env/player_base.py +46 -0
  130. cuju/gfootball/env/players/__init__.py +16 -0
  131. cuju/gfootball/env/players/agent.py +39 -0
  132. cuju/gfootball/env/players/bot.py +217 -0
  133. cuju/gfootball/env/players/gamepad.py +81 -0
  134. cuju/gfootball/env/players/keyboard.py +72 -0
  135. cuju/gfootball/env/players/lazy.py +31 -0
  136. cuju/gfootball/env/players/ppo2_cnn.py +119 -0
  137. cuju/gfootball/env/players/replay.py +40 -0
  138. cuju/gfootball/env/remote_football_env.py +189 -0
  139. cuju/gfootball/env/scenario_builder.py +125 -0
  140. cuju/gfootball/env/script_helpers.py +130 -0
  141. cuju/gfootball/env/script_helpers_test.py +107 -0
  142. cuju/gfootball/env/wrappers.py +440 -0
  143. cuju/gfootball/env/wrappers_test.py +150 -0
  144. cuju/gfootball/eval_server/__init__.py +17 -0
  145. cuju/gfootball/eval_server/config.py +30 -0
  146. cuju/gfootball/eval_server/example_client.py +107 -0
  147. cuju/gfootball/eval_server/proto/game_server.proto +62 -0
  148. cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
  149. cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
  150. cuju/gfootball/eval_server/proto/master.proto +25 -0
  151. cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
  152. cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
  153. cuju/gfootball/eval_server/utils.py +52 -0
  154. cuju/gfootball/examples/__init__.py +16 -0
  155. cuju/gfootball/examples/models.py +66 -0
  156. cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
  157. cuju/gfootball/examples/run_ppo2.py +123 -0
  158. cuju/gfootball/play_game.py +73 -0
  159. cuju/gfootball/replay.py +43 -0
  160. cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
  161. cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
  162. cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
  163. cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
  164. cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
  165. cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
  166. cuju/gfootball/scenarios/5_vs_5.py +46 -0
  167. cuju/gfootball/scenarios/__init__.py +31 -0
  168. cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
  169. cuju/gfootball/scenarios/academy_corner.py +59 -0
  170. cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
  171. cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
  172. cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
  173. cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
  174. cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
  175. cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
  176. cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
  177. cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
  178. cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
  179. cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
  180. cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
  181. cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
  182. cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
  183. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
  184. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
  185. cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
  186. cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
  187. cuju/gfootball/scenarios/tests/__init__.py +31 -0
  188. cuju/gfootball/scenarios/tests/corner_test.py +38 -0
  189. cuju/gfootball/scenarios/tests/goal_test.py +35 -0
  190. cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
  191. cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
  192. cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
  193. cuju/gfootball/scenarios/tests/offside_test.py +39 -0
  194. cuju/gfootball/scenarios/tests/penalty.py +34 -0
  195. cuju/gfootball/scenarios/tests/second_half.py +33 -0
  196. cuju/gfootball/scenarios/tests/symmetric.py +53 -0
  197. cuju/gfootball_engine/__init__.py +31 -0
  198. cuju/gfootball_engine/_gameplayfootball.py +1624 -0
  199. cuju/gfootball_engine/_native.py +193 -0
  200. cuju/gfootball_engine/_pickle_names.py +114 -0
  201. cuju/gfootball_engine/_render_hooks.py +156 -0
  202. cuju/kaggle.py +425 -0
  203. cuju/multi_device.py +401 -0
  204. cuju/players.py +260 -0
  205. cuju/raw.py +93 -0
  206. cuju/scenarios.py +661 -0
  207. cuju/state.py +211 -0
  208. cuju/wrappers.py +325 -0
  209. cuju_engine-0.3.0.dist-info/METADATA +325 -0
  210. cuju_engine-0.3.0.dist-info/RECORD +222 -0
  211. cuju_engine-0.3.0.dist-info/WHEEL +5 -0
  212. cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
  213. cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
  214. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
  215. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
  216. cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
  217. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
  218. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
  219. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
  220. cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
  221. cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
  222. cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/check.py ADDED
@@ -0,0 +1,596 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Checks that this installation reproduces the expected outputs, on the CPU and on every GPU.
4
+
5
+ cuju check # every case on the CPU and on every visible GPU
6
+ cuju check --long # also the long cases, later episodes and the second half
7
+ cuju check --device cuda # one backend, which must then be present
8
+ cuju check --list # the cases, without playing them
9
+
10
+ It prints the setup, checks the package data against `data/SHA256SUMS`, and plays each case of
11
+ `data/digests.json`, four environments with fixed actions whose outputs and final states hash into
12
+ one SHA-256, against the digest of a build that matches GRF. The exit status is 0 when everything
13
+ that ran matched, else 1. An absent backend is reported and skipped unless `--device` names it,
14
+ when the status is 3.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import ctypes
21
+ import hashlib
22
+ import importlib.metadata
23
+ import json
24
+ import os
25
+ import platform
26
+ import shutil
27
+ import struct
28
+ import sys
29
+ import textwrap
30
+ import time
31
+
32
+ import torch
33
+
34
+ import cuju
35
+
36
+ from . import _checksums, _cli_parsers
37
+ from . import _cli_contract as contract
38
+ from ._batch import library as _libraries
39
+ from .errors import Error
40
+
41
+ DIGESTS = os.path.join(_checksums.DATA_DIRECTORY, 'digests.json')
42
+ # The processor features that the packaged CPU library needs.
43
+ _FEATURES = ('avx2', 'bmi2', 'fma')
44
+
45
+
46
+ def load_cases(long: bool = False) -> dict[str, dict]:
47
+ """Returns the cases of `data/digests.json` with their steps, and the long ones if `long`."""
48
+ with open(DIGESTS, encoding='utf-8') as handle:
49
+ expected = json.load(handle)
50
+ cases = {
51
+ name: {**entry, 'steps': expected['steps']} for name, entry in expected['cases'].items()
52
+ }
53
+ if long:
54
+ cases.update(expected.get('long_cases', {}))
55
+ for entry in cases.values():
56
+ entry.setdefault('seed', expected['seed'])
57
+ entry.setdefault('environments', expected['environments'])
58
+ return cases
59
+
60
+
61
+ def tensor_bytes(tensor: torch.Tensor) -> bytes:
62
+ """Returns the bytes of a tensor, read without numpy."""
63
+ tensor = tensor.detach().to('cpu').contiguous()
64
+ return ctypes.string_at(tensor.data_ptr(), tensor.numel() * tensor.element_size())
65
+
66
+
67
+ def actions_at(step: int, environments: int, agents: int, action_count: int) -> torch.Tensor:
68
+ """Returns the actions of a step from integer arithmetic alone, the same on every machine."""
69
+ values = [
70
+ [(step * 7 + environment * 3 + agent * 5) % action_count for agent in range(agents)]
71
+ for environment in range(environments)
72
+ ]
73
+ return torch.tensor(values, dtype=torch.int32)
74
+
75
+
76
+ def play_digest(assets, device, steps, seed=7, environments=4, **options) -> str:
77
+ """Plays a batch with the actions of `actions_at` and returns the SHA-256 of its outputs.
78
+
79
+ The digest covers every observation, reward and done flag of every step, then the state of
80
+ every environment at the end unless the batch stacks its observations. A GPU batch runs on
81
+ the current CUDA device.
82
+ """
83
+ batch = cuju.BatchEnvironment(
84
+ assets, environment_count=environments, device=device, seed=seed, **options
85
+ )
86
+ digest = hashlib.sha256()
87
+
88
+ def add(observation):
89
+ if isinstance(observation, dict):
90
+ for name in sorted(observation):
91
+ digest.update(tensor_bytes(observation[name]))
92
+ else:
93
+ digest.update(tensor_bytes(observation))
94
+
95
+ try:
96
+ add(batch.reset())
97
+ for step in range(steps):
98
+ actions = actions_at(step, environments, batch.agents, batch.action_count)
99
+ observation, reward, done, _ = batch.step(actions.to(device))
100
+ add(observation)
101
+ digest.update(tensor_bytes(reward))
102
+ digest.update(tensor_bytes(done))
103
+ if not batch.stacked:
104
+ for index in range(environments):
105
+ digest.update(batch.get_state(index))
106
+ finally:
107
+ batch.close()
108
+ return digest.hexdigest()
109
+
110
+
111
+ def _fatbin_sections(data: bytes) -> list[tuple[int, int]] | None:
112
+ """Returns the offset and size of each section that holds fat binaries, or `None`.
113
+
114
+ A 64-bit little-endian ELF file names it `.nv_fatbin`, a Windows DLL `.nv_fatb`.
115
+ """
116
+ if data[:6] == b'\x7fELF\x02\x01':
117
+ (table,) = struct.unpack_from('<Q', data, 0x28)
118
+ entry_size, count, names = struct.unpack_from('<HHH', data, 0x3A)
119
+
120
+ def section(index):
121
+ name, _, _, _, offset, size = struct.unpack_from(
122
+ '<IIQQQQ', data, table + index * entry_size
123
+ )
124
+ return name, offset, size
125
+
126
+ names_offset = section(names)[1]
127
+ found = []
128
+ for index in range(count):
129
+ name, offset, size = section(index)
130
+ start = names_offset + name
131
+ if data[start : data.index(b'\0', start)] == b'.nv_fatbin':
132
+ found.append((offset, size))
133
+ return found
134
+ if data[:2] == b'MZ':
135
+ (header,) = struct.unpack_from('<I', data, 0x3C)
136
+ if data[header : header + 4] != b'PE\0\0':
137
+ return None
138
+ _, count, _, _, _, optional_size, _ = struct.unpack_from('<HHIIIHH', data, header + 4)
139
+ table = header + 24 + optional_size
140
+ found = []
141
+ for index in range(count):
142
+ name, _, _, size, offset = struct.unpack_from('<8sIIII', data, table + index * 40)
143
+ if name.rstrip(b'\0') == b'.nv_fatb':
144
+ found.append((offset, size))
145
+ return found
146
+ return None
147
+
148
+
149
+ def cuda_architectures(path: str) -> list[str] | None:
150
+ """Returns the GPU code in a CUDA library's fat binary, or `None` for a file without one.
151
+
152
+ Machine code reads as `sm_86` and PTX as `compute_86`.
153
+ """
154
+ try:
155
+ with open(path, 'rb') as handle:
156
+ data = handle.read()
157
+ sections = _fatbin_sections(data)
158
+ if sections is None:
159
+ return None
160
+ found = []
161
+ for offset, size in sections:
162
+ position = offset
163
+ while position + 16 <= offset + size:
164
+ magic, _, header, length = struct.unpack_from('<IHHQ', data, position)
165
+ if magic != 0xBA55ED50:
166
+ position += 8
167
+ continue
168
+ entry = position + header
169
+ while entry < position + header + length:
170
+ # Each entry holds its kind, 1 for PTX and 2 for machine code, its header size,
171
+ # its payload size and, at byte 28, the architecture.
172
+ kind, _, entry_header, payload = struct.unpack_from('<HHIQ', data, entry)
173
+ (architecture,) = struct.unpack_from('<I', data, entry + 0x1C)
174
+ prefix = {1: 'compute', 2: 'sm'}.get(kind)
175
+ if prefix and f'{prefix}_{architecture}' not in found:
176
+ found.append(f'{prefix}_{architecture}')
177
+ entry += entry_header + payload
178
+ position += header + length
179
+ return sorted(found, key=lambda code: (code.startswith('compute'), int(code.split('_')[1])))
180
+ except (OSError, struct.error, ValueError):
181
+ return None
182
+
183
+
184
+ def code_for(capability: tuple[int, int], architectures: list[str]) -> str:
185
+ """Returns which code of the CUDA library a GPU of `capability` runs, as the driver picks it."""
186
+ major, minor = capability
187
+ machine = [int(code[3:]) for code in architectures if code.startswith('sm_')]
188
+ ptx = [int(code[8:]) for code in architectures if code.startswith('compute_')]
189
+ # Machine code runs on its own major version from its minor version up.
190
+ native = [code for code in machine if code // 10 == major and code % 10 <= minor]
191
+ if native:
192
+ return f'runs the machine code of sm_{max(native)}'
193
+ compiled = [code for code in ptx if code <= major * 10 + minor]
194
+ if compiled:
195
+ return (
196
+ f'runs the PTX of compute_{max(compiled)}, compiled by the driver for this GPU, which '
197
+ 'the digests below must then confirm'
198
+ )
199
+ return (
200
+ f'holds no code for compute capability {major}.{minor}: build cuju from the repository '
201
+ 'for this GPU'
202
+ )
203
+
204
+
205
+ def _processor():
206
+ """Returns the model and the flags of the processor, from `/proc/cpuinfo`."""
207
+ model, flags = platform.processor() or platform.machine(), set()
208
+ try:
209
+ with open('/proc/cpuinfo', encoding='ascii', errors='replace') as handle:
210
+ for line in handle:
211
+ key, _, value = line.partition(':')
212
+ if key.strip() == 'model name' and model in ('', 'x86_64'):
213
+ model = value.strip()
214
+ elif key.strip() == 'flags':
215
+ flags = set(value.split())
216
+ break
217
+ except OSError:
218
+ pass
219
+ return model, flags
220
+
221
+
222
+ def _cpu_quota():
223
+ """Returns the CPU quota of the cgroup of the process, such as `200000 100000`, or `None`."""
224
+ try:
225
+ with open('/sys/fs/cgroup/cpu.max', encoding='ascii') as handle:
226
+ quota = handle.read().strip()
227
+ except OSError:
228
+ return None
229
+ return None if quota.startswith('max') else quota
230
+
231
+
232
+ def _driver():
233
+ """Returns the NVIDIA driver's version and the CUDA version it supports, where they load."""
234
+ parts = []
235
+ try:
236
+ nvml = ctypes.CDLL('nvml.dll' if os.name == 'nt' else 'libnvidia-ml.so.1')
237
+ if nvml.nvmlInit_v2() == 0:
238
+ version = ctypes.create_string_buffer(96)
239
+ if nvml.nvmlSystemGetDriverVersion(version, 96) == 0:
240
+ parts.append(f'driver {version.value.decode()}')
241
+ nvml.nvmlShutdown()
242
+ except (OSError, AttributeError):
243
+ pass
244
+ try:
245
+ version = ctypes.c_int()
246
+ driver = 'nvcuda.dll' if os.name == 'nt' else 'libcuda.so.1'
247
+ if ctypes.CDLL(driver).cuDriverGetVersion(ctypes.byref(version)) == 0:
248
+ parts.append(f'CUDA {version.value // 1000}.{version.value % 1000 // 10}')
249
+ except (OSError, AttributeError):
250
+ pass
251
+ return ', '.join(parts) or 'not found'
252
+
253
+
254
+ def _version(module):
255
+ try:
256
+ return importlib.metadata.version(module)
257
+ except importlib.metadata.PackageNotFoundError:
258
+ return None
259
+
260
+
261
+ def _library(device):
262
+ """Returns the lines that describe the library of `device`, and its GPU code for `cuda`."""
263
+ path = cuju.library_path(device)
264
+ variable = _libraries._LIBRARIES[device][1]
265
+ source = f'from {variable}' if os.environ.get(variable) else 'of the package'
266
+ if not os.path.isfile(path):
267
+ return [f'{device} library: missing at {path} ({source})'], None
268
+ size = os.path.getsize(path) / 2**20
269
+ lines = [
270
+ f'{device} library: {path} ({source}), {size:.1f} MiB, '
271
+ f'SHA-256 {_checksums.file_sha256(path)}'
272
+ ]
273
+ architectures = cuda_architectures(path) if device == 'cuda' else None
274
+ if device == 'cuda':
275
+ machine = [code for code in architectures or [] if code.startswith('sm_')]
276
+ ptx = [code for code in architectures or [] if code.startswith('compute_')]
277
+ lines.append(
278
+ f' GPU code: machine code for {" ".join(machine) or "none"}; '
279
+ f'PTX for {" ".join(ptx) or "none"}'
280
+ if architectures is not None
281
+ else ' GPU code: unreadable'
282
+ )
283
+ return lines, architectures
284
+
285
+
286
+ def diagnostics() -> list[str]:
287
+ """Returns lines on this installation's versions, processor, libraries and GPUs."""
288
+ version = getattr(cuju, '__version__', None) or _version('cuju-engine') or 'from a source tree'
289
+ lines = [
290
+ f'cuju {version} at {os.path.dirname(os.path.abspath(cuju.__file__))}',
291
+ f'Python {platform.python_version()}, torch {torch.__version__} '
292
+ f'(CUDA {torch.version.cuda or "none"}), numpy {_version("numpy") or "none"}, '
293
+ f'gymnasium {_version("gymnasium") or "none"}',
294
+ ]
295
+ build_info = getattr(cuju, 'build_info', None)
296
+ if callable(build_info):
297
+ lines.append(f'build: {build_info()}')
298
+ libc = ' '.join(platform.libc_ver()).strip()
299
+ lines.append(f'{platform.platform()}{f", {libc}" if libc else ""}')
300
+ model, flags = _processor()
301
+ usable = len(os.sched_getaffinity(0)) if hasattr(os, 'sched_getaffinity') else os.cpu_count()
302
+ quota = _cpu_quota()
303
+ lines.append(
304
+ f'CPU: {model}, {os.cpu_count()} logical processors, {usable} usable by this process'
305
+ + (f', cgroup quota {quota}' if quota else '')
306
+ )
307
+ if platform.machine().lower() not in ('x86_64', 'amd64'):
308
+ missing = []
309
+ elif flags:
310
+ missing = [name.upper() for name in _FEATURES if name not in flags]
311
+ else:
312
+ # Without `/proc/cpuinfo`, the system answers for what it can, Windows for AVX2 alone.
313
+ missing = _libraries._missing_processor_features()
314
+ lines.append(
315
+ ' flags: nothing that the packaged CPU library needs is missing'
316
+ if not missing
317
+ else f' flags: {", ".join(missing)} missing, so the packaged CPU library cannot run here'
318
+ )
319
+ cpu_lines, _ = _library('cpu')
320
+ cuda_lines, architectures = _library('cuda')
321
+ lines += cpu_lines + cuda_lines
322
+ if torch.cuda.is_available():
323
+ lines.append(f'NVIDIA: {_driver()}')
324
+ for index in range(torch.cuda.device_count()):
325
+ properties = torch.cuda.get_device_properties(index)
326
+ capability = (properties.major, properties.minor)
327
+ line = (
328
+ f'GPU {index}: {properties.name}, compute capability {capability[0]}.'
329
+ f'{capability[1]}, {properties.total_memory / 2**30:.1f} GiB'
330
+ )
331
+ if architectures is not None:
332
+ line += f'; the CUDA library {code_for(capability, architectures)}'
333
+ lines.append(line)
334
+ else:
335
+ lines.append('GPU: none that PyTorch can use')
336
+ names = sorted(name for name in os.environ if name.startswith('CUJU_'))
337
+ if os.environ.get('CUDA_VISIBLE_DEVICES') is not None:
338
+ names.append('CUDA_VISIBLE_DEVICES')
339
+ lines.append(
340
+ 'environment: '
341
+ + (', '.join(f'{name}={os.environ[name]}' for name in names) or 'no CUJU_ variable set')
342
+ )
343
+ if not os.environ.get('CUJU_LOG'):
344
+ lines.append(' CUJU_LOG=1 logs the creation of every batch')
345
+ return lines
346
+
347
+
348
+ def check_data() -> list[str]:
349
+ """Returns the files of the package data that differ from `data/SHA256SUMS` or that it lacks."""
350
+ try:
351
+ listed = _checksums.read_checksums()
352
+ except (OSError, ValueError) as error:
353
+ return [f'the list cannot be read: {error}']
354
+ problems = []
355
+ for name, digest in listed.items():
356
+ path = os.path.join(_checksums.DATA_DIRECTORY, name)
357
+ if not os.path.isfile(path):
358
+ problems.append(f'{name} is missing')
359
+ elif _checksums.file_sha256(path) != digest:
360
+ problems.append(f'{name} differs')
361
+ problems += [f'{name} is not listed' for name in _checksums.data_files() if name not in listed]
362
+ return problems
363
+
364
+
365
+ def _loads(device):
366
+ """Returns why the library of `device` does not load here, or `None` if it does."""
367
+ try:
368
+ _libraries._load_library(None, device)
369
+ except (OSError, RuntimeError) as error:
370
+ return str(error)
371
+ return None
372
+
373
+
374
+ def _devices(requested):
375
+ """Returns the devices to play as `(label, device, CUDA index)`, and the notes on the absent."""
376
+ devices, notes = [], []
377
+ if requested in ('all', 'cpu'):
378
+ problem = _loads('cpu')
379
+ if problem is None:
380
+ devices.append(('cpu', 'cpu', None))
381
+ else:
382
+ notes.append(f'the CPU cases did not run, {problem}')
383
+ if requested in ('all', 'cuda'):
384
+ problem = _loads('cuda')
385
+ if problem is not None:
386
+ notes.append(f'the GPU cases did not run, {problem}')
387
+ elif not torch.cuda.is_available():
388
+ notes.append('the GPU cases did not run, no GPU that PyTorch can use')
389
+ else:
390
+ devices += [
391
+ (f'cuda:{index}', 'cuda', index) for index in range(torch.cuda.device_count())
392
+ ]
393
+ return devices, notes
394
+
395
+
396
+ def run_case(entry, device, index):
397
+ """Plays one case on `device`, on CUDA device `index` if given, and returns its digest."""
398
+ arguments = (entry['assets'], device, entry['steps'])
399
+ options = {'seed': entry['seed'], 'environments': entry['environments'], **entry['options']}
400
+ if index is None:
401
+ return play_digest(*arguments, **options)
402
+ with torch.cuda.device(index):
403
+ return play_digest(*arguments, **options)
404
+
405
+
406
+ def _list_cases(cases, arguments):
407
+ if arguments.json:
408
+ contract.emit(
409
+ 'engine.check.list/1',
410
+ {
411
+ 'cases': [
412
+ {
413
+ 'name': name,
414
+ 'assets': entry['assets'],
415
+ 'steps': entry['steps'],
416
+ 'options': entry['options'],
417
+ }
418
+ for name, entry in cases.items()
419
+ ]
420
+ },
421
+ )
422
+ elif cases:
423
+ rows = [
424
+ (name, str(entry['assets']), f'{entry["steps"]} steps', str(entry['options'] or ''))
425
+ for name, entry in cases.items()
426
+ ]
427
+ widths = [max(map(len, column)) for column in zip(*rows, strict=True)]
428
+ if sys.stdout.isatty():
429
+ columns = shutil.get_terminal_size().columns
430
+ widths[0] = min(widths[0], max(1, (columns - widths[2] - 6) // 2))
431
+ widths[1] = min(widths[1], max(1, columns - widths[0] - widths[2] - 6))
432
+ widths[3] = min(widths[3], max(0, columns - sum(widths[:3]) - 6))
433
+ for row in rows:
434
+ cells = []
435
+ for value, width in zip(row, widths, strict=True):
436
+ if width and len(value) > width:
437
+ value = value[: width - 1] + '…'
438
+ cells.append(f'{value:<{width}}' if width else '')
439
+ print(' '.join(cells).rstrip())
440
+ if not cases and not getattr(arguments, 'quiet', False):
441
+ print(
442
+ 'No cases are listed. Run cuju check --list --long to include the long cases.',
443
+ file=sys.stderr,
444
+ )
445
+ return 0
446
+
447
+
448
+ def _run(arguments: argparse.Namespace) -> int:
449
+ cases = load_cases(arguments.long or bool(arguments.case))
450
+ if arguments.case:
451
+ for name in arguments.case:
452
+ if name not in cases:
453
+ arguments._command_parser.error(
454
+ f'expected a named check case, found {name!r}',
455
+ hint='run cuju check --list --long to list the cases.',
456
+ )
457
+ cases = {name: cases[name] for name in arguments.case}
458
+
459
+ if arguments.list:
460
+ return _list_cases(cases, arguments)
461
+
462
+ quiet = getattr(arguments, 'quiet', False)
463
+ interactive = not quiet and sys.stderr.isatty()
464
+ columns = shutil.get_terminal_size().columns if interactive else 0
465
+ line_width = 0
466
+
467
+ def progress(text: str, *, update: bool = False) -> None:
468
+ nonlocal line_width
469
+ if quiet:
470
+ return
471
+ if interactive and update:
472
+ text = text[: max(1, columns - 1)]
473
+ print(f'\r{text:<{line_width}}', end='', file=sys.stderr, flush=True)
474
+ line_width = max(line_width, len(text))
475
+ else:
476
+ if line_width:
477
+ print(f'\r{" " * line_width}\r', end='', file=sys.stderr)
478
+ line_width = 0
479
+ print(text, file=sys.stderr)
480
+
481
+ setup = diagnostics()
482
+ for line in setup:
483
+ if interactive:
484
+ line = textwrap.fill(
485
+ line,
486
+ columns,
487
+ subsequent_indent=' ',
488
+ break_long_words=False,
489
+ break_on_hyphens=False,
490
+ replace_whitespace=False,
491
+ )
492
+ progress(line)
493
+
494
+ problems = check_data()
495
+ if not arguments.json:
496
+ detail = (
497
+ ', '.join(problems)
498
+ if problems
499
+ else f'{len(_checksums.data_files())} files match data/SHA256SUMS'
500
+ )
501
+ print(f'package data: {detail}')
502
+
503
+ failures = len(problems)
504
+ devices, notes = _devices(arguments.device)
505
+ results = []
506
+ for label, device, index in devices:
507
+ matched, started = 0, time.perf_counter()
508
+ for name, entry in cases.items():
509
+ begun = time.perf_counter()
510
+ found, error = None, None
511
+ try:
512
+ found = run_case(entry, device, index)
513
+ except Error as problem:
514
+ error = str(problem)
515
+ expected = entry['digest']
516
+ equal = error is None and expected is not None and found == expected
517
+ matched += equal
518
+ results.append(
519
+ {
520
+ 'device': label,
521
+ 'case': name,
522
+ 'expected': expected,
523
+ 'found': found,
524
+ 'matched': equal,
525
+ 'error': error,
526
+ }
527
+ )
528
+ if error is not None:
529
+ progress(f'{label:8} {name}: FAILED, {error}')
530
+ if device == 'cuda':
531
+ progress(f'{label:8} the other cases of this GPU did not run')
532
+ break
533
+ elif equal:
534
+ progress(f'{label:8} {name}: ok ({time.perf_counter() - begun:.1f} s)', update=True)
535
+ elif expected is None:
536
+ progress(f'{label:8} {name}: no expected digest yet, this build gives {found}')
537
+ else:
538
+ progress(f'{label:8} {name}: DIFFERENT, {found} instead of {expected}')
539
+ failures += len(cases) - matched
540
+ progress(
541
+ f'{label:8} {matched} of {len(cases)} cases match '
542
+ f'({time.perf_counter() - started:.0f} s)'
543
+ )
544
+
545
+ unavailable = not devices
546
+ if unavailable and not failures:
547
+ expected = (
548
+ 'a usable backend'
549
+ if arguments.device == 'all'
550
+ else (f'an available {arguments.device} backend')
551
+ )
552
+ return contract.fail(
553
+ 'cuju check',
554
+ f'expected {expected}, found none. ' + ', '.join(notes),
555
+ hint='run cuju check --device all to check the available backends.'
556
+ if arguments.device != 'all'
557
+ else 'run python -m pip show cuju-engine to check the installation.',
558
+ as_json=arguments.json,
559
+ status=contract.EXIT_ENVIRONMENT,
560
+ error_id='check.backend_unavailable',
561
+ values={'device': arguments.device},
562
+ )
563
+
564
+ status = contract.EXIT_NO if failures else 0
565
+ if unavailable:
566
+ contract.fail('cuju check', ', '.join(notes), status=status)
567
+ else:
568
+ for note in notes:
569
+ progress(note)
570
+
571
+ if arguments.json:
572
+ contract.emit(
573
+ 'engine.check/1',
574
+ {
575
+ 'diagnostics': setup,
576
+ 'data_problems': problems,
577
+ 'results': results,
578
+ 'backend_notes': notes,
579
+ 'failures': failures,
580
+ 'exit': status,
581
+ },
582
+ )
583
+ elif failures:
584
+ print(f'FAILED: {failures} checks differ or did not run')
585
+ else:
586
+ print('PASSED: every case that ran gave the expected digest')
587
+ return status
588
+
589
+
590
+ def main(argv: list[str] | None = None) -> int:
591
+ """Runs the self-check and returns its exit status."""
592
+ return contract.run_command(_cli_parsers.check(), _run, argv)
593
+
594
+
595
+ if __name__ == '__main__':
596
+ sys.exit(main())
cuju/cuju_cpu.dll ADDED
Binary file
cuju/cuju_cuda.dll ADDED
Binary file
cuju/cuju_render.dll ADDED
Binary file
cuju/data/SHA256SUMS ADDED
@@ -0,0 +1,20 @@
1
+ 836d0753028c9c5a9e057069a0299bc5ebe0b3a77187949d7127ebc06bc3baff animations.bin
2
+ a40355e3fb44913055128f8b0c78c12132521fdb6fa276932d2503cfb5518d48 assets/11_vs_11_competition_l0_r0.cjb
3
+ c520c6a7bb849be2ab2049835e4bf2617b90ae27084d1818a9887c56427d1ec9 assets/11_vs_11_easy_stochastic_l0_r0.cjb
4
+ 31067a2d70bc7c75dfc621fcce831e500b9b4d38ad71a52465207e87ad3f1fa8 assets/11_vs_11_hard_stochastic_l0_r0.cjb
5
+ d1d64a162ebd97bc10adc4110e39e86f5ac06af0a3f085f89c4bdebd29a5d408 assets/11_vs_11_kaggle_l0_r0.cjb
6
+ 9cd9251e81c872d1e669f132d5ddbe74b8a0e60b9d93689e24e3a039aabf5261 assets/11_vs_11_stochastic_l0_r0.cjb
7
+ 73ebdb630538e3d38fce2373efd1f021a8bbfca0a15a050497df1686c1ba992b assets/1_vs_1_easy_l0_r0.cjb
8
+ 5ad511c32c92ac200cec14ef1d2e0a9dd7eb63766f69c3e795a8d6a1bfe2b627 assets/5_vs_5_l0_r0.cjb
9
+ 7aff469c7f977cb87d2cedeefbec9cfd393982fcc6dd5d3c703786fbe912b34e assets/academy_3_vs_1_with_keeper_l0_r0.cjb
10
+ b10d62739f63d0630f639d322cffb80ccf5c8a1b97df600bc67e76cbbd028dd3 assets/academy_corner_l0_r0.cjb
11
+ ae59a81108955191a25e1757f5885d5517624ae91c1d20a372e20a892ebacff5 assets/academy_counterattack_easy_l0_r0.cjb
12
+ 4d6ce7dc34fd27f6d0edf3246fb2cef4057be8457c2d48b0beedc123b3a9471d assets/academy_counterattack_hard_l0_r0.cjb
13
+ b9fbe1b2f21e592fa1aa3e8e63275f54a862f52c6adf4578f4b0e50a88b7d174 assets/academy_empty_goal_close_l0_r0.cjb
14
+ a06feb99cda8987b9c38cb6afaf65c969f175c095b27d27fb7f283747d840882 assets/academy_empty_goal_l0_r0.cjb
15
+ c87444fe2aa0b6212be4b53c344fc29697d9823960080ba8eb1b520985528e83 assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb
16
+ 0b431fef82768f7ae036132d39205f075efacd30385c9c665793a1891f446f9e assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb
17
+ 3256df75c693b81033dc8c66aec73388bb44efbda5c2ec877d9e41d2079aa5b3 assets/academy_run_to_score_l0_r0.cjb
18
+ 669987980950d881e2333cb4076b4dd71b019d3fffa57a3b70c2f772093f97ef assets/academy_run_to_score_with_keeper_l0_r0.cjb
19
+ c2cde0f5011e979f588128773f05e60d583e1e099961dfb96a75a99b8eca31f5 assets/academy_single_goal_versus_lazy_l0_r0.cjb
20
+ 3d7d10819aa162960afc326baece8431cd8c3fd38fcec2a2bbc0310f2d78dc1b assets/test_example_multiagent_l0_r0.cjb
Binary file
Binary file
Binary file