"""A recurrent network of state layers with input-dependent bidirectional routing.""" import math from collections.abc import Sequence from typing import NamedTuple import torch from torch import Tensor, nn from torch.nn import functional as F from torch.utils.checkpoint import checkpoint try: # Optional Triton kernels (flash-linear-attention) for the CUDA memory scans. from fla.ops.gated_delta_rule import chunk_gated_delta_rule as _fla_delta_rule from fla.ops.hgrn import chunk_hgrn as _fla_hgrn except Exception: # ImportError, or fla refusing an unsupported platform _fla_delta_rule = _fla_hgrn = None LONG_CONTEXT = 262_144 # RecurrentGraphLM(vocab_size, **A100_40GB): one A100 40GB, ~0.8x the training # FLOPs/token of GPT-2 small. At vocab 50304: 51.7M parameters, 13.1M outside the # tied table; 675 MFLOP/token for training. width 256 keeps the per-layer GEMMs # on tensor cores and is fla's largest delta-rule head; 16 layers give 16 memory # heads with half-lives from 1 token to LONG_CONTEXT. A100_40GB = dict( width=256, num_layers=16, steps=4, top_k=4, embed_dim=768, memory_addressing="delta", memory_write_step=(0, 1, 2, 3), memory_source="state", concat_readout=True, ) def _memory_scan(log_keep: Tensor, addition: Tensor, initial: Tensor) -> Tensor: """Inclusive affine prefix scan with linear work and logarithmic dependency depth.""" length = addition.size(1) if length == 1: return addition + log_keep.exp() * initial.unsqueeze(1) # Reduce adjacent time steps to one equivalent update. Sum log retentions # so a very slow channel does not round its decay to one at every token. paired = length - length % 2 left = slice(0, paired, 2) right = slice(1, paired, 2) pair_log = log_keep[:, left] + log_keep[:, right] pair_add = addition[:, right] + log_keep[:, right].exp() * addition[:, left] ends = _memory_scan(pair_log, pair_add, initial) starts = torch.cat((initial.unsqueeze(1), ends[:, :-1]), dim=1) middles = addition[:, left] + log_keep[:, left].exp() * starts result = torch.stack((middles, ends), dim=2).flatten(1, 2) if paired < length: tail = addition[:, -1:] + log_keep[:, -1:].exp() * ends[:, -1:] result = torch.cat((result, tail), dim=1) return result def _delta_scan( query: Tensor, key: Tensor, value: Tensor, log_decay: Tensor, beta: Tensor, initial: Tensor, chunk: int = 64, ) -> tuple[Tensor, Tensor]: """Gated delta rule with exclusive reads, in chunked WY form. Per head: S_t = a_t (I - b_t k_t k_t^T) S_{t-1} + b_t k_t v_t^T, o_t = S_{t-1}^T q_t. Inputs [B, T, H, D] (gates [B, T, H]), state [B, H, Dk, Dv]. Unit keys and b_t in [0, 1] make every update a contraction along k_t, so S stays bounded. Work is O(T C D + T D^2); only the T / C chunk boundaries are sequential. """ batch, length, heads, _ = key.shape chunk = min(chunk, length) pad = -length % chunk q, k, v = (x.transpose(1, 2) for x in (query, key, value)) g, b = log_decay.transpose(1, 2), beta.transpose(1, 2) if pad: # Padded steps keep the state: decay 1, write strength 0, zero key. q, k, v = (F.pad(x, (0, 0, 0, pad)) for x in (q, k, v)) g, b = F.pad(g, (0, pad)), F.pad(b, (0, pad)) q, k, v = (x.unflatten(2, (-1, chunk)) for x in (q, k, v)) g, b = g.unflatten(2, (-1, chunk)), b.unflatten(2, (-1, chunk)) cumulative = g.cumsum(-1) exclusive = cumulative - g strict = torch.ones(chunk, chunk, dtype=torch.bool, device=k.device).tril(-1) # Mask exponents before exp so future positions never form inf * 0. decay = (cumulative.unsqueeze(-1) - cumulative.unsqueeze(-2)).masked_fill(~strict, -torch.inf).exp() read_decay = (exclusive.unsqueeze(-1) - cumulative.unsqueeze(-2)).masked_fill(~strict, -torch.inf).exp() # (I + A) U = b V - (b gamma K) S_0 with A strictly lower triangular. system = b.unsqueeze(-1) * (k @ k.transpose(-1, -2)) * decay solve = lambda rhs: torch.linalg.solve_triangular(system, rhs, upper=False, unitriangular=True) new_value = solve(b.unsqueeze(-1) * v) new_key = solve((b * cumulative.exp()).unsqueeze(-1) * k) attention = (q @ k.transpose(-1, -2)) * read_decay query_decayed = q * exclusive.exp().unsqueeze(-1) key_to_end = k * (cumulative[..., -1:] - cumulative).exp().unsqueeze(-1) chunk_decay = cumulative[..., -1].exp()[..., None, None] state, outputs = initial, [] for n in range(k.size(2)): update = new_value[:, :, n] - new_key[:, :, n] @ state outputs.append(query_decayed[:, :, n] @ state + attention[:, :, n] @ update) state = chunk_decay[:, :, n] * state + key_to_end[:, :, n].transpose(-1, -2) @ update out = torch.stack(outputs, 2).flatten(2, 3)[:, :, :length] return out.transpose(1, 2), state def _delta_scan_fla( query: Tensor, key: Tensor, value: Tensor, log_decay: Tensor, beta: Tensor, initial: Tensor, ) -> tuple[Tensor, Tensor]: """_delta_scan on fla's inclusive kernel. Its output at t is S_t^T q, so passing q_{t+1} in slot t yields the exclusive read of position t+1.""" shifted = torch.cat((query[:, 1:], torch.zeros_like(query[:, :1])), dim=1) out, final = _fla_delta_rule( shifted, key, value, log_decay, beta, scale=1.0, initial_state=initial.contiguous(), output_final_state=True, ) first = torch.einsum("bhkv,bhk->bhv", initial, query[:, 0]).unsqueeze(1) return torch.cat((first, out[:, :-1]), dim=1), final def _memory_scan_fla(log_keep: Tensor, addition: Tensor, initial: Tensor) -> Tensor: """_memory_scan on fla's HGRN kernel (h_t = exp(g_t) h_{t-1} + x_t), channels flattened.""" out, _ = _fla_hgrn(addition.flatten(2).contiguous(), log_keep.flatten(2).contiguous(), initial.flatten(1).contiguous()) return out.view_as(addition) class GraphMemory(NamedTuple): """Per-stream carry: memory hidden and previous graph inputs [steps,B,L,D]. hidden is [B,L,D] for a single vector or keyed memory step (the original layout), else [memory_steps, B, L, *state] with state D or D x D (delta). """ hidden: Tensor previous: Tensor def detach(self) -> "GraphMemory": return GraphMemory(self.hidden.detach(), self.previous.detach()) class LayerwiseMLP(nn.Module): """Independent MLP parameters per state layer, evaluated in one batch. The optional preceding-position input has its own projection, so hidden features can depend on token order instead of an unordered sum. """ def __init__(self, num_layers: int, width: int): super().__init__() self.up = nn.Parameter(torch.empty(num_layers, width, 2 * width)) self.past_up = nn.Parameter(torch.empty(num_layers, width, 2 * width)) self.down = nn.Parameter(torch.empty(num_layers, 2 * width, width)) self.up_bias = nn.Parameter(torch.zeros(num_layers, 2 * width)) self.down_bias = nn.Parameter(torch.zeros(num_layers, width)) # Each slice is a separate linear map with its own fan-in. nn.init.uniform_(self.up, -width**-0.5, width**-0.5) nn.init.uniform_(self.past_up, -width**-0.5, width**-0.5) nn.init.uniform_(self.down, -(2 * width)**-0.5, (2 * width)**-0.5) def forward(self, state: Tensor, past: Tensor | None = None) -> Tensor: hidden = torch.einsum("bld,ldf->blf", state, self.up) + self.up_bias if past is not None: hidden = hidden + torch.einsum("bld,ldf->blf", past, self.past_up) return torch.einsum("blf,lfd->bld", F.gelu(hidden), self.down) + self.down_bias class RecurrentGraphNet(nn.Module): """Map vectors [B, I] or causal feature sequences [B, T, I] to logits.""" _version = 4 def __init__( self, input_dim: int, output_dim: int, *, width: int = 32, num_layers: int = 8, steps: int = 3, top_k: int = 2, x0_mix: float = 0.1, memory_max_half_life: float = 64, memory_write_step: int | Sequence[int] = 0, memory_addressing: str = "vector", adaptive_readout: bool = False, protect_writes: bool = False, memory_source: str = "token", concat_readout: bool = False, readout_dim: int | None = None, ): """Defaults reproduce version 4 exactly. Sequence-model options: memory_write_step: one graph iteration, or several. Each listed iteration runs its own scan and replaces the memory context, so reads can compose across iterations instead of one scan per pass. memory_addressing: "vector" and "keyed" keep a diagonal [L, D] state; "delta" keeps a [L, D, D] matrix per layer under the gated delta rule, so a query recalls the value stored under a matching key. memory_source: "token" addresses from input features (version 4); "state" computes keys, queries, gates and values from the graph state at that iteration, so writes and reads depend on context. concat_readout: read all layers through a projection initialized to the layer mean, instead of the mean itself. readout_dim sets its width (the tied embedding width in RecurrentGraphLM). """ super().__init__() if min(input_dim, output_dim, steps) < 1 or width < 2: raise ValueError("Dimensions and steps must be positive, with width >= 2") if not 1 <= top_k < num_layers: raise ValueError("Expected 1 <= top_k < num_layers") if not 0 < x0_mix < 1: raise ValueError("Expected 0 < x0_mix < 1") if not math.isfinite(memory_max_half_life) or memory_max_half_life < 1: raise ValueError("Expected a finite memory_max_half_life >= 1") self.width = width self.num_layers = num_layers if memory_addressing not in ("vector", "keyed", "delta"): raise ValueError("memory_addressing must be vector, keyed or delta") if memory_source not in ("token", "state"): raise ValueError("memory_source must be token or state") if adaptive_readout and concat_readout: raise ValueError("Choose one of adaptive_readout and concat_readout") readout_dim = width if readout_dim is None else readout_dim if readout_dim < 1 or (readout_dim != width and not concat_readout): raise ValueError("readout_dim must be positive and needs concat_readout unless it equals width") self.adaptive_readout = adaptive_readout if adaptive_readout: self.pool_query = nn.Parameter(torch.zeros(width)) self.pool_norm_mix = nn.Parameter(torch.zeros(width)) self.concat_readout = concat_readout if concat_readout: self.pool_projection = nn.Linear(num_layers * width, readout_dim) if readout_dim == width: with torch.no_grad(): self.pool_projection.weight.copy_(torch.eye(width).repeat(1, num_layers) / num_layers) self.pool_projection.bias.zero_() if protect_writes and memory_addressing != "keyed": raise ValueError("protected writes require keyed addressing") self.protect_writes = protect_writes self.memory_addressing = memory_addressing self.memory_source = memory_source # Runtime settings, not architecture: memory scan kernels (see # _use_fla) and recomputing each graph iteration in backward. self.memory_backend = "auto" self.checkpoint_steps = False self.steps = steps self.memory_write_step = memory_write_step self.register_buffer("mix_reference_steps", torch.tensor(steps, dtype=torch.long)) self.top_k = top_k self.encoder = nn.Linear(input_dim, num_layers * width) self.norm = nn.LayerNorm(width) self.router = nn.Linear(width, width, bias=False) self.inter = nn.Sequential(nn.Linear(2 * width, width), nn.GELU(), nn.Linear(width, width)) self.intra = LayerwiseMLP(num_layers, width) # Keep per-step logits in checkpoints, but budget initial mixing over a full pass. step_mix = -math.expm1(math.log1p(-x0_mix) / steps) logit = math.log(step_mix) - math.log1p(-step_mix) self.mix_logit = nn.Parameter(torch.full((num_layers, 1), logit)) self.readout = nn.Linear(readout_dim, output_dim) # Delta mode: one projection gives the query (its shift is the key) and # the value; scalar decay and write strength come from both positions. self.memory_projection = nn.Linear(width, (2 if memory_addressing == "delta" else 3) * width) # Give layers a range of initial retention times, in tokens. log_rates = torch.linspace(0, -math.log(memory_max_half_life), num_layers, dtype=torch.float64, device="cpu") write_logits = torch.expm1(math.log(2) * log_rates.exp()).log() self.memory_write_bias = nn.Parameter(write_logits.to(self.mix_logit).unsqueeze(-1)) self.radius_bias = nn.Parameter(torch.full((num_layers, 1), math.log(math.expm1(1.0)))) self.radius_token_weight = nn.Parameter(torch.zeros(num_layers, width)) self.radius_memory_weight = nn.Parameter(torch.zeros(num_layers, width)) if memory_addressing == "delta": # Zero init: retention starts at the half-life spectrum, writes at 1/2. self.memory_gate = nn.Linear(2 * width, 2) nn.init.zeros_(self.memory_gate.weight) nn.init.zeros_(self.memory_gate.bias) else: self.memory_write_key = nn.Parameter(torch.zeros(width, width)) @property def memory_write_step(self) -> int | tuple[int, ...]: steps = self.memory_steps return steps[0] if len(steps) == 1 else steps @memory_write_step.setter def memory_write_step(self, value: int | Sequence[int]) -> None: values = (value,) if type(value) is int else tuple(value) if ( not values or any(type(v) is not int or not 0 <= v < self.steps for v in values) or list(values) != sorted(set(values)) ): raise ValueError("memory_write_step must index graph iterations in increasing order") self.memory_steps = values @property def _legacy_carry(self) -> bool: return len(self.memory_steps) == 1 and self.memory_addressing != "delta" def _load_from_state_dict(self, state_dict, prefix, local_metadata, *args): version = local_metadata.get("version", 1) key = prefix + "memory_write_key" if version < 2 and key not in state_dict and hasattr(self, "memory_write_key"): source = state_dict.get(prefix + "encoder.weight", self.memory_write_key) state_dict[key] = source.new_zeros(self.memory_write_key.shape) ref = prefix + "mix_reference_steps" if version < 3 and ref not in state_dict and prefix + "mix_logit" in state_dict: state_dict[ref] = state_dict[prefix + "mix_logit"].new_tensor(self.steps, dtype=torch.long) past = prefix + "intra.past_up" if version < 4 and past not in state_dict and prefix + "intra.up" in state_dict: # Earlier releases applied `up` to current + past: an exact conversion. state_dict[past] = state_dict[prefix + "intra.up"].clone() super()._load_from_state_dict(state_dict, prefix, local_metadata, *args) def _step_mix(self): logit = self.mix_logit if logit.dtype in (torch.bfloat16, torch.float16): logit = logit.float() # Preserve the learned total retention when varying recurrent depth. return -torch.expm1(F.logsigmoid(-logit) * (self.mix_reference_steps.to(logit.dtype) / self.steps)) def residual_radius(self, x0: Tensor, context: Tensor | None = None) -> Tensor: """Per-token, per-layer RMS budget for iterations with the given context.""" work = x0.float() if x0.dtype in (torch.float16, torch.bfloat16) else x0 token = F.layer_norm(work, (self.width,)) evidence = (token * self.radius_token_weight).sum(-1, keepdim=True) if context is not None: evidence = evidence + (context.to(work.dtype) * self.radius_memory_weight).sum(-1, keepdim=True) return F.softplus(self.radius_bias + evidence * self.width**-0.5) def _memory_context( self, x0: Tensor, hidden: Tensor | None, previous: Tensor | None = None, *, value_source: Tensor | None = None, ) -> tuple[Tensor, Tensor]: """Read the exclusive prefix, then blend a bounded payload into the carry. In keyed mode a single projection produces signed coordinates used for both operations: token t reads with its own address and writes the payload under the address from t-1. The write rate is still learned. """ normalized = self.norm(x0) # A preceding token can enable a fast write into a slow channel. # Zero key evidence preserves the channel's original retention law. if previous is None: first = torch.zeros_like(normalized[:, :1]) else: first = self.norm(previous.to(x0.dtype)).unsqueeze(1) preceding = torch.cat((first, normalized[:, :-1]), dim=1) # Promote before the dot products; casting an overflowed score cannot # recover opposite-signed token and key contributions. dtype = torch.float64 if x0.dtype == torch.float64 else torch.float32 with torch.autocast(x0.device.type, enabled=False): projection = self.memory_projection weight = projection.weight.to(dtype) offset = projection.bias.to(dtype) token = normalized.to(dtype) if value_source is None: write, value, read = F.linear(token, weight, offset).chunk(3, dim=-1) else: # Only the payload depends on the graph. Addressing, retention # and reading use the same token features as the input baseline. write_weight, value_weight, read_weight = weight.chunk(3) write_bias, value_bias, read_bias = offset.chunk(3) write = F.linear(token, write_weight, write_bias) value = F.linear(self.norm(value_source).to(dtype), value_weight, value_bias) read = F.linear(token, read_weight, read_bias) evidence = F.linear(preceding.to(dtype), self.memory_write_key.to(dtype)) if self.memory_addressing == "keyed": # Write under the preceding token's signed address and read # under the current one. Reuse addresses across positions. query = read.tanh() first_address = F.linear(first.to(dtype), weight[-self.width:], offset[-self.width:]).tanh() address = torch.cat((first_address, query[:, :-1]), dim=1) value = value.tanh() * address else: query = read.sigmoid() value = value.tanh() bias = self.memory_write_bias.to(write.dtype) write = write + bias + (1 + F.softplus(-bias)) * evidence if hidden is None: hidden = torch.zeros_like(value[:, 0]) if ( hidden.shape != value[:, 0].shape or hidden.device != value.device or hidden.dtype != value.dtype ): raise ValueError("Memory hidden shape, device and dtype must match the current stream") if self.protect_writes: # Effective rate = sigmoid(write) * address². Its logit form # preserves an accurate log retention even on slow channels. strength = address.square().clamp(1e-7, 1 - 1e-7) write = write + strength.log() - F.softplus(write + torch.log1p(-strength)) scan = _memory_scan_fla if self._use_fla(value, diagonal=True) else _memory_scan inclusive = scan(-F.softplus(write), write.sigmoid() * value, hidden) history = torch.cat((hidden.unsqueeze(1), inclusive[:, :-1]), dim=1) context = history * query return context.to(x0.dtype), inclusive[:, -1].clone() def _delta_context( self, source: Tensor, hidden: Tensor | None, previous: Tensor | None = None, *, value_source: Tensor | None = None, ) -> tuple[Tensor, Tensor]: """Matrix-memory read of the exclusive prefix, then a delta-rule write. Token t writes its value under the unit key from t-1 and reads with its own unit query. Matching keys overwrite rather than accumulate. """ normalized = self.norm(source) if previous is None: first = torch.zeros_like(normalized[:, :1]) else: first = self.norm(previous.to(source.dtype)).unsqueeze(1) preceding = torch.cat((first, normalized[:, :-1]), dim=1) dtype = torch.float64 if source.dtype == torch.float64 else torch.float32 with torch.autocast(source.device.type, enabled=False): read_weight, value_weight = self.memory_projection.weight.to(dtype).chunk(2) read_bias, value_bias = self.memory_projection.bias.to(dtype).chunk(2) token, preceding = normalized.to(dtype), preceding.to(dtype) query = F.normalize(F.linear(token, read_weight, read_bias), dim=-1) key = F.normalize(F.linear(preceding, read_weight, read_bias), dim=-1) payload = token if value_source is None else self.norm(value_source).to(dtype) value = F.linear(payload, value_weight, value_bias).tanh() gate = self.memory_gate decay, strength = F.linear( torch.cat((token, preceding), -1), gate.weight.to(dtype), gate.bias.to(dtype), ).unbind(-1) log_decay = -F.softplus(decay + self.memory_write_bias.to(dtype).squeeze(-1)) if hidden is None: hidden = value.new_zeros(value.size(0), self.num_layers, self.width, self.width) if ( hidden.shape != (value.size(0), self.num_layers, self.width, self.width) or hidden.device != value.device or hidden.dtype != value.dtype ): raise ValueError("Memory hidden shape, device and dtype must match the current stream") scan = _delta_scan_fla if self._use_fla(value) else _delta_scan context, final = scan(query, key, value, log_decay, strength.sigmoid(), hidden) return context.to(source.dtype), final def _use_fla(self, tensor: Tensor, *, diagonal: bool = False) -> bool: """memory_backend: "auto" uses fla for the delta rule on CUDA, "fla" also for the diagonal scan (HGRN), "torch" never. fla runs fp32 inputs through TF32 matmuls: expect ~1e-3 relative differences from torch.""" backend = self.memory_backend if backend not in ("auto", "fla", "torch"): raise ValueError("memory_backend must be auto, fla or torch") if backend == "torch" or (backend == "auto" and (diagonal or not tensor.is_cuda)): return False if _fla_delta_rule is None: if backend == "fla": raise RuntimeError("memory_backend='fla' needs flash-linear-attention") return False return True def _read_memory(self, i: int, state: Tensor, x0: Tensor, hidden: Tensor | None, memory: "GraphMemory | None"): """Memory context and outgoing carry for graph iteration i.""" if self.memory_source == "state": # Keys, queries, gates and payload all see context. The preceding # position's state at this iteration is exactly the carried boundary. source, first, payload = state, memory.previous[i] if memory is not None else None, None else: source, first, payload = x0, memory.previous[0] if memory is not None else None, state if i else None read = self._delta_context if self.memory_addressing == "delta" else self._memory_context return read(source, hidden, first, value_source=payload) def _proposals(self, normalized_state: Tensor) -> tuple[Tensor, Tensor, Tensor]: # Finite half-precision keys can overflow when squared in the dot product. score_dtype = torch.float64 if normalized_state.dtype == torch.float64 else torch.float32 with torch.autocast(normalized_state.device.type, enabled=False): keys = F.linear(normalized_state.to(score_dtype), self.router.weight.to(score_dtype)) scores = (keys @ keys.transpose(1, 2)) * self.width**-0.5 scores.diagonal(dim1=-2, dim2=-1).fill_(-torch.inf) neighbors = scores.topk(self.top_k, dim=-1).indices proposals = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, neighbors, True) return scores, neighbors, proposals @property def self_edges(self) -> Tensor: return torch.eye(self.num_layers, device=self.router.weight.device, dtype=torch.bool) def routing(self, normalized_state: Tensor) -> tuple[Tensor, Tensor]: """Return symmetric scores and active mask, both [batch, receiver, sender].""" scores, _, proposals = self._proposals(normalized_state) return scores, proposals | proposals.transpose(1, 2) # A message from j to i is inter([n_i, n_j]) = W2 gelu(A n_i + B n_j + b1) + b2. # W2 and b2 are linear, so the gated sum over senders factors as # W2 sum_j g_ij gelu(.) + b2 sum_j g_ij: per edge only an addition and an # activation remain, and every matrix product runs once per node. def _message_roles(self, nodes: Tensor) -> tuple[Tensor, Tensor]: first = self.inter[0] receive = F.linear(nodes, first.weight[:, :self.width], first.bias) send = F.linear(nodes, first.weight[:, self.width:]) return receive, send def _project_messages(self, summed: Tensor, mass: Tensor) -> Tensor: last = self.inter[-1] return F.linear(summed.to(last.weight.dtype), last.weight) + last.bias * mass def _compact_messages(self, nodes: Tensor) -> Tensor: scores, active = self.routing(nodes) batch, receiver, sender = active.nonzero(as_tuple=True) # The zero-logit option lets a node suppress even its sole neighbor. # All candidate scores participate in the denominator before sparsification. gate_logits = F.pad(scores, (0, 1), value=0.0) gates = gate_logits.softmax(-1)[batch, receiver, sender].unsqueeze(-1) receive, send = self._message_roles(nodes) hidden = self.inter[1](receive[batch, receiver] + send[batch, sender]) * gates destinations = batch * self.num_layers + receiver rows = nodes.size(0) * self.num_layers summed = hidden.new_zeros(rows, self.width).index_add(0, destinations, hidden) mass = gates.new_zeros(rows, 1).index_add(0, destinations, gates) return self._project_messages(summed, mass).view(nodes.shape) def _fixed_messages(self, nodes: Tensor) -> Tensor: """Fixed-size top-k dispatch, including the reverse of each one-sided proposal.""" scores, neighbors, proposals = self._proposals(nodes) gates = F.pad(scores, (0, 1)).softmax(-1) batch, layers, width = nodes.shape offsets = torch.arange(batch, device=nodes.device).view(-1, 1, 1) * layers destinations = (neighbors + offsets).flatten() receive, send = self._message_roles(nodes) activation = self.inter[1] shape = (batch, layers, self.top_k, width) weights = gates.gather(2, neighbors).unsqueeze(-1) sender = send.flatten(0, 1).index_select(0, destinations).view(shape) summed = (activation(receive.unsqueeze(2) + sender) * weights).sum(2) mass = weights.sum(2) if self.top_k < layers - 1: # Neighbor j also receives from i unless j proposed i itself, in which # case that edge already contributed above. reverse_weights = gates[:, :, :layers].transpose(1, 2).gather(2, neighbors) mutual = proposals.transpose(1, 2).gather(2, neighbors) weights = reverse_weights.masked_fill(mutual, 0).unsqueeze(-1) target = receive.flatten(0, 1).index_select(0, destinations).view(shape) reverse = activation(target + send.unsqueeze(2)) * weights summed = summed.flatten(0, 1).index_add(0, destinations, reverse.flatten(0, 2)).view_as(summed) mass = mass.flatten(0, 1).index_add(0, destinations, weights.flatten(0, 2)).view_as(mass) return self._project_messages(summed, mass) def _dense_messages(self, nodes: Tensor) -> Tensor: """All L x L pairs with inactive gates zeroed: no data-dependent shapes or scatter, so it traces under torch.compile and is deterministic.""" scores, active = self.routing(nodes) gates = F.pad(scores, (0, 1)).softmax(-1)[..., :-1].masked_fill(~active, 0) receive, send = self._message_roles(nodes) hidden = self.inter[1](receive.unsqueeze(2) + send.unsqueeze(1)) summed = (hidden * gates.unsqueeze(-1)).sum(2) return self._project_messages(summed, gates.sum(-1, keepdim=True)) def _messages(self, nodes: Tensor) -> Tensor: if torch.compiler.is_compiling() or torch.are_deterministic_algorithms_enabled(): return self._dense_messages(nodes) if nodes.device.type in ("cuda", "mps"): return self._fixed_messages(nodes) return self._compact_messages(nodes) def step( self, state: Tensor, x0: Tensor, *, context: Tensor | None = None, previous: Tensor | None = None, radius: Tensor | None = None, mix: Tensor | None = None, ) -> Tensor: """Update all positions and layers from the same snapshot.""" normalized = self.norm(state) nodes = normalized.reshape(-1, self.num_layers, self.width) incoming = self._messages(nodes) past = None if state.ndim == 4: # At position t the temporal branch reads only t-1 from the old state. if previous is None: first = torch.zeros_like(normalized[:, :1]) else: first = self.norm(previous.to(state.dtype)).unsqueeze(1) past = torch.cat((first, normalized[:, :-1]), dim=1).reshape_as(nodes) local = self.intra(nodes, past) work = local.float() if local.dtype in (torch.float16, torch.bfloat16) else local # Promote before summing individually finite low-precision branches. work = work + incoming if context is not None: work = work + context.reshape_as(nodes) # A fixed budget for this token prevents feedback through the scale itself. if radius is None: radius = self.residual_radius(x0, context) # RMS clipping in rescaled coordinates also handles large finite BF16/FP32 # values whose squares overflow FP32. The common scale cancels algebraically. magnitude = work.detach().abs().amax(dim=-1, keepdim=True).clamp_min(1) rescaled = work / magnitude rms = rescaled.norm(dim=-1, keepdim=True) * self.width**-0.5 direction = (rescaled / rms.maximum(magnitude.reciprocal())).reshape_as(state) candidate = state + direction * (radius / self.steps) if mix is None: mix = self._step_mix() updated = torch.lerp(candidate, x0.to(candidate.dtype), mix.to(candidate.dtype)) return updated.to(torch.promote_types(state.dtype, local.dtype)) def _encode_chunk(self, features: Tensor, memory: GraphMemory | None, *, carry_only: bool = False): if features.ndim not in (2, 3): raise ValueError("Expected features shaped [batch, input_dim] or [batch, time, input_dim]") if features.ndim == 3 and features.shape[1] == 0: raise ValueError("Expected at least one token") single = features.ndim == 2 sequence = features.unsqueeze(1) if single else features x0 = self.encoder(sequence).unflatten(-1, (self.num_layers, self.width)) if memory is not None: expected = (self.steps, sequence.size(0), self.num_layers, self.width) if memory.previous.shape != expected or memory.previous.device != x0.device: raise ValueError("Memory previous shape and device must match the current stream") memory_steps = self.memory_steps if memory_steps[-1] >= self.steps: raise ValueError("memory_write_step must be smaller than the current steps") carries = [None] * len(memory_steps) if memory is not None: if self._legacy_carry: carries = [memory.hidden] elif memory.hidden.size(0) != len(memory_steps): raise ValueError("Memory hidden must hold one carry per memory step") else: carries = list(memory.hidden.unbind(0)) state = x0 boundary, hidden = [], [] mix = self._step_mix() context = None # Iterations are cheap to recompute but each saves many activations. recompute = self.checkpoint_steps and torch.is_grad_enabled() run = (lambda f, *a, **k: checkpoint(f, *a, use_reentrant=False, **k)) if recompute else (lambda f, *a, **k: f(*a, **k)) for i in range(self.steps): if i in memory_steps: # Earlier iterations never read this scan. Their outputs for # every position are available before its prefix scan. A later # memory step replaces the context with a read of its own scan. carry = carries[memory_steps.index(i)] context, carry = run(self._read_memory, i, state, x0, carry, memory) hidden.append(carry) radius = self.residual_radius(x0, context) elif i == 0: radius = self.residual_radius(x0, None) boundary.append(state[:, -1]) previous = memory.previous[i] if memory is not None else None if carry_only and i >= memory_steps[-1]: # The prefix scans above need all positions. Their suffix reads # are enough for the remaining synchronous local graph steps: # each reads one preceding position, and only the final # position of each iteration enters GraphMemory.previous. remaining = self.steps - i - 1 if remaining == 0: return None, self._pack_memory(hidden, boundary) if state.size(1) > remaining: previous = state[:, -remaining - 1] state = state[:, -remaining:] x0 = x0[:, -remaining:] context = context[:, -remaining:] radius = radius[:, -remaining:] state = run(self.step, state, x0, context=context, previous=previous, radius=radius, mix=mix) return (state[:, 0] if single else state), self._pack_memory(hidden, boundary) def _pack_memory(self, hidden: list[Tensor], boundary: list[Tensor]) -> GraphMemory: return GraphMemory(hidden[0] if self._legacy_carry else torch.stack(hidden), torch.stack(boundary)) def encode(self, features: Tensor) -> Tensor: """Return final layer states [B, L, D] or [B, T, L, D] for a fresh stream.""" state, _ = self._encode_chunk(features, None) return state def pool(self, state: Tensor) -> Tensor: """Pool layers at each position. Width-preserving adapters start at the mean.""" if self.concat_readout: return self.pool_projection(state.flatten(-2)) if not self.adaptive_readout: return state.mean(-2) work = state.float() if state.dtype in (torch.float16, torch.bfloat16) else state scores = (F.layer_norm(work, (self.width,)) * self.pool_query).sum(-1) * self.width**-0.5 pooled = (work * scores.softmax(-1).unsqueeze(-1)).sum(-2) normalized = F.layer_norm(pooled, (self.width,)) return torch.lerp(pooled, normalized, self.pool_norm_mix.tanh()).to(state.dtype) def forward_chunk(self, features: Tensor, memory: GraphMemory | None = None) -> tuple[Tensor, GraphMemory]: """Continue a sequence using explicit carry; gradients cross chunks by default.""" state, memory = self._encode_chunk(features, memory) return self.readout(self.pool(state)), memory @staticmethod def diversity_loss(state: Tensor) -> Tensor: """Penalize collinear layers and degenerate zero-length directions.""" if state.dtype in (torch.float16, torch.bfloat16): state = state.float() directions = F.normalize(state, dim=-1) cosine = directions @ directions.transpose(-1, -2) layers = state.size(-2) diagonal = torch.eye(layers, device=state.device, dtype=torch.bool) overlap = cosine.masked_fill(diagonal, 0).square().sum((-1, -2)) unit_error = (directions.square().sum(-1) - 1).square().mean() return overlap.mean() / (layers * (layers - 1)) + unit_error def forward(self, features: Tensor, *, return_states: bool = False) -> Tensor | tuple[Tensor, Tensor]: state = self.encode(features) logits = self.readout(self.pool(state)) return (logits, state) if return_states else logits class RecurrentGraphLM(nn.Module): """Causal language model with tied input/output embeddings and streaming carry.""" def __init__( self, vocab_size: int, *, width: int = 32, num_layers: int = 8, steps: int = 3, top_k: int = 2, x0_mix: float = 0.1, memory_max_half_life: float = LONG_CONTEXT, memory_write_step: int | Sequence[int] = 0, memory_addressing: str = "vector", adaptive_readout: bool = False, protect_writes: bool = False, memory_source: str = "token", concat_readout: bool = False, embed_dim: int | None = None, ): """embed_dim decouples the tied vocabulary table from the node width; a different value needs concat_readout. See RecurrentGraphNet.""" super().__init__() embed_dim = width if embed_dim is None else embed_dim self.graph = RecurrentGraphNet( embed_dim, vocab_size, width=width, num_layers=num_layers, steps=steps, top_k=top_k, x0_mix=x0_mix, memory_max_half_life=memory_max_half_life, memory_write_step=memory_write_step, memory_addressing=memory_addressing, adaptive_readout=adaptive_readout, protect_writes=protect_writes, memory_source=memory_source, concat_readout=concat_readout, readout_dim=embed_dim, ) self.embedding = nn.Embedding(vocab_size, embed_dim) # The tied table is used once at input and once at readout. Scale both # appearances to temper width-driven growth of the initial logits. with torch.no_grad(): self.embedding.weight.mul_(embed_dim**-0.25) self.graph.readout.weight = self.embedding.weight self.register_load_state_dict_post_hook(self._retie_after_load) @staticmethod def _retie_after_load(module, incompatible_keys): module.graph.readout.weight = module.embedding.weight def _apply(self, fn, recurse=True): # Some device conversions replace the two references independently. tied = self.graph.readout.weight is self.embedding.weight result = super()._apply(fn, recurse) if tied: self.graph.readout.weight = self.embedding.weight return result def forward(self, tokens: Tensor, *, return_states: bool = False) -> Tensor | tuple[Tensor, Tensor]: return self.graph(self.embedding(tokens), return_states=return_states) def forward_chunk(self, tokens: Tensor, memory: GraphMemory | None = None) -> tuple[Tensor, GraphMemory]: return self.graph.forward_chunk(self.embedding(tokens), memory) def advance_chunk(self, tokens: Tensor, memory: GraphMemory | None = None) -> GraphMemory: """Compute the exact outgoing carry without materializing unused graph states.""" return self.graph._encode_chunk(self.embedding(tokens), memory, carry_only=True)[1] def encode_chunk(self, tokens: Tensor, memory: GraphMemory | None = None) -> tuple[Tensor, GraphMemory]: """Return graph states and stream carry without materializing vocabulary logits.""" return self.graph._encode_chunk(self.embedding(tokens), memory) @torch.no_grad() def init_output_prior(self, counts: Tensor, smoothing: float = 0.5) -> None: """Start the vocabulary bias at centered log unigram frequencies. Adam moves each bias entry by about one learning rate per update, so the default near-zero bias needs thousands of updates to span a prior of several nats. A token-independent state vector read through the tied embedding fits it sooner, but only along one direction, and it then fills the fixed per-step update budget and aligns every layer with the same vector. Call on a fresh model with counts from training data only. """ bias = self.graph.readout.bias if counts.shape != bias.shape: raise ValueError("Expected one count per vocabulary entry") counts = counts.detach().to(device="cpu", dtype=torch.float64) if not math.isfinite(smoothing) or smoothing <= 0: raise ValueError("smoothing must be finite and positive") if not counts.isfinite().all() or (counts < 0).any(): raise ValueError("Counts must be finite and nonnegative") log_prior = (counts + smoothing).log() bias.copy_((log_prior - log_prior.mean()).to(bias)) def optimizer_groups( model: nn.Module, weight_decay: float, *, lr: float | None = None, base_fan_in: int | None = None, ) -> list[dict]: """AdamW parameter groups that decay weight matrices only. Biases, norm affines, the readout's norm mix and the logits for memory retention, x0 anchoring and residual radius encode time scales or interpolation amounts rather than feature weights. Decoupled decay pulls them toward zero regardless of the data, e.g. it shortens a 262K-token half-life to ~9K tokens in 100K updates at lr=3e-4. Without base_fan_in: two groups (decay, keep) in model.parameters() order. base_fan_in (requires lr): a coherent Adam step changes each output of a linear map by about lr * fan_in, so a weight with a wider input gets lr * base_fan_in / fan_in. The A100_40GB preset's 4096-input readout projection diverged at lr=1e-3 without this. Embedding tables keep lr. """ if not math.isfinite(weight_decay) or weight_decay < 0: raise ValueError("weight_decay must be finite and nonnegative") if base_fan_in is not None and (lr is None or base_fan_in < 1): raise ValueError("base_fan_in must be positive and needs lr") norms = {id(p) for m in model.modules() if isinstance(m, nn.LayerNorm) for p in m.parameters(recurse=False)} tables = {id(m.weight) for m in model.modules() if isinstance(m, nn.Embedding)} groups: dict[tuple[bool, float], list[nn.Parameter]] = {(False, 1.0): [], (True, 1.0): []} for name, parameter in model.named_parameters(): fixed = id(parameter) in norms or name.endswith(("bias", "mix_logit", "pool_norm_mix")) scale = 1.0 if base_fan_in is not None and not fixed and parameter.ndim >= 2 and id(parameter) not in tables: # Linear weights are [out, in]; LayerwiseMLP weights are [layers, in, out]. fan_in = parameter.shape[-2] if parameter.ndim == 3 else parameter.shape[-1] scale = min(1.0, base_fan_in / fan_in) groups.setdefault((fixed, scale), []).append(parameter) result = [] for (fixed, scale), params in groups.items(): group = dict(params=params, weight_decay=0.0 if fixed else weight_decay) if lr is not None: group["lr"] = lr * scale if params or base_fan_in is None: result.append(group) return result