"""KLM 1.6 for Transformers, in plain PyTorch, so it runs on CPU or any GPU without custom kernels. Parameter names match the training code, and export_hf.py checks the logits against it before writing the weights. A sequence may hold several documents separated by : after each the attention mask, the Gated DeltaNet-2 state, its short convolutions and the n-gram history all restart, as they did in training. generate() decodes with a KLMCache, which keeps the attention layers' keys and values, the Gated DeltaNet-2 recurrent states and convolution windows, and the last two tokens for the n-gram lookup, so every new token costs one step. Left padding (batched generation) starts a new document at each row's first real token, so the pads are never seen; scoring also accepts right padding. """ from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as F from transformers import PreTrainedModel from transformers.generation import GenerationMixin from transformers.modeling_outputs import CausalLMOutputWithPast try: from .configuration_klm import KLMConfig # remote code: sibling module in the cache package except ImportError: from configuration_klm import KLMConfig # direct import from the repo folder CONV = 4 # short-convolution width class KLMCache: """Decoding state of a batch. `layers[i]` is an attention layer's (keys, values) or a Gated DeltaNet-2 layer's (recurrent state, (q, k, v) convolution windows).""" def __init__(self, n_layers: int): self.layers = [None] * n_layers self.length = 0 self.history = None # (B, <=2) last tokens, for the n-gram lookup self.docs = None # (B, length) document id of every cached position self.pos = None # (B,) position of the last token within its document def get_seq_length(self, layer_idx: int = 0) -> int: return self.length def reorder_cache(self, beam_idx: torch.Tensor) -> None: def pick(x): if isinstance(x, tuple): return tuple(pick(t) for t in x) return x.index_select(0, beam_idx.to(x.device)) self.layers = [pick(layer) for layer in self.layers] self.history, self.docs, self.pos = pick((self.history, self.docs, self.pos)) class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x): return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), self.eps) def segments(tokens, eos_id, cache, real=None): """Document-start flags, document ids and in-document positions of new tokens (B, T), continuing the cached sequence. `real` (B, T) marks non-pad tokens of a fresh sequence: a row's first real token after left padding starts a document.""" batch, seq_len = tokens.shape starts = torch.zeros_like(tokens, dtype=torch.bool) starts[:, 1:] = tokens[:, :-1] == eos_id if real is not None: starts[:, 1:] |= real[:, 1:] & ~real[:, :-1] idx = torch.arange(seq_len, device=tokens.device).expand(batch, seq_len) if cache is None or cache.length == 0: starts[:, 0] = True docs = starts.cumsum(1) return starts, docs, idx - torch.where(starts, idx, 0).cummax(1).values starts[:, 0] = cache.history[:, -1] == eos_id docs = cache.docs[:, -1:] + starts.cumsum(1) first = torch.where(starts, idx, -1).cummax(1).values pos = torch.where(first < 0, cache.pos[:, None] + 1 + idx, idx - first) return starts, docs, pos def lookup(keys, queries): """Row of each query in a sorted key bank: p + 1 where keys[p] == query, else 0 (unknown).""" queries = queries.to(keys.dtype) p = torch.searchsorted(keys, queries).clamp_(max=keys.numel() - 1) return torch.where(keys[p] == queries, p + 1, 0) class NgramMemory(nn.Module): """Learned rows for the most frequent bigrams and trigrams, found by exact key lookup. Missing history (row start, or right after ) is token 0.""" def __init__(self, cfg: KLMConfig): super().__init__() self.vocab_size = cfg.vocab_size self.register_buffer("bigram_keys", torch.zeros(cfg.n_bigrams, dtype=torch.int32)) self.register_buffer("trigram_keys", torch.zeros(cfg.n_trigrams, dtype=torch.int64)) self.bigram = nn.Embedding(cfg.n_bigrams + 1, cfg.ngram_dim) self.trigram = nn.Embedding(cfg.n_trigrams + 1, cfg.ngram_dim) self.bigram_proj = nn.Linear(cfg.ngram_dim, cfg.hidden_size, bias=False) self.trigram_proj = nn.Linear(cfg.ngram_dim, cfg.hidden_size, bias=False) def forward(self, tokens, history, eos_id): seq_len = tokens.shape[1] t = tokens.long() if history is None else torch.cat([history, tokens], 1).long() n, v = t.shape[1], self.vocab_size prev1 = F.pad(t, (1, 0))[:, :n] prev2 = F.pad(t, (2, 0))[:, :n] reset = prev1 == eos_id prev1 = prev1.masked_fill(reset, 0) prev2 = prev2.masked_fill(reset | (prev2 == eos_id), 0) bigram = (prev1 * v + t)[:, n - seq_len:] trigram = ((prev2 * v + prev1) * v + t)[:, n - seq_len:] return (self.bigram_proj(self.bigram(lookup(self.bigram_keys, bigram))) + self.trigram_proj(self.trigram(lookup(self.trigram_keys, trigram)))) def rope(x, positions, theta): """Half-rotation RoPE on (B, H, T, D) at absolute positions (T,).""" dim = x.shape[-1] freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device).float() / dim)) angles = positions.float()[:, None] * freqs cos, sin = angles.cos().to(x.dtype), angles.sin().to(x.dtype) x1, x2 = x.chunk(2, dim=-1) return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1) class Attention(nn.Module): """GQA with per-head QK-RMSNorm, RoPE, a sigmoid output gate, and a value residual that mixes each layer's values with the first attention layer's.""" def __init__(self, cfg: KLMConfig): super().__init__() dim = cfg.hidden_size self.n_heads, self.n_kv_heads = cfg.num_attention_heads, cfg.num_key_value_heads self.head_dim = dim // self.n_heads self.theta = cfg.rope_theta self.q_proj = nn.Linear(dim, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=False) self.gate_proj = nn.Linear(dim, dim, bias=False) self.o_proj = nn.Linear(dim, dim, bias=False) self.q_norm = RMSNorm(self.head_dim, cfg.rms_norm_eps) self.k_norm = RMSNorm(self.head_dim, cfg.rms_norm_eps) self.value_mix = nn.Parameter(torch.tensor([0.5, 0.5])) def forward(self, x, v_first, positions, mask, cached): batch, seq_len, dim = x.shape q = self.q_proj(x).view(batch, seq_len, self.n_heads, self.head_dim) k = self.k_proj(x).view(batch, seq_len, self.n_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, seq_len, self.n_kv_heads, self.head_dim) if v_first is None: v_first = v mix = self.value_mix.float() values = (mix[0] * v.float() + mix[1] * v_first.float()).to(x.dtype).transpose(1, 2) q = rope(self.q_norm(q.float()).transpose(1, 2), positions, self.theta).to(x.dtype) keys = rope(self.k_norm(k.float()).transpose(1, 2), positions, self.theta).to(x.dtype) if cached is not None: keys, values = torch.cat([cached[0], keys], 2), torch.cat([cached[1], values], 2) out = F.scaled_dot_product_attention(q, keys, values, attn_mask=mask, enable_gqa=True) out = out.transpose(1, 2).reshape(batch, seq_len, dim) return self.o_proj(out * torch.sigmoid(self.gate_proj(x))), v_first, (keys, values) def short_conv(weight, x, taps_valid, window): """Causal depthwise convolution plus SiLU that never reaches back past a document start. x (B, T, C); taps_valid (B, T, CONV) zeroes taps before the document start; window holds the previous CONV - 1 inputs (B, CONV - 1, C) or is None.""" batch, seq_len, channels = x.shape if window is None: window = x.new_zeros(batch, CONV - 1, channels) ext = torch.cat([window, x], 1) windows = ext.unfold(1, CONV, 1) # (B, T, C, CONV), oldest input first out = (windows * weight.view(channels, CONV).to(x.dtype) * taps_valid.unsqueeze(2)).sum(-1) return F.silu(out), ext[:, -(CONV - 1):] def l2norm(x): return x * torch.rsqrt((x * x).sum(-1, keepdim=True) + 1e-6) def recurrence(q, k, v, g, b, w, starts, state): """Gated DeltaNet-2 step by step in fp32: S <- (I - k (b*k)^T) diag(exp g) S + k (w*v)^T and o = q^T S / sqrt(K), with S cleared at every document start. Inputs are (B, T, H, K).""" batch, seq_len, heads, key_dim = k.shape q = q * key_dim**-0.5 if state is None: state = q.new_zeros(batch, heads, key_dim, v.shape[-1]) keep = (~starts).float() out = [] with torch.autocast(q.device.type, enabled=False): for t in range(seq_len): state = state * (keep[:, t, None, None, None] * g[:, t].exp().unsqueeze(-1)) erase = torch.einsum("bhk,bhkv->bhv", b[:, t] * k[:, t], state) state = state + k[:, t].unsqueeze(-1) * (w[:, t] * v[:, t] - erase).unsqueeze(-2) out.append(torch.einsum("bhk,bhkv->bhv", q[:, t], state)) return torch.stack(out, 1), state class GatedDeltaNet2(nn.Module): """Gated DeltaNet-2 in flash-linear-attention's parameter layout: q/k/v short convolutions, channel-wise erase (b) and write (w) gates, a low-rank channel-wise decay with A_log and dt_bias, and a sigmoid-gated RMSNorm on the output.""" def __init__(self, cfg: KLMConfig): super().__init__() dim, self.heads, self.head_dim = cfg.hidden_size, cfg.gdn_heads, cfg.gdn_head_dim inner = self.heads * self.head_dim self.decay_floor = cfg.decay_floor self.q_proj = nn.Linear(dim, inner, bias=False) self.k_proj = nn.Linear(dim, inner, bias=False) self.v_proj = nn.Linear(dim, inner, bias=False) self.q_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False) self.k_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False) self.v_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False) self.f_proj = nn.Sequential(nn.Linear(dim, self.head_dim, bias=False), nn.Linear(self.head_dim, inner, bias=False)) self.b_proj = nn.Linear(dim, inner, bias=False) self.w_proj = nn.Linear(dim, inner, bias=False) self.A_log = nn.Parameter(torch.zeros(self.heads)) self.dt_bias = nn.Parameter(torch.zeros(inner)) self.g_proj = nn.Sequential(nn.Linear(dim, self.head_dim, bias=False), nn.Linear(self.head_dim, inner, bias=True)) self.o_norm = RMSNorm(self.head_dim, cfg.gdn_norm_eps) self.o_proj = nn.Linear(inner, dim, bias=False) def log_decay(self, x): """-exp(A_log) * softplus(f(x) + dt_bias), combined in log space in fp32 and floored.""" s = self.f_proj(x).float().unflatten(-1, (self.heads, self.head_dim)) + self.dt_bias.float().view( self.heads, self.head_dim) log_act = torch.where(s < -20, s, F.softplus(s.clamp_min(-20)).log()) log_mag = self.A_log.float().unsqueeze(-1) + log_act ceiling = math.log(-self.decay_floor) return torch.where(log_mag >= ceiling, self.decay_floor, -log_mag.clamp(max=ceiling).exp()) def forward(self, x, starts, taps_valid, cached): batch, seq_len, _ = x.shape state, windows = cached if cached is not None else (None, (None, None, None)) q, wq = short_conv(self.q_conv1d.weight, self.q_proj(x), taps_valid, windows[0]) k, wk = short_conv(self.k_conv1d.weight, self.k_proj(x), taps_valid, windows[1]) v, wv = short_conv(self.v_conv1d.weight, self.v_proj(x), taps_valid, windows[2]) heads = lambda t: t.float().view(batch, seq_len, self.heads, self.head_dim) # noqa: E731 o, state = recurrence(l2norm(heads(q)), l2norm(heads(k)), heads(v), self.log_decay(x), torch.sigmoid(heads(self.b_proj(x))), torch.sigmoid(heads(self.w_proj(x))), starts, state) gate = self.g_proj(x).view(batch, seq_len, self.heads, self.head_dim) o = self.o_norm(o.to(x.dtype)) * torch.sigmoid(gate) return self.o_proj(o.reshape(batch, seq_len, -1)), (state, (wq, wk, wv)) class SwiGLU(nn.Module): def __init__(self, dim: int, hidden: int): super().__init__() self.gate = nn.Linear(dim, hidden, bias=False) self.up = nn.Linear(dim, hidden, bias=False) self.down = nn.Linear(hidden, dim, bias=False) def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x)) class Block(nn.Module): def __init__(self, cfg: KLMConfig, index: int): super().__init__() self.is_attention = cfg.is_attention(index) self.mixer_norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) self.mixer = Attention(cfg) if self.is_attention else GatedDeltaNet2(cfg) self.ffn_norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) self.ffn = SwiGLU(cfg.hidden_size, cfg.intermediate_size) class AttnResSources: """Block Attention Residual sources in preallocated buffers. Each source is RMS-normalized once, when it is added, so a consumer costs one matmul and one weighted sum.""" def __init__(self, first, capacity: int, eps: float): batch, seq_len, dim = first.shape self.values = first.new_empty(batch, seq_len, capacity, dim) self.normed = torch.empty(batch, seq_len, capacity, dim, dtype=torch.float32, device=first.device) self.n, self.eps = 0, eps self.add(first) def _norm(self, v): return F.rms_norm(v.float(), (v.shape[-1],), eps=self.eps) def add(self, v): self.values[:, :, self.n] = v self.normed[:, :, self.n] = self._norm(v) self.n += 1 def mix(self, query, partial=None): """Softmax mix of the sources weighted by query . RMSNorm(source); `partial` (the current layer's mixer output, seen only by its FFN) joins as one more source.""" n = self.n with torch.autocast(query.device.type, enabled=False): logits = self.normed[:, :, :n] @ query if partial is not None: logits = torch.cat([logits, (self._norm(partial) @ query).unsqueeze(-1)], -1) weights = logits.softmax(-1) out = (weights[..., :n, None].to(self.values.dtype) * self.values[:, :, :n]).sum(-2) if partial is not None: out = out + weights[..., n:].to(partial.dtype) * partial return out class KLM(nn.Module): def __init__(self, cfg: KLMConfig): super().__init__() self.cfg = cfg self.embed = nn.Embedding(cfg.vocab_size, cfg.hidden_size) self.memory = NgramMemory(cfg) self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.num_hidden_layers)]) n_consumers = 2 * cfg.num_hidden_layers + 1 # every mixer and FFN, plus the readout self.attn_res_query = nn.Parameter(torch.zeros(n_consumers, cfg.hidden_size)) self.attn_res_norm = nn.Parameter(torch.ones(n_consumers, cfg.hidden_size)) self.norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps) def forward(self, tokens, cache: KLMCache | None = None, real=None): cfg, eps = self.cfg, self.cfg.rms_norm_eps seq_len = tokens.shape[1] fresh = cache is None or cache.length == 0 starts, docs, pos = segments(tokens, cfg.eos_token_id, cache, real if fresh else None) offset = cache.length if cache is not None else 0 positions = torch.arange(offset, offset + seq_len, device=tokens.device) all_docs = docs if offset == 0 else torch.cat([cache.docs, docs], 1) causal = torch.arange(offset + seq_len, device=tokens.device)[None, :] <= positions[:, None] mask = ((docs[:, :, None] == all_docs[:, None, :]) & causal).unsqueeze(1) history = cache.history if offset else None lags = torch.arange(CONV - 1, -1, -1, device=tokens.device) taps_valid = (pos[..., None] >= lags).to(self.embed.weight.dtype) queries = (self.attn_res_query * self.attn_res_norm).float() sources = AttnResSources(self.embed(tokens), cfg.num_hidden_layers + 2, eps) sources.add(self.memory(tokens, history, cfg.eos_token_id)) v_first = None for i, block in enumerate(self.blocks): cached = cache.layers[i] if cache is not None else None h = block.mixer_norm(sources.mix(queries[2 * i])) if block.is_attention: out, v_first, new = block.mixer(h, v_first, positions, mask, cached) else: out, new = block.mixer(h, starts, taps_valid, cached) if cache is not None: cache.layers[i] = new ffn = block.ffn(block.ffn_norm(sources.mix(queries[2 * i + 1], out))) sources.add(out + ffn) x = self.norm(sources.mix(queries[-1])) if cache is not None: cache.history = (tokens if history is None else torch.cat([history, tokens], 1))[:, -2:] cache.docs, cache.pos = all_docs, pos[:, -1] cache.length = offset + seq_len return F.linear(x, self.embed.weight.to(x.dtype)) class KLMForCausalLM(PreTrainedModel, GenerationMixin): config_class = KLMConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules = ["Block"] _is_stateful = True # the recurrent state cannot be cropped, so no assisted decoding @classmethod def _supports_default_dynamic_cache(cls) -> bool: return False # generate() must not build a DynamicCache; forward returns a KLMCache def __init__(self, config: KLMConfig): super().__init__(config) self.model = KLM(config) self.post_init() def _init_weights(self, module): pass # every weight comes from the checkpoint def get_input_embeddings(self) -> nn.Embedding: return self.model.embed def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed = value def get_output_embeddings(self) -> nn.Embedding: return self.model.embed # tied: the output layer reads embed.weight def forward(self, input_ids, attention_mask=None, past_key_values=None, use_cache=None, labels=None, return_dict=True, **kwargs) -> CausalLMOutputWithPast: if past_key_values is not None and not isinstance(past_key_values, KLMCache): raise TypeError("past_key_values must be the KLMCache this model returned") cache = past_key_values if cache is None and use_cache: cache = KLMCache(self.config.num_hidden_layers) real = None if attention_mask is not None: mask = attention_mask.bool() left = (mask[:, 1:] >= mask[:, :-1]).all() if cache is not None and not left: raise ValueError("generation supports left padding only") if not left and not (mask[:, 1:] <= mask[:, :-1]).all(): raise ValueError("only left or right padding is supported") if left: real = mask[:, -input_ids.shape[1]:] logits = self.model(input_ids, cache, real) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1).float(), labels[:, 1:].flatten(), ignore_index=-100) return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=cache) @torch.no_grad() def fast_generate(self, prompts: list[list[int]], max_new_tokens: int = 200, temperature: float = 0.7, top_p: float = 0.9, seed: int = 0, stop_ids: tuple[int, ...] | None = None, slots: int = 128) -> list[list[int]]: """Batched generation on an NVIDIA GPU with Triton: `prompts` are token-id lists, the result is each prompt's new tokens (ending with the stop token when one came). Up to `slots` replies decode at once with fused kernels and CUDA graphs; greedy at temperature 0. generate() and forward() are unchanged by it.""" if self.device.type != "cuda": raise RuntimeError("fast_generate runs on an NVIDIA GPU; use generate() elsewhere") from .fast_decode import FastDecoder dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32 if getattr(self, "_fast", None) is None or self._fast.slots != slots: self._fast = FastDecoder(self, slots, dtype) stop = tuple(stop_ids) if stop_ids is not None else (self.config.eos_token_id,) return self._fast.generate(prompts, max_new_tokens, stop, temperature, top_p, seed) def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, use_cache=True, **kwargs): if past_key_values is not None and past_key_values.length: input_ids = input_ids[:, past_key_values.length:] return {"input_ids": input_ids, "past_key_values": past_key_values, "attention_mask": attention_mask, "use_cache": use_cache}