dew-lm 1.0.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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}"
dew/export.py ADDED
@@ -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