Run this model with HF Jobs
Run olaverse/YellowMIST-Encoder-15M-SEA on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/olaverse/YellowMIST-Encoder-15M-SEA. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/olaverse/YellowMIST-Encoder-15M-SEA on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use olaverse/YellowMIST-Encoder-15M-SEA with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use olaverse/YellowMIST-Encoder-15M-SEA with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="olaverse/YellowMIST-Encoder-15M-SEA")# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("olaverse/YellowMIST-Encoder-15M-SEA", device_map="auto") - Notebooks
- Google Colab
- Kaggle
YellowMIST-Encoder-15M-SEA (from base-sea-unsegmented-dew-1-enc-hybrid-full-s0)
Browse filesFiles changed (12)
- README.mdAdded+96
- config.jsonAdded+40
- dew/__init__.pyAdded+23
- dew/configuration_dew.pyAdded+144
- dew/export.pyAdded+87
- dew/modeling_dew.pyAdded+555
- dew/ops.pyAdded+121
- dew/presets.pyAdded+62
- eval.jsonAdded+38
- model.safetensorsAdded+3
- probes.csvAdded+8
- vocab.jsonAdded+1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596---license: apache-2.0library_name: transformerspipeline_tag: fill-masktags: [yellowmist, dew, character-level, encoder, multilingual, on-device, fill-mask]---
# YellowMIST-Encoder-15M-SEA
**YellowMIST Encoder** is a family of tiny character-level encoders to fine-tune for on-device text tasks:code-switching detection, word segmentation, autocorrect, restoring tone marks, punctuation and capitals,small NER. Each encoder covers one script or region group. This one covers **Thai, Lao, Khmer, Burmese and Tibetan**:10 languages.
- **15.0M parameters**, 60 MB in fp32 (about 15 MB once quantised to int8; that file is not exported yet)- Reads **characters** (NFC code points), so it needs no tokenizer and handles any spelling or tone marks in its script- Sees text in **both directions**, like BERT. It labels or fixes text; it does not generate it.
## Architecture
Dew hybrid encoder: 6 layers, `GGAGGA`. That is 4 bidirectional Gated DeltaNet layers (a fixed-size memory readforwards and backwards) and 2 attention layers, with a dense SwiGLU feed-forward block in each layer. Hidden size 320.Context of 512 characters in training; it runs on longer text. The first token of a text is its language tag (`<|lang:xxx_Xxxx|>`).
Why this layout: in a 3-seed pilot on the West Africa data, it beat a same-size transformer encoder on every test,by more than the seed-to-seed spread:
| Model (15M, same data and steps, 3 seeds) | masked chars | mark restoration | punctuation F1 | capitals F1 ||---|---|---|---|---|| **Dew hybrid (this architecture)** | **65.89 ± 0.13** | **82.89 ± 0.04** | **36.67 ± 0.35** | **59.07 ± 0.59** || Transformer encoder | 64.43 ± 0.19 | 82.44 ± 0.02 | 34.33 ± 1.10 | 57.07 ± 1.44 |
## Training
- Objective: masked characters. Spans of 3 characters are hidden at 15% of positions, and the model fills them in.- Data: web and chat text from the YellowMIST corpus, licence-screened. 1.58B unique characters in this group.- Trained on 8.0B characters (122,070 steps of 128 × 512). Small languages repeat at most 4 times; English is capped at a quarter of the training text.
## Results
Held-out documents (never trained on).
- **Masked characters filled in correctly: 81.0%**- Short fine-tune probes: punctuation F1 56.4
| Language | masked chars % | mark restoration % | punctuation F1 | capitals F1 | unique chars ||---|---|---|---|---|---|| `tha_Thai` | 80.3 | – | 81.9 | 77.6 | 311M || `mya_Mymr` | 77.2 | – | 60.7 | 90.0 | 317M || `khm_Khmr` | 79.3 | – | 42.7 | 82.4 | 298M || `lao_Laoo` | 85.4 | – | 62.2 | 95.9 | 297M || `bod_Tibt` | 82.4 | – | 36.4 | 79.5 | 298M || `dzo_Tibt` | 85.4 | – | 28.6 | 89.8 | 30M || `shn_Mymr` | 76.6 | – | 82.4 | 64.7 | 20M || `mnw_Mymr` | – | – | – | – | 4M || `ksw_Mymr` | – | – | – | – | 2M || `blk_Mymr` | – | – | – | – | <1M |
Mark restoration only runs for languages written with diacritics or tone marks. A `–` means no probe, or a languagewith under 1M characters of text, whose test set is too small to give a stable score. The group means above includeevery probed language. This script has no upper and lower case, so the capitals column only reflects Latin words mixed into the text.
## Use
```pythonimport json, sys, unicodedata, torchsys.path.insert(0, ".") # this repo, which ships the `dew` packageimport dew # registers the Dew architecture with transformersfrom transformers import AutoModelForMaskedLM
model = AutoModelForMaskedLM.from_pretrained(".").eval()v = json.load(open("vocab.json")) # {"vocab": [...], "labels": [...]}ids = {t: i for i, t in enumerate(v["vocab"])}
def encode(text, lang): text = unicodedata.normalize("NFC", text) return torch.tensor([[ids[f"<|lang:{lang}|>"]] + [ids.get(c, 1) for c in text]]) # 1 = <unk>
hidden = model.model(encode("Your text here", "tha_Thai"))[0] # [1, 1 + chars, 320], one vector per character```
To fine-tune, put a small head on `hidden` (one label per character or word) and train the whole model with a lowlearning rate (3e-4 worked for our tasks).
## Limits
- This is a base model, not a finished tool: fine-tune it for a task.- Speed on phone CPUs has not been measured yet. The DeltaNet layers use GPU kernels in training; an on-device build needs their recurrent form.- Masked-character accuracy measures how well the model knows the languages, not any one task. Compare it within a group, not across scripts.
## Licence
Apache-2.0.12345678910111213141516171819202122232425262728293031323334353637383940{ "architectures": [ "DewForMaskedLM" ], "aux_balance_coef": 0.01, "aux_passes_coef": 0.5, "aux_shared_coef": 0.5, "body": "GGAGGA", "causal": false, "coda": "", "conv_kernel": 4, "doorman": false, "expert_intermediate_size": 160, "ffn": "dense", "head_dim": 64, "hidden_size": 320, "initializer_range": 0.02, "intermediate_size": 1696, "linear_head_dim": 64, "linear_num_heads": 5, "max_loops": 1, "max_position_embeddings": 2048, "model_type": "dew", "num_attention_heads": 5, "num_experts": 8, "num_key_value_heads": 5, "pass_cap_prob": 0.25, "prelude": "", "qk_norm": true, "rms_norm_eps": 1e-06, "rope_theta": 10000.0, "router_threshold": 0.2, "shared_intermediate_size": 320, "shared_target": 0.15, "target_passes": 1.33, "torch_dtype": "float32", "transformers_version": "4.46.3", "vocab_size": 740, "warm_start": 0.2}1234567891011121314151617181920212223"""Dew: an LLM architecture family (Gated DeltaNet + attention hybrid, Nap thinker MoE,doorman napping and looping). model_type "dew".
from dew import DewConfig, DewForCausalLM, dew_config, fit_params model = DewForCausalLM(dew_config("dew-1-loop", vocab_size=32000, hidden_size=512))
Importing this package registers Dew with transformers' Auto classes."""from .configuration_dew import DewConfigfrom .modeling_dew import STAT_NAMES, DewForCausalLM, DewForMaskedLM, DewModelfrom .presets import PRESETS, count_params, dew_config, fit_params
__version__ = "1.0.0"__all__ = ["DewConfig", "DewModel", "DewForCausalLM", "DewForMaskedLM", "PRESETS", "dew_config", "fit_params", "count_params", "STAT_NAMES"]
try: from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM AutoConfig.register("dew", DewConfig, exist_ok=True) AutoModel.register(DewConfig, DewModel, exist_ok=True) AutoModelForCausalLM.register(DewConfig, DewForCausalLM, exist_ok=True) AutoModelForMaskedLM.register(DewConfig, DewForMaskedLM, exist_ok=True)except Exception: # transformers missing or too old: the model still works in plain PyTorch pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""DewConfig: one config describes every Dew model, from a 15M phone model to a large LLM.
The stack is embedding -> prelude -> body x (up to max_loops passes) -> coda -> norm -> head.Each of prelude / body / coda is a string of layer types:
G Gated DeltaNet layer (fixed-size memory, linear in text length) A attention layer (Qwen3-style: grouped-query, q/k norm, RoPE)
Examples transformer prelude="", body="AAAAAAAA", coda="", max_loops=1, ffn="dense" hybrid (2:1) prelude="", body="GGAGGA", coda="", max_loops=1, ffn="dense" Nap hybrid same as hybrid with ffn="nap" Nap & Loop prelude="G", body="GGA", coda="A", max_loops=3, doorman=True, ffn="nap"
Every layer has a mixer (G or A) and a thinker (ffn): "dense" is a SwiGLU block, "nap" is theNap thinker (router over num_experts small experts + a nap room that does nothing, and ashared expert with a per-word on/off switch).
causal=False makes an encoder (masked-LM base): attention sees both sides, and every DeltaNetlayer reads the text forwards and backwards (two memories, outputs added). Encoders run one pass,no doorman; padding is masked by `attention_mask` and writes nothing to either memory.
The doorman (doorman=True) decides per word, before every body pass, whether the word goesthrough the body again. Stopping is final. A word that does not take a pass neither writesDeltaNet memory nor enters that pass's attention memory. With max_loops=1 the doorman islayer napping; with max_loops>1 it is "Nap & Loop"."""from __future__ import annotations
try: from transformers import PretrainedConfigexcept ImportError: # lets the model run without transformers installed class PretrainedConfig: # type: ignore[no-redef] model_type = ""
def __init__(self, **kw): for k, v in kw.items(): setattr(self, k, v)
def to_dict(self): return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
class DewConfig(PretrainedConfig): model_type = "dew" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, vocab_size: int = 16384, hidden_size: int = 320, causal: bool = True, # layout prelude: str = "G", body: str = "GGA", coda: str = "A", max_loops: int = 3, doorman: bool = True, target_passes: float = 1.33, pass_cap_prob: float = 0.25, warm_start: float = 0.2, # attention (A) num_attention_heads: int = 5, num_key_value_heads: int | None = None, head_dim: int | None = None, qk_norm: bool = True, rope_theta: float = 10000.0, max_position_embeddings: int = 2048, # Gated DeltaNet (G) linear_num_heads: int | None = None, linear_head_dim: int | None = None, conv_kernel: int = 4, # thinker ffn: str = "nap", intermediate_size: int = 864, num_experts: int = 8, expert_intermediate_size: int = 160, shared_intermediate_size: int = 320, router_threshold: float = 0.2, shared_target: float = 0.15, # auxiliary losses aux_balance_coef: float = 0.01, aux_passes_coef: float = 0.5, aux_shared_coef: float = 0.5, # misc rms_norm_eps: float = 1e-6, initializer_range: float = 0.02, tie_word_embeddings: bool = True, **kwargs, ): for s, name in ((prelude, "prelude"), (body, "body"), (coda, "coda")): if set(s) - {"G", "A"}: raise ValueError(f"{name} may only contain G and A, got {s!r}") if not body and max_loops > 1: raise ValueError("max_loops > 1 needs a body") if not causal and (max_loops > 1 or doorman): raise ValueError("encoders (causal=False) run one pass without a doorman") if ffn not in ("dense", "nap"): raise ValueError("ffn must be 'dense' or 'nap'") self.vocab_size = vocab_size self.hidden_size = hidden_size self.causal = bool(causal) self.prelude, self.body, self.coda = prelude, body, coda self.max_loops = max(1, int(max_loops)) self.doorman = bool(doorman) self.target_passes = target_passes self.pass_cap_prob = pass_cap_prob self.warm_start = warm_start self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads or num_attention_heads self.head_dim = head_dim or hidden_size // num_attention_heads self.qk_norm = qk_norm self.rope_theta = rope_theta self.max_position_embeddings = max_position_embeddings self.linear_num_heads = linear_num_heads or num_attention_heads self.linear_head_dim = linear_head_dim or hidden_size // self.linear_num_heads self.conv_kernel = conv_kernel self.ffn = ffn self.intermediate_size = intermediate_size self.num_experts = num_experts self.expert_intermediate_size = expert_intermediate_size self.shared_intermediate_size = shared_intermediate_size self.router_threshold = router_threshold self.shared_target = shared_target self.aux_balance_coef = aux_balance_coef self.aux_passes_coef = aux_passes_coef self.aux_shared_coef = aux_shared_coef self.rms_norm_eps = rms_norm_eps self.initializer_range = initializer_range super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
@property def layer_passes(self) -> float: """Layer-passes per word at the target loop count (compute, not parameters).""" passes = self.target_passes if (self.doorman and self.max_loops > 1) else self.max_loops return len(self.prelude) + passes * len(self.body) + len(self.coda)
def describe(self) -> str: loop = f" x{self.max_loops} passes" + (" (doorman)" if self.doorman else "") if self.max_loops > 1 else \ (" (doorman napping)" if self.doorman else "") kind = "Dew-enc" if not self.causal else "Dew" think = (f" {self.num_experts}x{self.expert_intermediate_size}+nap+shared{self.shared_intermediate_size}" if self.ffn == "nap" else f" {self.intermediate_size}") return f"{kind} [{self.prelude or '-'} | {self.body}{loop} | {self.coda or '-'}] d={self.hidden_size} ffn={self.ffn}{think}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""ONNX export of Dew as a one-word step model.
Inputs : input_ids [B] int64, position [1] int64, then every state tensor from init_state()Outputs: logits [B, vocab], then the new state tensors (same order, names prefixed "new_")
DeltaNet memories and convolution buffers have a fixed size; attention keys/values/keep grow byone word per step (dynamic axis "p<i>"). Start from zero-length attention state (seeinitial_state_numpy) and feed each step's outputs back in."""from __future__ import annotations
from pathlib import Path
import numpy as npimport torchimport torch.nn as nn
class _Step(nn.Module): def __init__(self, lm): super().__init__() self.lm = lm
def forward(self, input_ids, position, *state): logits, new = self.lm.step(input_ids, position, list(state)) return (logits, *new)
def initial_state_numpy(lm, batch: int = 1): return [t.cpu().numpy() for t in lm.init_state(batch, device=torch.device("cpu"))]
def export_onnx(lm, out_dir, name: str = "dew", int8: bool = True, opset: int = 17) -> dict: lm = lm.float().eval().cpu() out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) kinds = lm.model.state_kinds() # trace with two words already in the attention memory, so its length is a real dynamic axis state = lm.init_state(1, device=torch.device("cpu")) with torch.no_grad(): for t, tok in enumerate((1, 2)): _, state = lm.step(torch.tensor([tok]), torch.tensor([t]), state) ids, pos = torch.tensor([3]), torch.tensor([2]) in_names = ["input_ids", "position"] + kinds out_names = ["logits"] + [f"new_{k}" for k in kinds] dyn = {"input_ids": {0: "batch"}, "logits": {0: "batch"}} for i, k in enumerate(kinds): ax = {0: "batch"} if k.endswith(("_keys", "_values")): ax[2] = f"p{i}" elif k.endswith("_keep"): ax[1] = f"p{i}" dyn[k] = ax dyn[f"new_{k}"] = {a: (v + "n" if v.startswith("p") else v) for a, v in ax.items()} f = out_dir / f"{name}.onnx" with torch.no_grad(): torch.onnx.export(_Step(lm), (ids, pos, *state), str(f), input_names=in_names, output_names=out_names, dynamic_axes=dyn, opset_version=opset, dynamo=False) res = {"onnx": str(f), "onnx_mb": f.stat().st_size / 1e6} if int8: from onnxruntime.quantization import QuantType, quantize_dynamic q = out_dir / f"{name}.int8.onnx" quantize_dynamic(str(f), str(q), weight_type=QuantType.QInt8) res.update(int8=str(q), int8_mb=q.stat().st_size / 1e6) return res
def verify_onnx(lm, onnx_path, n_words: int = 24, seed: int = 0) -> float: """Feed the same words to ONNX (step by step) and to the PyTorch full-sequence forward. Returns the largest absolute logit difference.""" import onnxruntime as ort lm = lm.float().eval().cpu() g = torch.Generator().manual_seed(seed) ids = torch.randint(0, lm.config.vocab_size, (1, n_words), generator=g) with torch.no_grad(): ref = lm(ids).logits[0].numpy() sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) names = [i.name for i in sess.get_inputs()] state = initial_state_numpy(lm) worst = 0.0 for t in range(n_words): feeds = {"input_ids": ids[:, t].numpy(), "position": np.array([t], dtype=np.int64)} feeds.update({n: s for n, s in zip(names[2:], state)}) out = sess.run(None, feeds) worst = max(worst, float(np.abs(out[0][0] - ref[t]).max())) state = out[1:] return worst123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555"""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 mathfrom dataclasses import dataclassfrom typing import Optional
import torchimport torch.nn as nnimport torch.nn.functional as F
from .configuration_dew import DewConfigfrom .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 = Trueexcept 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]
@dataclassclass 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Gated delta rule: the memory update inside Dew's DeltaNet layers.
Per head the memory is a matrix S (key dim x value dim). For each word t:
S <- exp(g_t) * S decay (g_t <= 0, log space) S <- S + beta_t * k_t (v_t - S^T k_t)^T delta write (beta_t in [0, 1]) o_t = S^T q_t * scale read
A word with beta = 0 and g = 0 leaves S exactly as it was: this is how a napping word"does not write to the whiteboard and causes no decay".
Three implementations, checked against each other by `python -m dew.selftest`: * fla Triton kernels from flash-linear-attention (fast training on GPU) * chunk pure PyTorch, chunked (WY / UT form), any device, used when fla is missing * step one word at a time, used for decoding and the ONNX export"""from __future__ import annotations
import inspectimport os
import torch
_FLA = None # None = not checked yet, False = unavailable
def _fla(): global _FLA if _FLA is None: _FLA = False if os.environ.get("DEW_NO_FLA") != "1": try: from fla.ops.gated_delta_rule import chunk_gated_delta_rule as f params = inspect.signature(f).parameters _FLA = (f, "head_first" in params) except Exception: _FLA = False return _FLA
def fla_available() -> bool: return bool(_fla())
def l2norm(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: return x * torch.rsqrt(x.pow(2).sum(-1, keepdim=True) + eps)
def gated_delta_rule(q, k, v, g, beta, impl: str = "auto"): """q, k: [B, T, H, K] (already L2-normalised), v: [B, T, H, V], g, beta: [B, T, H]. Returns o: [B, T, H, V] in v's dtype.""" scale = q.shape[-1] ** -0.5 f = _fla() if impl in ("auto", "fla") else False if f and q.is_cuda: fn, has_head_first = f kw = {"scale": scale, "output_final_state": False} if has_head_first: kw["head_first"] = False o, _ = fn(q, k, v, g.float(), beta.to(q.dtype), **kw) return o.to(v.dtype) if impl == "fla": raise RuntimeError("fla requested but not available") return chunk_reference(q, k, v, g, beta, scale).to(v.dtype)
def chunk_reference(q, k, v, g, beta, scale, chunk: int = 64): """Chunked gated delta rule in plain PyTorch (fp32). Same maths as fla's reference.""" dt = v.dtype with torch.autocast(q.device.type, enabled=False): q, k, v, g, beta = (x.float().transpose(1, 2) for x in (q, k, v, g, beta)) # [B, H, T, .] B, H, T, K = k.shape V = v.shape[-1] pad = (chunk - T % chunk) % chunk if pad: q, k, v = (torch.nn.functional.pad(x, (0, 0, 0, pad)) for x in (q, k, v)) g, beta = (torch.nn.functional.pad(x, (0, pad)) for x in (g, beta)) n = q.shape[2] // chunk q = q * scale kb = k * beta[..., None] vb = v * beta[..., None] q, k, kb, vb = (x.view(B, H, n, chunk, -1) for x in (q, k, kb, vb)) g = g.view(B, H, n, chunk).cumsum(-1) tri = torch.ones(chunk, chunk, dtype=torch.bool, device=q.device).tril() diff = (g[..., :, None] - g[..., None, :]).masked_fill(~tri, float("-inf")) L = diff.exp() # decay from j to i (i >= j) A = ((kb @ k.transpose(-1, -2)) * L).tril(-1) eye = torch.eye(chunk, device=q.device).expand_as(A) Tm = torch.linalg.solve_triangular(eye + A, eye, upper=False, unitriangular=True) # (I + A)^-1 kcd = Tm @ (kb * g.exp()[..., None]) u = Tm @ vb S = q.new_zeros(B, H, K, V) o = torch.empty_like(u) for i in range(n): qi, ki, gi = q[:, :, i], k[:, :, i], g[:, :, i] att = (qi @ ki.transpose(-1, -2) * L[:, :, i]).tril() vnew = u[:, :, i] - kcd[:, :, i] @ S o[:, :, i] = (qi * gi.exp()[..., None]) @ S + att @ vnew S = S * gi[..., -1, None, None].exp() + (ki * (gi[..., -1, None] - gi).exp()[..., None]).transpose(-1, -2) @ vnew o = o.view(B, H, n * chunk, V)[:, :, :T] return o.transpose(1, 2).to(dt)
def delta_step(q, k, v, g, beta, S): """One word. q, k: [B, H, K] (L2-normalised), v: [B, H, V], g, beta: [B, H], S: [B, H, K, V].""" scale = q.shape[-1] ** -0.5 S = S * g.exp()[..., None, None] kv = (k[..., None] * S).sum(-2) # S^T k S = S + k[..., None] * ((v - kv) * beta[..., None])[..., None, :] o = (q[..., None] * S).sum(-2) * scale return o, S
def recurrent_reference(q, k, v, g, beta): """Whole sequence, one word at a time (slow; for tests).""" B, T, H, K = q.shape S = q.new_zeros(B, H, K, v.shape[-1]).float() out = [] for t in range(T): o, S = delta_step(q[:, t].float(), k[:, t].float(), v[:, t].float(), g[:, t].float(), beta[:, t].float(), S) out.append(o) return torch.stack(out, 1)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Named Dew-1 layouts and sizing to a parameter budget.
from dew import dew_config, fit_params cfg = fit_params(dew_config("dew-1-loop", vocab_size=16384, hidden_size=320), 15_160_640)"""from __future__ import annotations
import torch
from .configuration_dew import DewConfig
PRESETS = { # Nap & Loop: 1 awake layer, a shared G-G-A block run 0-3 times per word, 1 awake attention layer "dew-1-loop": dict(prelude="G", body="GGA", coda="A", max_loops=3, doorman=True, ffn="nap"), # Nap hybrid: DeltaNet:attention 2:1, Nap thinker in every layer, no doorman "dew-1-nap": dict(prelude="", body="GGAGGA", coda="", max_loops=1, doorman=False, ffn="nap"), # Selective-memory hybrid: as dew-1-nap with a doorman that lets words skip the middle layers "dew-1-napskip": dict(prelude="G", body="GGAG", coda="A", max_loops=1, doorman=True, ffn="nap", target_passes=0.5), # Encoders (masked-LM bases): DeltaNet both ways + attention without the causal mask "dew-1-enc": dict(prelude="", body="GGAGGA", coda="", max_loops=1, doorman=False, ffn="nap", causal=False), "dew-1-enc-hybrid": dict(prelude="", body="GGAGGA", coda="", max_loops=1, doorman=False, ffn="dense", causal=False), "dew-1-enc-dense": dict(prelude="", body="AAAAAAAA", coda="", max_loops=1, doorman=False, ffn="dense", causal=False), # Controls "dew-1-hybrid": dict(prelude="", body="GGAGGA", coda="", max_loops=1, doorman=False, ffn="dense"), "dew-1-dense": dict(prelude="", body="AAAAAAAA", coda="", max_loops=1, doorman=False, ffn="dense"),}
def dew_config(preset: str, **overrides) -> DewConfig: if preset not in PRESETS: raise KeyError(f"unknown preset {preset!r}; choose from {sorted(PRESETS)}") return DewConfig(**{**PRESETS[preset], **overrides})
def count_params(cfg: DewConfig) -> int: from .modeling_dew import DewForCausalLM, DewForMaskedLM with torch.device("meta"): m = DewForCausalLM(cfg) if cfg.causal else DewForMaskedLM(cfg) if cfg.tie_word_embeddings: m.lm_head.weight = m.model.embed_tokens.weight return sum(p.numel() for p in m.parameters())
def fit_params(cfg: DewConfig, target: int, multiple: int = 8) -> DewConfig: """Resize the thinkers so the whole model has about `target` parameters. Nap thinker: expert width (shared expert = 2x expert width). Dense: intermediate size.""" key = "expert_intermediate_size" if cfg.ffn == "nap" else "intermediate_size"
def with_width(w): kw = cfg.to_dict() kw[key] = int(w) if cfg.ffn == "nap": kw["shared_intermediate_size"] = int(2 * w) for k in ("model_type", "transformers_version", "architectures"): kw.pop(k, None) return DewConfig(**kw)
a, b = 64, 128 na, nb = count_params(with_width(a)), count_params(with_width(b)) slope = (nb - na) / (b - a) w = max(multiple, round((a + (target - na) / slope) / multiple) * multiple) return with_width(w)1234567891011121314151617181920212223242526272829303132333435363738{ "masked_char_acc": 0.8095743063347418, "per_lang": { "tha_Thai": { "loss": 0.7260199314539173, "acc": 0.8032003325020781 }, "mya_Mymr": { "loss": 0.8427602969302005, "acc": 0.7720282626766417 }, "khm_Khmr": { "loss": 0.7837338721068423, "acc": 0.7930174563591023 }, "lao_Laoo": { "loss": 0.5285024032529354, "acc": 0.8539068994181214 }, "bod_Tibt": { "loss": 0.6268825007793017, "acc": 0.8241895261845387 }, "dzo_Tibt": { "loss": 0.4927422451358583, "acc": 0.8543225270157938 }, "shn_Mymr": { "loss": 0.8448312756852887, "acc": 0.7663551401869159 } }, "params": 14982288, "steps": 122070, "chars_trained": 7999979520, "group": "sea-unsegmented", "source_run": "base-sea-unsegmented-dew-1-enc-hybrid-full-s0"}123version https://git-lfs.github.com/spec/v1oid sha256:8761f3af69043e7244e566f14b76c33f5b1bf14f7000864c9fcfb620de8bbfb8size 5994224012345678run,task,label,punct_f1,case_f1base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,tha_Thai,0.8187134502923976,0.7757255936675461base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,mya_Mymr,0.6067415730337079,0.8996960486322189base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,khm_Khmr,0.4269535673839185,0.8237367802585194base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,lao_Laoo,0.6215916648193305,0.9592391304347826base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,bod_Tibt,0.36421725239616615,0.7948717948717948base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,dzo_Tibt,0.2857142857142857,0.8979591836734694base-sea-unsegmented-dew-1-enc-hybrid-full-s0,punct,shn_Mymr,0.8235294117647058,0.64705882352941181{"vocab": ["<pad>", "<unk>", "<mask>", "<eot>", "<|lang:tha_Thai|>", "<|lang:mya_Mymr|>", "<|lang:khm_Khmr|>", "<|lang:lao_Laoo|>", "<|lang:bod_Tibt|>", "<|lang:dzo_Tibt|>", "<|lang:shn_Mymr|>", "<|lang:mnw_Mymr|>", "<|lang:ksw_Mymr|>", "<|lang:blk_Mymr|>", " ", "་", "်", "း", "တ", "ས", "ི", "ု", "ိ", "ာ", "မ", "က", "ေ", "ག", "ད", "ပ", "ོ", "င", "្", "ན", "လ", "ា", "າ", "ນ", "བ", "ུ", "သ", "ར", "า", "န", "", "ེ", "ၼ", "น", "ន", "ང", "མ", "ွ", "ူ", "ဝ", "အ", "ၢ", "ီ", "ႈ", "រ", "འ", "ལ", "ร", "่", "ရ", "္", "ກ", "ក", "อ", "່", "့", "པ", "ဲ", "ྱ", "ံ", "เ", "ก", "ཱ", "ງ", "ប", "ง", "ດ", "້", "ັ", "้", "ၵ", "ម", "ະ", "ม", "ស", ".", "ཏ", "စ", "ယ", "ႇ", "ອ", "ត", "ั", "ျ", "ង", "ြ", "ເ", "\n", "ှ", "ี", "ວ", "ມ", "ႉ", "ล", "ល", "ခ", "ว", "ႃ", "ย", "ด", "ဒ", "ཡ", "ဂ", "ၣ", "ཀ", "ສ", "ີ", "ລ", "ท", "།", "ບ", "ྲ", "ႆ", "ທ", "ါ", "ထ", "ົ", "။", "ិ", "់", "บ", "យ", "ส", "ည", "ิ", "ต", "ค", "ဖ", "ဵ", "ទ", "ၤ", "ห", "ុ", "၊", "ព", ",", "ແ", "ដ", "ၚ", "ច", "ཨ", "ំ", "ຍ", "ྟ", "េ", "ะ", "ဟ", "ၸ", "ຫ", "ປ", "ິ", "ཁ", "ဆ", "ཚ", "ជ", "ី", "ป", "ཝ", "แ", "ຕ", "ไ", "ើ", "จ", "ຂ", "ဢ", "ဘ", "ྒ", "ႁ", "អ", "ຄ", "វ", "e", "ພ", "ၶ", "ཞ", "ཾ", "ែ", "ྷ", "ཐ", "ໃ", "គ", "a", "ື", "ຈ", "ោ", "ូ", "ຊ", "ข", "ใ", "พ", "ื", "0", ")", "ཆ", "(", "ໍ", "1", "ุ", "o", "็", "ႂ", "2", "ཙ", "i", "ះ", "ຮ", "n", "ဗ", "ช", "t", "ู", "ྐ", "ໄ", "ួ", "r", "ཅ", "ខ", "ၠ", "ណ", "์", "ញ", "ဍ", "ཕ", "ཉ", "ູ", "ຸ", "-", "ྡ", "ហ", "ำ", "ཧ", "ថ", "โ", "ႄ", "ཛ", "ធ", "s", "ៅ", "ླ", "ཟ", "ၽ", "ྤ", "ဇ", "ႏ", "ཤ", "ႅ", "។", "ၞ", "ຽ", "ភ", "ၟ", "၀", "l", "ໂ", "ຳ", "ဏ", "ឹ", "ྩ", "ផ", "ถ", "ຜ", "ຖ", "ผ", "ဳ", "ྦ", "ึ", "ꩻ", "d", "ྨ", "u", "5", "៉", "ຢ", "h", "”", "3", "c", "ྶ", "ཊ", "ฟ", "ຼ", "ៃ", "9", "ณ", "m", "ཎ", "“", "S", "ྭ", "ྣ", "ซ", "ໜ", "4", "8", "ဓ", "…", "ၾ", "၁", "\"", "ྙ", "ຶ", "ྠ", "័", "ภ", "A", "6", "p", "g", "C", "ៀ", "7", "ၺ", "/", "y", "ศ", "ญ", "ྑ", "ឆ", "'", "ဿ", "ဃ", "ဴ", "ཇ", "၂", "႔", "ໝ", "ឡ", "’", ":", "P", "ธ", "ႊ", "‘", "៊", "ྛ", "T", "ྫ", "ྗ", "ษ", "ឺ", "ဥ", "M", "b", "༡", "N", "៍", "ၜ", "D", "២", "ๆ", "១", "ឋ", "០", "ຣ", "I", "f", "k", "?", "|", "ྔ", "༠", "w", "៏", "༢", "B", "O", "R", "L", "–", "E", "v", "ဉ", "ៈ", "ឈ", "ဦ", "၃", "၏", "ၥ", "ຟ", "F", "!", "၅", "ឲ", "]", "[", "ឱ", "ໆ", "ឃ", "H", "ៗ", "຺", "၄", "ឿ", "ၿ", "U", "ྪ", "G", "ဌ", "ឌ", "၉", "ฉ", "V", "K", "ဋ", "༔", "", "ឬ", "%", "ၯ", "ឯ", "၆", "၈", "៖", "ឧ", "༣", "ฝ", "W", "၇", "ဈ", "¶", "=", "ဎ", "៣", ">", "ဧ", "༩", ";", "༥", "႕", "ฐ", "៌", "༤", "༦", "ຝ", "྄", "༧", "៥", "x", "༌", "J", "៤", "༨", "»", "၍", "៩", "ႀ", "๊", "ဣ", "ၦ", "ฮ", "ཋ", "ཌ", "ឥ", "៦", "ၲ", "《", "ฤ", "》", "ၱ", "༹", "ྻ", "ྜ", "៧", "z", "<", "៨", "ဠ", "ྞ", "Y", "«", "ฎ", "ྕ", "*", "ၡ", "႐", "ฏ", "X", "ฒ", "ฯ", "_", "j", "ฆ", "၌", "๋", "៕", "ឍ", "ဤ", "໌", "ྥ", "#", "ຠ", "ྚ", "ၝ", "ႜ", "༉", "+", "ၻ", "ႋ", "ၪ", "ဨ", "•", "ຎ", "ฑ", "Z", "႒", "—", "ၳ", "ၧ", "ႝ", "ํ", "\\", "Q", "", "၎", "�", "༄", "༽", "−", "༸", "$", "ฬ", "ၨ", "‚", "ཻ", "༅", "@", "ၷ", "&", "ཿ", "q", "ຘ", "ႎ", "༼", "႑", """, "", "ຏ", "ၩ", "ឪ", "ႛ", "ຐ", "๑", "ဪ", "໋", "{", "ဩ", "ၫ", "}", "ຓ", "~", "ຉ", "·", "႓", "ྀ", "ၭ", "๒", "↑", "^", "→", "ཽ", "ྸ", "໊", "ឫ", "【", "】", "`", "๓", ",", "‹", "ឮ", "๕", ")", "´", "(", "႞", "°", "️", "๔", "๐", "ཥ", "༎", "›", "ၰ", "ྃ", "༴", "博", "៎", "亚", "๙", "、", "႘", "ل", "é", "ၬ", "⃣", "‑", "༵", "ꩡ", "๗", "", "ྵ", "学", "๖", "×", "ྰ", "႖", "育", "ا", "佛", "ü", "§", "๘", "ā", "←", "国", "文", "ı", "体", "໐", "ฌ", "ꧦ", "฿", "年", "ၐ", "教", "中", "æ", "©", "●", "႙", "€", "໑", "", "🙏", "႗", "ꧤ", "论", "", "ឭ", "ꧣ", ";", "ྋ", "྾", "ş", "ö", "ᆸ", "÷", "៑", "👉", "ꩪ", "", "༑", "„", "ၹ", "﹪", "😀", "的", "ႌ", "", "大", "á", "。", "者", "༷", "ي", "±", "ø", "ó", "ه", "و", "ཪ", "م", "ຯ", "໒", "史", "祖", "ฺ", "会", "版", "्", "尊", "ၴ", "໕", "十", "ႍ", "章", "导", "႟", "出", "ឝ", "①", "②", "社", "༈", "ː", "‡", "航", "ၛ", "?", "′", "第", "‰", "ꩦ", "", "ç", "໘", "③", "藏", "宗", "࣭", "和", "关", "ຌ", "女", "ᆩ", "人", "£", "═", "已", "ຆ", "一", "闭", "评", "��", "⑥", "⑧"], "labels": ["tha_Thai", "mya_Mymr", "khm_Khmr", "lao_Laoo", "bod_Tibt", "dzo_Tibt", "shn_Mymr", "mnw_Mymr", "ksw_Mymr", "blk_Mymr"]}README.mdAdded+96
config.jsonAdded+40
dew/__init__.pyAdded+23
dew/configuration_dew.pyAdded+144
dew/export.pyAdded+87
dew/modeling_dew.pyAdded+555
dew/ops.pyAdded+121
dew/presets.pyAdded+62
eval.jsonAdded+38
model.safetensorsAdded+3
probes.csvAdded+8
vocab.jsonAdded+1