weightspaceprogramming 0.1.0.dev1__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.
- weightspaceprogramming-0.1.0.dev1/LICENSE +202 -0
- weightspaceprogramming-0.1.0.dev1/MANIFEST.in +4 -0
- weightspaceprogramming-0.1.0.dev1/PKG-INFO +140 -0
- weightspaceprogramming-0.1.0.dev1/README.md +116 -0
- weightspaceprogramming-0.1.0.dev1/SOURCES.md +10 -0
- weightspaceprogramming-0.1.0.dev1/pyproject.toml +41 -0
- weightspaceprogramming-0.1.0.dev1/setup.cfg +4 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/__init__.py +10 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/__main__.py +3 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/cli.py +52 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/core.py +143 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/inspection.py +55 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/lessons.json +30 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming/lessons.py +20 -0
- weightspaceprogramming-0.1.0.dev1/src/weightspaceprogramming.egg-info/SOURCES.txt +13 -0
- weightspaceprogramming-0.1.0.dev1/tests/test_toolkit.py +148 -0
|
@@ -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,140 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: weightspaceprogramming
|
|
3
|
+
Version: 0.1.0.dev1
|
|
4
|
+
Summary: Learn weight-space programming with runnable NumPy experiments.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://weightspaceprogramming.tech/
|
|
7
|
+
Project-URL: Examples, https://github.com/weightspaceprogramming/examples
|
|
8
|
+
Project-URL: Guide, https://weightspaceprogramming.tech/build/code-and-implementations/
|
|
9
|
+
Project-URL: Source, https://github.com/weightspaceprogramming/weightspaceprogramming
|
|
10
|
+
Project-URL: Issues, https://github.com/weightspaceprogramming/weightspaceprogramming/issues
|
|
11
|
+
Keywords: weight-space-programming,neural-networks,education,lora,numpy
|
|
12
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
13
|
+
Classifier: Intended Audience :: Education
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
License-File: SOURCES.md
|
|
20
|
+
Requires-Dist: numpy<3,>=1.24
|
|
21
|
+
Provides-Extra: plot
|
|
22
|
+
Requires-Dist: matplotlib>=3.8; extra == "plot"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# weightspaceprogramming
|
|
26
|
+
|
|
27
|
+
Learn weight-space programming by changing small networks and seeing what they compute. Run seven NumPy lessons, inspect NPZ weights, generate channel heatmaps, and check that a consistent hidden-unit permutation preserves a network's output.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
python -m pip install --pre weightspaceprogramming
|
|
33
|
+
weightspaceprogramming lesson list
|
|
34
|
+
weightspaceprogramming lesson lora
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Python 3.10+ and NumPy. The lessons run locally on CPU without accounts, API keys or model downloads.
|
|
38
|
+
|
|
39
|
+
## Write a function into weights
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from weightspaceprogramming import binary_inputs, neuron
|
|
43
|
+
|
|
44
|
+
x = binary_inputs(2)
|
|
45
|
+
print(neuron(x, [1, 1], bias=-1.5, activation="step").tolist())
|
|
46
|
+
# [0, 0, 0, 1] — AND
|
|
47
|
+
|
|
48
|
+
print(neuron(x, [1, 1], bias=-0.5, activation="step").tolist())
|
|
49
|
+
# [0, 1, 1, 1] — OR
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The same inputs produce a different function after changing one bias. A step neuron returns 1 when its preactivation is zero or positive.
|
|
53
|
+
|
|
54
|
+
## Lessons
|
|
55
|
+
|
|
56
|
+
- `neuron`: change the slope and offset of a linear neuron.
|
|
57
|
+
- `boolean`: encode AND and OR in threshold-neuron weights.
|
|
58
|
+
- `xor`: construct a two-layer XOR network.
|
|
59
|
+
- `compile`: construct an affine program's weights, then reuse them on new inputs.
|
|
60
|
+
- `generator`: fit a numerical descriptor-to-weights map by least squares and generate a new neuron program.
|
|
61
|
+
- `lora`: apply a rank-one update and compare the original and edited outputs.
|
|
62
|
+
- `norms`: inspect a synthetic input-layer kernel and permute hidden units while preserving its function.
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
weightspaceprogramming lesson xor
|
|
66
|
+
weightspaceprogramming lesson xor --show-code
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The Python API exposes the exact lesson source for notebooks and browser runners:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from weightspaceprogramming import lesson_source
|
|
73
|
+
print(lesson_source("xor"))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Apply a LoRA update
|
|
77
|
+
|
|
78
|
+
The package uses row-vector inputs: `output = input @ W`. For a weight matrix with shape `(inputs, outputs)`, the low-rank factors have shapes `(inputs, rank)` and `(rank, outputs)`.
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import numpy as np
|
|
82
|
+
from weightspaceprogramming import apply_lora
|
|
83
|
+
|
|
84
|
+
w = np.eye(2)
|
|
85
|
+
edited = apply_lora(w, [[1.0], [0.0]], [[0.0, 2.0]])
|
|
86
|
+
x = np.array([[3.0, 4.0]])
|
|
87
|
+
print((x @ w).tolist()) # [[3.0, 4.0]]
|
|
88
|
+
print((x @ edited).tolist()) # [[3.0, 10.0]]
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`apply_lora` returns `W + scale * A @ B` and leaves the supplied arrays unchanged.
|
|
92
|
+
|
|
93
|
+
## Read input-channel weights
|
|
94
|
+
|
|
95
|
+
For an HWC input grid, `channel_norms` computes the L2 norm across the first layer's hidden units at every cell and channel. It returns an array with shape `(channels, height, width)`.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from weightspaceprogramming import channel_norms
|
|
99
|
+
|
|
100
|
+
print(channel_norms([[3, 4], [0, 2]], (1, 2, 1)).tolist())
|
|
101
|
+
# [[[5.0, 2.0]]]
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Inspect your own NPZ checkpoint:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
weightspaceprogramming inspect network.npz \
|
|
108
|
+
--key actor/dense1/kernel --shape 10 10 5 --output norms.json
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
NPZ files load with pickle disabled. The kernel must be a finite real matrix with one row per flattened HWC input and one column per hidden unit.
|
|
112
|
+
|
|
113
|
+
Add plotting when needed:
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
python -m pip install --pre 'weightspaceprogramming[plot]'
|
|
117
|
+
weightspaceprogramming inspect network.npz \
|
|
118
|
+
--key actor/dense1/kernel --shape 10 10 5 --plot heatmaps.svg
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`permute_hidden(weights, biases, permutation, layer=0)` copies the parameters and reorders a hidden layer's incoming columns, biases and outgoing rows together. `mlp` evaluates the original and reordered networks with the same activation functions.
|
|
122
|
+
|
|
123
|
+
## From small networks to research implementations
|
|
124
|
+
|
|
125
|
+
[Program-as-Weights](https://weightspaceprogramming.tech/research/program-as-weights/) introduces a programming paradigm for fuzzy functions, a compiler–interpreter interface and FuzzyBench. PAW specifically trains a compiler to generate LoRA adapters that edit a frozen interpreter's weights from a natural-language function specification. [Run the PAW urgency and routing examples](https://github.com/weightspaceprogramming/examples#2-compile-and-reuse-an-email-urgency-function-with-paw) with the official SDK.
|
|
126
|
+
|
|
127
|
+
[Tracr](https://github.com/weightspaceprogramming/examples#1-compile-a-token-counter-with-tracr) compiles exact RASP programs into transformer weights. The [Sparks weight-reading experiment](https://weightspaceprogramming.tech/build/code-and-implementations/#weight-reading) applies the channel-norm computation to four published game policies and reports their permutation checks. PAW and Tracr keep their own installation instructions and dependencies.
|
|
128
|
+
|
|
129
|
+
Explore the [field guide](https://weightspaceprogramming.tech/) and [code and implementations](https://weightspaceprogramming.tech/build/code-and-implementations/).
|
|
130
|
+
|
|
131
|
+
## Development
|
|
132
|
+
|
|
133
|
+
Get the [source code](https://github.com/weightspaceprogramming/weightspaceprogramming) or [report an issue](https://github.com/weightspaceprogramming/weightspaceprogramming/issues).
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
python -m pip install -e .
|
|
137
|
+
python -m unittest discover -s tests -v
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Implementation provenance ships with the distribution in `SOURCES.md`. Package code is licensed under Apache-2.0.
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# weightspaceprogramming
|
|
2
|
+
|
|
3
|
+
Learn weight-space programming by changing small networks and seeing what they compute. Run seven NumPy lessons, inspect NPZ weights, generate channel heatmaps, and check that a consistent hidden-unit permutation preserves a network's output.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install --pre weightspaceprogramming
|
|
9
|
+
weightspaceprogramming lesson list
|
|
10
|
+
weightspaceprogramming lesson lora
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Python 3.10+ and NumPy. The lessons run locally on CPU without accounts, API keys or model downloads.
|
|
14
|
+
|
|
15
|
+
## Write a function into weights
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from weightspaceprogramming import binary_inputs, neuron
|
|
19
|
+
|
|
20
|
+
x = binary_inputs(2)
|
|
21
|
+
print(neuron(x, [1, 1], bias=-1.5, activation="step").tolist())
|
|
22
|
+
# [0, 0, 0, 1] — AND
|
|
23
|
+
|
|
24
|
+
print(neuron(x, [1, 1], bias=-0.5, activation="step").tolist())
|
|
25
|
+
# [0, 1, 1, 1] — OR
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The same inputs produce a different function after changing one bias. A step neuron returns 1 when its preactivation is zero or positive.
|
|
29
|
+
|
|
30
|
+
## Lessons
|
|
31
|
+
|
|
32
|
+
- `neuron`: change the slope and offset of a linear neuron.
|
|
33
|
+
- `boolean`: encode AND and OR in threshold-neuron weights.
|
|
34
|
+
- `xor`: construct a two-layer XOR network.
|
|
35
|
+
- `compile`: construct an affine program's weights, then reuse them on new inputs.
|
|
36
|
+
- `generator`: fit a numerical descriptor-to-weights map by least squares and generate a new neuron program.
|
|
37
|
+
- `lora`: apply a rank-one update and compare the original and edited outputs.
|
|
38
|
+
- `norms`: inspect a synthetic input-layer kernel and permute hidden units while preserving its function.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
weightspaceprogramming lesson xor
|
|
42
|
+
weightspaceprogramming lesson xor --show-code
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The Python API exposes the exact lesson source for notebooks and browser runners:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from weightspaceprogramming import lesson_source
|
|
49
|
+
print(lesson_source("xor"))
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Apply a LoRA update
|
|
53
|
+
|
|
54
|
+
The package uses row-vector inputs: `output = input @ W`. For a weight matrix with shape `(inputs, outputs)`, the low-rank factors have shapes `(inputs, rank)` and `(rank, outputs)`.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import numpy as np
|
|
58
|
+
from weightspaceprogramming import apply_lora
|
|
59
|
+
|
|
60
|
+
w = np.eye(2)
|
|
61
|
+
edited = apply_lora(w, [[1.0], [0.0]], [[0.0, 2.0]])
|
|
62
|
+
x = np.array([[3.0, 4.0]])
|
|
63
|
+
print((x @ w).tolist()) # [[3.0, 4.0]]
|
|
64
|
+
print((x @ edited).tolist()) # [[3.0, 10.0]]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`apply_lora` returns `W + scale * A @ B` and leaves the supplied arrays unchanged.
|
|
68
|
+
|
|
69
|
+
## Read input-channel weights
|
|
70
|
+
|
|
71
|
+
For an HWC input grid, `channel_norms` computes the L2 norm across the first layer's hidden units at every cell and channel. It returns an array with shape `(channels, height, width)`.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from weightspaceprogramming import channel_norms
|
|
75
|
+
|
|
76
|
+
print(channel_norms([[3, 4], [0, 2]], (1, 2, 1)).tolist())
|
|
77
|
+
# [[[5.0, 2.0]]]
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Inspect your own NPZ checkpoint:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
weightspaceprogramming inspect network.npz \
|
|
84
|
+
--key actor/dense1/kernel --shape 10 10 5 --output norms.json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
NPZ files load with pickle disabled. The kernel must be a finite real matrix with one row per flattened HWC input and one column per hidden unit.
|
|
88
|
+
|
|
89
|
+
Add plotting when needed:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
python -m pip install --pre 'weightspaceprogramming[plot]'
|
|
93
|
+
weightspaceprogramming inspect network.npz \
|
|
94
|
+
--key actor/dense1/kernel --shape 10 10 5 --plot heatmaps.svg
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`permute_hidden(weights, biases, permutation, layer=0)` copies the parameters and reorders a hidden layer's incoming columns, biases and outgoing rows together. `mlp` evaluates the original and reordered networks with the same activation functions.
|
|
98
|
+
|
|
99
|
+
## From small networks to research implementations
|
|
100
|
+
|
|
101
|
+
[Program-as-Weights](https://weightspaceprogramming.tech/research/program-as-weights/) introduces a programming paradigm for fuzzy functions, a compiler–interpreter interface and FuzzyBench. PAW specifically trains a compiler to generate LoRA adapters that edit a frozen interpreter's weights from a natural-language function specification. [Run the PAW urgency and routing examples](https://github.com/weightspaceprogramming/examples#2-compile-and-reuse-an-email-urgency-function-with-paw) with the official SDK.
|
|
102
|
+
|
|
103
|
+
[Tracr](https://github.com/weightspaceprogramming/examples#1-compile-a-token-counter-with-tracr) compiles exact RASP programs into transformer weights. The [Sparks weight-reading experiment](https://weightspaceprogramming.tech/build/code-and-implementations/#weight-reading) applies the channel-norm computation to four published game policies and reports their permutation checks. PAW and Tracr keep their own installation instructions and dependencies.
|
|
104
|
+
|
|
105
|
+
Explore the [field guide](https://weightspaceprogramming.tech/) and [code and implementations](https://weightspaceprogramming.tech/build/code-and-implementations/).
|
|
106
|
+
|
|
107
|
+
## Development
|
|
108
|
+
|
|
109
|
+
Get the [source code](https://github.com/weightspaceprogramming/weightspaceprogramming) or [report an issue](https://github.com/weightspaceprogramming/weightspaceprogramming/issues).
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
python -m pip install -e .
|
|
113
|
+
python -m unittest discover -s tests -v
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Implementation provenance ships with the distribution in `SOURCES.md`. Package code is licensed under Apache-2.0.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Implementation and research sources
|
|
2
|
+
|
|
3
|
+
The channel-norm computation and NPZ loader are adapted from `weight_reading.py` in [weightspaceprogramming/examples](https://github.com/weightspaceprogramming/examples/blob/41e3a63c80c8bfbdda2c3f1c0c47c0d6f33b6f4b/weight_reading.py). That implementation was written for the field guide and tested on four Sparks policy networks. The package generalizes its hidden-unit permutation operation to dense networks.
|
|
4
|
+
|
|
5
|
+
The seven packaged lessons use synthetic arrays. Download the four Sparks policy networks through the [reproduction instructions](https://weightspaceprogramming.tech/build/code-and-implementations/#weight-reading).
|
|
6
|
+
|
|
7
|
+
- **Sparks of Weight-Space Programming**, Rikiya Takehi, Jayden Teoh, Alex Zhang and Omar Khattab. [Original blog](https://rikiyat.github.io/blog/weight-space-programming/) and [released experiment logs](https://github.com/RikiyaT/lm_understand-logs). The separate four-network experiment retains their checkpoint attribution and CC BY 4.0 terms.
|
|
8
|
+
- **Program-as-Weights: A Programming Paradigm for Fuzzy Functions**, Wentao Zhang, Liliana Hotsko, Woojeong Kim, Pengyu Nie, Stuart Shieber and Yuntian Deng. [Paper](https://arxiv.org/abs/2607.02512).
|
|
9
|
+
- **LoRA: Low-Rank Adaptation of Large Language Models**, Edward J. Hu and colleagues. [Paper](https://arxiv.org/abs/2106.09685). This package writes the low-rank multiplication in the row-vector convention `X @ (W + scale * A @ B)`.
|
|
10
|
+
- **Tracr: Compiled Transformers as a Laboratory for Interpretability**, David Lindner and colleagues. [Paper](https://arxiv.org/abs/2301.05062).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools==80.1.0", "wheel==0.45.1"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "weightspaceprogramming"
|
|
7
|
+
version = "0.1.0.dev1"
|
|
8
|
+
description = "Learn weight-space programming with runnable NumPy experiments."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = ["numpy>=1.24,<3"]
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
license-files = ["LICENSE", "SOURCES.md"]
|
|
14
|
+
keywords = ["weight-space-programming", "neural-networks", "education", "lora", "numpy"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
17
|
+
"Intended Audience :: Education",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
plot = ["matplotlib>=3.8"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://weightspaceprogramming.tech/"
|
|
27
|
+
Examples = "https://github.com/weightspaceprogramming/examples"
|
|
28
|
+
Guide = "https://weightspaceprogramming.tech/build/code-and-implementations/"
|
|
29
|
+
Source = "https://github.com/weightspaceprogramming/weightspaceprogramming"
|
|
30
|
+
Issues = "https://github.com/weightspaceprogramming/weightspaceprogramming/issues"
|
|
31
|
+
|
|
32
|
+
[project.scripts]
|
|
33
|
+
weightspaceprogramming = "weightspaceprogramming.cli:main"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools]
|
|
36
|
+
package-dir = {"" = "src"}
|
|
37
|
+
packages = ["weightspaceprogramming"]
|
|
38
|
+
include-package-data = false
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.package-data]
|
|
41
|
+
weightspaceprogramming = ["lessons.json"]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Learn weight-space programming with small NumPy experiments."""
|
|
2
|
+
from .core import (LinearWeightGenerator, apply_lora, binary_inputs, compile_affine,
|
|
3
|
+
fit_linear_generator, mlp, neuron, permute_hidden)
|
|
4
|
+
from .inspection import channel_norms, load_arrays, plot_channel_norms
|
|
5
|
+
from .lessons import lesson_names, lesson_source
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0.dev1"
|
|
8
|
+
__all__ = ["LinearWeightGenerator", "apply_lora", "binary_inputs", "compile_affine",
|
|
9
|
+
"fit_linear_generator", "mlp", "neuron", "permute_hidden", "channel_norms",
|
|
10
|
+
"load_arrays", "plot_channel_norms", "lesson_names", "lesson_source"]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Run a lesson or inspect an NPZ input-layer kernel."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from . import __version__, channel_norms, lesson_names, lesson_source, load_arrays, plot_channel_norms
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main(argv=None):
|
|
10
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
11
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
12
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
13
|
+
lesson = sub.add_parser("lesson", help="Run an offline Python lesson")
|
|
14
|
+
lesson.add_argument("name", choices=("list", *lesson_names()))
|
|
15
|
+
lesson.add_argument("--show-code", action="store_true")
|
|
16
|
+
inspect = sub.add_parser("inspect", help="Compute channel norms from a local NPZ kernel")
|
|
17
|
+
inspect.add_argument("checkpoint", type=Path)
|
|
18
|
+
inspect.add_argument("--key", default="actor/dense1/kernel")
|
|
19
|
+
inspect.add_argument("--shape", type=int, nargs=3, required=True, metavar=("H", "W", "C"))
|
|
20
|
+
inspect.add_argument("--output", type=Path, help="Save numeric JSON (otherwise print it)")
|
|
21
|
+
inspect.add_argument("--plot", type=Path, help="Save a PNG or SVG; requires the plot extra")
|
|
22
|
+
args = parser.parse_args(argv)
|
|
23
|
+
try:
|
|
24
|
+
if args.command == "lesson":
|
|
25
|
+
if args.name == "list":
|
|
26
|
+
print("\n".join(lesson_names()))
|
|
27
|
+
elif args.show_code:
|
|
28
|
+
print(lesson_source(args.name), end="")
|
|
29
|
+
else:
|
|
30
|
+
exec(compile(lesson_source(args.name), f"<lesson:{args.name}>", "exec"), {"__name__": "__main__"})
|
|
31
|
+
return 0
|
|
32
|
+
arrays = load_arrays(args.checkpoint)
|
|
33
|
+
if args.key not in arrays:
|
|
34
|
+
raise ValueError(f"Kernel {args.key!r} is absent; keys: {', '.join(arrays)}")
|
|
35
|
+
norms = channel_norms(arrays[args.key], tuple(args.shape))
|
|
36
|
+
data = {"kernel": args.key, "grid_shape_hwc": args.shape,
|
|
37
|
+
"computation": "sqrt(sum_j W[(row*width+column)*channels+channel,j]^2)",
|
|
38
|
+
"norm_maps_chw": norms.tolist()}
|
|
39
|
+
encoded = json.dumps(data, indent=2) + "\n"
|
|
40
|
+
if args.output:
|
|
41
|
+
args.output.write_text(encoded, encoding="utf-8")
|
|
42
|
+
else:
|
|
43
|
+
print(encoded, end="")
|
|
44
|
+
if args.plot:
|
|
45
|
+
plot_channel_norms(norms, output=args.plot)
|
|
46
|
+
return 0
|
|
47
|
+
except (ValueError, OSError, ImportError) as error:
|
|
48
|
+
parser.exit(1, f"{error}\n")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
if __name__ == "__main__":
|
|
52
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Small networks with row-vector inputs: y = x @ W + b."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _array(value, name):
|
|
8
|
+
result = np.asarray(value)
|
|
9
|
+
if result.dtype.kind not in "biuf" or not np.isfinite(result).all():
|
|
10
|
+
raise ValueError(f"{name} must contain finite real numbers")
|
|
11
|
+
return result.astype(np.float64)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _activate(x, activation):
|
|
15
|
+
if activation == "linear":
|
|
16
|
+
return x
|
|
17
|
+
if activation == "step":
|
|
18
|
+
return (x >= 0).astype(np.int64)
|
|
19
|
+
if activation == "relu":
|
|
20
|
+
return np.maximum(x, 0)
|
|
21
|
+
if activation == "tanh":
|
|
22
|
+
return np.tanh(x)
|
|
23
|
+
raise ValueError("activation must be linear, step, relu or tanh")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def neuron(x, weights, bias=0.0, activation="linear"):
|
|
27
|
+
"""Evaluate a neuron; the final input axis holds its features.
|
|
28
|
+
|
|
29
|
+
A step activation returns 1 at zero and above, and 0 below zero.
|
|
30
|
+
"""
|
|
31
|
+
x, weights, bias = _array(x, "x"), _array(weights, "weights"), _array(bias, "bias")
|
|
32
|
+
if weights.ndim != 1 or weights.size == 0:
|
|
33
|
+
raise ValueError("weights must be a nonempty vector")
|
|
34
|
+
if x.ndim == 0 or x.shape[-1] != weights.size:
|
|
35
|
+
raise ValueError("the final input dimension must match the weights")
|
|
36
|
+
if bias.ndim != 0:
|
|
37
|
+
raise ValueError("bias must be a scalar")
|
|
38
|
+
return _activate(x @ weights + bias, activation)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def binary_inputs(n_features=2):
|
|
42
|
+
"""All binary inputs, ordered from all zeros to all ones (1–16 features)."""
|
|
43
|
+
if type(n_features) is not int or not 1 <= n_features <= 16:
|
|
44
|
+
raise ValueError("n_features must be an integer between 1 and 16")
|
|
45
|
+
rows = np.arange(2 ** n_features, dtype=np.int64)[:, None]
|
|
46
|
+
return (rows >> np.arange(n_features - 1, -1, -1)) & 1
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _layers(weights, biases):
|
|
50
|
+
if len(weights) == 0 or len(weights) != len(biases):
|
|
51
|
+
raise ValueError("supply one bias vector for each nonempty weight layer")
|
|
52
|
+
ws, bs = [], []
|
|
53
|
+
for index, (weight, bias) in enumerate(zip(weights, biases)):
|
|
54
|
+
w, b = _array(weight, "weights"), _array(bias, "biases")
|
|
55
|
+
if w.ndim != 2 or 0 in w.shape:
|
|
56
|
+
raise ValueError("each weight matrix must have shape (inputs, outputs)")
|
|
57
|
+
if b.shape != (w.shape[1],):
|
|
58
|
+
raise ValueError("each bias must have one element per output")
|
|
59
|
+
if index and ws[-1].shape[1] != w.shape[0]:
|
|
60
|
+
raise ValueError("adjacent weight matrices must have matching widths")
|
|
61
|
+
ws.append(w)
|
|
62
|
+
bs.append(b)
|
|
63
|
+
return ws, bs
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def mlp(x, weights, biases, activation="tanh", output_activation="linear"):
|
|
67
|
+
"""Run dense layers, applying activation between layers and output_activation last."""
|
|
68
|
+
ws, bs = _layers(weights, biases)
|
|
69
|
+
output = _array(x, "x")
|
|
70
|
+
if output.ndim == 0 or output.shape[-1] != ws[0].shape[0]:
|
|
71
|
+
raise ValueError("the final input dimension must match the first layer")
|
|
72
|
+
_activate(np.array(0.0), activation)
|
|
73
|
+
for index, (weight, bias) in enumerate(zip(ws, bs)):
|
|
74
|
+
output = _activate(output @ weight + bias,
|
|
75
|
+
output_activation if index == len(ws) - 1 else activation)
|
|
76
|
+
return output
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def compile_affine(scale, shift):
|
|
80
|
+
"""Construct W and b for the exact one-input program f(x) = scale*x + shift."""
|
|
81
|
+
scale, shift = _array(scale, "scale"), _array(shift, "shift")
|
|
82
|
+
if scale.ndim or shift.ndim:
|
|
83
|
+
raise ValueError("scale and shift must be scalars")
|
|
84
|
+
return np.array([[float(scale)]]), np.array([float(shift)])
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class LinearWeightGenerator:
|
|
89
|
+
"""A fitted affine map from numerical descriptors to target weight arrays."""
|
|
90
|
+
coefficients: np.ndarray
|
|
91
|
+
weight_shape: tuple
|
|
92
|
+
|
|
93
|
+
def generate(self, descriptor):
|
|
94
|
+
"""Generate weights for one descriptor or a batch of descriptors."""
|
|
95
|
+
x = _array(descriptor, "descriptor")
|
|
96
|
+
if x.ndim not in (1, 2) or x.shape[-1] != self.coefficients.shape[0] - 1:
|
|
97
|
+
raise ValueError("descriptor width must match the generator's training inputs")
|
|
98
|
+
design = np.concatenate([x, np.ones((*x.shape[:-1], 1))], axis=-1)
|
|
99
|
+
return (design @ self.coefficients).reshape((*x.shape[:-1], *self.weight_shape))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def fit_linear_generator(descriptors, target_weights):
|
|
103
|
+
"""Fit descriptor→weights by least squares, with a learned constant offset."""
|
|
104
|
+
x, y = _array(descriptors, "descriptors"), _array(target_weights, "target_weights")
|
|
105
|
+
if x.ndim != 2 or 0 in x.shape or y.ndim < 2 or x.shape[0] != y.shape[0] or 0 in y.shape:
|
|
106
|
+
raise ValueError("supply nonempty descriptor and target batches with the same row count")
|
|
107
|
+
design = np.column_stack([x, np.ones(len(x))])
|
|
108
|
+
if np.linalg.matrix_rank(design) < design.shape[1]:
|
|
109
|
+
raise ValueError("descriptors must identify each input dimension and the constant offset")
|
|
110
|
+
coefficients = np.linalg.lstsq(design, y.reshape(len(y), -1), rcond=None)[0]
|
|
111
|
+
return LinearWeightGenerator(coefficients, y.shape[1:])
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def apply_lora(weights, a, b, scale=1.0):
|
|
115
|
+
"""Return W + scale*A@B; W is (in,out), A (in,rank), B (rank,out).
|
|
116
|
+
|
|
117
|
+
The input arrays are unchanged. This convention matches row-vector x @ W.
|
|
118
|
+
"""
|
|
119
|
+
w, a, b, scale = (_array(weights, "weights"), _array(a, "a"),
|
|
120
|
+
_array(b, "b"), _array(scale, "scale"))
|
|
121
|
+
if w.ndim != 2 or a.ndim != 2 or b.ndim != 2 or 0 in w.shape or 0 in a.shape or 0 in b.shape:
|
|
122
|
+
raise ValueError("weights, a and b must be nonempty matrices")
|
|
123
|
+
if a.shape[0] != w.shape[0] or b.shape[1] != w.shape[1] or a.shape[1] != b.shape[0]:
|
|
124
|
+
raise ValueError("LoRA factors must have shapes (inputs, rank) and (rank, outputs)")
|
|
125
|
+
if scale.ndim:
|
|
126
|
+
raise ValueError("scale must be a scalar")
|
|
127
|
+
return w + float(scale) * (a @ b)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def permute_hidden(weights, biases, permutation, layer=0):
|
|
131
|
+
"""Reorder one hidden layer and its connections; return copied parameters."""
|
|
132
|
+
ws, bs = _layers(weights, biases)
|
|
133
|
+
if type(layer) is not int or not 0 <= layer < len(ws) - 1:
|
|
134
|
+
raise ValueError("layer must name a hidden layer with a following weight matrix")
|
|
135
|
+
p = np.asarray(permutation)
|
|
136
|
+
width = ws[layer].shape[1]
|
|
137
|
+
if p.ndim != 1 or p.dtype.kind not in "iu" or not np.array_equal(np.sort(p), np.arange(width)):
|
|
138
|
+
raise ValueError("permutation must contain every hidden-unit index exactly once")
|
|
139
|
+
ws, bs = [w.copy() for w in ws], [b.copy() for b in bs]
|
|
140
|
+
ws[layer] = ws[layer][:, p]
|
|
141
|
+
bs[layer] = bs[layer][p]
|
|
142
|
+
ws[layer + 1] = ws[layer + 1][p, :]
|
|
143
|
+
return ws, bs
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Inspect finite real NPZ weights and visualize input-channel magnitudes."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def channel_norms(kernel, grid_shape):
|
|
8
|
+
"""L2 norms over hidden units, with HWC inputs; result has shape C,H,W."""
|
|
9
|
+
if len(grid_shape) != 3 or any(type(n) is not int or n <= 0 for n in grid_shape):
|
|
10
|
+
raise ValueError("grid_shape must contain three positive integers: height, width, channels")
|
|
11
|
+
values = np.asarray(kernel)
|
|
12
|
+
if values.ndim != 2 or values.shape[1] == 0:
|
|
13
|
+
raise ValueError("Kernel must have shape (input features, hidden units)")
|
|
14
|
+
if values.dtype.kind not in "fiu" or not np.isfinite(values).all():
|
|
15
|
+
raise ValueError("Kernel must contain finite real numbers")
|
|
16
|
+
if values.shape[0] != np.prod(grid_shape):
|
|
17
|
+
raise ValueError("Kernel input dimension does not equal height * width * channels")
|
|
18
|
+
try:
|
|
19
|
+
with np.errstate(over="raise", invalid="raise"):
|
|
20
|
+
values = values.astype(np.float64)
|
|
21
|
+
shaped = values.reshape(*grid_shape, values.shape[1])
|
|
22
|
+
return np.sqrt(np.sum(shaped * shaped, axis=-1)).transpose(2, 0, 1)
|
|
23
|
+
except FloatingPointError as error:
|
|
24
|
+
raise ValueError("Squared kernel magnitudes exceed float64 range") from error
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_arrays(path):
|
|
28
|
+
"""Read an NPZ checkpoint without pickle deserialization."""
|
|
29
|
+
with np.load(path, allow_pickle=False) as archive:
|
|
30
|
+
return {key: archive[key] for key in archive.files}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def plot_channel_norms(norms, labels=None, output=None):
|
|
34
|
+
"""Draw channel maps on one shared color scale; requires the plot extra.
|
|
35
|
+
|
|
36
|
+
Return the matplotlib Figure. If output is provided, save it to that path.
|
|
37
|
+
"""
|
|
38
|
+
try:
|
|
39
|
+
import matplotlib.pyplot as plt
|
|
40
|
+
except ImportError as error:
|
|
41
|
+
raise ImportError('Install plotting with pip install "weightspaceprogramming[plot]"') from error
|
|
42
|
+
maps = np.asarray(norms)
|
|
43
|
+
if maps.ndim != 3 or 0 in maps.shape or maps.dtype.kind not in "fiu" or not np.isfinite(maps).all() or (maps < 0).any():
|
|
44
|
+
raise ValueError("norms must be a nonempty, finite, nonnegative (channels,height,width) array")
|
|
45
|
+
labels = list(labels) if labels is not None else [f"Channel {i}" for i in range(len(maps))]
|
|
46
|
+
if len(labels) != len(maps):
|
|
47
|
+
raise ValueError("supply one label per channel")
|
|
48
|
+
figure, axes = plt.subplots(1, len(maps), squeeze=False, figsize=(3 * len(maps), 3))
|
|
49
|
+
for axis, values, label in zip(axes[0], maps, labels):
|
|
50
|
+
image = axis.imshow(values, vmin=0, vmax=float(maps.max()) or 1.0, cmap="viridis", interpolation="nearest")
|
|
51
|
+
axis.set_title(label)
|
|
52
|
+
figure.colorbar(image, ax=list(axes[0]), label="L2 norm across hidden units", shrink=0.7)
|
|
53
|
+
if output is not None:
|
|
54
|
+
figure.savefig(Path(output), bbox_inches="tight")
|
|
55
|
+
return figure
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"neuron": {
|
|
3
|
+
"title": "Change a neuron",
|
|
4
|
+
"code": "from weightspaceprogramming import neuron\n\n# y = 2*x - 1. Change the weight or bias, then run again.\nx = [[0], [1], [2], [3]]\nprint(neuron(x, weights=[2], bias=-1).tolist())\n"
|
|
5
|
+
},
|
|
6
|
+
"boolean": {
|
|
7
|
+
"title": "Program AND and OR",
|
|
8
|
+
"code": "from weightspaceprogramming import binary_inputs, neuron\n\nx = binary_inputs(2)\nprint(\"inputs:\", x.tolist())\nprint(\"AND:\", neuron(x, [1, 1], bias=-1.5, activation=\"step\").tolist())\nprint(\"OR:\", neuron(x, [1, 1], bias=-0.5, activation=\"step\").tolist())\n"
|
|
9
|
+
},
|
|
10
|
+
"xor": {
|
|
11
|
+
"title": "Write a two-layer XOR network",
|
|
12
|
+
"code": "from weightspaceprogramming import binary_inputs, mlp\n\n# Hidden neurons compute OR and AND. The output computes OR - 2*AND.\nweights = [[[1, 1], [1, 1]], [[1], [-2]]]\nbiases = [[-0.5, -1.5], [-0.5]]\nx = binary_inputs(2)\ny = mlp(x, weights, biases, activation=\"step\", output_activation=\"step\")\nprint(\"XOR:\", y[:, 0].tolist())\n"
|
|
13
|
+
},
|
|
14
|
+
"compile": {
|
|
15
|
+
"title": "Construct weights, then execute",
|
|
16
|
+
"code": "from weightspaceprogramming import compile_affine, mlp\n\n# Construct the parameters for f(x) = 3*x + 2 once.\nw, b = compile_affine(scale=3, shift=2)\nprint(\"weights:\", w.tolist(), \"bias:\", b.tolist())\n# Reuse those parameters on new inputs.\nprint(\"outputs:\", mlp([[0], [1], [4]], [w], [b])[:, 0].tolist())\n"
|
|
17
|
+
},
|
|
18
|
+
"generator": {
|
|
19
|
+
"title": "Learn a descriptor-to-weights map",
|
|
20
|
+
"code": "import numpy as np\nfrom weightspaceprogramming import fit_linear_generator, neuron\n\n# Each numerical descriptor is [slope, intercept]. Its target is a neuron program.\ndescriptors = np.array([[-2, -1], [-1, 1], [1, -1], [2, 1]], dtype=float)\nprograms = np.column_stack([2 * descriptors[:, 0], 0.5 * descriptors[:, 1] - 1])\ngenerator = fit_linear_generator(descriptors, programs)\n# Generate a new program from a descriptor absent from the training examples.\nprogram = generator.generate([3, 2])\nprint(\"generated [weight, bias]:\", (np.round(program, 6) + 0.0).tolist())\nprint(\"outputs:\", (np.round(neuron([[0], [1], [2]], program[:1], program[1]), 6) + 0.0).tolist())\n"
|
|
21
|
+
},
|
|
22
|
+
"lora": {
|
|
23
|
+
"title": "Change a function with a rank-one update",
|
|
24
|
+
"code": "import numpy as np\nfrom weightspaceprogramming import apply_lora\n\n# Row-vector convention: output = input @ W; update = A @ B.\nw = np.eye(2)\na = np.array([[1.0], [0.0]])\nb = np.array([[0.0, 2.0]])\nedited = apply_lora(w, a, b)\nx = np.array([[3.0, 4.0]])\nprint(\"base output:\", (x @ w).tolist())\nprint(\"edited output:\", (x @ edited).tolist())\nprint(\"update rank:\", int(np.linalg.matrix_rank(edited - w)))\nprint(\"base unchanged:\", bool(np.array_equal(w, np.eye(2))))\n"
|
|
25
|
+
},
|
|
26
|
+
"norms": {
|
|
27
|
+
"title": "Read weights and permute hidden units",
|
|
28
|
+
"code": "import numpy as np\nfrom weightspaceprogramming import channel_norms, mlp, permute_hidden\n\n# A synthetic 1x2 grid with one input channel and two hidden units.\nw1 = np.array([[3.0, 4.0], [0.0, 2.0]])\nw2 = np.array([[1.0], [-2.0]])\nweights, biases = [w1, w2], [np.array([0.1, -0.2]), np.array([0.3])]\nmaps = channel_norms(w1, (1, 2, 1))\nprint(\"channel norms:\", maps.tolist())\nreordered, reordered_biases = permute_hidden(weights, biases, [1, 0])\nx = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])\nprint(\"same norm maps:\", bool(np.allclose(maps, channel_norms(reordered[0], (1, 2, 1)))))\nprint(\"same outputs:\", bool(np.allclose(mlp(x, weights, biases), mlp(x, reordered, reordered_biases))))\n"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Editable, deterministic examples shared by the Python and browser lessons."""
|
|
2
|
+
from importlib.resources import files
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _lessons():
|
|
7
|
+
return json.loads(files("weightspaceprogramming").joinpath("lessons.json").read_text(encoding="utf-8"))
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def lesson_names():
|
|
11
|
+
"""Return the available lesson names in teaching order."""
|
|
12
|
+
return tuple(_lessons())
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def lesson_source(name):
|
|
16
|
+
"""Return a lesson's complete runnable Python source."""
|
|
17
|
+
try:
|
|
18
|
+
return _lessons()[name]["code"]
|
|
19
|
+
except KeyError as error:
|
|
20
|
+
raise ValueError(f"Unknown lesson {name!r}; choose from {', '.join(lesson_names())}") from error
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
SOURCES.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
src/weightspaceprogramming/__init__.py
|
|
7
|
+
src/weightspaceprogramming/__main__.py
|
|
8
|
+
src/weightspaceprogramming/cli.py
|
|
9
|
+
src/weightspaceprogramming/core.py
|
|
10
|
+
src/weightspaceprogramming/inspection.py
|
|
11
|
+
src/weightspaceprogramming/lessons.json
|
|
12
|
+
src/weightspaceprogramming/lessons.py
|
|
13
|
+
tests/test_toolkit.py
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import unittest
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from weightspaceprogramming import (apply_lora, binary_inputs, channel_norms, compile_affine,
|
|
13
|
+
fit_linear_generator, lesson_names, lesson_source,
|
|
14
|
+
load_arrays, mlp, neuron, permute_hidden)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ToolkitTests(unittest.TestCase):
|
|
18
|
+
def test_neuron_and_boolean_tables(self):
|
|
19
|
+
self.assertEqual(neuron([[0], [1], [2]], [3], -1).tolist(), [-1, 2, 5])
|
|
20
|
+
x = binary_inputs(2)
|
|
21
|
+
self.assertEqual(x.tolist(), [[0, 0], [0, 1], [1, 0], [1, 1]])
|
|
22
|
+
self.assertEqual(neuron(x, [1, 1], -1.5, "step").tolist(), [0, 0, 0, 1])
|
|
23
|
+
self.assertEqual(neuron(x, [1, 1], -0.5, "step").tolist(), [0, 1, 1, 1])
|
|
24
|
+
self.assertEqual(neuron([0], [1], activation="step"), 1)
|
|
25
|
+
|
|
26
|
+
def test_xor_written_in_weights(self):
|
|
27
|
+
weights = [[[1, 1], [1, 1]], [[1], [-2]]]
|
|
28
|
+
biases = [[-0.5, -1.5], [-0.5]]
|
|
29
|
+
actual = mlp(binary_inputs(), weights, biases, "step", "step")[:, 0]
|
|
30
|
+
np.testing.assert_array_equal(actual, [0, 1, 1, 0])
|
|
31
|
+
|
|
32
|
+
def test_exact_compilation_reused_on_new_inputs(self):
|
|
33
|
+
for scale, shift in [(3, 2), (-2.5, 0.3), (0, -4)]:
|
|
34
|
+
w, b = compile_affine(scale, shift)
|
|
35
|
+
inputs = np.array([[-7.0], [0], [2], [13]])
|
|
36
|
+
np.testing.assert_allclose(mlp(inputs, [w], [b]), scale * inputs + shift)
|
|
37
|
+
|
|
38
|
+
def test_learned_generator_predicts_unseen_weights(self):
|
|
39
|
+
x = np.array([[-2, -1], [-1, 1], [1, -1], [2, 1]])
|
|
40
|
+
y = np.column_stack([2 * x[:, 0], 0.5 * x[:, 1] - 1])
|
|
41
|
+
generator = fit_linear_generator(x, y)
|
|
42
|
+
np.testing.assert_allclose(generator.generate([3, 2]), [6, 0], atol=1e-12)
|
|
43
|
+
np.testing.assert_allclose(generator.generate([[3, 2], [-4, 3]]), [[6, 0], [-8, 0.5]], atol=1e-12)
|
|
44
|
+
tensor_generator = fit_linear_generator(x, y.reshape(4, 1, 2))
|
|
45
|
+
self.assertEqual(tensor_generator.generate([3, 2]).shape, (1, 2))
|
|
46
|
+
with self.assertRaises(ValueError):
|
|
47
|
+
fit_linear_generator([[1], [1]], [[2], [3]])
|
|
48
|
+
|
|
49
|
+
def test_lora_matches_factorized_application_and_preserves_base(self):
|
|
50
|
+
rng = np.random.default_rng(7)
|
|
51
|
+
w, a, b = rng.normal(size=(4, 3)), rng.normal(size=(4, 2)), rng.normal(size=(2, 3))
|
|
52
|
+
original = w.copy()
|
|
53
|
+
x = rng.normal(size=(8, 4))
|
|
54
|
+
edited = apply_lora(w, a, b, scale=0.25)
|
|
55
|
+
np.testing.assert_allclose(x @ edited, x @ w + 0.25 * (x @ a) @ b, atol=1e-12)
|
|
56
|
+
np.testing.assert_array_equal(w, original)
|
|
57
|
+
self.assertFalse(np.shares_memory(w, edited))
|
|
58
|
+
|
|
59
|
+
def test_channel_norms_against_independent_cell_loop(self):
|
|
60
|
+
rng = np.random.default_rng(5)
|
|
61
|
+
kernel = rng.normal(size=(3 * 4 * 2, 7))
|
|
62
|
+
expected = np.empty((2, 3, 4))
|
|
63
|
+
for channel in range(2):
|
|
64
|
+
for row in range(3):
|
|
65
|
+
for column in range(4):
|
|
66
|
+
vector = kernel[(row * 4 + column) * 2 + channel]
|
|
67
|
+
expected[channel, row, column] = sum(float(v) ** 2 for v in vector) ** 0.5
|
|
68
|
+
np.testing.assert_allclose(channel_norms(kernel, (3, 4, 2)), expected, atol=1e-12)
|
|
69
|
+
np.testing.assert_allclose(channel_norms([[3, 4], [0, 2]], (1, 2, 1)), [[[5, 2]]])
|
|
70
|
+
|
|
71
|
+
def test_integer_norms_and_overflow_rejection(self):
|
|
72
|
+
np.testing.assert_allclose(channel_norms(np.array([[30000, 40000]], dtype=np.int64), (1, 1, 1)), [[[50000]]])
|
|
73
|
+
with self.assertRaises(ValueError):
|
|
74
|
+
channel_norms([[1e308]], (1, 1, 1))
|
|
75
|
+
|
|
76
|
+
def test_hidden_permutation_preserves_composed_network(self):
|
|
77
|
+
rng = np.random.default_rng(19)
|
|
78
|
+
weights = [rng.normal(size=(6, 5)), rng.normal(size=(5, 4)), rng.normal(size=(4, 2))]
|
|
79
|
+
biases = [rng.normal(size=(5,)), rng.normal(size=(4,)), rng.normal(size=(2,))]
|
|
80
|
+
originals = [w.copy() for w in weights]
|
|
81
|
+
inputs = rng.normal(size=(32, 6))
|
|
82
|
+
for activation in ["tanh", "relu", "step"]:
|
|
83
|
+
for layer, permutation in [(0, [3, 0, 4, 1, 2]), (1, [2, 0, 3, 1])]:
|
|
84
|
+
changed, bs = permute_hidden(weights, biases, permutation, layer)
|
|
85
|
+
np.testing.assert_allclose(mlp(inputs, weights, biases, activation), mlp(inputs, changed, bs, activation), atol=1e-12)
|
|
86
|
+
for a, b in zip(originals, weights):
|
|
87
|
+
np.testing.assert_array_equal(a, b)
|
|
88
|
+
changed, _ = permute_hidden(weights, biases, [3, 0, 4, 1, 2])
|
|
89
|
+
np.testing.assert_allclose(channel_norms(weights[0], (2, 3, 1)), channel_norms(changed[0], (2, 3, 1)), atol=1e-12)
|
|
90
|
+
|
|
91
|
+
def test_invalid_shapes_and_nonfinite_inputs(self):
|
|
92
|
+
calls = [
|
|
93
|
+
lambda: neuron([1, 2], [1]),
|
|
94
|
+
lambda: neuron([1], [float("nan")]),
|
|
95
|
+
lambda: neuron([1], [1], activation="sigmoid"),
|
|
96
|
+
lambda: neuron([1j], [1]),
|
|
97
|
+
lambda: binary_inputs(0),
|
|
98
|
+
lambda: binary_inputs(True),
|
|
99
|
+
lambda: mlp([[1]], [[[1, 2]], [[3]]], [[0, 0], [0]]),
|
|
100
|
+
lambda: mlp([[1]], [[[1]]], [[0, 1]]),
|
|
101
|
+
lambda: apply_lora([[1, 2]], [[1]], [[1]]),
|
|
102
|
+
lambda: channel_norms([[1, 2]], (1, 2, 1)),
|
|
103
|
+
lambda: channel_norms([[float("inf")]], (1, 1, 1)),
|
|
104
|
+
lambda: channel_norms([[1]], (1, 1, True)),
|
|
105
|
+
lambda: permute_hidden([[[1, 2]], [[1], [2]]], [[0, 0], [0]], [0, 0]),
|
|
106
|
+
lambda: permute_hidden([[[1]]], [[0]], [0]),
|
|
107
|
+
]
|
|
108
|
+
for call in calls:
|
|
109
|
+
with self.subTest(call=call):
|
|
110
|
+
with self.assertRaises(ValueError):
|
|
111
|
+
call()
|
|
112
|
+
|
|
113
|
+
def test_npz_reader_rejects_pickled_objects(self):
|
|
114
|
+
with tempfile.TemporaryDirectory() as temp:
|
|
115
|
+
path = Path(temp) / "weights.npz"
|
|
116
|
+
np.savez(path, w=np.eye(2))
|
|
117
|
+
np.testing.assert_array_equal(load_arrays(path)["w"], np.eye(2))
|
|
118
|
+
np.savez(path, w=np.array([{"value": 1}], dtype=object))
|
|
119
|
+
with self.assertRaises(ValueError):
|
|
120
|
+
load_arrays(path)
|
|
121
|
+
|
|
122
|
+
def test_all_packaged_lessons_execute(self):
|
|
123
|
+
expected = {
|
|
124
|
+
"neuron": "[-1.0, 1.0, 3.0, 5.0]",
|
|
125
|
+
"boolean": "AND: [0, 0, 0, 1]",
|
|
126
|
+
"xor": "XOR: [0, 1, 1, 0]",
|
|
127
|
+
"compile": "outputs: [2.0, 5.0, 14.0]",
|
|
128
|
+
"generator": "outputs: [0.0, 6.0, 12.0]",
|
|
129
|
+
"lora": "edited output: [[3.0, 10.0]]",
|
|
130
|
+
"norms": "same outputs: True",
|
|
131
|
+
}
|
|
132
|
+
self.assertEqual(set(lesson_names()), set(expected))
|
|
133
|
+
for name in lesson_names():
|
|
134
|
+
with self.subTest(lesson=name), contextlib.redirect_stdout(io.StringIO()) as out:
|
|
135
|
+
exec(compile(lesson_source(name), name, "exec"), {"__name__": "__main__"})
|
|
136
|
+
self.assertIn(expected[name], out.getvalue())
|
|
137
|
+
|
|
138
|
+
def test_cli_inspects_local_file(self):
|
|
139
|
+
with tempfile.TemporaryDirectory() as temp:
|
|
140
|
+
path = Path(temp) / "weights.npz"
|
|
141
|
+
np.savez(path, kernel=np.array([[3, 4], [0, 2]]))
|
|
142
|
+
result = subprocess.run([sys.executable, "-m", "weightspaceprogramming", "inspect", str(path),
|
|
143
|
+
"--key", "kernel", "--shape", "1", "2", "1"], capture_output=True, text=True, check=True)
|
|
144
|
+
self.assertEqual(json.loads(result.stdout)["norm_maps_chw"], [[[5.0, 2.0]]])
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
unittest.main()
|