dew-lm 1.0.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.
- dew_lm-1.0.0/LICENSE +215 -0
- dew_lm-1.0.0/PKG-INFO +66 -0
- dew_lm-1.0.0/README.md +44 -0
- dew_lm-1.0.0/dew/__init__.py +23 -0
- dew_lm-1.0.0/dew/configuration_dew.py +144 -0
- dew_lm-1.0.0/dew/export.py +87 -0
- dew_lm-1.0.0/dew/modeling_dew.py +569 -0
- dew_lm-1.0.0/dew/ops.py +152 -0
- dew_lm-1.0.0/dew/presets.py +64 -0
- dew_lm-1.0.0/dew/selftest.py +312 -0
- dew_lm-1.0.0/dew_lm.egg-info/PKG-INFO +66 -0
- dew_lm-1.0.0/dew_lm.egg-info/SOURCES.txt +15 -0
- dew_lm-1.0.0/dew_lm.egg-info/dependency_links.txt +1 -0
- dew_lm-1.0.0/dew_lm.egg-info/requires.txt +11 -0
- dew_lm-1.0.0/dew_lm.egg-info/top_level.txt +1 -0
- dew_lm-1.0.0/pyproject.toml +26 -0
- dew_lm-1.0.0/setup.cfg +4 -0
dew_lm-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
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.
|
|
203
|
+
Copyright 2024 Olaverse Labs
|
|
204
|
+
|
|
205
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
206
|
+
you may not use this file except in compliance with the License.
|
|
207
|
+
You may obtain a copy of the License at
|
|
208
|
+
|
|
209
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
210
|
+
|
|
211
|
+
Unless required by applicable law or agreed to in writing, software
|
|
212
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
213
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
214
|
+
implied. See the License for the specific language governing
|
|
215
|
+
permissions and limitations under the License.
|
dew_lm-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dew-lm
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Dew: hybrid Gated DeltaNet + attention LM architecture with the Nap thinker and doorman looping
|
|
5
|
+
Author: Olaverse
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://huggingface.co/olaverse
|
|
8
|
+
Project-URL: Repository, https://github.com/Olaverse-Labs/dew
|
|
9
|
+
Project-URL: Issues, https://github.com/Olaverse-Labs/dew/issues
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: torch>=2.4
|
|
14
|
+
Provides-Extra: hf
|
|
15
|
+
Requires-Dist: transformers>=4.44; extra == "hf"
|
|
16
|
+
Provides-Extra: fast
|
|
17
|
+
Requires-Dist: flash-linear-attention; extra == "fast"
|
|
18
|
+
Provides-Extra: export
|
|
19
|
+
Requires-Dist: onnx; extra == "export"
|
|
20
|
+
Requires-Dist: onnxruntime; extra == "export"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# Dew
|
|
24
|
+
|
|
25
|
+
Dew is a small-model architecture family: Gated DeltaNet layers (a linear-time recurrent memory) mixed with attention,
|
|
26
|
+
with optional extras for thinking longer on hard words. It runs as a causal language model or as a bidirectional
|
|
27
|
+
encoder, plugs into Hugging Face `transformers`, and exports to ONNX.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install dew-lm # PyTorch only
|
|
31
|
+
pip install "dew-lm[hf]" # + transformers Auto classes
|
|
32
|
+
pip install "dew-lm[export]" # + ONNX export
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from dew import DewForCausalLM, dew_config, fit_params
|
|
37
|
+
|
|
38
|
+
cfg = fit_params(dew_config("dew-1-hybrid", vocab_size=16384), 15_000_000) # size it to ~15M parameters
|
|
39
|
+
model = DewForCausalLM(cfg)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Presets
|
|
43
|
+
|
|
44
|
+
| Preset | Layers | Use |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `dew-1-hybrid` | DeltaNet, DeltaNet, attention, repeated | causal LM (the default) |
|
|
47
|
+
| `dew-1-hybrid-light` | DeltaNet, attention, attention, repeated | causal LM, more attention |
|
|
48
|
+
| `dew-1-dense` | attention only | causal LM baseline |
|
|
49
|
+
| `dew-1-enc-hybrid` | hybrid, bidirectional | encoder (masked LM) |
|
|
50
|
+
| `dew-1-enc-dense` | attention only, bidirectional | encoder baseline |
|
|
51
|
+
| `dew-1-nap`, `dew-1-napskip`, `dew-1-loop` | hybrid with the Nap mixture-of-experts feed-forward, skipping and looping | research |
|
|
52
|
+
|
|
53
|
+
The YellowMIST models ([olaverse on Hugging Face](https://huggingface.co/olaverse)) are built on Dew.
|
|
54
|
+
|
|
55
|
+
## Checks
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
python -m dew.selftest # chunked == step-by-step maths, presets, Hugging Face round trip, ONNX export
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
On a GPU, `flash-linear-attention` (`pip install "dew-lm[fast]"`) speeds up training; it is checked against the
|
|
62
|
+
PyTorch path when installed.
|
|
63
|
+
|
|
64
|
+
## Licence
|
|
65
|
+
|
|
66
|
+
Apache-2.0.
|
dew_lm-1.0.0/README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Dew
|
|
2
|
+
|
|
3
|
+
Dew is a small-model architecture family: Gated DeltaNet layers (a linear-time recurrent memory) mixed with attention,
|
|
4
|
+
with optional extras for thinking longer on hard words. It runs as a causal language model or as a bidirectional
|
|
5
|
+
encoder, plugs into Hugging Face `transformers`, and exports to ONNX.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install dew-lm # PyTorch only
|
|
9
|
+
pip install "dew-lm[hf]" # + transformers Auto classes
|
|
10
|
+
pip install "dew-lm[export]" # + ONNX export
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from dew import DewForCausalLM, dew_config, fit_params
|
|
15
|
+
|
|
16
|
+
cfg = fit_params(dew_config("dew-1-hybrid", vocab_size=16384), 15_000_000) # size it to ~15M parameters
|
|
17
|
+
model = DewForCausalLM(cfg)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Presets
|
|
21
|
+
|
|
22
|
+
| Preset | Layers | Use |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| `dew-1-hybrid` | DeltaNet, DeltaNet, attention, repeated | causal LM (the default) |
|
|
25
|
+
| `dew-1-hybrid-light` | DeltaNet, attention, attention, repeated | causal LM, more attention |
|
|
26
|
+
| `dew-1-dense` | attention only | causal LM baseline |
|
|
27
|
+
| `dew-1-enc-hybrid` | hybrid, bidirectional | encoder (masked LM) |
|
|
28
|
+
| `dew-1-enc-dense` | attention only, bidirectional | encoder baseline |
|
|
29
|
+
| `dew-1-nap`, `dew-1-napskip`, `dew-1-loop` | hybrid with the Nap mixture-of-experts feed-forward, skipping and looping | research |
|
|
30
|
+
|
|
31
|
+
The YellowMIST models ([olaverse on Hugging Face](https://huggingface.co/olaverse)) are built on Dew.
|
|
32
|
+
|
|
33
|
+
## Checks
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
python -m dew.selftest # chunked == step-by-step maths, presets, Hugging Face round trip, ONNX export
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
On a GPU, `flash-linear-attention` (`pip install "dew-lm[fast]"`) speeds up training; it is checked against the
|
|
40
|
+
PyTorch path when installed.
|
|
41
|
+
|
|
42
|
+
## Licence
|
|
43
|
+
|
|
44
|
+
Apache-2.0.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Dew: an LLM architecture family (Gated DeltaNet + attention hybrid, Nap thinker MoE,
|
|
2
|
+
doorman napping and looping). model_type "dew".
|
|
3
|
+
|
|
4
|
+
from dew import DewConfig, DewForCausalLM, dew_config, fit_params
|
|
5
|
+
model = DewForCausalLM(dew_config("dew-1-loop", vocab_size=32000, hidden_size=512))
|
|
6
|
+
|
|
7
|
+
Importing this package registers Dew with transformers' Auto classes.
|
|
8
|
+
"""
|
|
9
|
+
from .configuration_dew import DewConfig
|
|
10
|
+
from .modeling_dew import STAT_NAMES, DewForCausalLM, DewForMaskedLM, DewModel
|
|
11
|
+
from .presets import PRESETS, count_params, dew_config, fit_params
|
|
12
|
+
|
|
13
|
+
__version__ = "1.0.0"
|
|
14
|
+
__all__ = ["DewConfig", "DewModel", "DewForCausalLM", "DewForMaskedLM", "PRESETS", "dew_config", "fit_params", "count_params", "STAT_NAMES"]
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM
|
|
18
|
+
AutoConfig.register("dew", DewConfig, exist_ok=True)
|
|
19
|
+
AutoModel.register(DewConfig, DewModel, exist_ok=True)
|
|
20
|
+
AutoModelForCausalLM.register(DewConfig, DewForCausalLM, exist_ok=True)
|
|
21
|
+
AutoModelForMaskedLM.register(DewConfig, DewForMaskedLM, exist_ok=True)
|
|
22
|
+
except Exception: # transformers missing or too old: the model still works in plain PyTorch
|
|
23
|
+
pass
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""DewConfig: one config describes every Dew model, from a 15M phone model to a large LLM.
|
|
2
|
+
|
|
3
|
+
The stack is embedding -> prelude -> body x (up to max_loops passes) -> coda -> norm -> head.
|
|
4
|
+
Each of prelude / body / coda is a string of layer types:
|
|
5
|
+
|
|
6
|
+
G Gated DeltaNet layer (fixed-size memory, linear in text length)
|
|
7
|
+
A attention layer (Qwen3-style: grouped-query, q/k norm, RoPE)
|
|
8
|
+
|
|
9
|
+
Examples
|
|
10
|
+
transformer prelude="", body="AAAAAAAA", coda="", max_loops=1, ffn="dense"
|
|
11
|
+
hybrid (2:1) prelude="", body="GGAGGA", coda="", max_loops=1, ffn="dense"
|
|
12
|
+
Nap hybrid same as hybrid with ffn="nap"
|
|
13
|
+
Nap & Loop prelude="G", body="GGA", coda="A", max_loops=3, doorman=True, ffn="nap"
|
|
14
|
+
|
|
15
|
+
Every layer has a mixer (G or A) and a thinker (ffn): "dense" is a SwiGLU block, "nap" is the
|
|
16
|
+
Nap thinker (router over num_experts small experts + a nap room that does nothing, and a
|
|
17
|
+
shared expert with a per-word on/off switch).
|
|
18
|
+
|
|
19
|
+
causal=False makes an encoder (masked-LM base): attention sees both sides, and every DeltaNet
|
|
20
|
+
layer reads the text forwards and backwards (two memories, outputs added). Encoders run one pass,
|
|
21
|
+
no doorman; padding is masked by `attention_mask` and writes nothing to either memory.
|
|
22
|
+
|
|
23
|
+
The doorman (doorman=True) decides per word, before every body pass, whether the word goes
|
|
24
|
+
through the body again. Stopping is final. A word that does not take a pass neither writes
|
|
25
|
+
DeltaNet memory nor enters that pass's attention memory. With max_loops=1 the doorman is
|
|
26
|
+
layer napping; with max_loops>1 it is "Nap & Loop".
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
from transformers import PretrainedConfig
|
|
32
|
+
except ImportError: # lets the model run without transformers installed
|
|
33
|
+
class PretrainedConfig: # type: ignore[no-redef]
|
|
34
|
+
model_type = ""
|
|
35
|
+
|
|
36
|
+
def __init__(self, **kw):
|
|
37
|
+
for k, v in kw.items():
|
|
38
|
+
setattr(self, k, v)
|
|
39
|
+
|
|
40
|
+
def to_dict(self):
|
|
41
|
+
return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class DewConfig(PretrainedConfig):
|
|
45
|
+
model_type = "dew"
|
|
46
|
+
keys_to_ignore_at_inference = ["past_key_values"]
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
vocab_size: int = 16384,
|
|
51
|
+
hidden_size: int = 320,
|
|
52
|
+
causal: bool = True,
|
|
53
|
+
# layout
|
|
54
|
+
prelude: str = "G",
|
|
55
|
+
body: str = "GGA",
|
|
56
|
+
coda: str = "A",
|
|
57
|
+
max_loops: int = 3,
|
|
58
|
+
doorman: bool = True,
|
|
59
|
+
target_passes: float = 1.33,
|
|
60
|
+
pass_cap_prob: float = 0.25,
|
|
61
|
+
warm_start: float = 0.2,
|
|
62
|
+
# attention (A)
|
|
63
|
+
num_attention_heads: int = 5,
|
|
64
|
+
num_key_value_heads: int | None = None,
|
|
65
|
+
head_dim: int | None = None,
|
|
66
|
+
qk_norm: bool = True,
|
|
67
|
+
rope_theta: float = 10000.0,
|
|
68
|
+
max_position_embeddings: int = 2048,
|
|
69
|
+
# Gated DeltaNet (G)
|
|
70
|
+
linear_num_heads: int | None = None,
|
|
71
|
+
linear_head_dim: int | None = None,
|
|
72
|
+
conv_kernel: int = 4,
|
|
73
|
+
# thinker
|
|
74
|
+
ffn: str = "nap",
|
|
75
|
+
intermediate_size: int = 864,
|
|
76
|
+
num_experts: int = 8,
|
|
77
|
+
expert_intermediate_size: int = 160,
|
|
78
|
+
shared_intermediate_size: int = 320,
|
|
79
|
+
router_threshold: float = 0.2,
|
|
80
|
+
shared_target: float = 0.15,
|
|
81
|
+
# auxiliary losses
|
|
82
|
+
aux_balance_coef: float = 0.01,
|
|
83
|
+
aux_passes_coef: float = 0.5,
|
|
84
|
+
aux_shared_coef: float = 0.5,
|
|
85
|
+
# misc
|
|
86
|
+
rms_norm_eps: float = 1e-6,
|
|
87
|
+
initializer_range: float = 0.02,
|
|
88
|
+
tie_word_embeddings: bool = True,
|
|
89
|
+
**kwargs,
|
|
90
|
+
):
|
|
91
|
+
for s, name in ((prelude, "prelude"), (body, "body"), (coda, "coda")):
|
|
92
|
+
if set(s) - {"G", "A"}:
|
|
93
|
+
raise ValueError(f"{name} may only contain G and A, got {s!r}")
|
|
94
|
+
if not body and max_loops > 1:
|
|
95
|
+
raise ValueError("max_loops > 1 needs a body")
|
|
96
|
+
if not causal and (max_loops > 1 or doorman):
|
|
97
|
+
raise ValueError("encoders (causal=False) run one pass without a doorman")
|
|
98
|
+
if ffn not in ("dense", "nap"):
|
|
99
|
+
raise ValueError("ffn must be 'dense' or 'nap'")
|
|
100
|
+
self.vocab_size = vocab_size
|
|
101
|
+
self.hidden_size = hidden_size
|
|
102
|
+
self.causal = bool(causal)
|
|
103
|
+
self.prelude, self.body, self.coda = prelude, body, coda
|
|
104
|
+
self.max_loops = max(1, int(max_loops))
|
|
105
|
+
self.doorman = bool(doorman)
|
|
106
|
+
self.target_passes = target_passes
|
|
107
|
+
self.pass_cap_prob = pass_cap_prob
|
|
108
|
+
self.warm_start = warm_start
|
|
109
|
+
self.num_attention_heads = num_attention_heads
|
|
110
|
+
self.num_key_value_heads = num_key_value_heads or num_attention_heads
|
|
111
|
+
self.head_dim = head_dim or hidden_size // num_attention_heads
|
|
112
|
+
self.qk_norm = qk_norm
|
|
113
|
+
self.rope_theta = rope_theta
|
|
114
|
+
self.max_position_embeddings = max_position_embeddings
|
|
115
|
+
self.linear_num_heads = linear_num_heads or num_attention_heads
|
|
116
|
+
self.linear_head_dim = linear_head_dim or hidden_size // self.linear_num_heads
|
|
117
|
+
self.conv_kernel = conv_kernel
|
|
118
|
+
self.ffn = ffn
|
|
119
|
+
self.intermediate_size = intermediate_size
|
|
120
|
+
self.num_experts = num_experts
|
|
121
|
+
self.expert_intermediate_size = expert_intermediate_size
|
|
122
|
+
self.shared_intermediate_size = shared_intermediate_size
|
|
123
|
+
self.router_threshold = router_threshold
|
|
124
|
+
self.shared_target = shared_target
|
|
125
|
+
self.aux_balance_coef = aux_balance_coef
|
|
126
|
+
self.aux_passes_coef = aux_passes_coef
|
|
127
|
+
self.aux_shared_coef = aux_shared_coef
|
|
128
|
+
self.rms_norm_eps = rms_norm_eps
|
|
129
|
+
self.initializer_range = initializer_range
|
|
130
|
+
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def layer_passes(self) -> float:
|
|
134
|
+
"""Layer-passes per word at the target loop count (compute, not parameters)."""
|
|
135
|
+
passes = self.target_passes if (self.doorman and self.max_loops > 1) else self.max_loops
|
|
136
|
+
return len(self.prelude) + passes * len(self.body) + len(self.coda)
|
|
137
|
+
|
|
138
|
+
def describe(self) -> str:
|
|
139
|
+
loop = f" x{self.max_loops} passes" + (" (doorman)" if self.doorman else "") if self.max_loops > 1 else \
|
|
140
|
+
(" (doorman napping)" if self.doorman else "")
|
|
141
|
+
kind = "Dew-enc" if not self.causal else "Dew"
|
|
142
|
+
think = (f" {self.num_experts}x{self.expert_intermediate_size}+nap+shared{self.shared_intermediate_size}"
|
|
143
|
+
if self.ffn == "nap" else f" {self.intermediate_size}")
|
|
144
|
+
return f"{kind} [{self.prelude or '-'} | {self.body}{loop} | {self.coda or '-'}] d={self.hidden_size} ffn={self.ffn}{think}"
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""ONNX export of Dew as a one-word step model.
|
|
2
|
+
|
|
3
|
+
Inputs : input_ids [B] int64, position [1] int64, then every state tensor from init_state()
|
|
4
|
+
Outputs: logits [B, vocab], then the new state tensors (same order, names prefixed "new_")
|
|
5
|
+
|
|
6
|
+
DeltaNet memories and convolution buffers have a fixed size; attention keys/values/keep grow by
|
|
7
|
+
one word per step (dynamic axis "p<i>"). Start from zero-length attention state (see
|
|
8
|
+
initial_state_numpy) and feed each step's outputs back in.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import torch
|
|
16
|
+
import torch.nn as nn
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _Step(nn.Module):
|
|
20
|
+
def __init__(self, lm):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.lm = lm
|
|
23
|
+
|
|
24
|
+
def forward(self, input_ids, position, *state):
|
|
25
|
+
logits, new = self.lm.step(input_ids, position, list(state))
|
|
26
|
+
return (logits, *new)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def initial_state_numpy(lm, batch: int = 1):
|
|
30
|
+
return [t.cpu().numpy() for t in lm.init_state(batch, device=torch.device("cpu"))]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def export_onnx(lm, out_dir, name: str = "dew", int8: bool = True, opset: int = 17) -> dict:
|
|
34
|
+
lm = lm.float().eval().cpu()
|
|
35
|
+
out_dir = Path(out_dir)
|
|
36
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
kinds = lm.model.state_kinds()
|
|
38
|
+
# trace with two words already in the attention memory, so its length is a real dynamic axis
|
|
39
|
+
state = lm.init_state(1, device=torch.device("cpu"))
|
|
40
|
+
with torch.no_grad():
|
|
41
|
+
for t, tok in enumerate((1, 2)):
|
|
42
|
+
_, state = lm.step(torch.tensor([tok]), torch.tensor([t]), state)
|
|
43
|
+
ids, pos = torch.tensor([3]), torch.tensor([2])
|
|
44
|
+
in_names = ["input_ids", "position"] + kinds
|
|
45
|
+
out_names = ["logits"] + [f"new_{k}" for k in kinds]
|
|
46
|
+
dyn = {"input_ids": {0: "batch"}, "logits": {0: "batch"}}
|
|
47
|
+
for i, k in enumerate(kinds):
|
|
48
|
+
ax = {0: "batch"}
|
|
49
|
+
if k.endswith(("_keys", "_values")):
|
|
50
|
+
ax[2] = f"p{i}"
|
|
51
|
+
elif k.endswith("_keep"):
|
|
52
|
+
ax[1] = f"p{i}"
|
|
53
|
+
dyn[k] = ax
|
|
54
|
+
dyn[f"new_{k}"] = {a: (v + "n" if v.startswith("p") else v) for a, v in ax.items()}
|
|
55
|
+
f = out_dir / f"{name}.onnx"
|
|
56
|
+
with torch.no_grad():
|
|
57
|
+
torch.onnx.export(_Step(lm), (ids, pos, *state), str(f), input_names=in_names, output_names=out_names,
|
|
58
|
+
dynamic_axes=dyn, opset_version=opset, dynamo=False)
|
|
59
|
+
res = {"onnx": str(f), "onnx_mb": f.stat().st_size / 1e6}
|
|
60
|
+
if int8:
|
|
61
|
+
from onnxruntime.quantization import QuantType, quantize_dynamic
|
|
62
|
+
q = out_dir / f"{name}.int8.onnx"
|
|
63
|
+
quantize_dynamic(str(f), str(q), weight_type=QuantType.QInt8)
|
|
64
|
+
res.update(int8=str(q), int8_mb=q.stat().st_size / 1e6)
|
|
65
|
+
return res
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def verify_onnx(lm, onnx_path, n_words: int = 24, seed: int = 0) -> float:
|
|
69
|
+
"""Feed the same words to ONNX (step by step) and to the PyTorch full-sequence forward.
|
|
70
|
+
Returns the largest absolute logit difference."""
|
|
71
|
+
import onnxruntime as ort
|
|
72
|
+
lm = lm.float().eval().cpu()
|
|
73
|
+
g = torch.Generator().manual_seed(seed)
|
|
74
|
+
ids = torch.randint(0, lm.config.vocab_size, (1, n_words), generator=g)
|
|
75
|
+
with torch.no_grad():
|
|
76
|
+
ref = lm(ids).logits[0].numpy()
|
|
77
|
+
sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
|
|
78
|
+
names = [i.name for i in sess.get_inputs()]
|
|
79
|
+
state = initial_state_numpy(lm)
|
|
80
|
+
worst = 0.0
|
|
81
|
+
for t in range(n_words):
|
|
82
|
+
feeds = {"input_ids": ids[:, t].numpy(), "position": np.array([t], dtype=np.int64)}
|
|
83
|
+
feeds.update({n: s for n, s in zip(names[2:], state)})
|
|
84
|
+
out = sess.run(None, feeds)
|
|
85
|
+
worst = max(worst, float(np.abs(out[0][0] - ref[t]).max()))
|
|
86
|
+
state = out[1:]
|
|
87
|
+
return worst
|