"""Gated delta rule: the memory update inside Dew's DeltaNet layers. Per head the memory is a matrix S (key dim x value dim). For each word t: S <- exp(g_t) * S decay (g_t <= 0, log space) S <- S + beta_t * k_t (v_t - S^T k_t)^T delta write (beta_t in [0, 1]) o_t = S^T q_t * scale read A word with beta = 0 and g = 0 leaves S exactly as it was: this is how a napping word "does not write to the whiteboard and causes no decay". Three implementations, checked against each other by `python -m dew.selftest`: * fla Triton kernels from flash-linear-attention (fast training on GPU) * chunk pure PyTorch, chunked (WY / UT form), any device, used when fla is missing * step one word at a time, used for decoding and the ONNX export """ from __future__ import annotations import inspect import os import torch _FLA = None # None = not checked yet, False = unavailable def _fla(): global _FLA if _FLA is None: _FLA = False if os.environ.get("DEW_NO_FLA") != "1": try: from fla.ops.gated_delta_rule import chunk_gated_delta_rule as f params = inspect.signature(f).parameters _FLA = (f, "head_first" in params) except Exception: _FLA = False return _FLA def fla_available() -> bool: return bool(_fla()) def l2norm(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: return x * torch.rsqrt(x.pow(2).sum(-1, keepdim=True) + eps) def gated_delta_rule(q, k, v, g, beta, impl: str = "auto"): """q, k: [B, T, H, K] (already L2-normalised), v: [B, T, H, V], g, beta: [B, T, H]. Returns o: [B, T, H, V] in v's dtype.""" scale = q.shape[-1] ** -0.5 f = _fla() if impl in ("auto", "fla") else False if f and q.is_cuda: fn, has_head_first = f kw = {"scale": scale, "output_final_state": False} if has_head_first: kw["head_first"] = False o, _ = fn(q, k, v, g.float(), beta.to(q.dtype), **kw) return o.to(v.dtype) if impl == "fla": raise RuntimeError("fla requested but not available") return chunk_reference(q, k, v, g, beta, scale).to(v.dtype) def chunk_reference(q, k, v, g, beta, scale, chunk: int = 64): """Chunked gated delta rule in plain PyTorch (fp32). Same maths as fla's reference.""" dt = v.dtype with torch.autocast(q.device.type, enabled=False): q, k, v, g, beta = (x.float().transpose(1, 2) for x in (q, k, v, g, beta)) # [B, H, T, .] B, H, T, K = k.shape V = v.shape[-1] pad = (chunk - T % chunk) % chunk if pad: q, k, v = (torch.nn.functional.pad(x, (0, 0, 0, pad)) for x in (q, k, v)) g, beta = (torch.nn.functional.pad(x, (0, pad)) for x in (g, beta)) n = q.shape[2] // chunk q = q * scale kb = k * beta[..., None] vb = v * beta[..., None] q, k, kb, vb = (x.view(B, H, n, chunk, -1) for x in (q, k, kb, vb)) g = g.view(B, H, n, chunk).cumsum(-1) tri = torch.ones(chunk, chunk, dtype=torch.bool, device=q.device).tril() diff = (g[..., :, None] - g[..., None, :]).masked_fill(~tri, float("-inf")) L = diff.exp() # decay from j to i (i >= j) A = ((kb @ k.transpose(-1, -2)) * L).tril(-1) eye = torch.eye(chunk, device=q.device).expand_as(A) Tm = torch.linalg.solve_triangular(eye + A, eye, upper=False, unitriangular=True) # (I + A)^-1 kcd = Tm @ (kb * g.exp()[..., None]) u = Tm @ vb S = q.new_zeros(B, H, K, V) o = torch.empty_like(u) for i in range(n): qi, ki, gi = q[:, :, i], k[:, :, i], g[:, :, i] att = (qi @ ki.transpose(-1, -2) * L[:, :, i]).tril() vnew = u[:, :, i] - kcd[:, :, i] @ S o[:, :, i] = (qi * gi.exp()[..., None]) @ S + att @ vnew S = S * gi[..., -1, None, None].exp() + (ki * (gi[..., -1, None] - gi).exp()[..., None]).transpose(-1, -2) @ vnew o = o.view(B, H, n * chunk, V)[:, :, :T] return o.transpose(1, 2).to(dt) def delta_step(q, k, v, g, beta, S): """One word. q, k: [B, H, K] (L2-normalised), v: [B, H, V], g, beta: [B, H], S: [B, H, K, V].""" scale = q.shape[-1] ** -0.5 S = S * g.exp()[..., None, None] kv = (k[..., None] * S).sum(-2) # S^T k S = S + k[..., None] * ((v - kv) * beta[..., None])[..., None, :] o = (q[..., None] * S).sum(-2) * scale return o, S def recurrent_reference(q, k, v, g, beta): """Whole sequence, one word at a time (slow; for tests).""" B, T, H, K = q.shape S = q.new_zeros(B, H, K, v.shape[-1]).float() out = [] for t in range(T): o, S = delta_step(q[:, t].float(), k[:, t].float(), v[:, t].float(), g[:, t].float(), beta[:, t].float(), S) out.append(o) return torch.stack(out, 1)