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.
- cuju/__init__.py +217 -0
- cuju/__main__.py +262 -0
- cuju/_batch/__init__.py +4 -0
- cuju/_batch/allocator.py +52 -0
- cuju/_batch/assets.py +68 -0
- cuju/_batch/environment.py +1890 -0
- cuju/_batch/frame_stack.py +114 -0
- cuju/_batch/library.py +190 -0
- cuju/_batch/log.py +103 -0
- cuju/_batch/memory.py +70 -0
- cuju/_batch/operators.py +55 -0
- cuju/_batch/pinned.py +39 -0
- cuju/_batch/pixels.py +207 -0
- cuju/_batch/state.py +77 -0
- cuju/_checksums.py +60 -0
- cuju/_cli_contract.py +244 -0
- cuju/_cli_parsers.py +191 -0
- cuju/_completion.py +277 -0
- cuju/_dump_to_txt.py +66 -0
- cuju/_grf_config.py +331 -0
- cuju/_library_path.py +141 -0
- cuju/_media.py +113 -0
- cuju/_pixels.py +276 -0
- cuju/_plugins.py +106 -0
- cuju/_python_players.py +224 -0
- cuju/_replay_command.py +109 -0
- cuju/_replay_player.py +42 -0
- cuju/_replays.py +414 -0
- cuju/_script_helpers.py +109 -0
- cuju/_version.py +6 -0
- cuju/action_log.py +371 -0
- cuju/check.py +596 -0
- cuju/cuju_cpu.dll +0 -0
- cuju/cuju_cuda.dll +0 -0
- cuju/cuju_render.dll +0 -0
- cuju/data/SHA256SUMS +20 -0
- cuju/data/animations.bin +0 -0
- cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
- cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
- cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
- cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
- cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
- cuju/data/digests.json +186 -0
- cuju/data/render_digests.json.z +0 -0
- cuju/data/scenarios/11_vs_11_competition.py +45 -0
- cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
- cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
- cuju/data/scenarios/1_vs_1_easy.py +25 -0
- cuju/data/scenarios/5_vs_5.py +33 -0
- cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
- cuju/data/scenarios/academy_corner.py +45 -0
- cuju/data/scenarios/academy_counterattack_easy.py +45 -0
- cuju/data/scenarios/academy_counterattack_hard.py +45 -0
- cuju/data/scenarios/academy_empty_goal.py +25 -0
- cuju/data/scenarios/academy_empty_goal_close.py +25 -0
- cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_to_score.py +30 -0
- cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
- cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
- cuju/data/scenarios/test_example_multiagent.py +28 -0
- cuju/dumps.py +942 -0
- cuju/engine_status.py +106 -0
- cuju/env.py +1168 -0
- cuju/errors.py +108 -0
- cuju/gfootball/GRF_SOURCES +86 -0
- cuju/gfootball/__init__.py +60 -0
- cuju/gfootball/_cv2.py +43 -0
- cuju/gfootball/_gym/__init__.py +88 -0
- cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
- cuju/gfootball/_gym/_vendored/__init__.py +43 -0
- cuju/gfootball/_gym/_vendored/core.py +361 -0
- cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
- cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
- cuju/gfootball/_gym/_vendored/error.py +230 -0
- cuju/gfootball/_gym/_vendored/logger.py +56 -0
- cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
- cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
- cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
- cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
- cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
- cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
- cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
- cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
- cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
- cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
- cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
- cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
- cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
- cuju/gfootball/_gym/_vendored/version.py +5 -0
- cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
- cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
- cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
- cuju/gfootball/dump_to_txt.py +49 -0
- cuju/gfootball/dump_to_video.py +33 -0
- cuju/gfootball/env/__init__.py +271 -0
- cuju/gfootball/env/config.py +163 -0
- cuju/gfootball/env/constants.py +33 -0
- cuju/gfootball/env/controller_base.py +114 -0
- cuju/gfootball/env/event_queue.py +54 -0
- cuju/gfootball/env/football_action_set.py +220 -0
- cuju/gfootball/env/football_action_set_test.py +76 -0
- cuju/gfootball/env/football_env.py +225 -0
- cuju/gfootball/env/football_env_core.py +447 -0
- cuju/gfootball/env/football_env_test.py +692 -0
- cuju/gfootball/env/gym_test.py +47 -0
- cuju/gfootball/env/observation_preprocessing.py +94 -0
- cuju/gfootball/env/observation_processor.py +526 -0
- cuju/gfootball/env/observation_rotation.py +163 -0
- cuju/gfootball/env/observation_rotation_test.py +84 -0
- cuju/gfootball/env/player_base.py +46 -0
- cuju/gfootball/env/players/__init__.py +16 -0
- cuju/gfootball/env/players/agent.py +39 -0
- cuju/gfootball/env/players/bot.py +217 -0
- cuju/gfootball/env/players/gamepad.py +81 -0
- cuju/gfootball/env/players/keyboard.py +72 -0
- cuju/gfootball/env/players/lazy.py +31 -0
- cuju/gfootball/env/players/ppo2_cnn.py +119 -0
- cuju/gfootball/env/players/replay.py +40 -0
- cuju/gfootball/env/remote_football_env.py +189 -0
- cuju/gfootball/env/scenario_builder.py +125 -0
- cuju/gfootball/env/script_helpers.py +130 -0
- cuju/gfootball/env/script_helpers_test.py +107 -0
- cuju/gfootball/env/wrappers.py +440 -0
- cuju/gfootball/env/wrappers_test.py +150 -0
- cuju/gfootball/eval_server/__init__.py +17 -0
- cuju/gfootball/eval_server/config.py +30 -0
- cuju/gfootball/eval_server/example_client.py +107 -0
- cuju/gfootball/eval_server/proto/game_server.proto +62 -0
- cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
- cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
- cuju/gfootball/eval_server/proto/master.proto +25 -0
- cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
- cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
- cuju/gfootball/eval_server/utils.py +52 -0
- cuju/gfootball/examples/__init__.py +16 -0
- cuju/gfootball/examples/models.py +66 -0
- cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
- cuju/gfootball/examples/run_ppo2.py +123 -0
- cuju/gfootball/play_game.py +73 -0
- cuju/gfootball/replay.py +43 -0
- cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
- cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
- cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
- cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
- cuju/gfootball/scenarios/5_vs_5.py +46 -0
- cuju/gfootball/scenarios/__init__.py +31 -0
- cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
- cuju/gfootball/scenarios/academy_corner.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
- cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
- cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
- cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
- cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
- cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
- cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
- cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
- cuju/gfootball/scenarios/tests/__init__.py +31 -0
- cuju/gfootball/scenarios/tests/corner_test.py +38 -0
- cuju/gfootball/scenarios/tests/goal_test.py +35 -0
- cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
- cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
- cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
- cuju/gfootball/scenarios/tests/offside_test.py +39 -0
- cuju/gfootball/scenarios/tests/penalty.py +34 -0
- cuju/gfootball/scenarios/tests/second_half.py +33 -0
- cuju/gfootball/scenarios/tests/symmetric.py +53 -0
- cuju/gfootball_engine/__init__.py +31 -0
- cuju/gfootball_engine/_gameplayfootball.py +1624 -0
- cuju/gfootball_engine/_native.py +193 -0
- cuju/gfootball_engine/_pickle_names.py +114 -0
- cuju/gfootball_engine/_render_hooks.py +156 -0
- cuju/kaggle.py +425 -0
- cuju/multi_device.py +401 -0
- cuju/players.py +260 -0
- cuju/raw.py +93 -0
- cuju/scenarios.py +661 -0
- cuju/state.py +211 -0
- cuju/wrappers.py +325 -0
- cuju_engine-0.3.0.dist-info/METADATA +325 -0
- cuju_engine-0.3.0.dist-info/RECORD +222 -0
- cuju_engine-0.3.0.dist-info/WHEEL +5 -0
- cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
- cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""GRF's `FrameStack` in the pickle of a stacked state, a deque of four numpy observations."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import collections
|
|
8
|
+
import importlib
|
|
9
|
+
import pickle
|
|
10
|
+
import warnings
|
|
11
|
+
|
|
12
|
+
# GRF: `FrameStack(env, 4)` keeps the last four observations, the oldest first.
|
|
13
|
+
FRAMES = 4
|
|
14
|
+
|
|
15
|
+
# The globals that the pickle of the deque names, as numpy before and after 2 spell them. A pickle
|
|
16
|
+
# of protocol 2, as this module writes, holds the bytes of each array through `_codecs.encode`.
|
|
17
|
+
_GLOBALS = {
|
|
18
|
+
('collections', 'deque'),
|
|
19
|
+
('_codecs', 'encode'),
|
|
20
|
+
('builtins', 'bytes'),
|
|
21
|
+
('numpy', 'ndarray'),
|
|
22
|
+
('numpy', 'dtype'),
|
|
23
|
+
('numpy._core.multiarray', '_reconstruct'),
|
|
24
|
+
('numpy.core.multiarray', '_reconstruct'),
|
|
25
|
+
('numpy._core.numeric', '_frombuffer'),
|
|
26
|
+
('numpy.core.numeric', '_frombuffer'),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _numpy():
|
|
31
|
+
try:
|
|
32
|
+
import numpy
|
|
33
|
+
except ImportError:
|
|
34
|
+
raise ModuleNotFoundError(
|
|
35
|
+
'expected numpy for a stacked state, whose frames GRF pickles as numpy arrays'
|
|
36
|
+
) from None
|
|
37
|
+
return numpy
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def frames_of(stack, agents):
|
|
41
|
+
"""Returns GRF's four frames of one environment's stack, a CPU tensor `[agents, ..., 4 * n]`.
|
|
42
|
+
|
|
43
|
+
GRF stacks what its single-agent wrappers return, so one agent's frames drop the agent axis.
|
|
44
|
+
"""
|
|
45
|
+
numpy = _numpy()
|
|
46
|
+
array = stack.numpy()
|
|
47
|
+
width = array.shape[-1] // FRAMES
|
|
48
|
+
frames = [
|
|
49
|
+
numpy.ascontiguousarray(array[..., width * frame : width * (frame + 1)])
|
|
50
|
+
for frame in range(FRAMES)
|
|
51
|
+
]
|
|
52
|
+
return [frame[0] if agents == 1 else frame for frame in frames]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def pickled_frames(frames):
|
|
56
|
+
"""Returns the pickle of GRF's deque of `frames` without its protocol and stop opcodes.
|
|
57
|
+
|
|
58
|
+
The bytes serve as the value of one key of a pickle that writes no memo of its own.
|
|
59
|
+
"""
|
|
60
|
+
data = pickle.dumps(collections.deque(frames, maxlen=FRAMES), protocol=2)
|
|
61
|
+
assert data[:2] == b'\x80\x02' and data[-1:] == b'.'
|
|
62
|
+
return data[2:-1]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def find_class(module, name):
|
|
66
|
+
"""Returns the global that the pickle of the frames names, or `None` for any other."""
|
|
67
|
+
if (module, name) not in _GLOBALS:
|
|
68
|
+
return None
|
|
69
|
+
if not module.startswith('numpy'):
|
|
70
|
+
return getattr(importlib.import_module(module), name)
|
|
71
|
+
_numpy()
|
|
72
|
+
# A state saved under one numpy names its core module as that numpy spells it.
|
|
73
|
+
other = (
|
|
74
|
+
module.replace('numpy._core', 'numpy.core')
|
|
75
|
+
if '._core' in module
|
|
76
|
+
else module.replace('numpy.core', 'numpy._core')
|
|
77
|
+
)
|
|
78
|
+
for candidate in (module, other):
|
|
79
|
+
try:
|
|
80
|
+
with warnings.catch_warnings():
|
|
81
|
+
warnings.simplefilter('ignore')
|
|
82
|
+
return getattr(importlib.import_module(candidate), name)
|
|
83
|
+
except (ImportError, AttributeError):
|
|
84
|
+
continue
|
|
85
|
+
raise pickle.UnpicklingError(f'cannot resolve `{module}.{name}` with this numpy')
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def stack_bytes(frames, agents, shape, dtype):
|
|
89
|
+
"""Returns the stack of GRF's `frames` as the batch holds it, `[agents, *shape[:-1], 4 * c]`.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
frames: The deque of the state's `FrameStack`.
|
|
93
|
+
agents: The number of agents of the environment.
|
|
94
|
+
shape: The shape of one agent's frame, such as `(115,)`.
|
|
95
|
+
dtype: The type of the observations, `float32` or `uint8`.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ValueError: If the frames are not four observations of that shape and type.
|
|
99
|
+
"""
|
|
100
|
+
numpy = _numpy()
|
|
101
|
+
frames = list(frames) if isinstance(frames, (collections.deque, list, tuple)) else None
|
|
102
|
+
expected = tuple(shape) if agents == 1 else (agents, *shape)
|
|
103
|
+
if frames is None or len(frames) != FRAMES:
|
|
104
|
+
raise ValueError(f'expected the {FRAMES} frames of GRF in the FrameStack of the state')
|
|
105
|
+
arrays = []
|
|
106
|
+
for frame in frames:
|
|
107
|
+
array = numpy.asarray(frame)
|
|
108
|
+
if array.shape != expected or array.dtype != numpy.dtype(dtype):
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f'expected frames of the shape {expected} and the type {dtype} in the state, '
|
|
111
|
+
f'found {array.shape} and {array.dtype}'
|
|
112
|
+
)
|
|
113
|
+
arrays.append(array.reshape((agents, *shape)))
|
|
114
|
+
return numpy.ascontiguousarray(numpy.concatenate(arrays, axis=-1)).tobytes()
|
cuju/_batch/library.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""The library of each backend, the device a batch runs on, and the C signatures of the library."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ctypes
|
|
9
|
+
import os
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
|
|
14
|
+
from .._cli_contract import quote_path
|
|
15
|
+
from .._library_path import ( # noqa: F401, the names that this module has always held
|
|
16
|
+
_LIBRARIES,
|
|
17
|
+
_PACKAGE_DIRECTORY,
|
|
18
|
+
_automatic,
|
|
19
|
+
_backend,
|
|
20
|
+
_check_processor,
|
|
21
|
+
_missing_processor_features,
|
|
22
|
+
library_path,
|
|
23
|
+
)
|
|
24
|
+
from ..errors import DeviceError, LibraryError, MissingFileError
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _placement(device: Any) -> torch.device:
|
|
28
|
+
"""Returns the torch device that a batch of `device` runs on, the current GPU for `cuda`."""
|
|
29
|
+
if _backend(device) == 'cpu':
|
|
30
|
+
return torch.device('cpu')
|
|
31
|
+
if not torch.cuda.is_available():
|
|
32
|
+
raise DeviceError(
|
|
33
|
+
f'expected a CUDA GPU for device={str(device)!r}, found none that PyTorch can use; '
|
|
34
|
+
"pass device='cpu' to run the batch on the CPU"
|
|
35
|
+
)
|
|
36
|
+
index = torch.device(device).index
|
|
37
|
+
if index is None:
|
|
38
|
+
index = torch.cuda.current_device()
|
|
39
|
+
count = torch.cuda.device_count()
|
|
40
|
+
if not 0 <= index < count:
|
|
41
|
+
raise DeviceError(
|
|
42
|
+
f'expected a CUDA device from cuda:0 to cuda:{count - 1}, found cuda:{index}; '
|
|
43
|
+
'PyTorch sees only these GPUs (CUDA_VISIBLE_DEVICES may hide others)'
|
|
44
|
+
)
|
|
45
|
+
return torch.device('cuda', index)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Configuration(ctypes.Structure):
|
|
49
|
+
"""`cuju_configuration` of the C API."""
|
|
50
|
+
|
|
51
|
+
_fields_ = [
|
|
52
|
+
('version', ctypes.c_int),
|
|
53
|
+
('assets', ctypes.POINTER(ctypes.c_char_p)),
|
|
54
|
+
('asset_count', ctypes.c_int),
|
|
55
|
+
('assignment', ctypes.c_void_p),
|
|
56
|
+
('animations', ctypes.c_char_p),
|
|
57
|
+
('environment_count', ctypes.c_int),
|
|
58
|
+
('seed', ctypes.c_ulonglong),
|
|
59
|
+
('action_set', ctypes.c_int),
|
|
60
|
+
('observation', ctypes.c_int),
|
|
61
|
+
('checkpoints', ctypes.c_int),
|
|
62
|
+
('numpy_legacy', ctypes.c_int),
|
|
63
|
+
('auto_reset', ctypes.c_int),
|
|
64
|
+
('threads', ctypes.c_int),
|
|
65
|
+
('ticks_per_step', ctypes.c_int),
|
|
66
|
+
('smm_width', ctypes.c_int),
|
|
67
|
+
('smm_height', ctypes.c_int),
|
|
68
|
+
('stack', ctypes.c_int),
|
|
69
|
+
('fixed_seeds', ctypes.c_void_p),
|
|
70
|
+
('agent_counts', ctypes.c_void_p),
|
|
71
|
+
('episode_number', ctypes.c_int),
|
|
72
|
+
('first_index', ctypes.c_ulonglong),
|
|
73
|
+
('allocate', ctypes.c_void_p),
|
|
74
|
+
('release', ctypes.c_void_p),
|
|
75
|
+
('allocator_context', ctypes.c_void_p),
|
|
76
|
+
('pin_threads', ctypes.c_int),
|
|
77
|
+
('numa', ctypes.c_int),
|
|
78
|
+
('page_aligned', ctypes.c_int),
|
|
79
|
+
('render_mode', ctypes.c_int),
|
|
80
|
+
('referee_animations', ctypes.c_int),
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# `CUJU_CONFIGURATION_VERSION` of the C API.
|
|
85
|
+
_CONFIGURATION_VERSION = 3
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _load_library(path=None, device='cuda'):
|
|
89
|
+
"""Loads the library of `device`, by default at `library_path`, and declares its signatures."""
|
|
90
|
+
variable = _LIBRARIES[device][1]
|
|
91
|
+
if path is None and os.environ.get(variable) and not os.path.isfile(os.environ[variable]):
|
|
92
|
+
raise MissingFileError(
|
|
93
|
+
f'the environment variable {variable} names {quote_path(os.environ[variable])}, '
|
|
94
|
+
'which is no file'
|
|
95
|
+
)
|
|
96
|
+
path = path or library_path(device)
|
|
97
|
+
if not os.path.isfile(path):
|
|
98
|
+
# A CPU-only build, such as the wheels for macOS and Linux on Arm, has no CUDA library.
|
|
99
|
+
advice = (
|
|
100
|
+
"pass device='cpu', or build the package with a CUDA compiler"
|
|
101
|
+
if device == 'cuda'
|
|
102
|
+
else 'build the package with that backend or pick the other device'
|
|
103
|
+
)
|
|
104
|
+
raise MissingFileError(
|
|
105
|
+
f'expected the library of the backend {device} at {quote_path(path)}, '
|
|
106
|
+
f'which this installation lacks; {advice}'
|
|
107
|
+
)
|
|
108
|
+
if device == 'cpu':
|
|
109
|
+
_check_processor(path)
|
|
110
|
+
library = ctypes.CDLL(path)
|
|
111
|
+
pointer, integer, string = ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p
|
|
112
|
+
library.cuju_backend.restype = string
|
|
113
|
+
backend = library.cuju_backend().decode()
|
|
114
|
+
if backend != device:
|
|
115
|
+
raise LibraryError(
|
|
116
|
+
f'expected the library of the backend {device} at {quote_path(path)}, found {backend}'
|
|
117
|
+
)
|
|
118
|
+
library.cuju_last_error.restype = string
|
|
119
|
+
library.cuju_environment_create.restype = pointer
|
|
120
|
+
library.cuju_environment_create.argtypes = [ctypes.POINTER(_Configuration)]
|
|
121
|
+
library.cuju_environment_destroy.argtypes = [pointer]
|
|
122
|
+
library.cuju_memory_estimate.argtypes = [
|
|
123
|
+
ctypes.POINTER(_Configuration),
|
|
124
|
+
ctypes.POINTER(ctypes.c_ulonglong),
|
|
125
|
+
]
|
|
126
|
+
library.cuju_local_memory_bytes.argtypes = [ctypes.POINTER(ctypes.c_ulonglong)]
|
|
127
|
+
library.cuju_environment_memory_bytes.restype = ctypes.c_ulonglong
|
|
128
|
+
library.cuju_environment_memory_bytes.argtypes = [pointer]
|
|
129
|
+
library.cuju_environment_count.argtypes = [pointer]
|
|
130
|
+
library.cuju_environment_threads.argtypes = [pointer]
|
|
131
|
+
library.cuju_environment_agents.argtypes = [pointer, pointer, pointer]
|
|
132
|
+
library.cuju_environment_players.argtypes = [pointer, pointer, pointer]
|
|
133
|
+
library.cuju_environment_set_difficulty.argtypes = [pointer, pointer]
|
|
134
|
+
library.cuju_environment_difficulty.argtypes = [pointer, pointer]
|
|
135
|
+
library.cuju_environment_difficulty.restype = None
|
|
136
|
+
library.cuju_environment_set_render.argtypes = [pointer, pointer, integer, integer]
|
|
137
|
+
library.cuju_engine_render_state_version.restype = ctypes.c_uint
|
|
138
|
+
library.cuju_engine_render_state_version.argtypes = []
|
|
139
|
+
library.cuju_engine_render_state_size.restype = ctypes.c_ulonglong
|
|
140
|
+
library.cuju_engine_render_state_size.argtypes = []
|
|
141
|
+
library.cuju_engine_internal_render_state.argtypes = [pointer, ctypes.c_ulonglong, integer]
|
|
142
|
+
library.cuju_environment_render_event_size.restype = ctypes.c_ulonglong
|
|
143
|
+
library.cuju_environment_render_event_size.argtypes = []
|
|
144
|
+
library.cuju_environment_enable_render_events.argtypes = [pointer, integer]
|
|
145
|
+
library.cuju_environment_render_events.argtypes = [pointer, integer, pointer, integer, pointer]
|
|
146
|
+
library.cuju_environment_render_states.argtypes = [
|
|
147
|
+
pointer,
|
|
148
|
+
pointer,
|
|
149
|
+
integer,
|
|
150
|
+
pointer,
|
|
151
|
+
ctypes.c_ulonglong,
|
|
152
|
+
pointer,
|
|
153
|
+
]
|
|
154
|
+
library.cuju_environment_reset.argtypes = [pointer, pointer, pointer, pointer]
|
|
155
|
+
library.cuju_environment_reset_done.argtypes = [pointer, pointer]
|
|
156
|
+
library.cuju_environment_reset_masked.argtypes = [
|
|
157
|
+
pointer,
|
|
158
|
+
pointer,
|
|
159
|
+
integer,
|
|
160
|
+
pointer,
|
|
161
|
+
pointer,
|
|
162
|
+
pointer,
|
|
163
|
+
integer,
|
|
164
|
+
]
|
|
165
|
+
library.cuju_environment_step.argtypes = [pointer, pointer, integer, pointer, integer]
|
|
166
|
+
library.cuju_environment_step_async.argtypes = [pointer, pointer, integer, pointer]
|
|
167
|
+
library.cuju_environment_step_wait.argtypes = [pointer]
|
|
168
|
+
library.cuju_environment_synchronize.argtypes = [pointer, pointer]
|
|
169
|
+
library.cuju_environment_get_state.restype = pointer
|
|
170
|
+
library.cuju_environment_get_state.argtypes = [pointer, integer, pointer, pointer]
|
|
171
|
+
library.cuju_environment_set_state.argtypes = [
|
|
172
|
+
pointer,
|
|
173
|
+
integer,
|
|
174
|
+
ctypes.c_char_p,
|
|
175
|
+
ctypes.c_ulonglong,
|
|
176
|
+
pointer,
|
|
177
|
+
]
|
|
178
|
+
library.cuju_environment_set_stack.argtypes = [
|
|
179
|
+
pointer,
|
|
180
|
+
integer,
|
|
181
|
+
string,
|
|
182
|
+
ctypes.c_char_p,
|
|
183
|
+
ctypes.c_ulonglong,
|
|
184
|
+
]
|
|
185
|
+
library.cuju_environment_roles.argtypes = [pointer, integer, pointer, integer]
|
|
186
|
+
library.cuju_environment_buffer.restype = pointer
|
|
187
|
+
library.cuju_environment_buffer.argtypes = [pointer, string]
|
|
188
|
+
library.cuju_environment_raw_field.restype = string
|
|
189
|
+
library.cuju_environment_raw_field.argtypes = [pointer, integer, pointer, pointer, pointer]
|
|
190
|
+
return library
|
cuju/_batch/log.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The log that `CUJU_LOG=1` turns on, a line for each batch created, through the logger `cuju`.
|
|
4
|
+
|
|
5
|
+
The lines go to the handlers of the program's logging when it configured any, and otherwise to
|
|
6
|
+
standard error, each starting with `cuju:`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
import torch
|
|
19
|
+
|
|
20
|
+
LOGGER = logging.getLogger('cuju')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _StandardError(logging.StreamHandler):
|
|
24
|
+
"""Writes to the `sys.stderr` of each moment, which a test or a notebook may replace."""
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def stream(self):
|
|
28
|
+
return sys.stderr
|
|
29
|
+
|
|
30
|
+
@stream.setter
|
|
31
|
+
def stream(self, value):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def enabled() -> bool:
|
|
36
|
+
"""Returns whether `CUJU_LOG` is set to a value other than an empty string or `0`."""
|
|
37
|
+
return os.environ.get('CUJU_LOG', '') not in ('', '0')
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _handler():
|
|
41
|
+
"""Readies the logger, with a handler to standard error unless the program has handlers."""
|
|
42
|
+
LOGGER.setLevel(logging.INFO)
|
|
43
|
+
if LOGGER.handlers or logging.getLogger().handlers:
|
|
44
|
+
return
|
|
45
|
+
handler = _StandardError()
|
|
46
|
+
handler.setFormatter(logging.Formatter('cuju: %(message)s'))
|
|
47
|
+
LOGGER.addHandler(handler)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def info(message: str) -> None:
|
|
51
|
+
"""Logs a line if `CUJU_LOG` asks for it."""
|
|
52
|
+
if enabled():
|
|
53
|
+
_handler()
|
|
54
|
+
LOGGER.info(message)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def start(device: str, torch_device: torch.device | None = None) -> tuple[float, int | None] | None:
|
|
58
|
+
"""Returns the time and the free device memory before a batch's creation, or `None` if off.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
device: The backend of the batch, `cuda` or `cpu`.
|
|
62
|
+
torch_device: The batch's own `torch.device`, whose free memory counts on the GPU, which
|
|
63
|
+
need not be the current CUDA device.
|
|
64
|
+
"""
|
|
65
|
+
if not enabled():
|
|
66
|
+
return None
|
|
67
|
+
_handler()
|
|
68
|
+
free = None
|
|
69
|
+
if device == 'cuda':
|
|
70
|
+
import torch
|
|
71
|
+
|
|
72
|
+
if torch.cuda.is_available():
|
|
73
|
+
index = None if torch_device is None else torch_device.index
|
|
74
|
+
free = torch.cuda.mem_get_info(index)[0]
|
|
75
|
+
return time.perf_counter(), free
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def created(batch, assets, library, started) -> None:
|
|
79
|
+
"""Logs the creation of `batch` from `assets` through `library`, begun at `started`."""
|
|
80
|
+
if started is None:
|
|
81
|
+
return
|
|
82
|
+
began, free = started
|
|
83
|
+
seconds = time.perf_counter() - began
|
|
84
|
+
if batch.device == 'cuda':
|
|
85
|
+
import torch
|
|
86
|
+
|
|
87
|
+
index = batch._torch_device.index
|
|
88
|
+
major, minor = torch.cuda.get_device_capability(index)
|
|
89
|
+
place = (
|
|
90
|
+
f'cuda:{index} ({torch.cuda.get_device_name(index)}, compute capability '
|
|
91
|
+
f'{major}.{minor})'
|
|
92
|
+
)
|
|
93
|
+
if free is not None:
|
|
94
|
+
# Other users of the GPU blur this difference of the free memory.
|
|
95
|
+
taken = (free - torch.cuda.mem_get_info(index)[0]) / 2**20
|
|
96
|
+
place += f', about {taken:.0f} MiB of device memory'
|
|
97
|
+
else:
|
|
98
|
+
place = f'the CPU with {batch.threads} threads'
|
|
99
|
+
LOGGER.info(
|
|
100
|
+
f'created {batch.environment_count} environments of {assets} on {place} through '
|
|
101
|
+
f'{library} in {seconds:.2f} s: {batch.agents} agents, {batch.players} players a team, '
|
|
102
|
+
f'{batch._representation}'
|
|
103
|
+
)
|
cuju/_batch/memory.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""The memory that a batch takes on its GPU, and the warning when it exceeds the free memory."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ctypes
|
|
9
|
+
import warnings
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
from ..errors import _from_library
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _free_device_memory(device, allocator):
|
|
17
|
+
"""Returns the bytes of a GPU that a new batch may take, or `None` where none are known."""
|
|
18
|
+
try:
|
|
19
|
+
free, _ = torch.cuda.mem_get_info(device)
|
|
20
|
+
except RuntimeError:
|
|
21
|
+
return None
|
|
22
|
+
if allocator == 'torch':
|
|
23
|
+
# PyTorch's cache holds memory that the driver counts as taken but the batch may use.
|
|
24
|
+
free += torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)
|
|
25
|
+
return free
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# The CUDA devices on which this process created a batch, so that the driver holds the local memory
|
|
29
|
+
# of the kernels there.
|
|
30
|
+
_LOCAL_MEMORY_HELD = set()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _local_memory_bytes(library, device):
|
|
34
|
+
"""Returns the local memory that a batch on `device` adds for its kernels, 0 once one did."""
|
|
35
|
+
if device.type != 'cuda' or device.index in _LOCAL_MEMORY_HELD:
|
|
36
|
+
return 0
|
|
37
|
+
local = ctypes.c_ulonglong()
|
|
38
|
+
with torch.cuda.device(device):
|
|
39
|
+
if library.cuju_local_memory_bytes(ctypes.byref(local)) != 0:
|
|
40
|
+
raise _from_library(library.cuju_last_error().decode())
|
|
41
|
+
return local.value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _warn_memory(requested, free, device, local=0):
|
|
45
|
+
"""Warns if a batch requested more memory than its GPU had free before its creation.
|
|
46
|
+
|
|
47
|
+
`requested` counts `local`, the local memory that the creation added for the kernels.
|
|
48
|
+
"""
|
|
49
|
+
if requested <= free:
|
|
50
|
+
return
|
|
51
|
+
kernels = ''
|
|
52
|
+
if local:
|
|
53
|
+
kernels = f', {local / 2**20:.1f} MiB of it for the local memory of the kernels,'
|
|
54
|
+
# The WDDM driver of Windows and WSL spills into shared system memory without an error.
|
|
55
|
+
warnings.warn(
|
|
56
|
+
f'the batch requested {requested / 2**20:.1f} MiB of {device}{kernels} and the GPU had '
|
|
57
|
+
f'{free / 2**20:.1f} MiB free before its creation. On Windows and WSL the WDDM driver may '
|
|
58
|
+
'then place the batch in shared system memory, which runs many times slower and raises '
|
|
59
|
+
'no error. Use fewer environments, or check cuju.memory_estimate before the creation',
|
|
60
|
+
stacklevel=3,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _MemoryEstimate(int):
|
|
65
|
+
"""The bytes of a batch, as `memory_estimate` returns them, with `local_memory_bytes`."""
|
|
66
|
+
|
|
67
|
+
def __new__(cls, value, local_memory_bytes=0):
|
|
68
|
+
estimate = super().__new__(cls, value)
|
|
69
|
+
estimate.local_memory_bytes = local_memory_bytes
|
|
70
|
+
return estimate
|
cuju/_batch/operators.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The `torch.library` operators through which `torch.compile` traces a step without a break.
|
|
4
|
+
|
|
5
|
+
`cuju::step` and `cuju::reset_done` name the batch by a key and mutate its output tensors, which
|
|
6
|
+
they take as arguments, so that the compiler orders every read of an output after the call and
|
|
7
|
+
never drops the call. Each runs the same library call as the eager method.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import itertools
|
|
11
|
+
import weakref
|
|
12
|
+
|
|
13
|
+
import torch
|
|
14
|
+
|
|
15
|
+
# The batches by key, which drop a batch once it dies.
|
|
16
|
+
_BATCHES: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
|
|
17
|
+
_KEYS = itertools.count(1)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def register(batch) -> int:
|
|
21
|
+
"""Returns a new key under which the operators find `batch`."""
|
|
22
|
+
key = next(_KEYS)
|
|
23
|
+
_BATCHES[key] = batch
|
|
24
|
+
return key
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _batch(key):
|
|
28
|
+
batch = _BATCHES.get(key)
|
|
29
|
+
if batch is None:
|
|
30
|
+
raise RuntimeError('the batch of this compiled step is gone')
|
|
31
|
+
return batch
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# PyTorch 2.4 brought `custom_op`; before it, `torch.compile` breaks the graph at a step instead.
|
|
35
|
+
AVAILABLE = hasattr(torch.library, 'custom_op')
|
|
36
|
+
|
|
37
|
+
if AVAILABLE:
|
|
38
|
+
# `custom_op` reads the annotations as the schema, so they stay types, not strings.
|
|
39
|
+
@torch.library.custom_op('cuju::step', mutates_args=('outputs',))
|
|
40
|
+
def step(batch: int, actions: torch.Tensor, outputs: list[torch.Tensor]) -> None:
|
|
41
|
+
"""Steps the batch of key `batch` with `actions` and writes its output tensors `outputs`."""
|
|
42
|
+
_batch(batch)._operator_step(actions, outputs)
|
|
43
|
+
|
|
44
|
+
@step.register_fake
|
|
45
|
+
def _step_fake(batch, actions, outputs):
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
@torch.library.custom_op('cuju::reset_done', mutates_args=('outputs',))
|
|
49
|
+
def reset_done(batch: int, outputs: list[torch.Tensor]) -> None:
|
|
50
|
+
"""Resets the ended environments of the batch of key `batch` and writes `outputs`."""
|
|
51
|
+
_batch(batch)._operator_reset_done(outputs)
|
|
52
|
+
|
|
53
|
+
@reset_done.register_fake
|
|
54
|
+
def _reset_done_fake(batch, outputs):
|
|
55
|
+
return None
|
cuju/_batch/pinned.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Page-locked output buffers of a CPU batch, through CUDA's `cudaHostRegister`."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
# The library gives each buffer of such a batch whole pages of its own.
|
|
10
|
+
_PAGE = 4096
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def register(ranges: list[tuple[int, int]]) -> list[int]:
|
|
14
|
+
"""Page-locks each `(pointer, bytes)` range and returns the pointers for `unregister`.
|
|
15
|
+
|
|
16
|
+
Raises:
|
|
17
|
+
RuntimeError: If CUDA refuses a range, after the ranges locked before it are released.
|
|
18
|
+
"""
|
|
19
|
+
runtime = torch.cuda.cudart()
|
|
20
|
+
registered: list[int] = []
|
|
21
|
+
try:
|
|
22
|
+
for pointer, size in ranges:
|
|
23
|
+
status = runtime.cudaHostRegister(pointer, (size + _PAGE - 1) // _PAGE * _PAGE, 0)
|
|
24
|
+
if int(status) != 0:
|
|
25
|
+
raise RuntimeError(
|
|
26
|
+
f'cudaHostRegister refused {size} bytes of the batch, with error {int(status)}'
|
|
27
|
+
)
|
|
28
|
+
registered.append(pointer)
|
|
29
|
+
except BaseException:
|
|
30
|
+
unregister(registered)
|
|
31
|
+
raise
|
|
32
|
+
return registered
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def unregister(pointers: list[int]) -> None:
|
|
36
|
+
"""Releases what `register` locked. The batch must outlive the call."""
|
|
37
|
+
runtime = torch.cuda.cudart()
|
|
38
|
+
for pointer in pointers:
|
|
39
|
+
runtime.cudaHostUnregister(pointer)
|