dragonscale 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 (68) hide show
  1. dragonscale-0.1.0/LICENSE +201 -0
  2. dragonscale-0.1.0/PKG-INFO +463 -0
  3. dragonscale-0.1.0/README.md +429 -0
  4. dragonscale-0.1.0/pyproject.toml +54 -0
  5. dragonscale-0.1.0/setup.cfg +4 -0
  6. dragonscale-0.1.0/src/dragonscale/__init__.py +39 -0
  7. dragonscale-0.1.0/src/dragonscale/analysis/__init__.py +29 -0
  8. dragonscale-0.1.0/src/dragonscale/analysis/absorb.py +229 -0
  9. dragonscale-0.1.0/src/dragonscale/analysis/jacobian.py +59 -0
  10. dragonscale-0.1.0/src/dragonscale/analysis/report.py +208 -0
  11. dragonscale-0.1.0/src/dragonscale/analysis/rules.py +281 -0
  12. dragonscale-0.1.0/src/dragonscale/analysis/suggest.py +108 -0
  13. dragonscale-0.1.0/src/dragonscale/analysis/trace.py +171 -0
  14. dragonscale-0.1.0/src/dragonscale/functional/__init__.py +35 -0
  15. dragonscale-0.1.0/src/dragonscale/functional/layers.py +53 -0
  16. dragonscale-0.1.0/src/dragonscale/functional/rows.py +261 -0
  17. dragonscale-0.1.0/src/dragonscale/layer_types.py +131 -0
  18. dragonscale-0.1.0/src/dragonscale/monitor.py +82 -0
  19. dragonscale-0.1.0/src/dragonscale/nn/__init__.py +27 -0
  20. dragonscale-0.1.0/src/dragonscale/nn/gain.py +21 -0
  21. dragonscale-0.1.0/src/dragonscale/nn/layers.py +157 -0
  22. dragonscale-0.1.0/src/dragonscale/optim.py +143 -0
  23. dragonscale-0.1.0/src/dragonscale/patch/__init__.py +7 -0
  24. dragonscale-0.1.0/src/dragonscale/patch/forwards.py +24 -0
  25. dragonscale-0.1.0/src/dragonscale/patch/grouped.py +148 -0
  26. dragonscale-0.1.0/src/dragonscale/patch/patched.py +303 -0
  27. dragonscale-0.1.0/src/dragonscale/patch/session.py +195 -0
  28. dragonscale-0.1.0/src/dragonscale/patch/state.py +93 -0
  29. dragonscale-0.1.0/src/dragonscale/plan/__init__.py +9 -0
  30. dragonscale-0.1.0/src/dragonscale/plan/build.py +53 -0
  31. dragonscale-0.1.0/src/dragonscale/plan/layer_plan.py +81 -0
  32. dragonscale-0.1.0/src/dragonscale/plan/presets.py +27 -0
  33. dragonscale-0.1.0/src/dragonscale/plan/rules.py +39 -0
  34. dragonscale-0.1.0/src/dragonscale/plan/validate.py +119 -0
  35. dragonscale-0.1.0/src/dragonscale/spec/__init__.py +6 -0
  36. dragonscale-0.1.0/src/dragonscale/spec/defaults.py +36 -0
  37. dragonscale-0.1.0/src/dragonscale/spec/rows.py +68 -0
  38. dragonscale-0.1.0/src/dragonscale.egg-info/PKG-INFO +463 -0
  39. dragonscale-0.1.0/src/dragonscale.egg-info/SOURCES.txt +66 -0
  40. dragonscale-0.1.0/src/dragonscale.egg-info/dependency_links.txt +1 -0
  41. dragonscale-0.1.0/src/dragonscale.egg-info/requires.txt +22 -0
  42. dragonscale-0.1.0/src/dragonscale.egg-info/top_level.txt +3 -0
  43. dragonscale-0.1.0/src/dragonscale_common/__init__.py +8 -0
  44. dragonscale-0.1.0/src/dragonscale_common/imports.py +24 -0
  45. dragonscale-0.1.0/src/dragonscale_common/log.py +47 -0
  46. dragonscale-0.1.0/src/dragonscale_common/problems.py +16 -0
  47. dragonscale-0.1.0/src/dragonscale_common/registry.py +66 -0
  48. dragonscale-0.1.0/src/dragonscale_kernels/__init__.py +9 -0
  49. dragonscale-0.1.0/src/dragonscale_kernels/backends/__init__.py +1 -0
  50. dragonscale-0.1.0/src/dragonscale_kernels/backends/compile.py +20 -0
  51. dragonscale-0.1.0/src/dragonscale_kernels/backends/eager/__init__.py +22 -0
  52. dragonscale-0.1.0/src/dragonscale_kernels/backends/eager/rows.py +89 -0
  53. dragonscale-0.1.0/src/dragonscale_kernels/backends/eager/scale.py +35 -0
  54. dragonscale-0.1.0/src/dragonscale_kernels/backends/tilelang/__init__.py +3 -0
  55. dragonscale-0.1.0/src/dragonscale_kernels/backends/triton/__init__.py +23 -0
  56. dragonscale-0.1.0/src/dragonscale_kernels/backends/triton/common.py +47 -0
  57. dragonscale-0.1.0/src/dragonscale_kernels/backends/triton/grouped.py +172 -0
  58. dragonscale-0.1.0/src/dragonscale_kernels/backends/triton/rows.py +255 -0
  59. dragonscale-0.1.0/src/dragonscale_kernels/constraints.py +26 -0
  60. dragonscale-0.1.0/src/dragonscale_kernels/error_stats.py +56 -0
  61. dragonscale-0.1.0/src/dragonscale_kernels/errors.py +5 -0
  62. dragonscale-0.1.0/src/dragonscale_kernels/hardware.py +47 -0
  63. dragonscale-0.1.0/src/dragonscale_kernels/layout.py +42 -0
  64. dragonscale-0.1.0/src/dragonscale_kernels/ops.py +79 -0
  65. dragonscale-0.1.0/src/dragonscale_kernels/registry.py +92 -0
  66. dragonscale-0.1.0/src/dragonscale_kernels/tuning.py +148 -0
  67. dragonscale-0.1.0/tests/test_analysis.py +144 -0
  68. dragonscale-0.1.0/tests/test_patch.py +187 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Shih-Ying Yeh (A.K.A. KohakuBlueLeaf)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,463 @@
1
+ Metadata-Version: 2.4
2
+ Name: dragonscale
3
+ Version: 0.1.0
4
+ Summary: Keeps weight sizes from drifting during training: finds the scales a model's loss cannot see and normalizes the weights behind them.
5
+ Author-email: "Shih-Ying Yeh(KohakuBlueLeaf)" <apolloyeh0123@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/KohakuBlueleaf/DragonScale
8
+ Keywords: pytorch,weight-normalization,training-stability,triton
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: torch>=2.9
17
+ Provides-Extra: triton
18
+ Requires-Dist: triton>=3.7; extra == "triton"
19
+ Provides-Extra: tilelang
20
+ Requires-Dist: tilelang; extra == "tilelang"
21
+ Provides-Extra: hf
22
+ Requires-Dist: transformers; extra == "hf"
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Requires-Dist: ruff; extra == "dev"
26
+ Requires-Dist: black; extra == "dev"
27
+ Requires-Dist: matplotlib; extra == "dev"
28
+ Requires-Dist: kohaku-engine; extra == "dev"
29
+ Provides-Extra: measure
30
+ Requires-Dist: transformers; extra == "measure"
31
+ Requires-Dist: matplotlib; extra == "measure"
32
+ Requires-Dist: kohaku-engine; extra == "measure"
33
+ Dynamic: license-file
34
+
35
+ # DragonScale
36
+
37
+ ![DragonScale: a pre-norm transformer's free scales drift where the loss cannot see them; EDM2 and nGPT fix every scale by construction; DragonScale finds the free scales in the model you have and gives each one owner, a gain the loss moves. Right: JiT-B/16's stream peak, stock 1,694 against arch 15, and a byte-level LM's loss against learning rate](docs/assets/teaser.png)
38
+
39
+ A PyTorch library that keeps weight and activation scales from drifting during training.
40
+
41
+ Some scales in a network can change without changing what the loss sees: in a transformer MLP you
42
+ can multiply `up` by 2 and divide `down` by 2 and get the same output. The loss gives no gradient
43
+ along such a direction, but every optimizer step still moves the weights a little along it, and
44
+ those moves add up. Over training the residual stream, the attention logits and the weight norms
45
+ grow, until fp16 overflows or training diverges. DragonScale finds these directions in any model,
46
+ gives the rows of the weights behind them a fixed length, and keeps one learned gain per row in
47
+ their place. Scales can still grow, but only through gains the loss sees and moves.
48
+
49
+ **Contents:** [Highlights](#highlights) · [Install](#install) · [Quick start](#quick-start) ·
50
+ [How it works](#how-it-works) · [Why scales drift](#why-scales-drift) · [Analysis](#analysis) ·
51
+ [Patching options](#patching-options) · [Optimizer](#optimizer) · [Checkpoints](#checkpoints) ·
52
+ [Kernels and speed](#kernels-and-speed) · [Measured](#measured) · [Repository](#repository)
53
+
54
+ ## Highlights
55
+
56
+ - **Finds the free scales of any model** in one forward pass: `ds.analysis.free_scales` follows the
57
+ scale of every parameter through every op and reports which directions the loss cannot see,
58
+ which of them move activations, and what the architecture could change.
59
+ - **Patches the model you already have, same output at step 0.** Linear, Conv, ConvTranspose,
60
+ Embedding and GPT-2's `Conv1D` get unit rows and a gain; tied weights share one gain; `bake`
61
+ returns stock modules.
62
+ - **The stream stays where the loss can see it.** JiT-B/16 at lr 1e-3: stock's stream peaks at
63
+ 1,694, `arch` at 15. Byte-level LM: stock trains up to lr 5e-3, `arch` up to 1.0, at a lower
64
+ best loss (0.930 against 0.947).
65
+ - **Costs little.** Triton kernels at 85–96% of memory bandwidth on large weights (V100, RTX 2080
66
+ Ti, 3090, 4090), against 54–64% for `torch.compile` and 21–25% for eager; a grouped launch for
67
+ many small layers; under `torch.compile` a patched model runs within 3–6% of stock at the same
68
+ memory.
69
+
70
+ ## Install
71
+
72
+ ```bash
73
+ uv pip install -e . # extras: triton, hf, measure, dev
74
+ ```
75
+
76
+ Needs Python 3.11+ and torch 2.9+.
77
+
78
+ ## Quick start
79
+
80
+ ```python
81
+ import torch
82
+ import dragonscale as ds
83
+
84
+ model = MyModel()
85
+
86
+ # Which scales does the loss not see, which of them are risky, what should the model change?
87
+ report = ds.analysis.free_scales(model, example_input)
88
+ print(report.describe())
89
+
90
+ # Unit rows and a gain on every Linear / Conv / Embedding; the output is unchanged.
91
+ session = ds.apply(model, ds.analysis.suggest(model, example_input, level="matrices"))
92
+
93
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) # gains are ordinary parameters
94
+ # ... train as usual ...
95
+
96
+ session.bake() # back to stock modules with the trained weights, same output
97
+ ```
98
+
99
+ `ds.apply` works on a model you already have: an existing checkpoint is converted with the same
100
+ output at step 0. Training from scratch works the same way.
101
+
102
+ ## How it works
103
+
104
+ ```mermaid
105
+ flowchart LR
106
+ model["your model"] --> report["free_scales(model, x)<br/>free directions, dangerous ones,<br/>architecture notes"]
107
+ report --> plan["suggest(model, x, level)<br/>report / minimal / matrices / absorb"]
108
+ plan --> apply["ds.apply(model, plan)<br/>unit rows + gain per layer<br/>same output"]
109
+ apply --> train["train as usual<br/>any optimizer"]
110
+ train --> out["session.bake()<br/>stock modules"]
111
+ train --> native["session.canonicalize()<br/>ds.nn modules"]
112
+ ```
113
+
114
+ A patched layer computes with unit rows times a gain; the architecture notes are what a weight
115
+ patch cannot do, and belong in the model code. The `arch` models in [Measured](#measured) follow
116
+ them: every input enters through a norm without affine, the blocks write the residual stream with
117
+ unit rows and gains, and the output layer reads the stream directly with unit rows and no gain.
118
+ There is no final norm: a norm in front of the output hides the stream's scale from the loss and
119
+ makes it free. In JiT the conditioning and in-context tokens are attended to and never written,
120
+ so they keep the scale they entered with.
121
+
122
+ ## Why scales drift
123
+
124
+ Give every parameter tensor $\theta_i$ a log-scale $s_i$ and look at the model as a function of
125
+ $\theta_i e^{s_i}$. A **free direction** is a vector $s$ along which the output does not change:
126
+
127
+ ```math
128
+ f(\theta_1 e^{s_1}, \dots, \theta_n e^{s_n}) = f(\theta_1, \dots, \theta_n).
129
+ ```
130
+
131
+ Examples: `up` $\times c$ with `down` $\times 1/c$; `q` $\times c$ with `k` $\times 1/c$; a norm's
132
+ gain $\times c$ with every layer that reads it $\times 1/c$; and any weight followed by a norm on
133
+ its own.
134
+
135
+ The loss is constant along a free direction, so its gradient has no component there. For a weight
136
+ $w$ whose scale is free, $\langle \nabla_w L, w\rangle = 0$, and one step $w' = w - \eta g$ gives
137
+
138
+ ```math
139
+ \lVert w' \rVert^2 = \lVert w \rVert^2 + \eta^2 \lVert g \rVert^2 \ \ge\ \lVert w \rVert^2 .
140
+ ```
141
+
142
+ The norm can only grow. With Adam every entry moves about $\eta$ per step whatever its gradient,
143
+ so a row of $n$ entries grows like a random walk, and a matrix row moves about $\sqrt{n}$ times
144
+ faster than a single gain. A free direction is **dangerous** when it moves activations and has a
145
+ matrix in it: that is where the drift is fast and the network sees it.
146
+
147
+ ## What DragonScale changes
148
+
149
+ A patched layer uses unit rows times a gain in place of its weight:
150
+
151
+ ```math
152
+ W_{\text{eff}} = \mathrm{diag}(g)\, r\, \frac{W}{\lVert W \rVert_{\text{row}}}
153
+ ```
154
+
155
+ with $r$ the row radius (1 for linears and convs, $\sqrt{\text{dim}}$ for embeddings, so their rows
156
+ have unit RMS). The raw row length $\lVert W \rVert_{\text{row}}$ no longer reaches the output, so
157
+ the scale that drifted now lives in $g$: one number per row, moved by a gradient that is aligned
158
+ with the loss instead of by noise. The gradient reaching $W$ is tangent to its rows,
159
+
160
+ ```math
161
+ \frac{\partial L}{\partial W} = \frac{g\, r}{\lVert W \rVert}\,\bigl(I - \hat w \hat w^\top\bigr)\, \frac{\partial L}{\partial W_{\text{eff}}},
162
+ ```
163
+
164
+ so the raw rows still grow, slowly, and their growth shrinks the effective step of the direction:
165
+ a per-row $1/\sqrt{t}$ schedule.
166
+
167
+ ## Analysis
168
+
169
+ `ds.analysis.free_scales(model, *inputs)` runs one forward pass, follows the scale of every
170
+ parameter through every op, and solves for the free directions. For a one-block pre-norm LM:
171
+
172
+ ```text
173
+ 7 free direction(s), 7 dangerous, 6 constraints over 13 groups
174
+ dangerous: +1*embed.weight +1*pos.weight +1*blocks.0.out.weight +1*blocks.0.down.weight
175
+ dangerous: +1*blocks.0.norm1.weight -2*blocks.0.k.weight -1*blocks.0.out.weight
176
+ dangerous: +1*blocks.0.q.weight -1*blocks.0.k.weight
177
+ dangerous: +1*blocks.0.v.weight -1*blocks.0.out.weight
178
+ dangerous: +1*blocks.0.norm2.weight -1*blocks.0.gate.weight -1*blocks.0.down.weight
179
+ dangerous: +1*blocks.0.up.weight -1*blocks.0.down.weight
180
+ dangerous: +1*norm.weight -1*head.weight
181
+ architecture:
182
+ attention calls [0]: q and k trade scale freely; normalize q and k (QK-norm) with a gain on one side only
183
+ embed.weight, pos.weight, blocks.0.out.weight, blocks.0.down.weight scale the residual stream together; give the model input a fixed scale (an embedding: mode 'unit')
184
+ ```
185
+
186
+ `gate` and `down` do not trade freely: SiLU pins the scale of `gate`.
187
+
188
+ `ds.analysis.suggest(model, *inputs, level=...)` turns the report into a plan:
189
+
190
+ | level | plan |
191
+ | --- | --- |
192
+ | `report` | nothing; read the report and its architecture notes |
193
+ | `minimal` | unit rows and a gain only on the layers in a dangerous direction |
194
+ | `matrices` | unit rows and a gain on every Linear / Conv / Embedding |
195
+ | `absorb` | each norm's affine is moved into the layers that read it and frozen; each layer whose row scale can move into the next layer (`v` into `out`, `up` into `down`) gets unit rows without a gain; the rest get unit rows and a gain |
196
+
197
+ Every level keeps the model's output. `absorb` plans carry the moves; run them before applying:
198
+
199
+ ```python
200
+ plan = ds.analysis.suggest(model, x, level="absorb")
201
+ session = ds.apply(model, ds.analysis.absorb_plan(model, plan, x))
202
+ ```
203
+
204
+ `ds.analysis.absorb(model, source, *inputs, into=None)` makes one move by hand; it finds the
205
+ consumers when `into` is None, refuses a move that is not free, and checks that the output did not
206
+ change. `ds.analysis.scale_jacobian` gives the spectrum of the same scale map numerically.
207
+
208
+ The architecture notes are what a weight patch cannot do; they belong in the model code.
209
+
210
+ ## Patching options
211
+
212
+ Plans are data: `ds.make_plan(model, rules)` matches `ds.Rule(match, **options)` against module
213
+ paths or types, first match wins. `ds.apply` accepts a plan, a rule list or a preset name
214
+ (`unit_gain`, `unit`, `linear_unit_gain`, `conv_unit_gain`, `parametrize_unit_gain`).
215
+
216
+ | option | values | meaning |
217
+ | --- | --- | --- |
218
+ | `mode` | `unit_gain`, `unit`, `plain` | unit rows times a gain, unit rows alone, untouched |
219
+ | `gain` | `channel`, `scalar` | one gain per row, or one for the layer |
220
+ | `init` | `preserve`, `ones`, `reset`, `absorb` | gain = row length (same output), gain = 1, re-initialize then preserve, rows already moved by `absorb_plan` |
221
+ | `install` | `forward`, `parametrize`, `bake` | replace the module's forward, a torch parametrization, write the unit-row weight once |
222
+ | `method` | `normalize`, `rescale` | divide by the row length in every forward, or use the raw rows and let the optimizer rescale them after each step |
223
+
224
+ Supported layers: Linear, Conv1d/2d/3d, ConvTranspose1d/2d/3d, Embedding and transformers'
225
+ `Conv1D` (GPT-2); `ds.layer_types.register_layer_type` adds more. Tied weights (an LM head shared
226
+ with the embedding) are patched as one layer with one gain.
227
+
228
+ `ds.nn` has the same layers as modules (`UnitRowLinear`, `UnitRowConv2d`, `UnitRowEmbedding`, ...)
229
+ for new models, and `ds.functional.unit_rows(w, spec, gain)` does it for a bare weight.
230
+
231
+ ## Optimizer
232
+
233
+ `method="normalize"` needs nothing from the optimizer. `method="rescale"` needs the gradient
234
+ decorator, which works with any torch optimizer through its step hooks:
235
+
236
+ ```python
237
+ decorator = ds.optim.attach(optimizer, session)
238
+ ```
239
+
240
+ Before each step it removes the part of each gradient that would change a row's length; after the
241
+ step it removes the same part from the momentum (Adam's `exp_avg`, SGD's and Muon's
242
+ `momentum_buffer`) and rescales each row back to its radius. Second moments are left alone.
243
+
244
+ ## Checkpoints
245
+
246
+ | call | result |
247
+ | --- | --- |
248
+ | `session.state_dict("raw")` | raw weights and gains, under the module's own keys plus `<path>.gain` |
249
+ | `session.state_dict("baked")` | the unit-row weights under the stock keys; loads into the stock model |
250
+ | `session.bake()` | the model becomes stock modules with the unit-row weights, same output |
251
+ | `session.canonicalize()` | the patched modules become `ds.nn` modules in place (`native` state dict) |
252
+ | `session.remove()` | everything undone; the weights keep what training wrote |
253
+
254
+ `load_state_dict(state, format)` reads all three formats. Patched models work with
255
+ `copy.deepcopy`, `torch.save` of the whole model (`forward` install) and FSDP2.
256
+
257
+ `ds.monitor.Monitor(session)` reads each patched layer's output size, gains and raw row lengths
258
+ during training.
259
+
260
+ ## Kernels and speed
261
+
262
+ The unit-row op is memory-bound: it reads a weight and writes one of the same size, so its speed
263
+ is its effective bandwidth, the bytes it must move over its time. The Triton kernels read a row
264
+ once when it fits 64 KB. On an 11008 x 4096 weight, forward + backward, they reach 85–96% of the
265
+ card's memory bandwidth, against 54–64% for `torch.compile` and 21–25% for eager. Every fp32
266
+ result matches fp64 to about 1e-7.
267
+
268
+ ![Unit-row forward + backward effective bandwidth per backend on three weight shapes, on a V100, RTX 2080 Ti, 3090 and 4090](docs/assets/kernels.png)
269
+
270
+ A unit-row Linear against a plain `nn.Linear`, forward + backward with the matmul, fp32 weights
271
+ under fp16 autocast: 96% of the plain layer's speed on a 4096 -> 11008 layer and 99% on 768 ->
272
+ 2048, with Triton or `torch.compile`; eager reaches 87% and 96%.
273
+
274
+ ![Unit-row Linear speed as a share of the plain Linear's, per backend, on three layer shapes, on an RTX 2080 Ti, 3090 and 4090](docs/assets/layer_speed.png)
275
+
276
+ On a 256 -> 768 layer the unit-row launches are a visible share of a 1 ms step where the matmul
277
+ finishes faster than the host launches (73% on the 3090), and hidden where it does not (98% on
278
+ the 2080 Ti). Small layers are bound by launch time, about 0.06 ms per call on an RTX 4090. In eager mode a
279
+ forward pre-hook computes the weights of every eligible layer in one autograd node and a few
280
+ launches (`ds.apply(..., group=True)`, the default); under `torch.compile` the op is traced as
281
+ plain torch ops and fused. Whole training step of the byte-level LM (8 blocks, dim 256, batch
282
+ 64 x 256, fp16 AMP) on an RTX 4090:
283
+
284
+ | preset | eager, per layer | eager, grouped | `torch.compile` |
285
+ | --- | --- | --- | --- |
286
+ | stock | 18.8 ms | 18.8 ms | 15.6 ms |
287
+ | matrices | 30.5 ms | 21.2 ms | 16.6 ms (+6%) |
288
+ | arch | 33.3 ms | 25.5 ms | 16.0 ms (+3%) |
289
+
290
+ `arch` in eager mode pays for its own extra norms and casts (830 kernel launches against 681);
291
+ compile fuses them. Peak memory under compile: 1.44 GB stock, 1.43 GB matrices, 1.55 GB arch.
292
+
293
+ | backend | used when | ops |
294
+ | --- | --- | --- |
295
+ | `triton` | CUDA, sm70 and up | every row op, grouped launch |
296
+ | `compile` | CUDA | `torch.compile` of the eager ops |
297
+ | `eager` | always | the reference, fp32 accumulation, fp64 kept |
298
+
299
+ `ds.apply(model, plan, backend=...)` pins one; by default the fastest available is used.
300
+ Benchmarks: `kogine run measure/ops/speed.py` (the op), `kogine run measure/ops/overhead.py`
301
+ (a layer against the plain layer).
302
+
303
+ ## Measured
304
+
305
+ These runs check one thing: whether the scales stay put and the loss trains normally. They report
306
+ held-out loss and hidden-state statistics only. All runs are in [`measure/`](measure) and run
307
+ through [kogine](https://github.com/KohakuBlueleaf/KohakuEngine); every number comes from one
308
+ config file.
309
+
310
+ | preset | what it is |
311
+ | --- | --- |
312
+ | `stock` | the model as written |
313
+ | `matrices` | `suggest(level="matrices")` on the stock model |
314
+ | `arch` | `suggest(level="absorb")` plus the architecture notes done in the model code (see [How it works](#how-it-works)) |
315
+
316
+ A run **failed** when it diverged or its best held-out loss stayed above 2.0.
317
+
318
+ ### Byte-level LM
319
+
320
+ A pre-norm transformer (dim 256, 8 blocks, SwiGLU) on the bytes of the Python standard library,
321
+ AdamW, constant learning rate, no weight decay, 5k steps unless stated.
322
+
323
+ **A: learning rate x precision.**
324
+
325
+ ![Byte-level LM, best held-out loss and peak residual stream against learning rate, fp16 and fp32, per preset](docs/assets/a_lr_precision.png)
326
+
327
+ | preset | precision | best loss (lr) | largest lr that trains |
328
+ | --- | --- | --- | --- |
329
+ | stock | fp16 | 0.947 (2e-3) | 5e-3 |
330
+ | stock | fp32 | 0.957 (2e-3) | 5e-3 |
331
+ | matrices | fp16 | 0.954 (5e-3) | 5e-2 |
332
+ | matrices | fp32 | 0.955 (5e-3) | 5e-2 |
333
+ | arch | fp16 | 0.930 (5e-3) | 1.0 |
334
+ | arch | fp32 | 0.936 (0.1) | 1.0 |
335
+
336
+ `arch` trains at every learning rate up to 1.0; past 0.2 its best loss rises (1.05 at 0.5, 1.00
337
+ at 1.0 in fp16). fp32 fails where fp16 does: stock at lr 1e-2 and above ends near loss 2.4 with a stream of 1e6
338
+ to 1e12 in fp32, and diverges in fp16. The precision is not the cause.
339
+
340
+ **B: longer runs, 16k steps** at lr 2e-3 and 1e-2, fp16.
341
+
342
+ ![Byte-level LM over 16k steps: peak stream, largest raw row length and largest writer gain against step](docs/assets/b_long.png)
343
+
344
+ | preset | lr 2e-3: best loss, peak stream | lr 1e-2: best loss, peak stream |
345
+ | --- | --- | --- |
346
+ | stock | 0.957, 1,438 | failed at step 1k |
347
+ | matrices | 0.958, 147 | 0.962, 770 |
348
+ | arch | 0.939, 184 | 0.939, 263 |
349
+
350
+ The corpus is 10.7 MB; past a few thousand steps every preset memorizes it and the held-out loss
351
+ climbs back to 1.1–1.2.
352
+
353
+ **C and E: depth 4 / 8 / 16 / 32 and width 128 / 256 / 512 / 1024**, peak stream:
354
+
355
+ <p align="center">
356
+ <img src="docs/assets/depth.png" width="49%" alt="Byte-level LM, peak stream against depth per preset">
357
+ <img src="docs/assets/width.png" width="49%" alt="Byte-level LM, peak stream against width per preset">
358
+ </p>
359
+
360
+ C, depth (best held-out loss):
361
+
362
+ | preset | lr | depth 4 | depth 8 | depth 16 | depth 32 |
363
+ | --- | --- | --- | --- | --- | --- |
364
+ | stock | 2e-3 | 0.995 | 0.956 | 0.941 | 0.936 |
365
+ | stock | 1e-2 | failed | failed | failed | failed |
366
+ | stock | 5e-2 | failed | failed | failed | failed |
367
+ | matrices | 2e-3 | 0.994 | 0.954 | 0.939 | 0.935 |
368
+ | matrices | 1e-2 | 1.006 | 0.960 | 0.939 | 0.932 |
369
+ | matrices | 5e-2 | 1.110 | 1.147 | 0.991 | failed |
370
+ | arch | 2e-3 | 0.946 | 0.936 | 0.932 | 0.927 |
371
+ | arch | 1e-2 | 0.938 | 0.937 | 0.925 | 0.925 |
372
+ | arch | 5e-2 | 0.943 | 0.953 | 0.938 | 0.925 |
373
+
374
+ **D: weight decay on stock** (best held-out loss, peak stream).
375
+
376
+ | weight decay | lr 1e-3 | lr 3e-3 | lr 1e-2 | lr 3e-2 | lr 0.1 |
377
+ | --- | --- | --- | --- | --- | --- |
378
+ | 0.01 | 0.975, 136 | 0.947, 791 | failed | failed | failed |
379
+ | 0.1 | 0.965, 52 | 0.942, 156 | 1.038, 6,790 | 1.299, 25,300 | failed |
380
+
381
+ Weight decay 0.1 keeps stock training at lr 1e-2 and 3e-2, with the stream still at 7k–25k.
382
+
383
+ E, width (best held-out loss):
384
+
385
+ | preset | lr | width 128 | width 256 | width 512 | width 1024 |
386
+ | --- | --- | --- | --- | --- | --- |
387
+ | stock | 2e-3 | 0.990 | 0.955 | 0.948 | failed |
388
+ | stock | 1e-2 | 1.035 | failed | failed | failed |
389
+ | stock | 5e-2 | failed | failed | failed | failed |
390
+ | matrices | 2e-3 | 0.987 | 0.958 | 0.940 | 0.982 |
391
+ | matrices | 1e-2 | 0.977 | 0.967 | 1.121 | 1.187 |
392
+ | matrices | 5e-2 | 0.970 | 1.047 | failed | failed |
393
+ | arch | 2e-3 | 0.970 | 0.938 | 0.932 | 0.953 |
394
+ | arch | 1e-2 | 0.951 | 0.942 | 0.940 | 0.944 |
395
+ | arch | 5e-2 | 0.952 | 0.942 | 0.935 | 0.946 |
396
+
397
+ Stock's stream grows with width (207, 516, 1,812 at lr 2e-3) and width 1024 diverges at the
398
+ smallest learning rate. `arch` trains at every depth and width at all three learning rates.
399
+
400
+ **Loss against stream size**, every run of A–E: the frontier per preset (left) and each setup's
401
+ learning-rate sweep as one line (right).
402
+
403
+ <p align="center">
404
+ <img src="docs/assets/pareto.png" width="49%" alt="Best held-out loss against peak stream for every byte-level LM run, Pareto frontier per preset">
405
+ <img src="docs/assets/pareto_setups.png" width="49%" alt="Best held-out loss against peak stream, one line per setup">
406
+ </p>
407
+
408
+ ### JiT-B/16 on Flowers-102
409
+
410
+ Pixel-space diffusion with the JiT recipe (x-prediction, velocity loss) at 256 px, batch 64, the
411
+ time and class as conditioning tokens, fp16.
412
+
413
+ ![JiT-B/16 at lr 1e-3: image-token stream RMS through depth, and its peak over 2k steps, for stock, arch with a final norm and arch](docs/assets/final_norm.png)
414
+
415
+ | model, lr 1e-3, 2k steps | stream RMS, block 0 -> 11 | peak | held-out loss |
416
+ | --- | --- | --- | --- |
417
+ | stock | 49 -> 150 | 1,694 | 0.419 |
418
+ | arch with a final norm | 19 -> 93 | 1,239 | 0.425 |
419
+ | arch | 1.4 -> 0.8 | 15 | 0.444 |
420
+
421
+ A final norm in front of the output makes the stream's scale free, and it grows in the patched
422
+ model as in stock. Without it, and with the context tokens read-only, the stream stays near 1.
423
+
424
+ ![JiT-B/16 over 10k steps per preset and learning rate: held-out velocity loss and peak stream](docs/assets/jit.png)
425
+
426
+ The loss is compared from step 2k: the first few hundred steps' losses are outliers.
427
+
428
+ | preset | lr | best held-out loss, steps 2k-10k | peak stream |
429
+ | --- | --- | --- | --- |
430
+ | stock | 2e-4 | 0.264 | 779 |
431
+ | stock | 1e-3 | 0.219 | 4,506 |
432
+ | stock | 3e-3 | 0.247 | 23,804 |
433
+ | matrices | 2e-4 | 0.260 | 710 |
434
+ | matrices | 1e-3 | 0.216 | 1,294 |
435
+ | matrices | 3e-3 | 0.217 | 2,055 |
436
+ | arch | 2e-4 | 0.234 | 29 |
437
+ | arch | 1e-3 | 0.175 | 28 |
438
+ | arch | 3e-3 | 0.183 | 86 |
439
+
440
+ Over 10k steps stock's stream peaks at 779 to 23,804, rising with the learning rate; `arch` stays
441
+ at 28 to 86, and its held-out loss is the lowest at every learning rate.
442
+
443
+ Reproduce, for example:
444
+
445
+ ```bash
446
+ kogine run measure/bytelm/train.py --set BUILD_CORPUS=true
447
+ kogine workflow parallel measure/bytelm/train.py --config measure/bytelm/configs/a_stock.py --workers 2
448
+ kogine run measure/plots.py
449
+ ```
450
+
451
+ ## Repository
452
+
453
+ | path | contents |
454
+ | --- | --- |
455
+ | `src/dragonscale/` | the library: analysis, plans, patching, the grouped launch, the gradient decorator, unit-row modules |
456
+ | `src/dragonscale_kernels/` | the row ops per backend: eager reference, `torch.compile`, Triton |
457
+ | `src/dragonscale_common/` | helpers shared by both, without torch: logger, name registry, dotted-path import, problem lists |
458
+ | `measure/` | experiments, op benchmarks and figures, one folder each, run with kogine |
459
+ | `tests/` | patch / remove / bake / canonicalize, the grouped launch, and the analysis on hand-checked models |
460
+
461
+ ## License
462
+
463
+ Apache-2.0.