""" Gated DeltaNet language model — fully official (flash-linear-attention). This module is built ENTIRELY from the official `flash-linear-attention` (fla) library and has NO dependency on any other file under ``model/``: * token mixer : ``fla.layers.GatedDeltaNet`` (official Triton kernel) * normalization: ``fla.modules.RMSNorm`` (official fused RMSNorm) Gated DeltaNet (Yang, Kautz, Hatamizadeh, 2024 — "Gated Delta Networks: Improving Mamba2 with Delta Rule") is a linear-attention / RNN-style sequence mixer that carries an explicit recurrent state and needs NO positional encoding. The only thing added on top of the official building blocks is the thin language-model scaffolding (token embedding, tied lm_head, loss, generation, optimizer config) needed to plug into this repo's train/test scripts, exposing the same public surface as the other models: forward(idx, targets) -> (logits, loss), .generate(), .configure_optimizers(), .estimate_mfu(), .get_num_params(), and a ``.layers`` ModuleList. Requires an environment with a recent torch/triton and ``pip install flash-linear-attention`` (e.g. the dedicated ``fla`` conda env). The module itself imports cleanly even without fla installed (the import is guarded); only *instantiating* GatedDeltaNet requires fla to be present. """ import math import inspect from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F # Official building blocks. Guarded so the module still imports in environments # without fla (e.g. the torch-2.0 gptenv); constructing the model will then raise # a clear error pointing at the fla env. try: from fla.layers import GatedDeltaNet as _FLAGatedDeltaNet from fla.modules import RMSNorm as _FLARMSNorm from fla.models.utils import Cache as _FLACache _HAS_FLA = True except Exception: _FLAGatedDeltaNet = None _FLARMSNorm = None _FLACache = None _HAS_FLA = False @dataclass class GatedDeltaNetConfig: n_embd: int # hidden size (D) n_layer: int head_dim: int = 64 # per-head key/query dim; num_heads = n_embd // head_dim expand_v: float = 2.0 # value expansion factor (fla default 2) conv_size: int = 4 # short causal conv width conv_bias: bool = False use_gate: bool = True # output gating branch (official default) use_short_conv: bool = True allow_neg_eigval: bool = False vocab_size: int = 64 norm_eps: float = 1e-5 pad_id: int = 0 # ignore_index for the loss (padding token) model_type: str = "gated-deltanet" @property def num_heads(self) -> int: assert self.n_embd % self.head_dim == 0, \ f"n_embd ({self.n_embd}) must be divisible by head_dim ({self.head_dim})" return self.n_embd // self.head_dim class ResidualBlock(nn.Module): """Pre-norm residual wrapper around the official fla GatedDeltaNet mixer.""" def __init__(self, config: GatedDeltaNetConfig, layer_idx: int): super().__init__() self.norm = _FLARMSNorm(config.n_embd, eps=config.norm_eps) self.mixer = _FLAGatedDeltaNet( hidden_size=config.n_embd, expand_v=config.expand_v, head_dim=config.head_dim, num_heads=config.num_heads, mode="chunk", use_gate=config.use_gate, use_short_conv=config.use_short_conv, allow_neg_eigval=config.allow_neg_eigval, conv_size=config.conv_size, conv_bias=config.conv_bias, norm_eps=config.norm_eps, layer_idx=layer_idx, ) def forward(self, x, past_key_values=None, use_cache=False): # fla layer returns (hidden_states, attentions, past_key_values) out = self.mixer( self.norm(x), past_key_values=past_key_values, use_cache=use_cache, ) y = out[0] if isinstance(out, (tuple, list)) else out return x + y class GatedDeltaNet(nn.Module): def __init__(self, config: GatedDeltaNetConfig): super().__init__() if not _HAS_FLA: raise ImportError( "GatedDeltaNet requires the `flash-linear-attention` package. " "Run in the dedicated `fla` conda env (torch>=2.5 + triton), e.g.:\n" " PYTHONNOUSERSITE=1 conda run -n fla python train_maze.py --model gated-deltanet ..." ) self.config = config self.embedding = nn.Embedding(config.vocab_size, config.n_embd, padding_idx=0) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) self.lm_head.weight = self.embedding.weight # weight tying self.layers = nn.ModuleList( [ResidualBlock(config, layer_idx=i) for i in range(config.n_layer)] ) self.out_norm = _FLARMSNorm(config.n_embd, eps=config.norm_eps) # Only initialize the embedding/head; leave the official fla layers with # their own (carefully chosen) initialization. torch.nn.init.normal_(self.embedding.weight, mean=0.0, std=0.02) print(f"number of parameters: {self.get_num_params() / 1e6:.2f}M") def forward(self, idx, targets=None, past_key_values=None, use_cache=False): x = self.embedding(idx) for layer in self.layers: x = layer(x, past_key_values=past_key_values, use_cache=use_cache) x = self.out_norm(x) if targets is not None: logits = self.lm_head(x) loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=self.config.pad_id, ) else: logits = self.lm_head(x[:, [-1], :]) loss = None return logits, loss @torch.no_grad() def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, return_confidence=False): """Autoregressive generation matching the contract of the other models. Uses fla's recurrent state cache: the prompt is consumed once, then each new token is fed individually (q_len=1 -> fused_recurrent kernel). This is O(T) instead of re-running the full prefix every step (which would retrigger Triton autotune/compile for every new sequence length and make generation appear to hang). """ confidences = [] if return_confidence else None top3_tokens = [] if return_confidence else None top3_probs = [] if return_confidence else None B = idx.size(0) past_key_values = _FLACache() if _HAS_FLA else None for step in range(max_new_tokens): # First step: consume the whole prompt; later steps: feed only the # last generated token, reusing the recurrent state in the cache. step_input = idx if step == 0 else idx[:, -1:] logits, _ = self(step_input, past_key_values=past_key_values, use_cache=True) if temperature <= 0: probs = F.softmax(logits[:, -1, :], dim=-1) idx_next = probs.argmax(dim=-1, keepdim=True) else: logits = logits[:, -1, :] / temperature if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float('Inf') probs = F.softmax(logits, dim=-1) idx_next = torch.multinomial(probs, num_samples=1) if return_confidence: sampled_probs = probs.gather(1, idx_next).squeeze(-1) confidences.append(sampled_probs.cpu().tolist()) top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1) top3_tokens.append(top3_token_ids.cpu().tolist()) top3_probs.append(top3_prob_vals.cpu().tolist()) idx = torch.cat((idx, idx_next), dim=1) if return_confidence: if B == 1: return (idx, [c[0] for c in confidences], [t[0] for t in top3_tokens], [p[0] for p in top3_probs]) T = len(confidences) conf_bs = [[confidences[t][b] for t in range(T)] for b in range(B)] tok_bs = [[top3_tokens[t][b] for t in range(T)] for b in range(B)] prob_bs = [[top3_probs[t][b] for t in range(T)] for b in range(B)] return idx, conf_bs, tok_bs, prob_bs return idx def configure_optimizers(self, weight_decay, learning_rate, betas, device_type): param_dict = {pn: p for pn, p in self.named_parameters() if p.requires_grad} decay_params = [p for n, p in param_dict.items() if p.dim() >= 2] nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2] optim_groups = [ {"params": decay_params, "weight_decay": weight_decay}, {"params": nodecay_params, "weight_decay": 0.0}, ] num_decay = sum(p.numel() for p in decay_params) num_nodecay = sum(p.numel() for p in nodecay_params) print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay:,} parameters") print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay:,} parameters") fused_available = "fused" in inspect.signature(torch.optim.AdamW).parameters use_fused = fused_available and device_type == "cuda" extra_args = dict(fused=True) if use_fused else {} optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args) print(f"using fused AdamW: {use_fused}") return optimizer def estimate_mfu(self, fwdbwd_per_iter, dt): return -1 def get_num_params(self, non_embedding=True): n_params = sum(p.numel() for p in self.parameters()) if non_embedding: n_params -= self.embedding.weight.numel() return n_params