okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
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 9lay = Layout.from_config(text_config) 10tm, n = compressed_token_map(tokenizer_json_path) # needs the `tokenizers` package 11h = Hasher(lay, tm, multipliers(lay, n), pad=tm[text_config["engram_pad_token_id"]]) 12h.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 : 22if n < 2 : 23return False 24if n % 2 == 0 : 25return n == 2 26i = 3 27while i * i <= n : 28if n % i == 0 : 29return False 30i += 2 31return 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).""" 36c = start + 1 37while not _is_prime (c )or c in seen : 38c += 1 39return c 40 41 42@dataclass( frozen = True ) 43class Layout : 44layer_ids :tuple [int , ...] 45num_embeddings :tuple [int , ...] 46max_ngram :int 47n_heads :int 48head_dim :int 49primes :tuple [tuple [tuple [int , ...], ...], ...]# [layer][n-gram size - 2][head] 50 51@classmethod 52def from_config (cls ,t :dict )-> "Layout" : 53layer_ids = tuple (t ["engram_layer_ids" ]) 54mx ,nh = t ["engram_max_ngram_size" ],t ["engram_n_heads" ] 55primes ,seen = [],set () 56for _ in layer_ids : 57per = [] 58for _ in range (mx - 1 ): 59sizes ,cur = [],t ["engram_vocab_size" ]- 1 60for _ in range (nh ): 61cur = _next_prime (cur ,seen ) 62seen .add (cur ) 63sizes .append (cur ) 64per .append (tuple (sizes )) 65primes .append (tuple (per )) 66lay = cls (layer_ids ,tuple (t ["engram_num_embeddings" ]),mx ,nh ,t ["engram_head_dim" ],tuple (primes )) 67for i ,n in enumerate (lay .num_embeddings ): 68got = sum (p for per in lay .primes [i ]for p in per ) 69if got != n : 70raise ValueError ("engram layer %d: the primes sum to %d, the config says %d rows" % (i ,got ,n )) 71return lay 72 73def flat_primes (self )-> np .ndarray : 74"""[n_layers, (max_ngram - 1) * n_heads] int64, in hash-column order.""" 75return np .array ([[p for per in layer for p in per ]for layer in self .primes ],dtype = np .int64 ) 76 77def offsets (self )-> np .ndarray : 78f = self .flat_primes () 79return 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).""" 84bound = max (1 , (np .iinfo (np .int64 ).max // compressed_vocab )// 2 ) 85rows = [] 86for lid in lay .layer_ids : 87g = np .random .default_rng (10007 * lid ) 88rows .append (g .integers (low = 0 ,high = bound ,size = (lay .max_ngram ,),dtype = np .int64 )* 2 + 1 ) 89return 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).""" 94from tokenizers import Regex ,Tokenizer ,normalizers 95 96tok = Tokenizer .from_file (str (tokenizer_json )) 97sentinel = "" 98norm = normalizers .Sequence ([ 99normalizers .NFKC (),normalizers .NFD (),normalizers .StripAccents (),normalizers .Lowercase (), 100normalizers .Replace (Regex (r"[ \t\r\n]+" )," " ),normalizers .Replace (Regex (r"^ $" ),sentinel ), 101normalizers .Strip (),normalizers .Replace (sentinel ," " ), 102 ]) 103n = tok .get_vocab_size (with_added_tokens = True ) 104key_to_new :dict [str ,int ]= {} 105lookup = np .zeros (n ,dtype = np .int64 ) 106for tid in range (n ): 107text = tok .decode ([tid ],skip_special_tokens = False ) 108if "�" in text : 109key = tok .id_to_token (tid ) 110else : 111normalized = norm .normalize_str (text ) 112key = normalized if normalized else text 113new = key_to_new .get (key ) 114if new is None : 115new = len (key_to_new ) 116key_to_new [key ]= new 117lookup [tid ]= new 118return lookup ,len (key_to_new ) 119 120 121class Hasher : 122def __init__ (self ,lay :Layout ,token_map :np .ndarray ,mult :np .ndarray ,pad :int ): 123self .lay ,self .tm ,self .mult ,self .pad = lay ,token_map ,mult ,int (pad ) 124self .primes = np .array (lay .primes ,dtype = np .int64 )# [L, max_ngram - 1, heads] 125self .off = lay .offsets ()# [L, cols] 126 127def ids (self ,tokens )-> np .ndarray : 128"""Absolute table rows [T, n_layers, cols] for a sequence that starts at position 0 (no dead tokens).""" 129c = self .tm [np .asarray (tokens ,dtype = np .int64 )] 130T = len (c ) 131pos = np .arange (T ) 132toks = [] 133blocked = np .zeros (T ,dtype = bool ) 134for s in range (self .lay .max_ngram ): 135src = c [np .clip (pos - s ,0 ,None )] 136blocked = blocked | (pos < s ) 137toks .append (np .where (blocked ,self .pad ,src )) 138toks = np .stack (toks ,axis =- 1 )# [T, max_ngram] 139prod = toks [:,None , :]* self .mult [None ]# [T, L, max_ngram] 140rolling ,out = prod [...,0 ], [] 141for i in range (1 ,self .lay .max_ngram ): 142rolling = np .bitwise_xor (rolling ,prod [...,i ]) 143out .append (rolling [...,None ]% self .primes [None , :,i - 1 ]) 144return np .concatenate (out ,axis =- 1 )+ self .off [None ]