Upload alea/ngram.py with huggingface_hub
Browse files- alea/ngram.py +84 -0
alea/ngram.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cheap capacity modules: auxiliary token embedding + hashed n-gram encoder.
|
| 2 |
+
|
| 3 |
+
Both inject into the backbone's input embeddings through zero-init gates, so a
|
| 4 |
+
model loaded from an existing checkpoint starts bit-identical and the new
|
| 5 |
+
capacity ramps in only where it reduces loss.
|
| 6 |
+
|
| 7 |
+
AuxEmbedding: a second full embedding table (~150M params on Qwen3 vocab) —
|
| 8 |
+
pure per-token lexical memory, no attention cost.
|
| 9 |
+
|
| 10 |
+
NGramEncoder: per-position rolling hash of the last n token ids -> embedding
|
| 11 |
+
row. ~100M params across a few orders; adds local-context lexical features the
|
| 12 |
+
transformer spends layers reconstructing.
|
| 13 |
+
"""
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
|
| 17 |
+
# multiplicative hash constants (odd, < 2^63)
|
| 18 |
+
_HASH_P = 1000003
|
| 19 |
+
_SENTINEL = 1 << 20 # salt added to out-of-range positions so boundary
|
| 20 |
+
# n-grams don't collide with interior ones
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class AuxEmbedding(nn.Module):
|
| 24 |
+
"""Second trainable embedding table, gated additively into input embeds.
|
| 25 |
+
|
| 26 |
+
vocab x dim matches the backbone embedding (~155M params for Qwen3-0.6B).
|
| 27 |
+
Gate starts at 0 -> zero effect at init.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, vocab_size, dim):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.emb = nn.Embedding(vocab_size, dim)
|
| 33 |
+
nn.init.normal_(self.emb.weight, std=0.02)
|
| 34 |
+
self.gate = nn.Parameter(torch.zeros(1))
|
| 35 |
+
|
| 36 |
+
def forward(self, input_ids):
|
| 37 |
+
return self.gate * self.emb(input_ids)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class NGramEncoder(nn.Module):
|
| 41 |
+
"""Per-position n-gram features via rolling hash into embedding buckets.
|
| 42 |
+
|
| 43 |
+
For each order n, position i's key is hash(ids[i-n+1..i]) mod buckets.
|
| 44 |
+
Orders share no parameters; outputs are concatenated and projected to
|
| 45 |
+
d_model through a zero-init linear (gate is inside the projection).
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(self, d_model, orders=(2, 3, 4), buckets=262144, d_ng=128):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.orders = tuple(orders)
|
| 51 |
+
self.buckets = buckets
|
| 52 |
+
self.embs = nn.ModuleList(
|
| 53 |
+
[nn.Embedding(buckets, d_ng) for _ in self.orders])
|
| 54 |
+
for e in self.embs:
|
| 55 |
+
nn.init.normal_(e.weight, std=0.02)
|
| 56 |
+
self.proj = nn.Linear(len(self.orders) * d_ng, d_model)
|
| 57 |
+
nn.init.zeros_(self.proj.weight)
|
| 58 |
+
nn.init.zeros_(self.proj.bias)
|
| 59 |
+
|
| 60 |
+
def _hash(self, ids, n):
|
| 61 |
+
"""ids [B,L] long -> bucket index [B,L] of the n-gram ending at i."""
|
| 62 |
+
B, L = ids.shape
|
| 63 |
+
dev = ids.device
|
| 64 |
+
h = torch.zeros(B, L, dtype=torch.long, device=dev)
|
| 65 |
+
for k in range(n - 1, -1, -1):
|
| 66 |
+
shifted = torch.full_like(ids, _SENTINEL)
|
| 67 |
+
if k > 0:
|
| 68 |
+
shifted[:, k:] = ids[:, :-k]
|
| 69 |
+
else:
|
| 70 |
+
shifted = ids
|
| 71 |
+
h = (h * _HASH_P + shifted) % self.buckets
|
| 72 |
+
return h
|
| 73 |
+
|
| 74 |
+
def forward(self, input_ids):
|
| 75 |
+
feats = [emb(self._hash(input_ids, n))
|
| 76 |
+
for emb, n in zip(self.embs, self.orders)]
|
| 77 |
+
return self.proj(torch.cat(feats, dim=-1))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def ngram_param_count(vocab_size, d_model, orders=(2, 3, 4),
|
| 81 |
+
buckets=262144, d_ng=128):
|
| 82 |
+
ngram = len(orders) * buckets * d_ng + len(orders) * d_ng * d_model
|
| 83 |
+
aux = vocab_size * d_model + 1
|
| 84 |
+
return ngram, aux
|