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
cuju/action_log.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Digests of a batch's outputs, and logs of a run's actions that replay it bit for bit.
|
|
4
|
+
|
|
5
|
+
`Digest` hashes outputs as the package's self-check does, and `digest` plays the self-check's
|
|
6
|
+
run of a scenario and returns its SHA-256, the same on every backend and machine. An `ActionLog`
|
|
7
|
+
creates a batch, takes its calls in place of the batch's and logs them with their actions, and
|
|
8
|
+
`replay` plays a saved log again, on either backend, and checks every digest.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ctypes
|
|
14
|
+
import hashlib
|
|
15
|
+
import importlib.metadata
|
|
16
|
+
import json
|
|
17
|
+
import zipfile
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import torch
|
|
21
|
+
|
|
22
|
+
from . import BatchEnvironment
|
|
23
|
+
|
|
24
|
+
__all__ = ['ActionLog', 'Digest', 'digest', 'replay']
|
|
25
|
+
|
|
26
|
+
# The version of the log's format.
|
|
27
|
+
_FORMAT = 1
|
|
28
|
+
# The options that change no output, which a log leaves to the machine that replays it.
|
|
29
|
+
_MACHINE_OPTIONS = (
|
|
30
|
+
'device',
|
|
31
|
+
'library',
|
|
32
|
+
'threads',
|
|
33
|
+
'pin_memory',
|
|
34
|
+
'allocator',
|
|
35
|
+
'pin_threads',
|
|
36
|
+
'numa',
|
|
37
|
+
'debug',
|
|
38
|
+
'check_actions',
|
|
39
|
+
)
|
|
40
|
+
# The machine options that a replay takes, the device being an argument of its own.
|
|
41
|
+
_REPLAY_OPTIONS = _MACHINE_OPTIONS[1:]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Digest:
|
|
45
|
+
"""The SHA-256 of a sequence of outputs.
|
|
46
|
+
|
|
47
|
+
Tensors hash as the bytes of their elements in order, on any device. A dictionary hashes its
|
|
48
|
+
values in the order of its sorted keys, and bytes hash as they are.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self) -> None:
|
|
52
|
+
self._hash = hashlib.sha256()
|
|
53
|
+
|
|
54
|
+
def update(self, value: Any) -> None:
|
|
55
|
+
"""Adds a tensor, a dictionary or sequence of them, or bytes.
|
|
56
|
+
|
|
57
|
+
Raises:
|
|
58
|
+
TypeError: If `value` is none of these.
|
|
59
|
+
"""
|
|
60
|
+
if isinstance(value, torch.Tensor):
|
|
61
|
+
tensor = value.detach().to('cpu').contiguous()
|
|
62
|
+
self._hash.update(
|
|
63
|
+
ctypes.string_at(tensor.data_ptr(), tensor.numel() * tensor.element_size())
|
|
64
|
+
)
|
|
65
|
+
elif isinstance(value, dict):
|
|
66
|
+
for key in sorted(value):
|
|
67
|
+
self.update(value[key])
|
|
68
|
+
elif isinstance(value, (list, tuple)):
|
|
69
|
+
for item in value:
|
|
70
|
+
self.update(item)
|
|
71
|
+
elif isinstance(value, (bytes, bytearray)):
|
|
72
|
+
self._hash.update(value)
|
|
73
|
+
else:
|
|
74
|
+
raise TypeError(f'expected tensors, dictionaries, sequences or bytes, found {value!r}')
|
|
75
|
+
|
|
76
|
+
def copy(self) -> Digest:
|
|
77
|
+
"""Returns a digest of the same outputs, which goes on apart."""
|
|
78
|
+
other = Digest()
|
|
79
|
+
other._hash = self._hash.copy()
|
|
80
|
+
return other
|
|
81
|
+
|
|
82
|
+
def hexdigest(self) -> str:
|
|
83
|
+
"""Returns the SHA-256 so far in hexadecimal."""
|
|
84
|
+
return self._hash.hexdigest()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _states(batch, value):
|
|
88
|
+
"""Adds the state of every environment of a batch without a stack to the digest `value`."""
|
|
89
|
+
if not batch.stacked:
|
|
90
|
+
for index in range(batch.environment_count):
|
|
91
|
+
value.update(batch.get_state(index))
|
|
92
|
+
return value
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _digest_actions(step: int, environment_count: int, agents: int, action_count: int) -> Any:
|
|
96
|
+
"""Returns the actions of a step of `digest`, `[environment_count, agents]` `int32`."""
|
|
97
|
+
values = [
|
|
98
|
+
[(step * 7 + environment * 3 + agent * 5) % action_count for agent in range(agents)]
|
|
99
|
+
for environment in range(environment_count)
|
|
100
|
+
]
|
|
101
|
+
return torch.tensor(values, dtype=torch.int32)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def digest(
|
|
105
|
+
assets: Any,
|
|
106
|
+
device: str = 'cpu',
|
|
107
|
+
steps: int = 100,
|
|
108
|
+
seed: int = 7,
|
|
109
|
+
environment_count: int = 4,
|
|
110
|
+
**options: Any,
|
|
111
|
+
) -> str:
|
|
112
|
+
"""Plays a batch with fixed actions and returns the SHA-256 of its outputs.
|
|
113
|
+
|
|
114
|
+
Agent `a` of environment `e` takes action `(7 * step + 3 * e + 5 * a) % action_count` at each
|
|
115
|
+
step, the same on every machine. The digest covers the observation of the reset, the
|
|
116
|
+
observation, reward and done flags of every step, then the state of every environment unless
|
|
117
|
+
the batch stacks its observations. The package's self-check compares such digests, 100 steps
|
|
118
|
+
of 4 environments with seed 7, with those in its `digests.json`.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
assets: The assets of the batch, as `BatchEnvironment` takes them.
|
|
122
|
+
device: `cpu` or `cuda`, which give the same digest.
|
|
123
|
+
steps: The steps after the reset.
|
|
124
|
+
seed: The seed of the batch.
|
|
125
|
+
environment_count: The number of environments.
|
|
126
|
+
**options: Other keyword arguments of `BatchEnvironment`.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
The SHA-256 in hexadecimal.
|
|
130
|
+
"""
|
|
131
|
+
batch = BatchEnvironment(
|
|
132
|
+
assets, environment_count=environment_count, device=device, seed=seed, **options
|
|
133
|
+
)
|
|
134
|
+
try:
|
|
135
|
+
value = Digest()
|
|
136
|
+
value.update(batch.reset())
|
|
137
|
+
for step in range(steps):
|
|
138
|
+
actions = _digest_actions(step, environment_count, batch.agents, batch.action_count)
|
|
139
|
+
observation, reward, done, _ = batch.step(actions.to(batch._torch_device))
|
|
140
|
+
value.update(observation)
|
|
141
|
+
value.update(reward)
|
|
142
|
+
value.update(done)
|
|
143
|
+
return _states(batch, value).hexdigest()
|
|
144
|
+
finally:
|
|
145
|
+
batch.close()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _plain(value):
|
|
149
|
+
"""Returns an option as a value of JSON, with tensors and tuples as lists."""
|
|
150
|
+
if isinstance(value, torch.Tensor):
|
|
151
|
+
return value.tolist()
|
|
152
|
+
if isinstance(value, (list, tuple)):
|
|
153
|
+
return [_plain(item) for item in value]
|
|
154
|
+
if isinstance(value, dict):
|
|
155
|
+
return {key: _plain(item) for key, item in value.items()}
|
|
156
|
+
return value
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _host_values(values):
|
|
160
|
+
"""Returns per-environment arguments of `reset` as values of JSON, or `None`."""
|
|
161
|
+
return None if values is None else _plain(torch.as_tensor(values))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class ActionLog:
|
|
165
|
+
"""A batch whose calls, actions and outputs are logged for `replay`.
|
|
166
|
+
|
|
167
|
+
Call the log's `reset`, `step`, `reset_done` and `set_state` in place of the batch's, and they
|
|
168
|
+
return what the batch's return. `save` writes the options of the batch, every call with its
|
|
169
|
+
arguments, and the digest of the outputs after each call. The digest after the last call adds
|
|
170
|
+
the state of every environment, as `digest` does.
|
|
171
|
+
|
|
172
|
+
Attributes:
|
|
173
|
+
batch: The `BatchEnvironment` that the log created.
|
|
174
|
+
calls: The calls so far, each a dictionary with its name and arguments.
|
|
175
|
+
|
|
176
|
+
Examples:
|
|
177
|
+
>>> import torch
|
|
178
|
+
>>> import cuju
|
|
179
|
+
>>> log = cuju.ActionLog('5_vs_5_l4_r0', environment_count=8, device='cpu')
|
|
180
|
+
>>> _ = log.reset()
|
|
181
|
+
>>> for _ in range(100):
|
|
182
|
+
... _ = log.step(torch.randint(0, 19, (8, 4), dtype=torch.int32))
|
|
183
|
+
>>> log.save('run.zip')
|
|
184
|
+
>>> cuju.replay('run.zip') == log.hexdigest()
|
|
185
|
+
True
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
def __init__(self, assets: Any, **options: Any) -> None:
|
|
189
|
+
"""Creates the batch.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
assets: The assets of the batch, as `BatchEnvironment` takes them.
|
|
193
|
+
**options: The keyword arguments of `BatchEnvironment`. `device`, `library`,
|
|
194
|
+
`threads`, `pin_memory`, `allocator`, `pin_threads`, `numa`, `debug` and
|
|
195
|
+
`check_actions` change no output, so the log leaves them out and a replay chooses
|
|
196
|
+
its own.
|
|
197
|
+
|
|
198
|
+
Raises:
|
|
199
|
+
TypeError: If an option is no value of JSON, a tensor, or a sequence of them.
|
|
200
|
+
"""
|
|
201
|
+
self._assets = _plain(assets)
|
|
202
|
+
self._options = {
|
|
203
|
+
key: _plain(value) for key, value in options.items() if key not in _MACHINE_OPTIONS
|
|
204
|
+
}
|
|
205
|
+
json.dumps([self._assets, self._options])
|
|
206
|
+
self.batch = BatchEnvironment(assets, **options)
|
|
207
|
+
self.calls: list[dict[str, Any]] = []
|
|
208
|
+
self._actions: list[bytes] = []
|
|
209
|
+
self._states: list[bytes] = []
|
|
210
|
+
self._digest = Digest()
|
|
211
|
+
self._digests: list[bytes] = []
|
|
212
|
+
|
|
213
|
+
def _logged(self, call, *outputs):
|
|
214
|
+
"""Logs a call with the digest of its outputs."""
|
|
215
|
+
for output in outputs:
|
|
216
|
+
self._digest.update(output)
|
|
217
|
+
self.calls.append(call)
|
|
218
|
+
self._digests.append(bytes.fromhex(self._digest.hexdigest()))
|
|
219
|
+
|
|
220
|
+
def reset(self, seeds: Any = None, reverse: Any = None) -> Any:
|
|
221
|
+
"""Calls the batch's `reset` and logs it."""
|
|
222
|
+
observation = self.batch.reset(seeds=seeds, reverse=reverse)
|
|
223
|
+
call = {'call': 'reset', 'seeds': _host_values(seeds), 'reverse': _host_values(reverse)}
|
|
224
|
+
self._logged(call, observation)
|
|
225
|
+
return observation
|
|
226
|
+
|
|
227
|
+
def step(self, actions: Any) -> tuple[Any, Any, Any, dict[str, Any]]:
|
|
228
|
+
"""Calls the batch's `step` and logs it with its actions."""
|
|
229
|
+
result = self.batch.step(actions)
|
|
230
|
+
host = torch.as_tensor(actions).to('cpu', torch.int32).contiguous()
|
|
231
|
+
self._actions.append(ctypes.string_at(host.data_ptr(), host.numel() * host.element_size()))
|
|
232
|
+
self._logged({'call': 'step', 'shape': list(host.shape)}, *result[:3])
|
|
233
|
+
return result
|
|
234
|
+
|
|
235
|
+
def reset_done(self) -> None:
|
|
236
|
+
"""Calls the batch's `reset_done` and logs it."""
|
|
237
|
+
self.batch.reset_done()
|
|
238
|
+
self._logged({'call': 'reset_done'}, self.batch.observation())
|
|
239
|
+
|
|
240
|
+
def set_state(self, index: int, state: bytes) -> None:
|
|
241
|
+
"""Calls the batch's `set_state` and logs it with the state."""
|
|
242
|
+
self.batch.set_state(index, state)
|
|
243
|
+
self._states.append(bytes(state))
|
|
244
|
+
self._logged({'call': 'set_state', 'index': int(index)}, self.batch.observation())
|
|
245
|
+
|
|
246
|
+
def hexdigest(self) -> str:
|
|
247
|
+
"""Returns the SHA-256 of every output so far and of the state of every environment."""
|
|
248
|
+
return _states(self.batch, self._digest.copy()).hexdigest()
|
|
249
|
+
|
|
250
|
+
def save(self, path: str) -> None:
|
|
251
|
+
"""Writes the log to a ZIP file at `path`, which `replay` reads."""
|
|
252
|
+
try:
|
|
253
|
+
version = importlib.metadata.version('cuju-engine')
|
|
254
|
+
except importlib.metadata.PackageNotFoundError:
|
|
255
|
+
version = None
|
|
256
|
+
header = {
|
|
257
|
+
'format': _FORMAT,
|
|
258
|
+
'cuju': version,
|
|
259
|
+
'assets': self._assets,
|
|
260
|
+
'options': self._options,
|
|
261
|
+
'device': self.batch.device,
|
|
262
|
+
'calls': self.calls,
|
|
263
|
+
'digest': self.hexdigest(),
|
|
264
|
+
}
|
|
265
|
+
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as archive:
|
|
266
|
+
archive.writestr('log.json', json.dumps(header, indent=1))
|
|
267
|
+
archive.writestr('actions.bin', b''.join(self._actions))
|
|
268
|
+
archive.writestr('digests.bin', b''.join(self._digests))
|
|
269
|
+
for number, state in enumerate(self._states):
|
|
270
|
+
archive.writestr(f'states/{number}.bin', state)
|
|
271
|
+
|
|
272
|
+
def close(self) -> None:
|
|
273
|
+
"""Closes the batch."""
|
|
274
|
+
self.batch.close()
|
|
275
|
+
|
|
276
|
+
def __enter__(self) -> ActionLog:
|
|
277
|
+
return self
|
|
278
|
+
|
|
279
|
+
def __exit__(self, *exception: Any) -> None:
|
|
280
|
+
self.close()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def replay(path: str, device: str | None = None, **options: Any) -> str:
|
|
284
|
+
"""Plays a saved `ActionLog` again and checks the digest after every call.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
path: The file that `ActionLog.save` wrote.
|
|
288
|
+
device: `cpu` or `cuda`, or `None` for the device of the log, which give the same outputs.
|
|
289
|
+
**options: `library`, `threads`, `pin_memory`, `allocator`, `pin_threads`, `numa`,
|
|
290
|
+
`debug` or `check_actions` for the batch, which change no output. A log that an
|
|
291
|
+
earlier version wrote with any of them replays without them unless given here.
|
|
292
|
+
|
|
293
|
+
Returns:
|
|
294
|
+
The digest of the replay, equal to the log's.
|
|
295
|
+
|
|
296
|
+
Raises:
|
|
297
|
+
ValueError: If the file holds no log of this format, an option changes outputs, or the
|
|
298
|
+
outputs of a call differ from the log's, naming the first such call.
|
|
299
|
+
"""
|
|
300
|
+
unknown = sorted(set(options) - set(_REPLAY_OPTIONS))
|
|
301
|
+
if unknown:
|
|
302
|
+
raise ValueError(
|
|
303
|
+
f'expected only {", ".join(_REPLAY_OPTIONS)}, which change no output, found {unknown}'
|
|
304
|
+
)
|
|
305
|
+
with zipfile.ZipFile(path) as archive:
|
|
306
|
+
header = json.loads(archive.read('log.json'))
|
|
307
|
+
if header.get('format') != _FORMAT:
|
|
308
|
+
raise ValueError(
|
|
309
|
+
f'expected an action log of format {_FORMAT}, found {header.get("format")}'
|
|
310
|
+
)
|
|
311
|
+
actions = archive.read('actions.bin')
|
|
312
|
+
digests = archive.read('digests.bin')
|
|
313
|
+
states = [
|
|
314
|
+
archive.read(f'states/{number}.bin')
|
|
315
|
+
for number in range(sum(call['call'] == 'set_state' for call in header['calls']))
|
|
316
|
+
]
|
|
317
|
+
# An earlier version logged the machine options, which the replaying machine chooses instead.
|
|
318
|
+
batch_options = {
|
|
319
|
+
key: value for key, value in header['options'].items() if key not in _MACHINE_OPTIONS
|
|
320
|
+
}
|
|
321
|
+
for key in ('channel_dimensions',):
|
|
322
|
+
if key in batch_options:
|
|
323
|
+
batch_options[key] = tuple(batch_options[key])
|
|
324
|
+
for key in ('difficulty', 'agent_counts'):
|
|
325
|
+
if batch_options.get(key) is not None:
|
|
326
|
+
batch_options[key] = [tuple(pair) for pair in batch_options[key]]
|
|
327
|
+
batch = BatchEnvironment(
|
|
328
|
+
header['assets'], device=device or header['device'], **batch_options, **options
|
|
329
|
+
)
|
|
330
|
+
try:
|
|
331
|
+
value = Digest()
|
|
332
|
+
offset = 0
|
|
333
|
+
state = 0
|
|
334
|
+
for number, call in enumerate(header['calls']):
|
|
335
|
+
kind = call['call']
|
|
336
|
+
if kind == 'reset':
|
|
337
|
+
value.update(batch.reset(seeds=call['seeds'], reverse=call['reverse']))
|
|
338
|
+
elif kind == 'step':
|
|
339
|
+
count = 1
|
|
340
|
+
for size in call['shape']:
|
|
341
|
+
count *= size
|
|
342
|
+
step_actions = torch.frombuffer(
|
|
343
|
+
bytearray(actions[offset : offset + 4 * count]), dtype=torch.int32
|
|
344
|
+
).reshape(call['shape'])
|
|
345
|
+
offset += 4 * count
|
|
346
|
+
observation, reward, done, _ = batch.step(step_actions.to(batch._torch_device))
|
|
347
|
+
value.update((observation, reward, done))
|
|
348
|
+
elif kind == 'reset_done':
|
|
349
|
+
batch.reset_done()
|
|
350
|
+
value.update(batch.observation())
|
|
351
|
+
elif kind == 'set_state':
|
|
352
|
+
batch.set_state(call['index'], states[state])
|
|
353
|
+
state += 1
|
|
354
|
+
value.update(batch.observation())
|
|
355
|
+
else:
|
|
356
|
+
raise ValueError(f'expected the calls of an action log, found {kind!r}')
|
|
357
|
+
expected = digests[32 * number : 32 * number + 32].hex()
|
|
358
|
+
if value.hexdigest() != expected:
|
|
359
|
+
raise ValueError(
|
|
360
|
+
f'the outputs of call {number} ({kind}) differ from the log: the digest is '
|
|
361
|
+
f'{value.hexdigest()}, the log holds {expected}'
|
|
362
|
+
)
|
|
363
|
+
result = _states(batch, value).hexdigest()
|
|
364
|
+
finally:
|
|
365
|
+
batch.close()
|
|
366
|
+
if result != header['digest']:
|
|
367
|
+
raise ValueError(
|
|
368
|
+
f'the states after the last call differ from the log: the digest is {result}, the log '
|
|
369
|
+
f'holds {header["digest"]}'
|
|
370
|
+
)
|
|
371
|
+
return result
|