Text Generation
Transformers
Safetensors
English
pragya_e2
small-language-model
from-scratch
causal-lm
decoder-only
gqa
rope
swiglu
exclusive-gated-attention
engram
custom_code
Instructions to use RuVI-AI/Pragya-EXP2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use RuVI-AI/Pragya-EXP2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="RuVI-AI/Pragya-EXP2", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("RuVI-AI/Pragya-EXP2", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use RuVI-AI/Pragya-EXP2 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "RuVI-AI/Pragya-EXP2" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "RuVI-AI/Pragya-EXP2", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/RuVI-AI/Pragya-EXP2
- SGLang
How to use RuVI-AI/Pragya-EXP2 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "RuVI-AI/Pragya-EXP2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "RuVI-AI/Pragya-EXP2", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "RuVI-AI/Pragya-EXP2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "RuVI-AI/Pragya-EXP2", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use RuVI-AI/Pragya-EXP2 with Docker Model Runner:
docker model run hf.co/RuVI-AI/Pragya-EXP2
Upload 6 files
Browse files- config.py +121 -0
- kernel.py +88 -0
- model.py +0 -0
- model.safetensors +3 -0
- modeling_pragya.py +95 -0
- ngram.py +459 -0
config.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
use_liger=False
|
| 3 |
+
xla_on_gpu=False
|
| 4 |
+
# ---------------------------------------------------------------------------
|
| 5 |
+
# Core shape -- chosen for GPU efficiency, not just "a number that fits"
|
| 6 |
+
# ---------------------------------------------------------------------------
|
| 7 |
+
CONTEXT = 1024
|
| 8 |
+
max_gen_tokens = 1024
|
| 9 |
+
gen_headroom = 128
|
| 10 |
+
vocab_size = 8192+4096
|
| 11 |
+
# ββ Engram (static n-gram memory) ββββββββββββββββββββββββββββββββββ
|
| 12 |
+
use_engram = True
|
| 13 |
+
engram_layer_ids = (1, 8) # two layers, one early, one mid
|
| 14 |
+
engram_max_ngram = 3 # 2-gram + 3-gram tables
|
| 15 |
+
engram_vocab_size = (4096, 4096) # halved from default
|
| 16 |
+
engram_embed_per_ngram = 128
|
| 17 |
+
engram_n_heads = 4
|
| 18 |
+
engram_kernel_size = 4
|
| 19 |
+
engram_seed = 0
|
| 20 |
+
engram_compressed_vocab = 0 # 0 β set from tokenizer lookup
|
| 21 |
+
bias = False
|
| 22 |
+
d_rope = None
|
| 23 |
+
top_k = 64
|
| 24 |
+
moe_top_k = 2
|
| 25 |
+
use_triton_fusions = False
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
gradient_checkpointing = False
|
| 29 |
+
num_kv_heads = 4
|
| 30 |
+
pattern = "dense"
|
| 31 |
+
sliding_window_size = 512
|
| 32 |
+
|
| 33 |
+
tensor_parallel_size = 1
|
| 34 |
+
|
| 35 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
+
# Curriculum learning (token-level mixing across sources)
|
| 37 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
+
# Master switch. False = old behavior (uniform random over the whole
|
| 39 |
+
# flat token array). True = per-source anchor schedule below.
|
| 40 |
+
CURRICULUM_ENABLED = False
|
| 41 |
+
|
| 42 |
+
# Number of training steps the anchor schedule spans. Set equal to
|
| 43 |
+
# MAX_STEPS in train.py so the ramp completes at run end.
|
| 44 |
+
CURRICULUM_TOTAL_STEPS = 20000
|
| 45 |
+
|
| 46 |
+
# Sources, in curriculum order (easiest first). Each entry:
|
| 47 |
+
# (name, [glob_patterns], w@0, w@T/3, w@2T/3, w@T)
|
| 48 |
+
# Between anchors, weights interpolate linearly. Columns should sum
|
| 49 |
+
# to ~1.0 (the code renormalizes if not).
|
| 50 |
+
# Files matching none of the globs are EXCLUDED from training.
|
| 51 |
+
CURRICULUM_SOURCES = [
|
| 52 |
+
("tinystories", ["tinystories*.txt", "tiny_*.txt"],
|
| 53 |
+
0.70, 0.10, 0.03, 0.02),
|
| 54 |
+
("simplewiki", ["simplewiki*.txt", "wiki_*.txt"],
|
| 55 |
+
0.10, 0.70, 0.10, 0.03),
|
| 56 |
+
("cosmopedia", ["cosmopedia*.txt", "cosmo_*.txt"],
|
| 57 |
+
0.10, 0.10, 0.70, 0.10),
|
| 58 |
+
("finephrase", ["finephrase*.txt", "fine_*.txt"],
|
| 59 |
+
0.10, 0.10, 0.17, 0.85),
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
# Hard floor: no source ever drops below this fraction at any step.
|
| 63 |
+
# 0.0 disables. 0.02 = 2% minimum, prevents catastrophic forgetting.
|
| 64 |
+
CURRICULUM_FLOOR = 0.02
|
| 65 |
+
|
| 66 |
+
mod_capacity = 0.25
|
| 67 |
+
use_mtp = False
|
| 68 |
+
mtp_depth = 1
|
| 69 |
+
mtp_lambda = 0.1
|
| 70 |
+
use_nvfp4 = False
|
| 71 |
+
# config.py
|
| 72 |
+
use_fp8 = False
|
| 73 |
+
fp8_recipe = "rowwise_with_gw_hp" # default
|
| 74 |
+
fp8_bf16_tail_frac = 0.15 # default
|
| 75 |
+
use_int8 = False
|
| 76 |
+
int8_group_size = 128
|
| 77 |
+
mod_budget_coeff = 0.05
|
| 78 |
+
mod_gate_entropy_coeff = 0.0
|
| 79 |
+
mod_hard_eval = False
|
| 80 |
+
use_flexattention = True
|
| 81 |
+
numberoflayers = 16
|
| 82 |
+
numberofheads = 12
|
| 83 |
+
D_MODEL = 384
|
| 84 |
+
ALPHA_COMPILE_MODE="reduce-overhead"
|
| 85 |
+
num_kv_heads = 6
|
| 86 |
+
sliding_window_size = 512
|
| 87 |
+
use_sdpa=False
|
| 88 |
+
optimizer_8bit = True
|
| 89 |
+
use_wsd = True
|
| 90 |
+
wsd_decay_steps = 3500
|
| 91 |
+
ffn_mult = 8 // 3
|
| 92 |
+
use_moe = False
|
| 93 |
+
n_experts = 8
|
| 94 |
+
n_shared = 1
|
| 95 |
+
# T4 path
|
| 96 |
+
|
| 97 |
+
PRECISION = 'bf16'
|
| 98 |
+
GLOBAL_DTYPE = PRECISION
|
| 99 |
+
USE_ASYNC_LAYER_PREFETCH = True
|
| 100 |
+
intra_op_threads = 2
|
| 101 |
+
num_workers = 2
|
| 102 |
+
GPU_SIDE_BATCHING = True
|
| 103 |
+
DISABLE_MMAP = False
|
| 104 |
+
|
| 105 |
+
batch_size = 320
|
| 106 |
+
weight_decay = 0.01
|
| 107 |
+
use_static_lr = False
|
| 108 |
+
static_lr = 1e-3
|
| 109 |
+
learning_rate = 1e-3
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
attn_gate_window = 16
|
| 113 |
+
max_steps = 19000
|
| 114 |
+
data_parallel_only = True
|
| 115 |
+
use_fsdp = False
|
| 116 |
+
dropout = 0.0
|
| 117 |
+
use_muon = True
|
| 118 |
+
DATA_PATH = './training_data'
|
| 119 |
+
data_path = DATA_PATH
|
| 120 |
+
TOKENIZER_MODEL_PATH = './tokenizer'
|
| 121 |
+
use_streaming_batcher = False
|
kernel.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FlexAttention-only attention kernel.
|
| 2 |
+
|
| 3 |
+
One backend, one code path: no device probing, no backend dispatch, no try/except fallbacks.
|
| 4 |
+
Every attention layer calls `fused_attention(q, k, v, block_mask)`; what each layer may attend to
|
| 5 |
+
(causal / sliding window / same-document) lives entirely in the BlockMask, which GPT.forward builds
|
| 6 |
+
once per forward and shares across layers.
|
| 7 |
+
|
| 8 |
+
Requires CUDA + torch >= 2.5 (`create_block_mask(..., _compile=True)`). Attention-weight dropout is not
|
| 9 |
+
supported (DenseMHA refuses dropout > 0 at construction).
|
| 10 |
+
"""
|
| 11 |
+
import functools
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch.nn.attention.flex_attention import create_block_mask, flex_attention
|
| 15 |
+
|
| 16 |
+
_USE_COMPILED_FLEX = torch.cuda.is_available() and torch.version.cuda is not None
|
| 17 |
+
if _USE_COMPILED_FLEX:
|
| 18 |
+
_flex = torch.compile(flex_attention, dynamic=False)
|
| 19 |
+
else:
|
| 20 |
+
_flex = flex_attention
|
| 21 |
+
|
| 22 |
+
def fused_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, block_mask) -> torch.Tensor:
|
| 23 |
+
"""q: (B, Hq, T, D); k, v: (B, Hkv, T, D). GQA is handled natively (Hq may be a multiple of Hkv)."""
|
| 24 |
+
return _flex(q, k, v, block_mask=block_mask, enable_gqa=q.shape[1] != k.shape[1])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
# BlockMasks. One uniform mask_mod for every layer: `window = window_size or seq_len`, and since
|
| 29 |
+
# q - kv <= seq_len - 1 < seq_len, "no window" is the same expression as "window = seq_len".
|
| 30 |
+
# Both builders are compiler-disabled (BlockMask construction is not traced) and are called once per
|
| 31 |
+
# forward from GPT.forward -- that is the only graph boundary in the attention path.
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
|
| 34 |
+
@functools.lru_cache(maxsize=None)
|
| 35 |
+
def _causal_mask(seq_len: int, window_size, device_key: str):
|
| 36 |
+
window = window_size or seq_len
|
| 37 |
+
|
| 38 |
+
def mask_mod(b, h, q_idx, kv_idx):
|
| 39 |
+
return (kv_idx <= q_idx) & (q_idx - kv_idx < window)
|
| 40 |
+
|
| 41 |
+
return create_block_mask(mask_mod, B=None, H=None, Q_LEN=seq_len, KV_LEN=seq_len, device=device_key)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@torch.compiler.disable
|
| 45 |
+
def causal_masks(seq_len: int, windows, device) -> dict:
|
| 46 |
+
"""{window_size: BlockMask} for plain causal attention; cached per (seq_len, window, device)."""
|
| 47 |
+
return {w: _causal_mask(seq_len, w, str(device)) for w in windows}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@torch.compiler.disable
|
| 51 |
+
def doc_masks(doc_ids: torch.Tensor, windows) -> dict:
|
| 52 |
+
"""{window_size: BlockMask} for causal + same-document attention. doc_ids: (B, T) int, per batch.
|
| 53 |
+
_compile=True fuses mask_mod, so the (B, T, T) boolean grid is never materialised."""
|
| 54 |
+
b_, t_ = doc_ids.shape
|
| 55 |
+
|
| 56 |
+
def build(window_size):
|
| 57 |
+
window = window_size or t_
|
| 58 |
+
|
| 59 |
+
def mask_mod(b, h, q_idx, kv_idx):
|
| 60 |
+
return (doc_ids[b, q_idx] == doc_ids[b, kv_idx]) & (kv_idx <= q_idx) & (q_idx - kv_idx < window)
|
| 61 |
+
|
| 62 |
+
return create_block_mask(mask_mod, B=b_, H=None, Q_LEN=t_, KV_LEN=t_,
|
| 63 |
+
device=doc_ids.device, _compile=True)
|
| 64 |
+
|
| 65 |
+
return {w: build(w) for w in windows}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# Telemetry counters (model.py records its Liger/Triton success/fallback events here).
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
_backend_stats: dict[str, int] = {}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _record_backend(name: str) -> None:
|
| 76 |
+
# Inside a compiled region this body runs only at trace time, so counting here under-reports (verified:
|
| 77 |
+
# 5 compiled calls -> 3 counts). Record nothing while compiling rather than report wrong numbers.
|
| 78 |
+
if torch.compiler.is_compiling():
|
| 79 |
+
return
|
| 80 |
+
_backend_stats[name] = _backend_stats.get(name, 0) + 1
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_backend_stats() -> dict[str, int]:
|
| 84 |
+
return dict(_backend_stats)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def reset_backend_stats() -> None:
|
| 88 |
+
_backend_stats.clear()
|
model.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6bda020f242b2643ac1f753b31e43d178f76eccc81899ffe26798a33a0189a9
|
| 3 |
+
size 114127224
|
modeling_pragya.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import GenerationMixin, PreTrainedModel
|
| 5 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 6 |
+
|
| 7 |
+
from .configuration_pragya import PragyaConfig
|
| 8 |
+
from .model import GPT, GPTConfig
|
| 9 |
+
|
| 10 |
+
# Config field names that differ between PragyaConfig and GPTConfig.
|
| 11 |
+
_RENAMED = {"top_k": "gpt_top_k"}
|
| 12 |
+
# Fields GPTConfig stores as tuples, which PragyaConfig stores as lists.
|
| 13 |
+
_TUPLE_FIELDS = ("engram_layer_ids", "engram_vocab_size")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def to_gpt_config(cfg: PragyaConfig) -> GPTConfig:
|
| 17 |
+
"""Build a GPTConfig from every field, so no value comes from config.py defaults."""
|
| 18 |
+
kwargs = {}
|
| 19 |
+
for f in dataclasses.fields(GPTConfig):
|
| 20 |
+
value = getattr(cfg, _RENAMED.get(f.name, f.name))
|
| 21 |
+
if f.name in _TUPLE_FIELDS:
|
| 22 |
+
value = tuple(value)
|
| 23 |
+
kwargs[f.name] = value
|
| 24 |
+
return GPTConfig(**kwargs)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _non_persistent_buffers(module):
|
| 28 |
+
"""{name: tensor} for every non-persistent buffer in a torch module tree."""
|
| 29 |
+
out = {}
|
| 30 |
+
for prefix, sub in module.named_modules():
|
| 31 |
+
for buf_name in sub._non_persistent_buffers_set:
|
| 32 |
+
full = f"{prefix}.{buf_name}" if prefix else buf_name
|
| 33 |
+
out[full] = getattr(sub, buf_name)
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PragyaForCausalLM(PreTrainedModel, GenerationMixin):
|
| 38 |
+
config_class = PragyaConfig
|
| 39 |
+
base_model_prefix = "model"
|
| 40 |
+
main_input_name = "input_ids"
|
| 41 |
+
supports_gradient_checkpointing = False
|
| 42 |
+
# wte.weight and lm_head.weight are one tensor; save only lm_head.weight.
|
| 43 |
+
_tied_weights_keys = {"model.transformer.wte.weight": "model.lm_head.weight"}
|
| 44 |
+
|
| 45 |
+
def __init__(self, config: PragyaConfig):
|
| 46 |
+
super().__init__(config)
|
| 47 |
+
if config.use_engram and config.engram_compressed_vocab <= 0:
|
| 48 |
+
raise ValueError(
|
| 49 |
+
"engram_compressed_vocab must be set before loading. It is computed from the "
|
| 50 |
+
"tokenizer when the model is first built, so the export step must record it."
|
| 51 |
+
)
|
| 52 |
+
self.model = GPT(to_gpt_config(config))
|
| 53 |
+
self.post_init()
|
| 54 |
+
|
| 55 |
+
def _move_missing_keys_from_meta_to_device(self, missing_keys, device_map, device_mesh, hf_quantizer):
|
| 56 |
+
# Transformers replaces every non-persistent buffer (RoPE tables, XSA masks, Engram
|
| 57 |
+
# `mods`) with uninitialised memory when loading. They are derived from the config,
|
| 58 |
+
# so rebuild them from a freshly constructed GPT.
|
| 59 |
+
super()._move_missing_keys_from_meta_to_device(missing_keys, device_map, device_mesh, hf_quantizer)
|
| 60 |
+
fresh = GPT(to_gpt_config(self.config))
|
| 61 |
+
own = _non_persistent_buffers(self.model)
|
| 62 |
+
with torch.no_grad():
|
| 63 |
+
for name, buf in _non_persistent_buffers(fresh).items():
|
| 64 |
+
own[name].copy_(buf)
|
| 65 |
+
del fresh
|
| 66 |
+
# wte and lm_head are one tensor (checkpoint stores only lm_head). Re-tie after load.
|
| 67 |
+
self.model.transformer.wte.weight = self.model.lm_head.weight
|
| 68 |
+
|
| 69 |
+
def _init_weights(self, module):
|
| 70 |
+
# Weights come from GPT.__init__ (Engram tables, zero-init attention gate, tied
|
| 71 |
+
# embeddings) or from the checkpoint. Transformers' default would overwrite them.
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
def get_input_embeddings(self):
|
| 75 |
+
return self.model.transformer.wte
|
| 76 |
+
|
| 77 |
+
def get_output_embeddings(self):
|
| 78 |
+
return self.model.lm_head
|
| 79 |
+
|
| 80 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
|
| 81 |
+
if attention_mask is not None and not bool(torch.all(attention_mask == 1)):
|
| 82 |
+
# The model has no attention-mask support. Padded batches would silently
|
| 83 |
+
# attend to pad tokens, so refuse rather than return wrong results.
|
| 84 |
+
raise NotImplementedError(
|
| 85 |
+
"attention_mask with padding is not supported. Run one sequence at a time "
|
| 86 |
+
"or pass unpadded batches of equal length."
|
| 87 |
+
)
|
| 88 |
+
# With labels: full logits (B, T, V) and loss.
|
| 89 |
+
# Without labels: logits for the last position only, (B, 1, V).
|
| 90 |
+
logits, loss = self.model(input_ids, targets=labels)
|
| 91 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits)
|
| 92 |
+
|
| 93 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 94 |
+
# No KV cache: GPT keeps its own cache format, so every step runs on the full sequence.
|
| 95 |
+
return {"input_ids": input_ids}
|
ngram.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Engram -- static n-gram memory (arXiv:2601.07372, DeepSeek engram_demo_v1.py),
|
| 3 |
+
adapted for Veylon/Arya's standard transformer (hc_mult = 1, tiktoken).
|
| 4 |
+
|
| 5 |
+
Fixes vs. the drafted port (all verified in test_engram.py):
|
| 6 |
+
|
| 7 |
+
1. Hashing ran on CPU/numpy INSIDE forward(): a GPU->CPU sync + torch.compile
|
| 8 |
+
graph break on every Engram layer, every step (and fatal on XLA). Now the
|
| 9 |
+
hash is pure int64 torch ops on the model device, compile-friendly.
|
| 10 |
+
2. Every Engram layer built its own NgramHashMapping (re-decoding the whole
|
| 11 |
+
vocab) and each call hashed ALL layers, then kept one. Now ONE NgramHasher
|
| 12 |
+
lives on GPT, hashes all layers once per forward.
|
| 13 |
+
3. pad_id=None crashed np.pad; pad_id=-1 silently indexed the LAST lookup
|
| 14 |
+
entry. Left-context padding is now a dedicated reserved id (never
|
| 15 |
+
collides with a real token class).
|
| 16 |
+
4. nn.RMSNorm (torch>=2.4 only, eps=finfo(fp16)=1e-3 default) replaced by a local
|
| 17 |
+
_RMSNorm (eps=1e-5, weight cast to the input dtype) matching model.RMSNorm's eager
|
| 18 |
+
path. It does NOT upcast to fp32.
|
| 19 |
+
5. Gate dot-product computed in fp32 (sum over D in fp16 can overflow/lose
|
| 20 |
+
precision), cast back after the sigmoid.
|
| 21 |
+
6. The compressed-vocab lookup is now a persistent buffer, so a checkpoint
|
| 22 |
+
carries it and inference needs no tokenizer object.
|
| 23 |
+
7. sympy dependency dropped (trial-division primality is plenty for table sizes).
|
| 24 |
+
8. Special-id discovery no longer assumes TokenizerWrapper._special_ids is a
|
| 25 |
+
set of ints (dict / missing attr both handled).
|
| 26 |
+
9. embed_per_ngram % n_heads != 0 silently produced a wrong-width table ->
|
| 27 |
+
hard assert. Same for len(engram_vocab_size) < max_ngram-1.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
import math
|
| 33 |
+
import re
|
| 34 |
+
import unicodedata
|
| 35 |
+
import warnings
|
| 36 |
+
from typing import List, Sequence
|
| 37 |
+
|
| 38 |
+
import numpy as np
|
| 39 |
+
import torch
|
| 40 |
+
import torch.nn as nn
|
| 41 |
+
import torch.nn.functional as F
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 45 |
+
# Primes
|
| 46 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
|
| 48 |
+
def _is_prime(n: int) -> bool:
|
| 49 |
+
if n < 2:
|
| 50 |
+
return False
|
| 51 |
+
if n < 4:
|
| 52 |
+
return True
|
| 53 |
+
if n % 2 == 0 or n % 3 == 0:
|
| 54 |
+
return False
|
| 55 |
+
i = 5
|
| 56 |
+
while i * i <= n:
|
| 57 |
+
if n % i == 0 or n % (i + 2) == 0:
|
| 58 |
+
return False
|
| 59 |
+
i += 6
|
| 60 |
+
return True
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def find_next_prime(start: int, seen_primes: set) -> int:
|
| 64 |
+
candidate = start + 1
|
| 65 |
+
while True:
|
| 66 |
+
if _is_prime(candidate) and candidate not in seen_primes:
|
| 67 |
+
return candidate
|
| 68 |
+
candidate += 1
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
+
# CompressedTokenizer -- build-time only (numpy). Output is a lookup table.
|
| 73 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
|
| 75 |
+
class CompressedTokenizer:
|
| 76 |
+
"""Maps raw token IDs -> compressed IDs (NFKC / strip-accents / lowercase /
|
| 77 |
+
whitespace-collapse of each token's surface string). Build-time only: the
|
| 78 |
+
result (`lookup_table`) is handed to the model as a persistent buffer."""
|
| 79 |
+
|
| 80 |
+
_SENTINEL = "\uE000"
|
| 81 |
+
_WS_RE = re.compile(r"[ \t\r\n]+")
|
| 82 |
+
|
| 83 |
+
def __init__(self, tokenizer_wrapper):
|
| 84 |
+
self.tokenizer = tokenizer_wrapper
|
| 85 |
+
self._special_ids = self._collect_special_ids(tokenizer_wrapper)
|
| 86 |
+
self.lookup_table, self.num_new_token = self._build_lookup_table()
|
| 87 |
+
|
| 88 |
+
def __len__(self):
|
| 89 |
+
return self.num_new_token
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def _collect_special_ids(tw) -> set:
|
| 93 |
+
ids = set()
|
| 94 |
+
raw = getattr(tw, "_special_ids", None)
|
| 95 |
+
if raw is not None:
|
| 96 |
+
if isinstance(raw, dict):
|
| 97 |
+
for k, v in raw.items():
|
| 98 |
+
for cand in (k, v):
|
| 99 |
+
if isinstance(cand, (int, np.integer)):
|
| 100 |
+
ids.add(int(cand))
|
| 101 |
+
else:
|
| 102 |
+
for v in raw:
|
| 103 |
+
if isinstance(v, (int, np.integer)):
|
| 104 |
+
ids.add(int(v))
|
| 105 |
+
vs = int(tw.vocab_size)
|
| 106 |
+
for name in ("bos_id", "eos_id", "pad_id"):
|
| 107 |
+
v = getattr(tw, name, None)
|
| 108 |
+
if isinstance(v, (int, np.integer)) and 0 <= int(v) < vs:
|
| 109 |
+
ids.add(int(v))
|
| 110 |
+
return ids
|
| 111 |
+
|
| 112 |
+
@classmethod
|
| 113 |
+
def _normalize(cls, text: str) -> str:
|
| 114 |
+
text = unicodedata.normalize("NFKC", text)
|
| 115 |
+
text = unicodedata.normalize("NFD", text)
|
| 116 |
+
text = "".join(c for c in text if unicodedata.category(c) != "Mn")
|
| 117 |
+
text = text.lower()
|
| 118 |
+
text = cls._WS_RE.sub(" ", text)
|
| 119 |
+
if text == " ": # lone space survives strip()
|
| 120 |
+
text = cls._SENTINEL
|
| 121 |
+
text = text.strip()
|
| 122 |
+
return text.replace(cls._SENTINEL, " ")
|
| 123 |
+
|
| 124 |
+
def _decode_id(self, tid: int) -> str:
|
| 125 |
+
tw = self.tokenizer
|
| 126 |
+
try:
|
| 127 |
+
enc = getattr(tw, "enc", None)
|
| 128 |
+
if enc is not None:
|
| 129 |
+
return enc.decode([tid])
|
| 130 |
+
return tw.decode([tid])
|
| 131 |
+
except Exception:
|
| 132 |
+
return ""
|
| 133 |
+
|
| 134 |
+
def _build_lookup_table(self):
|
| 135 |
+
key2new, new_tokens = {}, []
|
| 136 |
+
vocab_size = int(self.tokenizer.vocab_size)
|
| 137 |
+
lookup = np.empty(vocab_size, dtype=np.int64)
|
| 138 |
+
for tid in range(vocab_size):
|
| 139 |
+
if tid in self._special_ids:
|
| 140 |
+
key = f"__special_{tid}"
|
| 141 |
+
else:
|
| 142 |
+
text = self._decode_id(tid)
|
| 143 |
+
if not text or "\ufffd" in text:
|
| 144 |
+
key = f"__raw_{tid}"
|
| 145 |
+
else:
|
| 146 |
+
norm = self._normalize(text)
|
| 147 |
+
key = norm if norm else f"__raw_{tid}"
|
| 148 |
+
nid = key2new.get(key)
|
| 149 |
+
if nid is None:
|
| 150 |
+
nid = len(new_tokens)
|
| 151 |
+
key2new[key] = nid
|
| 152 |
+
new_tokens.append(key)
|
| 153 |
+
lookup[tid] = nid
|
| 154 |
+
return lookup, len(new_tokens)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 158 |
+
# NgramHasher -- static, deterministic, layer-specific, pure torch int64
|
| 159 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 160 |
+
|
| 161 |
+
class NgramHasher(nn.Module):
|
| 162 |
+
"""(B, T) raw ids -> per-layer embedding indices of shape (B, T, n_cols).
|
| 163 |
+
|
| 164 |
+
No parameters, no gradients. `lookup` and the hash multipliers `mult` are
|
| 165 |
+
persistent (state_dict); the prime moduli `mods` are re-derived from config.
|
| 166 |
+
`mult` comes from NumPy's Generator, which is not guaranteed stable across
|
| 167 |
+
NumPy releases, so it is saved with the checkpoint instead of re-derived.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def __init__(self, layer_ids: Sequence[int], max_ngram: int,
|
| 171 |
+
vocab_size_per_ngram: Sequence[int], n_heads: int,
|
| 172 |
+
compressed_vocab: int, raw_vocab_size: int, seed: int,
|
| 173 |
+
lookup: torch.Tensor | None = None):
|
| 174 |
+
super().__init__()
|
| 175 |
+
assert max_ngram >= 2, "engram_max_ngram must be >= 2"
|
| 176 |
+
assert len(vocab_size_per_ngram) >= max_ngram - 1, (
|
| 177 |
+
f"engram_vocab_size needs {max_ngram - 1} entries (ngram 2..{max_ngram}), "
|
| 178 |
+
f"got {len(vocab_size_per_ngram)}"
|
| 179 |
+
)
|
| 180 |
+
assert compressed_vocab > 0, "engram_compressed_vocab must be set (>0)"
|
| 181 |
+
|
| 182 |
+
self.layer_ids = tuple(int(l) for l in layer_ids)
|
| 183 |
+
self.max_ngram = int(max_ngram)
|
| 184 |
+
self.n_heads = int(n_heads)
|
| 185 |
+
self.n_cols = (self.max_ngram - 1) * self.n_heads
|
| 186 |
+
self.compressed_vocab = int(compressed_vocab)
|
| 187 |
+
# Reserved id for left-context padding: distinct from every token class.
|
| 188 |
+
self.pad_cid = self.compressed_vocab
|
| 189 |
+
|
| 190 |
+
if lookup is None:
|
| 191 |
+
# Every token would hash to class 0 and Engram would silently ignore its input. This is only
|
| 192 |
+
# valid if a checkpoint (which carries `lookup`) is loaded right after construction.
|
| 193 |
+
warnings.warn(
|
| 194 |
+
"NgramHasher built without a lookup table: all tokens map to class 0 until a checkpoint "
|
| 195 |
+
"containing `lookup` is loaded. Pass engram_lookup from CompressedTokenizer for training.",
|
| 196 |
+
stacklevel=2)
|
| 197 |
+
lookup = torch.zeros(int(raw_vocab_size), dtype=torch.int64)
|
| 198 |
+
else:
|
| 199 |
+
lookup = lookup.detach().to(torch.int64).clone()
|
| 200 |
+
assert lookup.numel() == int(raw_vocab_size), (
|
| 201 |
+
f"lookup has {lookup.numel()} entries, vocab_size={raw_vocab_size}")
|
| 202 |
+
assert int(lookup.max()) < self.compressed_vocab
|
| 203 |
+
self.register_buffer("lookup", lookup, persistent=True)
|
| 204 |
+
|
| 205 |
+
# Multipliers: r*2+1, bounded so tok*mult can never overflow int64.
|
| 206 |
+
# (+1 vocab slot for the reserved pad id.)
|
| 207 |
+
max_long = int(np.iinfo(np.int64).max)
|
| 208 |
+
M_max = max_long // (self.compressed_vocab + 1)
|
| 209 |
+
half_bound = max(1, M_max // 2)
|
| 210 |
+
PRIME_1 = 10007
|
| 211 |
+
mult = np.empty((len(self.layer_ids), self.max_ngram), dtype=np.int64)
|
| 212 |
+
for li, layer_id in enumerate(self.layer_ids):
|
| 213 |
+
g = np.random.default_rng(int(seed + PRIME_1 * int(layer_id)))
|
| 214 |
+
r = g.integers(low=0, high=half_bound, size=(self.max_ngram,), dtype=np.int64)
|
| 215 |
+
mult[li] = r * 2 + 1
|
| 216 |
+
self.register_buffer("mult", torch.from_numpy(mult), persistent=True)
|
| 217 |
+
|
| 218 |
+
# Distinct prime moduli per (layer, ngram order, head); unique globally.
|
| 219 |
+
seen: set = set()
|
| 220 |
+
self.head_sizes: List[List[int]] = [] # per layer: flat list, len n_cols
|
| 221 |
+
for _ in self.layer_ids:
|
| 222 |
+
flat = []
|
| 223 |
+
for ngram in range(2, self.max_ngram + 1):
|
| 224 |
+
search_start = int(vocab_size_per_ngram[ngram - 2]) - 1
|
| 225 |
+
for _h in range(self.n_heads):
|
| 226 |
+
found = find_next_prime(search_start, seen)
|
| 227 |
+
seen.add(found)
|
| 228 |
+
flat.append(found)
|
| 229 |
+
search_start = found
|
| 230 |
+
self.head_sizes.append(flat)
|
| 231 |
+
self.register_buffer(
|
| 232 |
+
"mods", torch.tensor(self.head_sizes, dtype=torch.int64), persistent=False)
|
| 233 |
+
head_offsets = []
|
| 234 |
+
for sizes in self.head_sizes:
|
| 235 |
+
offsets = []
|
| 236 |
+
offset = 0
|
| 237 |
+
for size in sizes:
|
| 238 |
+
offsets.append(offset)
|
| 239 |
+
offset += size
|
| 240 |
+
head_offsets.append(offsets)
|
| 241 |
+
self.register_buffer(
|
| 242 |
+
"head_offsets", torch.tensor(head_offsets, dtype=torch.int64), persistent=False)
|
| 243 |
+
|
| 244 |
+
def compress(self, idx: torch.Tensor) -> torch.Tensor:
|
| 245 |
+
return self.lookup[idx.long()] # idx is never negative (the -1 ignore index lives in targets)
|
| 246 |
+
|
| 247 |
+
def forward(self, idx: torch.Tensor, doc_ids: torch.Tensor | None = None,
|
| 248 |
+
cache: dict | None = None):
|
| 249 |
+
"""Hash tokens, optionally using cached history for incremental decoding.
|
| 250 |
+
|
| 251 |
+
doc_ids (B, T), when supplied, replaces cross-document history with the
|
| 252 |
+
left-padding id so packed documents hash as if processed separately.
|
| 253 |
+
"""
|
| 254 |
+
ids = self.compress(idx) # (B, T_new)
|
| 255 |
+
B, T_new = ids.shape
|
| 256 |
+
K = self.max_ngram - 1
|
| 257 |
+
|
| 258 |
+
if cache is not None:
|
| 259 |
+
hist_ids = cache.get("hash_hist_ids")
|
| 260 |
+
hist_doc = cache.get("hash_hist_doc")
|
| 261 |
+
if hist_ids is None:
|
| 262 |
+
hist_ids = ids.new_full((B, K), self.pad_cid)
|
| 263 |
+
hist_doc = (
|
| 264 |
+
torch.full((B, K), -1, dtype=doc_ids.dtype, device=doc_ids.device)
|
| 265 |
+
if doc_ids is not None else None
|
| 266 |
+
)
|
| 267 |
+
else:
|
| 268 |
+
hist_ids = hist_ids.to(device=ids.device)
|
| 269 |
+
if hist_doc is not None:
|
| 270 |
+
hist_doc = hist_doc.to(device=ids.device)
|
| 271 |
+
full_ids = torch.cat([hist_ids, ids], dim=1) # (B, K + T_new)
|
| 272 |
+
if doc_ids is not None and hist_doc is not None:
|
| 273 |
+
full_doc = torch.cat([hist_doc, doc_ids], dim=1)
|
| 274 |
+
else:
|
| 275 |
+
full_doc = doc_ids
|
| 276 |
+
cache["hash_hist_ids"] = full_ids[:, -K:].detach()
|
| 277 |
+
if full_doc is not None:
|
| 278 |
+
cache["hash_hist_doc"] = full_doc[:, -K:].detach()
|
| 279 |
+
else:
|
| 280 |
+
full_ids, full_doc = ids, doc_ids
|
| 281 |
+
|
| 282 |
+
T_full = full_ids.shape[1]
|
| 283 |
+
# Keep only one running hash per layer and one shifted-id tensor per order;
|
| 284 |
+
# broadcasting all layers and orders at once creates a large int64 product.
|
| 285 |
+
mixes = [full_ids * self.mult[li, 0] for li in range(len(self.layer_ids))]
|
| 286 |
+
out = {
|
| 287 |
+
layer_id: torch.empty(
|
| 288 |
+
(B, T_full, self.n_cols), dtype=torch.int64, device=full_ids.device)
|
| 289 |
+
for layer_id in self.layer_ids
|
| 290 |
+
}
|
| 291 |
+
for n in range(2, self.max_ngram + 1):
|
| 292 |
+
shifted = F.pad(full_ids, (n - 1, 0), value=self.pad_cid)[:, :T_full]
|
| 293 |
+
if full_doc is not None:
|
| 294 |
+
same = F.pad(full_doc, (n - 1, 0), value=-1)[:, :T_full] == full_doc
|
| 295 |
+
shifted = torch.where(same, shifted, torch.full_like(shifted, self.pad_cid))
|
| 296 |
+
lo = (n - 2) * self.n_heads
|
| 297 |
+
hi = lo + self.n_heads
|
| 298 |
+
for li, layer_id in enumerate(self.layer_ids):
|
| 299 |
+
mix = torch.bitwise_xor(mixes[li], shifted * self.mult[li, n - 1])
|
| 300 |
+
mixes[li] = mix
|
| 301 |
+
col = mix.unsqueeze(-1) % self.mods[li, lo:hi]
|
| 302 |
+
col += self.head_offsets[li, lo:hi]
|
| 303 |
+
out[layer_id][..., lo:hi] = col
|
| 304 |
+
if T_full > T_new:
|
| 305 |
+
out = {layer_id: values[:, -T_new:].contiguous() for layer_id, values in out.items()}
|
| 306 |
+
return out
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 310 |
+
# Modules
|
| 311 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 312 |
+
|
| 313 |
+
class _RMSNorm(nn.Module):
|
| 314 |
+
"""RMSNorm with fused accumulation for the input dtype."""
|
| 315 |
+
|
| 316 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 317 |
+
super().__init__()
|
| 318 |
+
self.eps = eps
|
| 319 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 320 |
+
|
| 321 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 322 |
+
return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), self.eps)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class ShortConv(nn.Module):
|
| 326 |
+
"""(B, T, D) -> (B, T, D). Depthwise causal conv, dilation = max_ngram."""
|
| 327 |
+
|
| 328 |
+
def __init__(self, hidden_size: int, kernel_size: int = 4,
|
| 329 |
+
dilation: int = 1, activation: bool = True):
|
| 330 |
+
super().__init__()
|
| 331 |
+
self.activation = activation
|
| 332 |
+
self.kernel_size = kernel_size
|
| 333 |
+
self.dilation = dilation
|
| 334 |
+
self.conv = nn.Conv1d(
|
| 335 |
+
hidden_size, hidden_size, kernel_size=kernel_size,
|
| 336 |
+
groups=hidden_size, bias=False,
|
| 337 |
+
padding=(kernel_size - 1) * dilation, dilation=dilation,
|
| 338 |
+
)
|
| 339 |
+
self.norm = _RMSNorm(hidden_size)
|
| 340 |
+
self.act_fn = nn.SiLU() if activation else None
|
| 341 |
+
|
| 342 |
+
def forward(self, x: torch.Tensor, doc_ids: torch.Tensor | None = None,
|
| 343 |
+
cache: dict | None = None) -> torch.Tensor:
|
| 344 |
+
T = x.shape[1]
|
| 345 |
+
K, d = self.kernel_size, self.dilation
|
| 346 |
+
rf = (K - 1) * d
|
| 347 |
+
B, _, D = x.shape
|
| 348 |
+
xn = self.norm(x) # (B, T, D)
|
| 349 |
+
|
| 350 |
+
if cache is not None:
|
| 351 |
+
hist_xn = cache.get("sc_hist_x")
|
| 352 |
+
hist_doc = cache.get("sc_hist_doc")
|
| 353 |
+
if hist_xn is None:
|
| 354 |
+
hist_xn = xn.new_zeros(B, rf, D)
|
| 355 |
+
hist_doc = (
|
| 356 |
+
torch.full((B, rf), -1, dtype=doc_ids.dtype, device=doc_ids.device)
|
| 357 |
+
if doc_ids is not None else None
|
| 358 |
+
)
|
| 359 |
+
else:
|
| 360 |
+
hist_xn = hist_xn.to(dtype=xn.dtype, device=xn.device)
|
| 361 |
+
if hist_doc is not None:
|
| 362 |
+
hist_doc = hist_doc.to(device=xn.device)
|
| 363 |
+
full_xn = torch.cat([hist_xn, xn], dim=1) if rf > 0 else xn
|
| 364 |
+
if doc_ids is not None and hist_doc is not None:
|
| 365 |
+
full_doc = torch.cat([hist_doc, doc_ids], dim=1) if rf > 0 else doc_ids
|
| 366 |
+
else:
|
| 367 |
+
full_doc = doc_ids
|
| 368 |
+
if rf > 0:
|
| 369 |
+
cache["sc_hist_x"] = full_xn[:, -rf:].detach()
|
| 370 |
+
if full_doc is not None:
|
| 371 |
+
cache["sc_hist_doc"] = full_doc[:, -rf:].detach()
|
| 372 |
+
else:
|
| 373 |
+
full_xn, full_doc = xn, doc_ids
|
| 374 |
+
|
| 375 |
+
T_full = full_xn.shape[1]
|
| 376 |
+
w = self.conv.weight[:, 0, :].to(full_xn.dtype) # (D, K)
|
| 377 |
+
xp = F.pad(full_xn, (0, 0, rf, 0))
|
| 378 |
+
|
| 379 |
+
tap = xp[:, :T_full]
|
| 380 |
+
if full_doc is not None and K > 1:
|
| 381 |
+
s = (K - 1) * d
|
| 382 |
+
same = F.pad(full_doc, (s, 0), value=-1)[:, :T_full] == full_doc
|
| 383 |
+
tap = tap * same.unsqueeze(-1)
|
| 384 |
+
y = tap * w[:, 0]
|
| 385 |
+
for j in range(1, K):
|
| 386 |
+
tap = xp[:, j * d:j * d + T_full]
|
| 387 |
+
if full_doc is not None:
|
| 388 |
+
s = (K - 1 - j) * d
|
| 389 |
+
same = F.pad(full_doc, (s, 0), value=-1)[:, :T_full] == full_doc
|
| 390 |
+
tap = tap * same.unsqueeze(-1)
|
| 391 |
+
y.addcmul_(tap, w[:, j])
|
| 392 |
+
if T_full > T:
|
| 393 |
+
y = y[:, -T:].contiguous()
|
| 394 |
+
if self.activation:
|
| 395 |
+
y = self.act_fn(y)
|
| 396 |
+
return y
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class MultiHeadEmbedding(nn.Module):
|
| 400 |
+
def __init__(self, list_of_N: List[int], D: int):
|
| 401 |
+
super().__init__()
|
| 402 |
+
self.embedding = nn.Embedding(sum(list_of_N), D)
|
| 403 |
+
self.reset_parameters()
|
| 404 |
+
|
| 405 |
+
def reset_parameters(self):
|
| 406 |
+
nn.init.normal_(self.embedding.weight, std=0.01)
|
| 407 |
+
|
| 408 |
+
def forward(self, hash_ids: torch.Tensor) -> torch.Tensor:
|
| 409 |
+
return self.embedding(hash_ids)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class Engram(nn.Module):
|
| 413 |
+
"""Static n-gram memory with conditional gated injection (hc_mult = 1).
|
| 414 |
+
|
| 415 |
+
forward() returns the DELTA to add to the residual stream:
|
| 416 |
+
x = x + engram(x, hash_ids)
|
| 417 |
+
"""
|
| 418 |
+
|
| 419 |
+
def __init__(self, hidden_size: int, head_sizes: List[int], max_ngram: int,
|
| 420 |
+
embed_per_ngram: int, n_heads: int, kernel_size: int):
|
| 421 |
+
super().__init__()
|
| 422 |
+
assert embed_per_ngram % n_heads == 0, (
|
| 423 |
+
f"engram_embed_per_ngram={embed_per_ngram} must be divisible by "
|
| 424 |
+
f"engram_n_heads={n_heads}")
|
| 425 |
+
self.hidden_size = hidden_size
|
| 426 |
+
d_head = embed_per_ngram // n_heads
|
| 427 |
+
engram_hidden = (max_ngram - 1) * embed_per_ngram
|
| 428 |
+
|
| 429 |
+
self.multi_head_embedding = MultiHeadEmbedding(list(head_sizes), d_head)
|
| 430 |
+
self.value_proj = nn.Linear(engram_hidden, hidden_size, bias=False)
|
| 431 |
+
self.key_proj = nn.Linear(engram_hidden, hidden_size, bias=False)
|
| 432 |
+
self.norm1 = _RMSNorm(hidden_size)
|
| 433 |
+
self.norm2 = _RMSNorm(hidden_size)
|
| 434 |
+
self.short_conv = ShortConv(hidden_size, kernel_size=kernel_size,
|
| 435 |
+
dilation=max_ngram)
|
| 436 |
+
self.reset_parameters()
|
| 437 |
+
|
| 438 |
+
def reset_parameters(self):
|
| 439 |
+
self.multi_head_embedding.reset_parameters()
|
| 440 |
+
nn.init.normal_(self.value_proj.weight, std=0.02)
|
| 441 |
+
nn.init.normal_(self.key_proj.weight, std=0.02)
|
| 442 |
+
# Zero-init the conv: ShortConv RMS-normalises its input, so without this the gated value is
|
| 443 |
+
# blown back up to ~1 rms and the initial delta is ~0.13 rms (larger than the residual stream at
|
| 444 |
+
# D<=256). With zeros the branch starts at ~0 and the conv weight gets gradient on step 1.
|
| 445 |
+
nn.init.zeros_(self.short_conv.conv.weight)
|
| 446 |
+
|
| 447 |
+
def forward(self, hidden_states: torch.Tensor, hash_ids: torch.Tensor,
|
| 448 |
+
doc_ids: torch.Tensor | None = None, cache: dict | None = None):
|
| 449 |
+
emb = self.multi_head_embedding(hash_ids).flatten(start_dim=-2) # (B,T,engram_hidden)
|
| 450 |
+
key = self.key_proj(emb)
|
| 451 |
+
nk = self.norm1(key)
|
| 452 |
+
nq = self.norm2(hidden_states)
|
| 453 |
+
# Product AND sum in fp32: with bf16 inputs, rounding nk*nq to bf16 first leaves gate errors up to
|
| 454 |
+
# ~0.02 (sqrt(|g|) amplifies small pre-activations); the casts fuse under torch.compile.
|
| 455 |
+
gate = (nk.float() * nq.float()).sum(dim=-1) / math.sqrt(self.hidden_size)
|
| 456 |
+
gate = gate.abs().clamp_min(1e-6).sqrt() * gate.sign()
|
| 457 |
+
gate = gate.sigmoid().unsqueeze(-1).to(hidden_states.dtype) # (B,T,1)
|
| 458 |
+
value = gate * self.value_proj(emb)
|
| 459 |
+
return value + self.short_conv(value, doc_ids, cache=cache)
|