okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
6.0 KiB144 linesraw
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3"""tools/ds4/engram_hash.py - DeepSeek-V4.1's Engram n-gram hashes (after DeepSeek's inference/engram.py, MIT).
4
5A position is hashed as the n-grams (2 .. max_ngram_size) that end there, each over n_heads heads; every (n-gram
6size, head) pair owns a prime-sized bucket range of the layer's table.  Token ids first go through a compressed map
7where tokens that normalize alike (NFKC, NFD, accents stripped, lowercased, whitespace runs collapsed) share an id.
8
9    lay = Layout.from_config(text_config)
10    tm, n = compressed_token_map(tokenizer_json_path)     # needs the `tokenizers` package
11    h = Hasher(lay, tm, multipliers(lay, n), pad=tm[text_config["engram_pad_token_id"]])
12    h.ids(tokens)  -> int64 [T, n_layers, (max_ngram_size - 1) * n_heads], absolute table rows
13"""
14from __future__ import annotations
15
16from dataclasses import dataclass
17
18import numpy as np
19
20
21def _is_prime(n: int) -> bool:
22    if n < 2:
23        return False
24    if n % 2 == 0:
25        return n == 2
26    i = 3
27    while i * i <= n:
28        if n % i == 0:
29            return False
30        i += 2
31    return True
32
33
34def _next_prime(start: int, seen: set[int]) -> int:
35    """The smallest prime above `start` that has not been handed out yet (engram.py's find_next_prime)."""
36    c = start + 1
37    while not _is_prime(c) or c in seen:
38        c += 1
39    return c
40
41
42@dataclass(frozen=True)
43class Layout:
44    layer_ids: tuple[int, ...]
45    num_embeddings: tuple[int, ...]
46    max_ngram: int
47    n_heads: int
48    head_dim: int
49    primes: tuple[tuple[tuple[int, ...], ...], ...]    # [layer][n-gram size - 2][head]
50
51    @classmethod
52    def from_config(cls, t: dict) -> "Layout":
53        layer_ids = tuple(t["engram_layer_ids"])
54        mx, nh = t["engram_max_ngram_size"], t["engram_n_heads"]
55        primes, seen = [], set()
56        for _ in layer_ids:
57            per = []
58            for _ in range(mx - 1):
59                sizes, cur = [], t["engram_vocab_size"] - 1
60                for _ in range(nh):
61                    cur = _next_prime(cur, seen)
62                    seen.add(cur)
63                    sizes.append(cur)
64                per.append(tuple(sizes))
65            primes.append(tuple(per))
66        lay = cls(layer_ids, tuple(t["engram_num_embeddings"]), mx, nh, t["engram_head_dim"], tuple(primes))
67        for i, n in enumerate(lay.num_embeddings):
68            got = sum(p for per in lay.primes[i] for p in per)
69            if got != n:
70                raise ValueError("engram layer %d: the primes sum to %d, the config says %d rows" % (i, got, n))
71        return lay
72
73    def flat_primes(self) -> np.ndarray:
74        """[n_layers, (max_ngram - 1) * n_heads] int64, in hash-column order."""
75        return np.array([[p for per in layer for p in per] for layer in self.primes], dtype=np.int64)
76
77    def offsets(self) -> np.ndarray:
78        f = self.flat_primes()
79        return np.concatenate([np.zeros((f.shape[0], 1), np.int64), np.cumsum(f, axis=1)[:, :-1]], axis=1)
80
81
82def multipliers(lay: Layout, compressed_vocab: int) -> np.ndarray:
83    """[n_layers, max_ngram] int64, odd, bounded so token * multiplier stays inside int64 (engram.py)."""
84    bound = max(1, (np.iinfo(np.int64).max // compressed_vocab) // 2)
85    rows = []
86    for lid in lay.layer_ids:
87        g = np.random.default_rng(10007 * lid)
88        rows.append(g.integers(low=0, high=bound, size=(lay.max_ngram,), dtype=np.int64) * 2 + 1)
89    return np.stack(rows)
90
91
92def compressed_token_map(tokenizer_json: str) -> tuple[np.ndarray, int]:
93    """engram.py's build_compressed_token_map over the raw Rust tokenizer (no clean-up of spaces)."""
94    from tokenizers import Regex, Tokenizer, normalizers
95
96    tok = Tokenizer.from_file(str(tokenizer_json))
97    sentinel = ""
98    norm = normalizers.Sequence([
99        normalizers.NFKC(), normalizers.NFD(), normalizers.StripAccents(), normalizers.Lowercase(),
100        normalizers.Replace(Regex(r"[ \t\r\n]+"), " "), normalizers.Replace(Regex(r"^ $"), sentinel),
101        normalizers.Strip(), normalizers.Replace(sentinel, " "),
102    ])
103    n = tok.get_vocab_size(with_added_tokens=True)
104    key_to_new: dict[str, int] = {}
105    lookup = np.zeros(n, dtype=np.int64)
106    for tid in range(n):
107        text = tok.decode([tid], skip_special_tokens=False)
108        if "�" in text:
109            key = tok.id_to_token(tid)
110        else:
111            normalized = norm.normalize_str(text)
112            key = normalized if normalized else text
113        new = key_to_new.get(key)
114        if new is None:
115            new = len(key_to_new)
116            key_to_new[key] = new
117        lookup[tid] = new
118    return lookup, len(key_to_new)
119
120
121class Hasher:
122    def __init__(self, lay: Layout, token_map: np.ndarray, mult: np.ndarray, pad: int):
123        self.lay, self.tm, self.mult, self.pad = lay, token_map, mult, int(pad)
124        self.primes = np.array(lay.primes, dtype=np.int64)            # [L, max_ngram - 1, heads]
125        self.off = lay.offsets()                                      # [L, cols]
126
127    def ids(self, tokens) -> np.ndarray:
128        """Absolute table rows [T, n_layers, cols] for a sequence that starts at position 0 (no dead tokens)."""
129        c = self.tm[np.asarray(tokens, dtype=np.int64)]
130        T = len(c)
131        pos = np.arange(T)
132        toks = []
133        blocked = np.zeros(T, dtype=bool)
134        for s in range(self.lay.max_ngram):
135            src = c[np.clip(pos - s, 0, None)]
136            blocked = blocked | (pos < s)
137            toks.append(np.where(blocked, self.pad, src))
138        toks = np.stack(toks, axis=-1)                                # [T, max_ngram]
139        prod = toks[:, None, :] * self.mult[None]                     # [T, L, max_ngram]
140        rolling, out = prod[..., 0], []
141        for i in range(1, self.lay.max_ngram):
142            rolling = np.bitwise_xor(rolling, prod[..., i])
143            out.append(rolling[..., None] % self.primes[None, :, i - 1])
144        return np.concatenate(out, axis=-1) + self.off[None]