disco-torch 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.
@@ -0,0 +1,191 @@
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 the 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 the 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 any 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
+ Copyright 2025 asystemoffields
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,250 @@
1
+ Metadata-Version: 2.4
2
+ Name: disco-torch
3
+ Version: 0.1.0
4
+ Summary: PyTorch port of DeepMind's Disco103 meta-learned RL update rule
5
+ Author: asystemoffields
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/asystemoffields/disco-torch
8
+ Project-URL: Repository, https://github.com/asystemoffields/disco-torch
9
+ Project-URL: Issues, https://github.com/asystemoffields/disco-torch/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
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: torch>=2.0
21
+ Requires-Dist: numpy>=1.24
22
+ Provides-Extra: hub
23
+ Requires-Dist: huggingface-hub>=0.20; extra == "hub"
24
+ Provides-Extra: examples
25
+ Requires-Dist: gymnasium>=1.0; extra == "examples"
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest; extra == "dev"
28
+ Requires-Dist: gymnasium>=1.0; extra == "dev"
29
+ Requires-Dist: huggingface-hub>=0.20; extra == "dev"
30
+ Provides-Extra: jax
31
+ Requires-Dist: jax; extra == "jax"
32
+ Requires-Dist: dm-haiku; extra == "jax"
33
+ Requires-Dist: rlax; extra == "jax"
34
+ Requires-Dist: distrax; extra == "jax"
35
+ Dynamic: license-file
36
+
37
+ # disco-torch
38
+
39
+ A PyTorch port of DeepMind's **Disco103** — the meta-learned reinforcement learning update rule from [*Discovering State-of-the-art Reinforcement Learning Algorithms*](https://doi.org/10.1038/s41586-025-09761-x) (Nature, 2025).
40
+
41
+ ## What is DiscoRL?
42
+
43
+ Instead of hand-crafted loss functions like PPO or GRPO, DiscoRL uses a small LSTM neural network (the "meta-network") that **generates loss targets** for RL agents. Given a rollout of agent experience — policy logits, rewards, advantages, auxiliary predictions — the meta-network outputs target distributions. The agent then minimizes KL divergence between its outputs and these learned targets.
44
+
45
+ The Disco103 checkpoint (754,778 parameters) was meta-trained by DeepMind across thousands of Atari-like environments. It generalizes as a drop-in update rule for new tasks — no reward shaping, no hyperparameter-specific loss design.
46
+
47
+ ## Why a PyTorch port?
48
+
49
+ The [original implementation](https://github.com/google-deepmind/disco_rl) uses JAX + Haiku. This port enables using Disco103 in PyTorch training pipelines without any JAX dependency at inference time.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install disco-torch
55
+ ```
56
+
57
+ With optional extras:
58
+
59
+ ```bash
60
+ pip install disco-torch[hub] # HuggingFace Hub weight downloads
61
+ pip install disco-torch[examples] # gymnasium for running examples
62
+ pip install disco-torch[dev] # pytest + all extras for development
63
+ ```
64
+
65
+ ### Weights
66
+
67
+ Option 1 — Download from HuggingFace Hub (requires `pip install disco-torch[hub]`):
68
+
69
+ ```python
70
+ from disco_torch import load_disco103_weights
71
+
72
+ rule = DiscoUpdateRule()
73
+ load_disco103_weights(rule) # auto-downloads from HuggingFace Hub
74
+ ```
75
+
76
+ Option 2 — Manual download from the [disco_rl repo](https://github.com/google-deepmind/disco_rl):
77
+
78
+ ```bash
79
+ cp path/to/disco_103.npz weights/
80
+ ```
81
+
82
+ ```python
83
+ load_disco103_weights(rule, "weights/disco_103.npz")
84
+ ```
85
+
86
+ ## Quick start
87
+
88
+ ```python
89
+ import torch
90
+ from disco_torch import DiscoUpdateRule, UpdateRuleInputs, load_disco103_weights
91
+
92
+ # Load the meta-network with pretrained weights
93
+ rule = DiscoUpdateRule()
94
+ load_disco103_weights(rule, "weights/disco_103.npz")
95
+
96
+ # Initialize meta-RNN state (persists across training steps)
97
+ state = rule.meta_net.initial_meta_rnn_state()
98
+
99
+ # Run the meta-network on a rollout
100
+ with torch.no_grad():
101
+ meta_out, new_state = rule.meta_net(inputs, state)
102
+ # meta_out["pi"] — policy loss targets [T, B, A]
103
+ # meta_out["y"] — value loss targets [T, B, 600]
104
+ # meta_out["z"] — auxiliary loss targets [T, B, 600]
105
+ ```
106
+
107
+ ### Full training loop
108
+
109
+ ```python
110
+ # At each learner step:
111
+ meta_out, new_meta_state = rule.unroll_meta_net(
112
+ rollout, agent_params, meta_state, unroll_fn, hyper_params
113
+ )
114
+
115
+ # Compute agent loss (KL divergence against meta-network targets)
116
+ loss, logs = rule.agent_loss(rollout, meta_out, hyper_params)
117
+
118
+ # Value function loss (no meta-gradient)
119
+ value_loss, value_logs = rule.agent_loss_no_meta(rollout, meta_out, hyper_params)
120
+ ```
121
+
122
+ ## Architecture
123
+
124
+ ```
125
+ Outer (per-trajectory):
126
+ y_net MLP [600 -> 16 -> 1] Value prediction embedding
127
+ z_net MLP [600 -> 16 -> 1] Auxiliary prediction embedding
128
+ policy_net Conv1dNet [9 -> 16 -> 2] Action-conditional embedding
129
+ trajectory_rnn LSTM(27, 256) Reverse-unrolled over trajectory
130
+ state_gate Linear(128 -> 256) Multiplicative gate from meta-RNN
131
+ y_head / z_head Linear(256 -> 600) Loss targets for y and z
132
+ pi_conv + head Conv1dNet [258 -> 16] -> 1 Policy loss target (per action)
133
+
134
+ Meta-RNN (per-lifetime):
135
+ Separate y/z/policy nets, input MLP(29 -> 16), LSTMCell(16, 128)
136
+ ```
137
+
138
+ The outer network processes each trajectory with a reverse-unrolled LSTM. The meta-RNN operates at a slower timescale — it sees batch-time averages and modulates the outer network via a multiplicative gate. This two-level architecture lets the update rule adapt its behavior over an agent's lifetime.
139
+
140
+ ## End-to-end example: Tiny Transformer
141
+
142
+ The flagship example trains a **1-layer causal transformer** (~141K params) to generate strictly increasing digit sequences, using Disco103 as the RL update rule. No supervised data — the agent learns purely from a per-token reward signal.
143
+
144
+ **[Open in Google Colab](examples/tinylm_disco_colab.ipynb)** (runs on free T4 GPU)
145
+
146
+ Using curriculum learning (sequence lengths 4→6→8), the agent achieves **86% strictly increasing** on 8-token sequences, discovering sequences like `[0, 1, 5, 6, 5, 7, 8, 9]`. See [`experiments.md`](experiments.md) for the full research log.
147
+
148
+ ```bash
149
+ # Standalone script (local GPU or CPU)
150
+ python examples/tinylm_disco.py --weights weights/disco_103.npz
151
+ ```
152
+
153
+ A simpler CartPole example is also provided for API reference:
154
+
155
+ ```bash
156
+ python examples/cartpole_disco.py --weights weights/disco_103.npz
157
+ ```
158
+
159
+ > **Note:** Disco103 was meta-trained on 103 complex environments (Atari, ProcGen, DMLab-30). Both CartPole and token generation are outside this distribution. See [`experiments.md`](experiments.md) for analysis of how this affects transfer.
160
+
161
+ ## Package structure
162
+
163
+ ```
164
+ disco_torch/
165
+ __init__.py Public API
166
+ types.py Dataclasses: UpdateRuleInputs, MetaNetInputOption, ValueOuts, etc.
167
+ transforms.py Input transforms and construct_input()
168
+ meta_net.py DiscoMetaNet — the full LSTM meta-network
169
+ update_rule.py DiscoUpdateRule — meta-net + value computation + loss
170
+ value_utils.py V-trace, TD-error, advantage estimation, Q-values
171
+ utils.py batch_lookup, signed_logp1, 2-hot encoding, EMA
172
+ load_weights.py Maps JAX/Haiku NPZ keys -> PyTorch modules
173
+
174
+ examples/
175
+ tinylm_disco.py Train a tiny transformer with Disco103 (standalone)
176
+ tinylm_disco_colab.ipynb Google Colab notebook (recommended)
177
+ cartpole_disco.py CartPole API reference example
178
+
179
+ scripts/
180
+ inspect_disco103.py Print NPZ weight names and shapes
181
+ validate_against_jax.py Numerical comparison: PyTorch vs JAX reference
182
+
183
+ tests/
184
+ test_utils.py Unit tests for utility functions
185
+ test_building_blocks.py Unit tests for network building blocks
186
+ test_meta_net.py Snapshot tests for meta-network forward pass
187
+ ```
188
+
189
+ ## Numerical validation
190
+
191
+ All outputs match the JAX reference implementation within float32 precision:
192
+
193
+ | Output | Max diff | Status |
194
+ |--------|----------|--------|
195
+ | pi (policy targets) | < 1.3e-06 | PASS |
196
+ | y (value targets) | < 1.3e-06 | PASS |
197
+ | z (auxiliary targets) | < 1.3e-06 | PASS |
198
+ | meta_input_emb | < 1.3e-06 | PASS |
199
+ | meta_rnn_h | < 1.3e-06 | PASS |
200
+
201
+ To run the test suite (no JAX required):
202
+
203
+ ```bash
204
+ pip install disco-torch[dev]
205
+ pytest
206
+ ```
207
+
208
+ To run JAX cross-validation (requires JAX + disco_rl):
209
+
210
+ ```bash
211
+ pip install disco_rl jax dm-haiku rlax distrax
212
+ python scripts/validate_against_jax.py
213
+ ```
214
+
215
+ ## Key implementation details
216
+
217
+ - **HaikuLSTMCell**: Haiku uses gate order `[i, g, f, o]` with a +1 forget gate bias, vs PyTorch's `[i, f, g, o]`. This is handled by a custom LSTM cell.
218
+ - **Weight mapping**: The 42 JAX/Haiku parameters have nested path names (e.g., `lstm/~/meta_lstm/~unroll/mlp_2/~/linear_0/w`). `load_weights.py` maps every one to the correct PyTorch module.
219
+ - **Conv1dBlock**: Each block concatenates per-action features with their mean across actions before the convolution — matching the JAX implementation's broadcast pattern.
220
+ - **Value utilities**: V-trace, Retrace-style Q-value estimation, signed hyperbolic transforms, and 2-hot categorical encoding are all ported.
221
+
222
+ ## Requirements
223
+
224
+ - Python >= 3.11
225
+ - PyTorch >= 2.0
226
+ - NumPy >= 1.24
227
+
228
+ ## License
229
+
230
+ Apache 2.0 — same as the original disco_rl.
231
+
232
+ ## Citation
233
+
234
+ If you use this port, please cite the original paper:
235
+
236
+ ```bibtex
237
+ @article{oh2025disco,
238
+ title={Discovering State-of-the-art Reinforcement Learning Algorithms},
239
+ author={Oh, Junhyuk and Farquhar, Greg and Kemaev, Iurii and Calian, Dan A. and Hessel, Matteo and Zintgraf, Luisa and Singh, Satinder and van Hasselt, Hado and Silver, David},
240
+ journal={Nature},
241
+ volume={648},
242
+ pages={312--319},
243
+ year={2025},
244
+ doi={10.1038/s41586-025-09761-x}
245
+ }
246
+ ```
247
+
248
+ ## Acknowledgments
249
+
250
+ This is a community port of [google-deepmind/disco_rl](https://github.com/google-deepmind/disco_rl). All credit for the algorithm, architecture, and pretrained weights goes to the original authors.
@@ -0,0 +1,214 @@
1
+ # disco-torch
2
+
3
+ A PyTorch port of DeepMind's **Disco103** — the meta-learned reinforcement learning update rule from [*Discovering State-of-the-art Reinforcement Learning Algorithms*](https://doi.org/10.1038/s41586-025-09761-x) (Nature, 2025).
4
+
5
+ ## What is DiscoRL?
6
+
7
+ Instead of hand-crafted loss functions like PPO or GRPO, DiscoRL uses a small LSTM neural network (the "meta-network") that **generates loss targets** for RL agents. Given a rollout of agent experience — policy logits, rewards, advantages, auxiliary predictions — the meta-network outputs target distributions. The agent then minimizes KL divergence between its outputs and these learned targets.
8
+
9
+ The Disco103 checkpoint (754,778 parameters) was meta-trained by DeepMind across thousands of Atari-like environments. It generalizes as a drop-in update rule for new tasks — no reward shaping, no hyperparameter-specific loss design.
10
+
11
+ ## Why a PyTorch port?
12
+
13
+ The [original implementation](https://github.com/google-deepmind/disco_rl) uses JAX + Haiku. This port enables using Disco103 in PyTorch training pipelines without any JAX dependency at inference time.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install disco-torch
19
+ ```
20
+
21
+ With optional extras:
22
+
23
+ ```bash
24
+ pip install disco-torch[hub] # HuggingFace Hub weight downloads
25
+ pip install disco-torch[examples] # gymnasium for running examples
26
+ pip install disco-torch[dev] # pytest + all extras for development
27
+ ```
28
+
29
+ ### Weights
30
+
31
+ Option 1 — Download from HuggingFace Hub (requires `pip install disco-torch[hub]`):
32
+
33
+ ```python
34
+ from disco_torch import load_disco103_weights
35
+
36
+ rule = DiscoUpdateRule()
37
+ load_disco103_weights(rule) # auto-downloads from HuggingFace Hub
38
+ ```
39
+
40
+ Option 2 — Manual download from the [disco_rl repo](https://github.com/google-deepmind/disco_rl):
41
+
42
+ ```bash
43
+ cp path/to/disco_103.npz weights/
44
+ ```
45
+
46
+ ```python
47
+ load_disco103_weights(rule, "weights/disco_103.npz")
48
+ ```
49
+
50
+ ## Quick start
51
+
52
+ ```python
53
+ import torch
54
+ from disco_torch import DiscoUpdateRule, UpdateRuleInputs, load_disco103_weights
55
+
56
+ # Load the meta-network with pretrained weights
57
+ rule = DiscoUpdateRule()
58
+ load_disco103_weights(rule, "weights/disco_103.npz")
59
+
60
+ # Initialize meta-RNN state (persists across training steps)
61
+ state = rule.meta_net.initial_meta_rnn_state()
62
+
63
+ # Run the meta-network on a rollout
64
+ with torch.no_grad():
65
+ meta_out, new_state = rule.meta_net(inputs, state)
66
+ # meta_out["pi"] — policy loss targets [T, B, A]
67
+ # meta_out["y"] — value loss targets [T, B, 600]
68
+ # meta_out["z"] — auxiliary loss targets [T, B, 600]
69
+ ```
70
+
71
+ ### Full training loop
72
+
73
+ ```python
74
+ # At each learner step:
75
+ meta_out, new_meta_state = rule.unroll_meta_net(
76
+ rollout, agent_params, meta_state, unroll_fn, hyper_params
77
+ )
78
+
79
+ # Compute agent loss (KL divergence against meta-network targets)
80
+ loss, logs = rule.agent_loss(rollout, meta_out, hyper_params)
81
+
82
+ # Value function loss (no meta-gradient)
83
+ value_loss, value_logs = rule.agent_loss_no_meta(rollout, meta_out, hyper_params)
84
+ ```
85
+
86
+ ## Architecture
87
+
88
+ ```
89
+ Outer (per-trajectory):
90
+ y_net MLP [600 -> 16 -> 1] Value prediction embedding
91
+ z_net MLP [600 -> 16 -> 1] Auxiliary prediction embedding
92
+ policy_net Conv1dNet [9 -> 16 -> 2] Action-conditional embedding
93
+ trajectory_rnn LSTM(27, 256) Reverse-unrolled over trajectory
94
+ state_gate Linear(128 -> 256) Multiplicative gate from meta-RNN
95
+ y_head / z_head Linear(256 -> 600) Loss targets for y and z
96
+ pi_conv + head Conv1dNet [258 -> 16] -> 1 Policy loss target (per action)
97
+
98
+ Meta-RNN (per-lifetime):
99
+ Separate y/z/policy nets, input MLP(29 -> 16), LSTMCell(16, 128)
100
+ ```
101
+
102
+ The outer network processes each trajectory with a reverse-unrolled LSTM. The meta-RNN operates at a slower timescale — it sees batch-time averages and modulates the outer network via a multiplicative gate. This two-level architecture lets the update rule adapt its behavior over an agent's lifetime.
103
+
104
+ ## End-to-end example: Tiny Transformer
105
+
106
+ The flagship example trains a **1-layer causal transformer** (~141K params) to generate strictly increasing digit sequences, using Disco103 as the RL update rule. No supervised data — the agent learns purely from a per-token reward signal.
107
+
108
+ **[Open in Google Colab](examples/tinylm_disco_colab.ipynb)** (runs on free T4 GPU)
109
+
110
+ Using curriculum learning (sequence lengths 4→6→8), the agent achieves **86% strictly increasing** on 8-token sequences, discovering sequences like `[0, 1, 5, 6, 5, 7, 8, 9]`. See [`experiments.md`](experiments.md) for the full research log.
111
+
112
+ ```bash
113
+ # Standalone script (local GPU or CPU)
114
+ python examples/tinylm_disco.py --weights weights/disco_103.npz
115
+ ```
116
+
117
+ A simpler CartPole example is also provided for API reference:
118
+
119
+ ```bash
120
+ python examples/cartpole_disco.py --weights weights/disco_103.npz
121
+ ```
122
+
123
+ > **Note:** Disco103 was meta-trained on 103 complex environments (Atari, ProcGen, DMLab-30). Both CartPole and token generation are outside this distribution. See [`experiments.md`](experiments.md) for analysis of how this affects transfer.
124
+
125
+ ## Package structure
126
+
127
+ ```
128
+ disco_torch/
129
+ __init__.py Public API
130
+ types.py Dataclasses: UpdateRuleInputs, MetaNetInputOption, ValueOuts, etc.
131
+ transforms.py Input transforms and construct_input()
132
+ meta_net.py DiscoMetaNet — the full LSTM meta-network
133
+ update_rule.py DiscoUpdateRule — meta-net + value computation + loss
134
+ value_utils.py V-trace, TD-error, advantage estimation, Q-values
135
+ utils.py batch_lookup, signed_logp1, 2-hot encoding, EMA
136
+ load_weights.py Maps JAX/Haiku NPZ keys -> PyTorch modules
137
+
138
+ examples/
139
+ tinylm_disco.py Train a tiny transformer with Disco103 (standalone)
140
+ tinylm_disco_colab.ipynb Google Colab notebook (recommended)
141
+ cartpole_disco.py CartPole API reference example
142
+
143
+ scripts/
144
+ inspect_disco103.py Print NPZ weight names and shapes
145
+ validate_against_jax.py Numerical comparison: PyTorch vs JAX reference
146
+
147
+ tests/
148
+ test_utils.py Unit tests for utility functions
149
+ test_building_blocks.py Unit tests for network building blocks
150
+ test_meta_net.py Snapshot tests for meta-network forward pass
151
+ ```
152
+
153
+ ## Numerical validation
154
+
155
+ All outputs match the JAX reference implementation within float32 precision:
156
+
157
+ | Output | Max diff | Status |
158
+ |--------|----------|--------|
159
+ | pi (policy targets) | < 1.3e-06 | PASS |
160
+ | y (value targets) | < 1.3e-06 | PASS |
161
+ | z (auxiliary targets) | < 1.3e-06 | PASS |
162
+ | meta_input_emb | < 1.3e-06 | PASS |
163
+ | meta_rnn_h | < 1.3e-06 | PASS |
164
+
165
+ To run the test suite (no JAX required):
166
+
167
+ ```bash
168
+ pip install disco-torch[dev]
169
+ pytest
170
+ ```
171
+
172
+ To run JAX cross-validation (requires JAX + disco_rl):
173
+
174
+ ```bash
175
+ pip install disco_rl jax dm-haiku rlax distrax
176
+ python scripts/validate_against_jax.py
177
+ ```
178
+
179
+ ## Key implementation details
180
+
181
+ - **HaikuLSTMCell**: Haiku uses gate order `[i, g, f, o]` with a +1 forget gate bias, vs PyTorch's `[i, f, g, o]`. This is handled by a custom LSTM cell.
182
+ - **Weight mapping**: The 42 JAX/Haiku parameters have nested path names (e.g., `lstm/~/meta_lstm/~unroll/mlp_2/~/linear_0/w`). `load_weights.py` maps every one to the correct PyTorch module.
183
+ - **Conv1dBlock**: Each block concatenates per-action features with their mean across actions before the convolution — matching the JAX implementation's broadcast pattern.
184
+ - **Value utilities**: V-trace, Retrace-style Q-value estimation, signed hyperbolic transforms, and 2-hot categorical encoding are all ported.
185
+
186
+ ## Requirements
187
+
188
+ - Python >= 3.11
189
+ - PyTorch >= 2.0
190
+ - NumPy >= 1.24
191
+
192
+ ## License
193
+
194
+ Apache 2.0 — same as the original disco_rl.
195
+
196
+ ## Citation
197
+
198
+ If you use this port, please cite the original paper:
199
+
200
+ ```bibtex
201
+ @article{oh2025disco,
202
+ title={Discovering State-of-the-art Reinforcement Learning Algorithms},
203
+ author={Oh, Junhyuk and Farquhar, Greg and Kemaev, Iurii and Calian, Dan A. and Hessel, Matteo and Zintgraf, Luisa and Singh, Satinder and van Hasselt, Hado and Silver, David},
204
+ journal={Nature},
205
+ volume={648},
206
+ pages={312--319},
207
+ year={2025},
208
+ doi={10.1038/s41586-025-09761-x}
209
+ }
210
+ ```
211
+
212
+ ## Acknowledgments
213
+
214
+ This is a community port of [google-deepmind/disco_rl](https://github.com/google-deepmind/disco_rl). All credit for the algorithm, architecture, and pretrained weights goes to the original authors.
@@ -0,0 +1,16 @@
1
+ """disco_torch: PyTorch port of DeepMind's Disco103 meta-learned RL update rule."""
2
+
3
+ from disco_torch.types import UpdateRuleInputs, ValueOuts, EmaState, MetaNetInputOption, TransformConfig
4
+ from disco_torch.update_rule import DiscoUpdateRule
5
+ from disco_torch.load_weights import load_disco103_weights, download_disco103_weights
6
+
7
+ __all__ = [
8
+ "DiscoUpdateRule",
9
+ "UpdateRuleInputs",
10
+ "ValueOuts",
11
+ "EmaState",
12
+ "MetaNetInputOption",
13
+ "TransformConfig",
14
+ "load_disco103_weights",
15
+ "download_disco103_weights",
16
+ ]