mujax 0.1.0__tar.gz

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 (39) hide show
  1. mujax-0.1.0/LICENSE +202 -0
  2. mujax-0.1.0/MANIFEST.in +2 -0
  3. mujax-0.1.0/PKG-INFO +148 -0
  4. mujax-0.1.0/README.md +111 -0
  5. mujax-0.1.0/mujax/__init__.py +55 -0
  6. mujax-0.1.0/mujax/actor.py +131 -0
  7. mujax-0.1.0/mujax/algorithm.py +53 -0
  8. mujax-0.1.0/mujax/algorithms/__init__.py +21 -0
  9. mujax-0.1.0/mujax/algorithms/gmz.py +116 -0
  10. mujax-0.1.0/mujax/algorithms/muzero.py +331 -0
  11. mujax-0.1.0/mujax/algorithms/smz.py +175 -0
  12. mujax-0.1.0/mujax/checkpoint.py +192 -0
  13. mujax-0.1.0/mujax/cli.py +72 -0
  14. mujax-0.1.0/mujax/config.py +101 -0
  15. mujax-0.1.0/mujax/experiment.py +368 -0
  16. mujax-0.1.0/mujax/learner.py +94 -0
  17. mujax-0.1.0/mujax/loggers.py +153 -0
  18. mujax-0.1.0/mujax/loop.py +129 -0
  19. mujax-0.1.0/mujax/observers.py +80 -0
  20. mujax-0.1.0/mujax/reanalyze.py +87 -0
  21. mujax-0.1.0/mujax/replay.py +218 -0
  22. mujax-0.1.0/mujax/types.py +60 -0
  23. mujax-0.1.0/mujax.egg-info/PKG-INFO +148 -0
  24. mujax-0.1.0/mujax.egg-info/SOURCES.txt +37 -0
  25. mujax-0.1.0/mujax.egg-info/dependency_links.txt +1 -0
  26. mujax-0.1.0/mujax.egg-info/entry_points.txt +2 -0
  27. mujax-0.1.0/mujax.egg-info/requires.txt +18 -0
  28. mujax-0.1.0/mujax.egg-info/top_level.txt +1 -0
  29. mujax-0.1.0/pyproject.toml +63 -0
  30. mujax-0.1.0/setup.cfg +4 -0
  31. mujax-0.1.0/tests/conftest.py +46 -0
  32. mujax-0.1.0/tests/test_checkpoint.py +65 -0
  33. mujax-0.1.0/tests/test_config.py +55 -0
  34. mujax-0.1.0/tests/test_experiment.py +79 -0
  35. mujax-0.1.0/tests/test_loggers.py +59 -0
  36. mujax-0.1.0/tests/test_loop.py +36 -0
  37. mujax-0.1.0/tests/test_networks.py +50 -0
  38. mujax-0.1.0/tests/test_replay.py +186 -0
  39. mujax-0.1.0/tests/test_support.py +13 -0
mujax-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ graft tests
2
+ global-exclude __pycache__ *.py[cod]
mujax-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: mujax
3
+ Version: 0.1.0
4
+ Summary: MuZero for Gymnasium environments, built on JAX and mctx.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/okayapinar/mujax
7
+ Project-URL: Repository, https://github.com/okayapinar/mujax
8
+ Project-URL: Issues, https://github.com/okayapinar/mujax/issues
9
+ Keywords: muzero,reinforcement-learning,jax,mcts,gymnasium
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: jax>=0.4.30
21
+ Requires-Dist: flax>=0.10.0
22
+ Requires-Dist: optax>=0.2.0
23
+ Requires-Dist: orbax-checkpoint>=0.11.0
24
+ Requires-Dist: mctx>=0.0.6
25
+ Requires-Dist: flashbax>=0.1.3
26
+ Requires-Dist: gymnasium>=1.1.0
27
+ Requires-Dist: numpy>=2.0.0
28
+ Requires-Dist: tqdm
29
+ Requires-Dist: rlax>=0.1.9
30
+ Requires-Dist: distrax>=0.1.9
31
+ Requires-Dist: tyro>=1.0.16
32
+ Provides-Extra: cuda12
33
+ Requires-Dist: jax[cuda12]>=0.4.30; extra == "cuda12"
34
+ Provides-Extra: wandb
35
+ Requires-Dist: wandb; extra == "wandb"
36
+ Dynamic: license-file
37
+
38
+ # mujax
39
+
40
+ Gumbel MuZero and Stochastic MuZero for [Gymnasium](https://gymnasium.farama.org/) environments, built on
41
+ JAX, [mctx](https://github.com/google-deepmind/mctx) and [flashbax](https://github.com/instadeepai/flashbax).
42
+
43
+ - **Two algorithms, one pipeline**: `GMZ` (Gumbel MuZero) and `SMZ` (Stochastic MuZero with afterstates and a
44
+ VQ chance codebook) share replay, reanalyze, actor, learner and checkpointing.
45
+ - **Single process**: actors and evaluator run in threads on CPU, the learner runs on GPU when available. The CPU
46
+ search releases the GIL, so `num_actors` actor threads (`--num-actors`) scale env throughput with the core count.
47
+ - **Reanalyze**: a fraction of every batch is re-searched with the latest parameters.
48
+ - **Categorical value/reward** with HL-Gauss targets in symlog space.
49
+ - **Symlog observations**: raw observations enter the networks through `signed_logp1` (DreamerV3), so no per-dimension normalization is needed.
50
+ - **Checkpoints**: best parameters by evaluation score plus full training state for resuming (Orbax), optional W&B upload.
51
+
52
+ The design is inspired by DeepMind's [Acme](https://github.com/google-deepmind/acme): the split into actor, learner,
53
+ replay and environment loop, the observers and the counter follow Acme's structure, reduced to a small single-process
54
+ library.
55
+
56
+ Requirements: 1-D `Box` observations and `Discrete` actions (use `gym.wrappers.FlattenObservation` otherwise).
57
+ Illegal actions can be masked through `info["invalid_actions"]`.
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install mujax # CPU
63
+ pip install "mujax[cuda12]" # NVIDIA GPU
64
+ pip install "mujax[wandb]" # Weights & Biases logging
65
+ ```
66
+
67
+ ## Command line
68
+
69
+ ```bash
70
+ mujax --env CartPole-v1 --num-steps 20000 gmz --num-simulations 16
71
+ mujax --env Acrobot-v1 smz --batch-size 1024
72
+ mujax --help # all options; `mujax gmz --help`, `mujax smz --help` for algorithm options
73
+ ```
74
+
75
+ Checkpoints are written to `checkpoints/<algo>_<timestamp>/`.
76
+
77
+ ## Python API
78
+
79
+ ```python
80
+ import gymnasium as gym
81
+ from mujax import CheckpointingConfig, ExperimentConfig, GMZConfig, load_actor, run_experiment
82
+
83
+
84
+ def make_env(num_envs):
85
+ return gym.make_vec(
86
+ "CartPole-v1", num_envs=num_envs, vectorization_mode="sync", vector_kwargs={"autoreset_mode": gym.vector.AutoresetMode.SAME_STEP}
87
+ )
88
+
89
+
90
+ run_experiment(
91
+ ExperimentConfig(
92
+ config=GMZConfig(batch_size=256).with_num_steps(20_000),
93
+ environment_factory=lambda seed: make_env(16),
94
+ eval_environment_factory=lambda seed: make_env(1),
95
+ max_num_learner_steps=20_000,
96
+ checkpointing=CheckpointingConfig(directory="checkpoints/cartpole"),
97
+ )
98
+ )
99
+
100
+ actor, metadata = load_actor("checkpoints/cartpole")
101
+ ```
102
+
103
+ Environments must use `AutoresetMode.SAME_STEP`. See [`examples/`](https://github.com/okayapinar/mujax/tree/master/examples) for complete training (`cartpole.py`) and evaluation (`evaluate.py`) scripts.
104
+
105
+ ### Logging
106
+
107
+ `create_writer` sends metrics to the terminal and, optionally, Weights & Biases; learner, actor and evaluator metrics are written under `learner/`, `actor/` and `evaluator/` with `learner_steps` as the step:
108
+
109
+ ```python
110
+ writer = create_writer(console=True, wandb_project="mujax")
111
+ ExperimentConfig(..., writer=writer)
112
+ ```
113
+
114
+ Any object with `write(step, scalars)`, `write_config(config)` and `close()` works as a writer (`mujax.Writer`). Without a writer only the progress bar is shown.
115
+
116
+ On the command line metrics are printed to the terminal (`--no-console` turns it off); add `--wandb` (`--wandb-project`) for W&B.
117
+
118
+ ## Layout
119
+
120
+ | Module | Contents |
121
+ | --- | --- |
122
+ | `config.py` | `MuZeroConfig`, shared hyperparameters |
123
+ | `algorithm.py` | `Algorithm`, `SearchPolicy`: the contract between the infrastructure and an algorithm |
124
+ | `algorithms/__init__.py` | `ALGORITHMS` registry, `algorithm_for` |
125
+ | `algorithms/muzero.py` | shared math of the MuZero family: `Support`, network blocks, loss skeleton |
126
+ | `algorithms/smz.py`, `algorithms/gmz.py` | algorithms: config, networks, search, loss |
127
+ | `replay.py`, `reanalyze.py` | flashbax replay and reanalyze iterator |
128
+ | `actor.py`, `learner.py`, `loop.py` | environment interaction, gradient step, environment loop |
129
+ | `observers.py`, `loggers.py`, `checkpoint.py` | metrics, terminal and W&B writers, Orbax checkpoints |
130
+ | `experiment.py` | `ExperimentConfig`, `run_experiment`, `load_actor` |
131
+
132
+ ## Development
133
+
134
+ ```bash
135
+ uv sync
136
+ uv run pytest
137
+ ```
138
+
139
+ ## References
140
+
141
+ - Schrittwieser et al., *Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model* (2020)
142
+ - Antonoglou et al., *Planning in Stochastic Environments with a Learned Model* (2022)
143
+ - Danihelka et al., *Policy Improvement by Planning with Gumbel* (2022)
144
+ - Hoffman et al., *Acme: A Research Framework for Distributed Reinforcement Learning* (2020)
145
+
146
+ ## License
147
+
148
+ Apache-2.0
mujax-0.1.0/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # mujax
2
+
3
+ Gumbel MuZero and Stochastic MuZero for [Gymnasium](https://gymnasium.farama.org/) environments, built on
4
+ JAX, [mctx](https://github.com/google-deepmind/mctx) and [flashbax](https://github.com/instadeepai/flashbax).
5
+
6
+ - **Two algorithms, one pipeline**: `GMZ` (Gumbel MuZero) and `SMZ` (Stochastic MuZero with afterstates and a
7
+ VQ chance codebook) share replay, reanalyze, actor, learner and checkpointing.
8
+ - **Single process**: actors and evaluator run in threads on CPU, the learner runs on GPU when available. The CPU
9
+ search releases the GIL, so `num_actors` actor threads (`--num-actors`) scale env throughput with the core count.
10
+ - **Reanalyze**: a fraction of every batch is re-searched with the latest parameters.
11
+ - **Categorical value/reward** with HL-Gauss targets in symlog space.
12
+ - **Symlog observations**: raw observations enter the networks through `signed_logp1` (DreamerV3), so no per-dimension normalization is needed.
13
+ - **Checkpoints**: best parameters by evaluation score plus full training state for resuming (Orbax), optional W&B upload.
14
+
15
+ The design is inspired by DeepMind's [Acme](https://github.com/google-deepmind/acme): the split into actor, learner,
16
+ replay and environment loop, the observers and the counter follow Acme's structure, reduced to a small single-process
17
+ library.
18
+
19
+ Requirements: 1-D `Box` observations and `Discrete` actions (use `gym.wrappers.FlattenObservation` otherwise).
20
+ Illegal actions can be masked through `info["invalid_actions"]`.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ pip install mujax # CPU
26
+ pip install "mujax[cuda12]" # NVIDIA GPU
27
+ pip install "mujax[wandb]" # Weights & Biases logging
28
+ ```
29
+
30
+ ## Command line
31
+
32
+ ```bash
33
+ mujax --env CartPole-v1 --num-steps 20000 gmz --num-simulations 16
34
+ mujax --env Acrobot-v1 smz --batch-size 1024
35
+ mujax --help # all options; `mujax gmz --help`, `mujax smz --help` for algorithm options
36
+ ```
37
+
38
+ Checkpoints are written to `checkpoints/<algo>_<timestamp>/`.
39
+
40
+ ## Python API
41
+
42
+ ```python
43
+ import gymnasium as gym
44
+ from mujax import CheckpointingConfig, ExperimentConfig, GMZConfig, load_actor, run_experiment
45
+
46
+
47
+ def make_env(num_envs):
48
+ return gym.make_vec(
49
+ "CartPole-v1", num_envs=num_envs, vectorization_mode="sync", vector_kwargs={"autoreset_mode": gym.vector.AutoresetMode.SAME_STEP}
50
+ )
51
+
52
+
53
+ run_experiment(
54
+ ExperimentConfig(
55
+ config=GMZConfig(batch_size=256).with_num_steps(20_000),
56
+ environment_factory=lambda seed: make_env(16),
57
+ eval_environment_factory=lambda seed: make_env(1),
58
+ max_num_learner_steps=20_000,
59
+ checkpointing=CheckpointingConfig(directory="checkpoints/cartpole"),
60
+ )
61
+ )
62
+
63
+ actor, metadata = load_actor("checkpoints/cartpole")
64
+ ```
65
+
66
+ Environments must use `AutoresetMode.SAME_STEP`. See [`examples/`](https://github.com/okayapinar/mujax/tree/master/examples) for complete training (`cartpole.py`) and evaluation (`evaluate.py`) scripts.
67
+
68
+ ### Logging
69
+
70
+ `create_writer` sends metrics to the terminal and, optionally, Weights & Biases; learner, actor and evaluator metrics are written under `learner/`, `actor/` and `evaluator/` with `learner_steps` as the step:
71
+
72
+ ```python
73
+ writer = create_writer(console=True, wandb_project="mujax")
74
+ ExperimentConfig(..., writer=writer)
75
+ ```
76
+
77
+ Any object with `write(step, scalars)`, `write_config(config)` and `close()` works as a writer (`mujax.Writer`). Without a writer only the progress bar is shown.
78
+
79
+ On the command line metrics are printed to the terminal (`--no-console` turns it off); add `--wandb` (`--wandb-project`) for W&B.
80
+
81
+ ## Layout
82
+
83
+ | Module | Contents |
84
+ | --- | --- |
85
+ | `config.py` | `MuZeroConfig`, shared hyperparameters |
86
+ | `algorithm.py` | `Algorithm`, `SearchPolicy`: the contract between the infrastructure and an algorithm |
87
+ | `algorithms/__init__.py` | `ALGORITHMS` registry, `algorithm_for` |
88
+ | `algorithms/muzero.py` | shared math of the MuZero family: `Support`, network blocks, loss skeleton |
89
+ | `algorithms/smz.py`, `algorithms/gmz.py` | algorithms: config, networks, search, loss |
90
+ | `replay.py`, `reanalyze.py` | flashbax replay and reanalyze iterator |
91
+ | `actor.py`, `learner.py`, `loop.py` | environment interaction, gradient step, environment loop |
92
+ | `observers.py`, `loggers.py`, `checkpoint.py` | metrics, terminal and W&B writers, Orbax checkpoints |
93
+ | `experiment.py` | `ExperimentConfig`, `run_experiment`, `load_actor` |
94
+
95
+ ## Development
96
+
97
+ ```bash
98
+ uv sync
99
+ uv run pytest
100
+ ```
101
+
102
+ ## References
103
+
104
+ - Schrittwieser et al., *Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model* (2020)
105
+ - Antonoglou et al., *Planning in Stochastic Environments with a Learned Model* (2022)
106
+ - Danihelka et al., *Policy Improvement by Planning with Gumbel* (2022)
107
+ - Hoffman et al., *Acme: A Research Framework for Distributed Reinforcement Learning* (2020)
108
+
109
+ ## License
110
+
111
+ Apache-2.0
@@ -0,0 +1,55 @@
1
+ """Stochastic MuZero and Gumbel MuZero, built on JAX, mctx and Gymnasium.
2
+
3
+ Module map:
4
+ config.py MuZeroConfig
5
+ algorithm.py Algorithm, SearchPolicy: the contract between the infrastructure and an algorithm
6
+ algorithms/ ALGORITHMS registry and the algorithms
7
+ muzero.py shared math of the MuZero family: Support, network blocks, loss skeleton
8
+ smz.py / gmz.py algorithms (config, networks, search, loss)
9
+ replay.py / reanalyze.py flashbax replay and reanalyze iterator
10
+ actor.py / learner.py / loop.py environment interaction, gradient step, env loop
11
+ observers.py / loggers.py / checkpoint.py metrics, terminal/W&B writers, orbax checkpoint
12
+ experiment.py ExperimentConfig, run_experiment, load_actor
13
+ """
14
+
15
+ from mujax.actor import Actor
16
+ from mujax.algorithm import Algorithm
17
+ from mujax.algorithms import ALGORITHMS, GMZ, SMZ, GMZConfig, SMZConfig, algorithm_for
18
+ from mujax.checkpoint import CheckpointingConfig
19
+ from mujax.config import MuZeroConfig
20
+ from mujax.experiment import EvaluationConfig, ExperimentConfig, load_actor, run_experiment
21
+ from mujax.learner import Learner
22
+ from mujax.loggers import ConsoleWriter, Logger, WandbWriter, Writer, create_writer
23
+ from mujax.loop import EnvironmentLoop
24
+ from mujax.observers import EnvLoopObserver, InfoKeysObserver
25
+ from mujax.types import EnvironmentSpec, make_environment_spec
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ __all__ = [
30
+ "ALGORITHMS",
31
+ "GMZ",
32
+ "SMZ",
33
+ "Actor",
34
+ "Algorithm",
35
+ "CheckpointingConfig",
36
+ "ConsoleWriter",
37
+ "EnvLoopObserver",
38
+ "EnvironmentLoop",
39
+ "EnvironmentSpec",
40
+ "EvaluationConfig",
41
+ "ExperimentConfig",
42
+ "GMZConfig",
43
+ "InfoKeysObserver",
44
+ "Learner",
45
+ "Logger",
46
+ "MuZeroConfig",
47
+ "SMZConfig",
48
+ "WandbWriter",
49
+ "Writer",
50
+ "algorithm_for",
51
+ "create_writer",
52
+ "load_actor",
53
+ "make_environment_spec",
54
+ "run_experiment",
55
+ ]
@@ -0,0 +1,131 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ import jax
7
+ import numpy as np
8
+
9
+ from mujax.algorithm import SearchPolicy
10
+ from mujax.replay import Adder
11
+ from mujax.types import SearchOutput, TimeStep, Transition
12
+
13
+
14
+ def invalid_actions_from_info(info: dict | None, num_envs: int, num_actions: int) -> np.ndarray:
15
+ """If `info["invalid_actions"]` (0/1 mask, 1 = invalid) is absent, all actions are treated as valid."""
16
+ raw = info.get("invalid_actions") if info else None
17
+ if raw is None:
18
+ return np.zeros((num_envs, num_actions), dtype=np.float32)
19
+ return np.asarray(raw, dtype=np.float32).reshape(num_envs, num_actions)
20
+
21
+
22
+ class Actor:
23
+ """The env-facing side: jitted search policy + learner params + writing to replay.
24
+
25
+ Observations are (num_envs, obs_dim), actions are (num_envs,).
26
+
27
+ Args:
28
+ get_params: () -> (params, learner_steps); usually `Learner.get_params`.
29
+ replay: if given (`Buffer.adder(i)`), every step is written there (training actor).
30
+ value_fn: (params, obs) -> search-free value (N,); for episodes cut by the time limit,
31
+ to bootstrap with V(final_obs). If None, a truncated episode is treated as terminated.
32
+ update_period: how many `select_action` calls between params fetches.
33
+ per_episode_update: if True, params are fetched only at episode start (evaluator: the score
34
+ matches the params that played that episode).
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ policy: SearchPolicy,
40
+ random_key: jax.Array,
41
+ get_params: Callable[[], tuple[Any, int]],
42
+ *,
43
+ num_actions: int,
44
+ replay: Adder | None = None,
45
+ value_fn: Callable[[Any, Any], Any] | None = None,
46
+ device: jax.Device | None = None,
47
+ update_period: int = 1,
48
+ per_episode_update: bool = False,
49
+ ) -> None:
50
+ self._search = jax.jit(policy)
51
+ self._key = random_key
52
+ self._get_params = get_params
53
+ self._num_actions = num_actions
54
+ self._replay = replay
55
+ self._value = jax.jit(value_fn) if value_fn is not None else None
56
+ self._device = device
57
+ self._update_period = max(1, update_period)
58
+ self._per_episode_update = per_episode_update
59
+ self._num_calls = 0
60
+ self._episode_start = True
61
+ self._last_search: SearchOutput | None = None
62
+ self._invalid_actions: np.ndarray | None = None
63
+ self._pull_params()
64
+
65
+ def _pull_params(self) -> None:
66
+ params, learner_steps = self._get_params()
67
+ self._params = (jax.device_put(params, self._device), learner_steps) # single assignment
68
+
69
+ def get_params(self) -> tuple[Any, int]:
70
+ """The (params, learner_steps) currently playing."""
71
+ return self._params
72
+
73
+ def observe_first(self, observation: np.ndarray, info: dict) -> None:
74
+ self._invalid_actions = invalid_actions_from_info(info, len(observation), self._num_actions)
75
+ self._episode_start = True
76
+
77
+ def select_action(self, observation: np.ndarray) -> np.ndarray:
78
+ self._num_calls += 1
79
+ if (self._per_episode_update and self._episode_start) or (not self._per_episode_update and self._num_calls % self._update_period == 0):
80
+ self._pull_params()
81
+ self._episode_start = False
82
+
83
+ params, learner_steps = self._params
84
+ self._key, search_key = jax.random.split(self._key)
85
+ search = self._search(params, np.asarray(observation), search_key, self._invalid_actions, learner_steps)
86
+ self._last_search = SearchOutput(
87
+ action=np.asarray(search.action, dtype=np.int32),
88
+ policy_probs=np.asarray(search.policy_probs, dtype=np.float32),
89
+ value=np.asarray(search.value, dtype=np.float32),
90
+ )
91
+ return self._last_search.action
92
+
93
+ def _final_values(self, step: TimeStep, truncated: np.ndarray) -> np.ndarray:
94
+ """V(final_obs) for truncated envs; under SAME_STEP the final observation is in `info["final_obs"]`."""
95
+ values = np.zeros(len(truncated), dtype=np.float32)
96
+ if not truncated.any():
97
+ return values
98
+ # To call the jit with a single shape, the whole batch is filled; non-truncated rows are discarded.
99
+ obs = np.zeros_like(np.asarray(step.observation), dtype=np.float32)
100
+ for index in np.flatnonzero(truncated):
101
+ obs[index] = step.info["final_obs"][index]
102
+ values[truncated] = np.asarray(self._value(self._params[0], obs))[truncated]
103
+ return values
104
+
105
+ def last_search(self) -> SearchOutput | None:
106
+ """Search output of the last `select_action`; EnvironmentLoop puts it into the TimeStep."""
107
+ return self._last_search
108
+
109
+ def observe(self, step: TimeStep) -> None:
110
+ terminated = np.asarray(step.terminated, dtype=bool)
111
+ truncated = np.asarray(step.truncated, dtype=bool) & ~terminated
112
+ done = terminated | truncated
113
+ if self._replay is not None:
114
+ if self._value is None: # V(final_obs) cannot be computed: a truncated episode is treated as terminated
115
+ terminated, truncated = done, np.zeros_like(truncated)
116
+ self._replay.add(
117
+ Transition(
118
+ observation=np.asarray(step.observation, dtype=np.float32),
119
+ action=self._last_search.action,
120
+ reward=np.asarray(step.reward, dtype=np.float32),
121
+ discount=np.where(terminated, 0.0, 1.0).astype(np.float32),
122
+ policy_probs=self._last_search.policy_probs,
123
+ value=self._last_search.value,
124
+ invalid_actions=self._invalid_actions,
125
+ truncated=truncated.astype(np.float32),
126
+ bootstrap_value=self._final_values(step, truncated),
127
+ )
128
+ )
129
+ self._invalid_actions = invalid_actions_from_info(step.info, len(done), self._num_actions)
130
+ if done.any():
131
+ self._episode_start = True