"""Dew: hybrid Gated DeltaNet + attention LM with the Nap thinker and doorman looping. Two ways to run a model: * forward(input_ids) whole sequence at once (training, scoring) * step(ids, position, state) one word at a time with a fixed-size DeltaNet state and an attention cache (decoding, ONNX export). Gives the same logits. """ from __future__ import annotations import math from dataclasses import dataclass from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from .configuration_dew import DewConfig from .ops import delta_step, gated_delta_rule, l2norm try: from transformers import PreTrainedModel from transformers.utils import ModelOutput try: from transformers import GenerationMixin except ImportError: GenerationMixin = object # type: ignore[misc,assignment] _HF = True except ImportError: # plain PyTorch fallback _HF = False PreTrainedModel = nn.Module # type: ignore[misc,assignment] ModelOutput = object # type: ignore[misc,assignment] GenerationMixin = object # type: ignore[misc,assignment] @dataclass class DewCausalLMOutput(ModelOutput): loss: Optional[torch.Tensor] = None logits: Optional[torch.Tensor] = None aux_loss: Optional[torch.Tensor] = None router_stats: Optional[torch.Tensor] = None # [passes/word, nap share, experts/word, shared on, nap-room share] STAT_NAMES = ("passes", "nap", "experts", "shared", "naproom") # --- small pieces -------------------------------------------------------------------------- class DewRMSNorm(nn.Module): def __init__(self, d: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(d)) self.eps = eps def forward(self, x): dt = x.dtype x = x.float() return (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight.float()).to(dt) def rope_tables(pos: torch.Tensor, dim: int, theta: float): """pos: [T] -> cos, sin: [T, dim] (HF rotate-half layout).""" inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=pos.device, dtype=torch.float32) / dim)) f = pos.float()[:, None] * inv[None] emb = torch.cat([f, f], -1) return emb.cos(), emb.sin() def _rot(x): a, b = x.chunk(2, -1) return torch.cat([-b, a], -1) def apply_rope(x, cos, sin): return (x.float() * cos + _rot(x.float()) * sin).to(x.dtype) # --- mixers -------------------------------------------------------------------------------- class DewAttention(nn.Module): """Qwen3-style attention: grouped-query heads, RMSNorm on q and k, RoPE. `keep` ([B, T], 1 = word stored in this layer's memory) hides napping words from later words.""" n_state = 3 def __init__(self, c: DewConfig): super().__init__() self.h, self.kvh, self.hd = c.num_attention_heads, c.num_key_value_heads, c.head_dim self.causal = c.causal d = c.hidden_size self.q_proj = nn.Linear(d, self.h * self.hd, bias=False) self.k_proj = nn.Linear(d, self.kvh * self.hd, bias=False) self.v_proj = nn.Linear(d, self.kvh * self.hd, bias=False) self.o_proj = nn.Linear(self.h * self.hd, d, bias=False) self.q_norm = DewRMSNorm(self.hd, c.rms_norm_eps) if c.qk_norm else None self.k_norm = DewRMSNorm(self.hd, c.rms_norm_eps) if c.qk_norm else None def _qkv(self, x): shp = x.shape[:-1] q = self.q_proj(x).view(*shp, self.h, self.hd) k = self.k_proj(x).view(*shp, self.kvh, self.hd) v = self.v_proj(x).view(*shp, self.kvh, self.hd) if self.q_norm is not None: q, k = self.q_norm(q), self.k_norm(k) return q, k, v def _rep(self, t): return t if self.h == self.kvh else t.repeat_interleave(self.h // self.kvh, 1) def forward(self, x, keep, cos, sin): B, T, _ = x.shape q, k, v = (t.transpose(1, 2) for t in self._qkv(x)) # [B, heads, T, hd] q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) k, v = self._rep(k), self._rep(v) if keep is None: y = F.scaled_dot_product_attention(q, k, v, is_causal=self.causal) else: eye = torch.eye(T, dtype=torch.bool, device=x.device) mask = (keep > 0.5)[:, None, :] | eye # a word always sees itself if self.causal: mask = mask & torch.ones(T, T, dtype=torch.bool, device=x.device).tril() y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask[:, None]) return self.o_proj(y.transpose(1, 2).reshape(B, T, self.h * self.hd)) def init_state(self, B, device, dtype): z = torch.zeros(B, self.kvh, 0, self.hd, device=device, dtype=dtype) return [z, z.clone(), torch.zeros(B, 0, device=device, dtype=dtype)] def step(self, x, m, cos, sin, K, V, keep): q, k, v = (t[:, :, None] for t in self._qkv(x)) # [B, heads, 1, hd] q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) K = torch.cat([K, k.to(K.dtype)], 2) V = torch.cat([V, v.to(V.dtype)], 2) keep = torch.cat([keep, m[:, None].to(keep.dtype)], 1) allow = torch.cat([keep[:, :-1], torch.ones_like(keep[:, :1])], 1) att = (q.float() @ self._rep(K).float().transpose(-1, -2)) * self.hd ** -0.5 # [B, h, 1, P] att = att + (allow[:, None, None, :].float() - 1.0) * 1e9 y = torch.softmax(att, -1) @ self._rep(V).float() return self.o_proj(y.reshape(x.shape[0], self.h * self.hd).to(x.dtype)), K, V, keep class DewGatedDeltaNet(nn.Module): """Gated DeltaNet (Yang et al. 2024) with short causal convolutions and an output gate. `m` ([B, T], 0 = napping) zeroes the word's write strength and decay, and its input to the convolutions, so a napping word leaves the memory exactly as it was.""" n_state = 2 def __init__(self, c: DewConfig): super().__init__() self.H, self.dk = c.linear_num_heads, c.linear_head_dim inner = self.H * self.dk d = c.hidden_size self.inner, self.kconv = inner, c.conv_kernel self.q_proj = nn.Linear(d, inner, bias=False) self.k_proj = nn.Linear(d, inner, bias=False) self.v_proj = nn.Linear(d, inner, bias=False) self.g_proj = nn.Linear(d, inner, bias=False) self.a_proj = nn.Linear(d, self.H, bias=False) self.b_proj = nn.Linear(d, self.H, bias=False) self.conv = nn.Conv1d(3 * inner, 3 * inner, c.conv_kernel, groups=3 * inner, bias=False) self.A_log = nn.Parameter(torch.zeros(self.H)) self.dt_bias = nn.Parameter(torch.zeros(self.H)) self.o_norm = DewRMSNorm(self.dk, c.rms_norm_eps) self.o_proj = nn.Linear(inner, d, bias=False) self.reset_gates() @torch.no_grad() def reset_gates(self): if self.A_log.is_meta: return self.A_log.copy_(torch.empty(self.H).uniform_(1, 16).log()) dt = torch.exp(torch.rand(self.H) * (math.log(0.1) - math.log(0.001)) + math.log(0.001)).clamp(min=1e-4) self.dt_bias.copy_(dt + torch.log(-torch.expm1(-dt))) # inverse softplus def _gates(self, x, m): beta = torch.sigmoid(self.b_proj(x).float()) g = -self.A_log.float().exp() * F.softplus(self.a_proj(x).float() + self.dt_bias.float()) if m is not None: beta, g = beta * m[..., None], g * m[..., None] return g, beta def _split(self, qkv, shp): q, k, v = qkv.split(self.inner, -1) q, k, v = (t.reshape(*shp, self.H, self.dk) for t in (q, k, v)) return l2norm(q.float()).to(v.dtype), l2norm(k.float()).to(v.dtype), v def forward(self, x, m, cos=None, sin=None): B, T, _ = x.shape xin = x if m is None else x * m[..., None].to(x.dtype) qkv = torch.cat([self.q_proj(xin), self.k_proj(xin), self.v_proj(xin)], -1) qkv = F.silu(self.conv(F.pad(qkv.transpose(1, 2), (self.kconv - 1, 0))).transpose(1, 2)) q, k, v = self._split(qkv, (B, T)) g, beta = self._gates(x, m) o = gated_delta_rule(q.contiguous(), k.contiguous(), v.contiguous(), g.contiguous(), beta.contiguous()) o = self.o_norm(o) * F.silu(self.g_proj(x)).view(B, T, self.H, self.dk).to(o.dtype) return self.o_proj(o.reshape(B, T, self.inner)) def init_state(self, B, device, dtype): return [torch.zeros(B, self.H, self.dk, self.dk, device=device, dtype=torch.float32), torch.zeros(B, 3 * self.inner, self.kconv - 1, device=device, dtype=dtype)] def step(self, x, m, cos, sin, S, cbuf): B = x.shape[0] xin = x * m[:, None].to(x.dtype) new = torch.cat([self.q_proj(xin), self.k_proj(xin), self.v_proj(xin)], -1) win = torch.cat([cbuf, new[..., None].to(cbuf.dtype)], -1) # oldest .. newest qkv = F.silu((win * self.conv.weight[:, 0, :].to(win.dtype)).sum(-1)) q, k, v = self._split(qkv, (B,)) g, beta = self._gates(x, None) g, beta = g * m[:, None], beta * m[:, None] o, S = delta_step(q.float(), k.float(), v.float(), g, beta, S) o = self.o_norm(o.to(x.dtype)) * F.silu(self.g_proj(x)).view(B, self.H, self.dk) return self.o_proj(o.reshape(B, self.inner)), S, win[..., 1:] class DewBiGatedDeltaNet(nn.Module): """Encoder DeltaNet: one Gated DeltaNet reads left to right, a second reads right to left; outputs add. Padding (m = 0) writes nothing to either memory, so a padded batch gives the same outputs.""" n_state = 0 def __init__(self, c: DewConfig): super().__init__() self.fwd, self.bwd = DewGatedDeltaNet(c), DewGatedDeltaNet(c) def forward(self, x, m, cos=None, sin=None): mb = None if m is None else m.flip(1) return self.fwd(x, m) + self.bwd(x.flip(1), mb).flip(1) # --- thinkers ------------------------------------------------------------------------------ class DewMLP(nn.Module): def __init__(self, d: int, f: int): super().__init__() self.gate_up = nn.Linear(d, 2 * f, bias=False) self.down = nn.Linear(f, d, bias=False) def forward(self, x, need_aux: bool = True): g, u = self.gate_up(x).chunk(2, -1) return self.down(F.silu(g) * u), None, None class DewNapThinker(nn.Module): """Router over E small experts plus a nap room (no expert, no cost). Every expert whose router share is >= router_threshold runs (the top slot always counts, so a word can nap); a shared expert is switched on or off per word. All experts run as one grouped matmul.""" def __init__(self, c: DewConfig): super().__init__() d, E, fe, fs = c.hidden_size, c.num_experts, c.expert_intermediate_size, c.shared_intermediate_size self.E, self.fe, self.c = E, fe, c self.router = nn.Linear(d, E + 1, bias=False) self.experts_in = nn.Linear(d, E * 2 * fe, bias=False) # per expert: [gate | up] self.experts_out = nn.Linear(E * fe, d, bias=False) self.shared = DewMLP(d, fs) self.switch = nn.Linear(d, 1, bias=True) def forward(self, x, need_aux: bool = True): shp = x.shape x2 = x.reshape(-1, shp[-1]) N, E, fe = x2.shape[0], self.E, self.fe p = torch.softmax(self.router(x2).float(), -1) # [N, E + 1], last = nap room sel = (p >= self.c.router_threshold) | (p >= p.amax(-1, keepdim=True)) w = (p * sel)[:, :E] h = self.experts_in(x2).view(N, E, 2 * fe) a = F.silu(h[..., :fe]) * h[..., fe:] * w[..., None].to(h.dtype) y = self.experts_out(a.reshape(N, E * fe)) sw = torch.sigmoid(self.switch(x2).float()).squeeze(-1) on = (sw > 0.5).float() gate = on + sw - sw.detach() # hard switch, soft gradient y = y + gate[:, None].to(y.dtype) * self.shared(x2)[0] if not need_aux: return y.view(shp), None, None f, P = sel.float().mean(0), p.mean(0) aux = self.c.aux_balance_coef * (E + 1) * (f * P).sum() + self.c.aux_shared_coef * (sw.mean() - self.c.shared_target) ** 2 stats = torch.stack([sel[:, :E].float().sum(1).mean(), on.mean(), (~sel[:, :E].any(1)).float().mean()]).detach() return y.view(shp), aux, stats # --- layer and model ----------------------------------------------------------------------- class DewLayer(nn.Module): def __init__(self, c: DewConfig, kind: str): super().__init__() self.kind = kind self.input_layernorm = DewRMSNorm(c.hidden_size, c.rms_norm_eps) self.mixer = (DewGatedDeltaNet(c) if c.causal else DewBiGatedDeltaNet(c)) if kind == "G" else DewAttention(c) self.post_attention_layernorm = DewRMSNorm(c.hidden_size, c.rms_norm_eps) self.mlp = DewNapThinker(c) if c.ffn == "nap" else DewMLP(c.hidden_size, c.intermediate_size) self.n_state = self.mixer.n_state def forward(self, x, m, cos, sin): x = x + self.mixer(self.input_layernorm(x), m, cos, sin) y, aux, st = self.mlp(self.post_attention_layernorm(x)) return x + y, aux, st def step(self, x, m, cos, sin, state): h, *state = self.mixer.step(self.input_layernorm(x), m, cos, sin, *state) x = x + h return x + self.mlp(self.post_attention_layernorm(x), need_aux=False)[0], state class DewPreTrainedModel(PreTrainedModel): if _HF: config_class = DewConfig base_model_prefix = "model" _no_split_modules = ["DewLayer"] supports_gradient_checkpointing = False def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(0.0, std) if getattr(module, "bias", None) is not None: module.bias.data.zero_() if getattr(module, "_dew_door", False): module.bias.data.fill_(1.0) # doormen start mostly awake elif isinstance(module, DewGatedDeltaNet): module.reset_gates() elif isinstance(module, DewRMSNorm): module.weight.data.fill_(1.0) if not _HF: def __init__(self, config): super().__init__() self.config = config def post_init(self): self.apply(self._init_weights) class DewModel(DewPreTrainedModel): def __init__(self, config: DewConfig): super().__init__(config) c = self.c = config self.embed_tokens = nn.Embedding(c.vocab_size, c.hidden_size) self.prelude = nn.ModuleList(DewLayer(c, t) for t in c.prelude) self.body = nn.ModuleList(DewLayer(c, t) for t in c.body) self.coda = nn.ModuleList(DewLayer(c, t) for t in c.coda) self.doors = None if c.doorman: self.doors = nn.ModuleList(nn.Linear(c.hidden_size, 1) for _ in range(c.max_loops)) for dl in self.doors: dl._dew_door = True self.pass_embed = nn.Parameter(torch.zeros(c.max_loops, c.hidden_size)) if c.max_loops > 1 else None self.norm = DewRMSNorm(c.hidden_size, c.rms_norm_eps) self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, v): self.embed_tokens = v def _rope(self, pos): return rope_tables(pos, self.c.head_dim, self.c.rope_theta) def forward(self, input_ids, pass_cap: int = 0, warm: bool = False, attention_mask=None): c = self.c x = self.embed_tokens(input_ids) B, T = input_ids.shape cos, sin = self._rope(torch.arange(T, device=input_ids.device)) aux = torch.zeros((), device=x.device) st = [] if not c.causal: # encoder: one pass, padding masked everywhere m = None if attention_mask is None else attention_mask.to(torch.float32) for L in list(self.prelude) + list(self.body) + list(self.coda): x, a, s = L(x, m, cos, sin) if a is not None: aux = aux + a st.append(s) think = torch.stack(st).mean(0) if st else torch.zeros(3, device=x.device) stats = torch.cat([torch.ones(1, device=x.device), torch.zeros(1, device=x.device), think]).detach() return self.norm(x), aux, stats def run(L, x, m): nonlocal aux x, a, s = L(x, m, cos, sin) if a is not None: aux = aux + a st.append(s) return x for L in self.prelude: x = run(L, x, None) n_loops = min(pass_cap, c.max_loops) if pass_cap else c.max_loops active = prod = expected = None passes = torch.full((B, T), float(n_loops), device=x.device) if self.doors is not None: passes = torch.zeros((B, T), device=x.device) for k in range(n_loops): m = gate = None if self.doors is not None: r = torch.sigmoid(self.doors[k](x).float()).squeeze(-1) hard = torch.ones_like(r) if warm else (r > 0.5).float() prev = torch.ones_like(r) if active is None else active m = prev * hard gate = prev * (hard + r - r.detach()) prod = r if prod is None else prod * r expected = prod if expected is None else expected + prod active = m passes = passes + m u = x if self.pass_embed is None else x + self.pass_embed[k].to(x.dtype) h = u for L in self.body: h = run(L, h, m) x = h if gate is None else x + gate[..., None].to(h.dtype) * (h - u) for L in self.coda: x = run(L, x, None) if self.doors is not None and self.training and not pass_cap and expected is not None: aux = aux + c.aux_passes_coef * (expected.mean() - c.target_passes) ** 2 think = torch.stack(st).mean(0) if st else torch.zeros(3, device=x.device) stats = torch.cat([torch.stack([passes.mean(), (passes == 0).float().mean()]), think]).detach() return self.norm(x), aux, stats # --- one word at a time --------------------------------------------------------------- def _instances(self): """Layer instances in state order: prelude, body once per pass, coda.""" return list(self.prelude) + [L for _ in range(self.c.max_loops) for L in self.body] + list(self.coda) def init_state(self, batch: int = 1, device=None, dtype=torch.float32): device = device or self.embed_tokens.weight.device out = [] for L in self._instances(): out += L.mixer.init_state(batch, device, dtype) return out def state_kinds(self): out = [] for i, L in enumerate(self._instances()): out += [f"l{i}_deltanet_memory", f"l{i}_conv"] if L.kind == "G" else [f"l{i}_keys", f"l{i}_values", f"l{i}_keep"] return out def step(self, input_ids, position, state): """input_ids: [B], position: [1] (int), state: list from init_state. Returns hidden [B, d], new state.""" c = self.c if not c.causal: raise ValueError("step() is for causal models; an encoder reads the whole text at once") x = self.embed_tokens(input_ids) B = x.shape[0] cos, sin = self._rope(position.reshape(1)) ones = torch.ones(B, device=x.device, dtype=torch.float32) new, i = [], 0 def run(L, x, m): nonlocal i x, s = L.step(x, m, cos, sin, state[i:i + L.n_state]) new.extend(s) i += L.n_state return x for L in self.prelude: x = run(L, x, ones) active = ones for k in range(c.max_loops): m = ones if self.doors is not None: r = torch.sigmoid(self.doors[k](x).float()).squeeze(-1) m = active * (r > 0.5).float() active = m u = x if self.pass_embed is None else x + self.pass_embed[k].to(x.dtype) h = u for L in self.body: h = run(L, h, m) x = h if self.doors is None else x + m[:, None].to(h.dtype) * (h - u) for L in self.coda: x = run(L, x, ones) return self.norm(x), new class DewForCausalLM(DewPreTrainedModel, *(() if GenerationMixin is object else (GenerationMixin,))): _tied_weights_keys = ["lm_head.weight"] def __init__(self, config: DewConfig): super().__init__(config) self.model = DewModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init() if not _HF and config.tie_word_embeddings: self.lm_head.weight = self.model.embed_tokens.weight def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, v): self.model.embed_tokens = v def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, v): self.lm_head = v def forward(self, input_ids=None, labels=None, attention_mask=None, pass_cap: int = 0, warm: bool = False, return_dict: bool = True, **kwargs): """attention_mask is accepted for API compatibility; padding inside a batch is not supported (pad on the right and ignore those labels with -100).""" h, aux, stats = self.model(input_ids, pass_cap=pass_cap, warm=warm) logits = self.lm_head(h) loss = None if labels is not None: ce = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.shape[-1]), labels[:, 1:].reshape(-1), ignore_index=-100) loss = ce + aux out = DewCausalLMOutput(loss=loss, logits=logits, aux_loss=aux, router_stats=stats) return out if return_dict else (loss, logits) def prepare_inputs_for_generation(self, input_ids, **kwargs): return {"input_ids": input_ids} # no HF cache: use step() for fast decoding def init_state(self, batch: int = 1, device=None, dtype=torch.float32): return self.model.init_state(batch, device, dtype) def step(self, input_ids, position, state): h, state = self.model.step(input_ids, position, state) return self.lm_head(h), state class DewForMaskedLM(DewPreTrainedModel): """Encoder base (causal=False): predicts masked tokens from both sides. labels = -100 where not masked.""" _tied_weights_keys = ["lm_head.weight"] def __init__(self, config: DewConfig): super().__init__(config) if config.causal: raise ValueError("DewForMaskedLM needs causal=False") self.model = DewModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init() if not _HF and config.tie_word_embeddings: self.lm_head.weight = self.model.embed_tokens.weight def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, v): self.model.embed_tokens = v def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, v): self.lm_head = v def forward(self, input_ids=None, labels=None, attention_mask=None, return_dict: bool = True, **kwargs): h, aux, stats = self.model(input_ids, attention_mask=attention_mask) logits = self.lm_head(h) loss = None if labels is not None: loss = F.cross_entropy(logits.float().reshape(-1, logits.shape[-1]), labels.reshape(-1), ignore_index=-100) + aux out = DewCausalLMOutput(loss=loss, logits=logits, aux_loss=aux, router_stats=stats) return out if return_dict else (loss, logits)