"""Fork tree: a generalisation of ``packed.Branches`` from one level of branches to any depth. ``packed.Branches`` is the depth-1 case (roots, then branches that continue them). A ``ForkTree`` is a forest of token segments (nodes). A node with ``parent >= 0`` continues its parent's whole path, as if its tokens were appended to the path of tokens from the root down to the parent. The decision serving layout is depth 2: state (root) -> question -> option:: request: root = system prompt + "State:" + state runs once child = "Instruction: ... Options: ... Grade this option: " one per question, from the root leaf = option text + chat tail one per option, from its question Stream order: levels one after another (every root, then every depth-1 node, ...); within a level nodes follow their parents' order, so the descendants of any node at any ancestor level are contiguous. Positions on from the parent's path. Per layer (``tree_forward``), the same exactness argument as ``packed.Branches``, one level at a time: - Gated DeltaNet: one short-convolution call over the whole stream (a node's sequence is the last ``kernel - 1`` conv inputs of its path, then its own tokens; all conv inputs of a layer exist before the layer runs), then one ``chunk_gated_delta_rule`` call per level, each starting from the previous level's final recurrent states gathered by parent. - Full attention: a node's queries attend to its own tokens (causal) and to every ancestor's tokens (no mask: they all come earlier). Each of those is one flash-attn varlen call per (level, ancestor level) over contiguous slices of the stream (the K/V of a parent is never expanded per child), and the partial results are merged by their log-sum-exp, which is the one softmax over the whole path up to rounding. ``attention="sdpa"`` instead gathers each node's complete path and runs one softmax (slow, the reference). A root may carry a ``Past``: the per-layer state a prefix cache holds after the root's first ``length`` tokens (last conv inputs, recurrent state, keys/values). The root then continues that prefix: positions start at ``length``, its queries also attend to the cached keys, its conv and delta rule start from the cached tails/state. ``capture=True`` returns the same per-layer state at the end of each root, for a cache to keep. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Sequence import torch import torch.nn.functional as F from .packed import ATTENTION_BACKENDS, _rope @dataclass class Past: """A cached prefix at a fork point, per layer index: GDN layers carry ``conv`` ([tail, conv_dim]: the last conv inputs) and ``state`` ([Hv, K, V] fp32), full-attention layers ``k``/``v`` ([length, Hkv, D], rotated keys).""" length: int conv: dict[int, torch.Tensor] = field(default_factory=dict) state: dict[int, torch.Tensor] = field(default_factory=dict) k: dict[int, torch.Tensor] = field(default_factory=dict) v: dict[int, torch.Tensor] = field(default_factory=dict) @dataclass class Level: start: int # stream offset of the level's first token end: int nodes: list[int] # input node ids, in stream order lengths: list[int] cu: torch.Tensor # [n+1] int32 cu_long: torch.Tensor # [n+1] long (fla) max_len: int parent_local: torch.Tensor | None # [n] long: index into the previous level's nodes ancestors: list[tuple[torch.Tensor, int]] # per ancestor level j < depth: (cu_q [n_j+1] int32, max_q) past_q: torch.Tensor | None = None # [Qp] long: level-token positions under a root with a past, past_cu_q: torch.Tensor | None = None # grouped by slot: [slots+1] int32 past_max_q: int = 0 @dataclass class ForkTree: input_ids: torch.Tensor # [T] long, stream order position_ids: torch.Tensor levels: list[Level] node_start: list[int] # stream offset of input node i lengths: list[int] # per input node parent: list[int] path: list[list[int]] # input node ids from the root down to the node tail: int # conv kernel - 1 pasts: list[Past] # the distinct pasts roots continue (roots may share one), "slots" root_slot: list[int] # per level-0 node (stream order): its slot, -1 for none past_roots: torch.Tensor | None # [m] long: level-0 positions of the roots that continue a past past_cu_k: torch.Tensor | None past_max_k: int conv_index: torch.Tensor # gathers conv inputs from [stream; past tails] conv_cu: torch.Tensor # long conv_keep: torch.Tensor capture_tail: torch.Tensor | None # [R*tail] indices of each root's last conv inputs in [stream; past tails] device: torch.device | str @property def tokens(self) -> int: return int(self.input_ids.shape[0]) @classmethod def build(cls, nodes: Sequence[tuple[int, Sequence[int]]], device: torch.device | str, *, tail: int = 3, pasts: dict[int, Past] | None = None) -> ForkTree: """``nodes[i] = (parent, ids)``: parent -1 for a root, else an earlier node. ``pasts[i]``: root i continues that cached prefix (``length`` >= ``tail``).""" n = len(nodes) if n == 0 or any(len(ids) < 1 for _, ids in nodes): raise ValueError("a fork tree needs nodes with at least one token each") parent = [p for p, _ in nodes] lengths = [len(ids) for _, ids in nodes] pasts = pasts or {} depth = [0] * n for i, p in enumerate(parent): if p >= i: raise ValueError("a node's parent must come before it") if p >= 0: depth[i] = depth[p] + 1 if any(parent[i] >= 0 for i in pasts): raise ValueError("only roots can carry a past") if any(p.length < tail for p in pasts.values()): raise ValueError(f"a past must cover at least the conv window ({tail} tokens)") n_levels = max(depth) + 1 # stream order: by level, within a level by the parent's stream rank, then input order rank = [0] * n by_level: list[list[int]] = [] at = 0 for d in range(n_levels): members = [i for i in range(n) if depth[i] == d] if d: members.sort(key=lambda i: (rank[parent[i]], i)) for r, i in enumerate(members): rank[i] = at + r at += len(members) by_level.append(members) local = {i: r for members in by_level for r, i in enumerate(members)} node_start, offset = [0] * n, 0 for members in by_level: for i in members: node_start[i] = offset offset += lengths[i] path = [[] for _ in range(n)] for members in by_level: for i in members: path[i] = (path[parent[i]] if parent[i] >= 0 else []) + [i] base = [0] * n # position of each node's first token for members in by_level: for i in members: base[i] = pasts[i].length if i in pasts else (base[parent[i]] + lengths[parent[i]] if parent[i] >= 0 else 0) total = offset ids = torch.empty(total, dtype=torch.long) pos = torch.empty(total, dtype=torch.long) for i in range(n): s = node_start[i] ids[s:s + lengths[i]] = torch.tensor(list(nodes[i][1]), dtype=torch.long) pos[s:s + lengths[i]] = torch.arange(base[i], base[i] + lengths[i]) dev = lambda t: t.to(device, non_blocking=True) # noqa: E731 root_members = by_level[0] past_list: list[Past] = [] slot_ids: dict[int, int] = {} root_slot = [] for i in root_members: if i in pasts: if id(pasts[i]) not in slot_ids: slot_ids[id(pasts[i])] = len(past_list) past_list.append(pasts[i]) root_slot.append(slot_ids[id(pasts[i])]) else: root_slot.append(-1) levels: list[Level] = [] for d, members in enumerate(by_level): lens = [lengths[i] for i in members] start = node_start[members[0]] cu = _cumsum(lens) ancestors = [] for j in range(d): counts = [0] * len(by_level[j]) for i in members: a = path[i][j] counts[local[a]] += lengths[i] ancestors.append((dev(_cumsum(counts)), max(counts))) level = Level(start, start + sum(lens), members, lens, dev(cu), dev(cu.long()), max(lens), dev(torch.tensor([local[parent[i]] for i in members])) if d else None, ancestors) if past_list: per_slot: list[list[int]] = [[] for _ in past_list] at_tok = 0 for i in members: slot = root_slot[local[path[i][0]]] if slot >= 0: per_slot[slot] += range(at_tok, at_tok + lengths[i]) at_tok += lengths[i] counts = [len(x) for x in per_slot] q_pos = [t for x in per_slot for t in x] if q_pos: level.past_q = dev(torch.tensor(q_pos, dtype=torch.long)) level.past_cu_q = dev(_cumsum(counts)) level.past_max_q = max(counts) levels.append(level) # one short-convolution call over every node: [tail rows of its path, own rows], rows indexing [stream; tails] index: list[int] = [] conv_lengths: list[int] = [] keep_rows: list[int] = [] capture: list[int] = [] for members in by_level: for i in members: rows: list[int] = [] need, a = tail, parent[i] while need > 0 and a >= 0: take = min(need, lengths[a]) rows = list(range(node_start[a] + lengths[a] - take, node_start[a] + lengths[a])) + rows need -= take if parent[a] < 0 and need > 0 and root_slot[local[a]] >= 0: k = root_slot[local[a]] rows = [total + k * tail + t for t in range(tail - need, tail)] + rows need = 0 a = parent[a] if parent[i] < 0 and i in pasts: k = root_slot[local[i]] rows = [total + k * tail + t for t in range(tail)] own = list(range(node_start[i], node_start[i] + lengths[i])) keep_rows += range(len(index) + len(rows), len(index) + len(rows) + lengths[i]) index += rows + own conv_lengths.append(len(rows) + lengths[i]) if parent[i] < 0: capture += (rows + own)[-tail:] if len(rows) + lengths[i] >= tail else [-1] * tail capture_tail = None if all(c >= 0 for c in capture): capture_tail = dev(torch.tensor(capture, dtype=torch.long)) pk, pmax = None, 0 if past_list: pk = dev(_cumsum([p.length for p in past_list])) pmax = max(p.length for p in past_list) # keep_rows must follow stream order; they do, because ``index`` was filled node by node in stream order with_past = [r for r, s_ in enumerate(root_slot) if s_ >= 0] return cls(dev(ids), dev(pos), levels, node_start, lengths, parent, path, tail, past_list, root_slot, dev(torch.tensor(with_past, dtype=torch.long)) if with_past else None, pk, pmax, dev(torch.tensor(index, dtype=torch.long)), dev(_cumsum(conv_lengths).long()), dev(torch.tensor(keep_rows, dtype=torch.long)), capture_tail, device) def _cumsum(lengths: list[int]) -> torch.Tensor: cu = torch.zeros(len(lengths) + 1, dtype=torch.int32) if lengths: cu[1:] = torch.tensor(lengths).cumsum(0) return cu @dataclass class _Ctx: tree: ForkTree cos: torch.Tensor sin: torch.Tensor attention: str capture: bool captured: dict[int, dict[str, torch.Tensor]] def _flash(q, k, v, cu_q, cu_k, max_q, max_k, scale, causal, lse: bool): from flash_attn import flash_attn_varlen_func if lse: out, l, _ = flash_attn_varlen_func(q, k, v, cu_q, cu_k, max_q, max_k, softmax_scale=scale, causal=causal, return_attn_probs=True) return out, l return flash_attn_varlen_func(q, k, v, cu_q, cu_k, max_q, max_k, softmax_scale=scale, causal=causal), None def _merge(parts: list[tuple[torch.Tensor, torch.Tensor]], dtype) -> torch.Tensor: """Softmax over the union of the keys of ``parts``: (out [Tq, H, D], lse [H, Tq]) each, over disjoint key sets.""" lse = torch.stack([l for _, l in parts]) # [P, H, Tq] weights = torch.exp(lse - torch.logsumexp(lse, 0, keepdim=True)) out = sum(w.transpose(0, 1)[..., None] * o.float() for w, (o, _) in zip(weights, parts)) return out.to(dtype) def _attention_flash(q, k, v, tree: ForkTree, scale: float, li: int) -> torch.Tensor: outs = [] past_k = past_v = None if tree.pasts: past_k = torch.cat([p.k[li] for p in tree.pasts]) past_v = torch.cat([p.v[li] for p in tree.pasts]) for d, lv in enumerate(tree.levels): s, e = lv.start, lv.end q_l = q[s:e] if d == 0 and not tree.pasts: outs.append(_flash(q_l, k[s:e], v[s:e], lv.cu, lv.cu, lv.max_len, lv.max_len, scale, True, False)[0]) continue parts = [_flash(q_l, k[s:e], v[s:e], lv.cu, lv.cu, lv.max_len, lv.max_len, scale, True, True)] for j, (cu_q, max_q) in enumerate(lv.ancestors): a = tree.levels[j] parts.append(_flash(q_l, k[a.start:a.end], v[a.start:a.end], cu_q, a.cu, max_q, a.max_len, scale, False, True)) if lv.past_q is not None: o, l = _flash(q_l[lv.past_q], past_k, past_v, lv.past_cu_q, tree.past_cu_k, lv.past_max_q, tree.past_max_k, scale, False, True) full_o = torch.zeros_like(parts[0][0]) full_l = torch.full_like(parts[0][1], float("-inf")) full_o[lv.past_q] = o full_l[:, lv.past_q] = l parts.append((full_o, full_l)) outs.append(_merge(parts, q.dtype)) return torch.cat(outs) if len(outs) > 1 else outs[0] def _attention_sdpa(q, k, v, tree: ForkTree, scale: float, li: int) -> torch.Tensor: """Reference: one softmax per node over its complete path (past, ancestors, own), bottom-right causal.""" out = torch.empty_like(q) past_of = {r: tree.pasts[s] for r, s in enumerate(tree.root_slot) if s >= 0} root_local = {i: r for r, i in enumerate(tree.levels[0].nodes)} for i in range(len(tree.parent)): keys, values = [], [] root = tree.path[i][0] if root_local[root] in past_of: keys.append(past_of[root_local[root]].k[li]) values.append(past_of[root_local[root]].v[li]) for a in tree.path[i]: keys.append(k[tree.node_start[a]:tree.node_start[a] + tree.lengths[a]]) values.append(v[tree.node_start[a]:tree.node_start[a] + tree.lengths[a]]) kk, vv = torch.cat(keys), torch.cat(values) s, n = tree.node_start[i], tree.lengths[i] mask = torch.ones(n, kk.shape[0], dtype=torch.bool, device=q.device).tril(kk.shape[0] - n) o = F.scaled_dot_product_attention(q[s:s + n].transpose(0, 1)[None], kk.transpose(0, 1)[None], vv.transpose(0, 1)[None], attn_mask=mask, scale=scale, enable_gqa=True) out[s:s + n] = o[0].transpose(0, 1) return out def _attention(m, x: torch.Tensor, ctx: _Ctx, li: int) -> torch.Tensor: T, hd = x.shape[0], m.head_dim q, gate = torch.chunk(m.q_proj(x).view(T, -1, hd * 2), 2, dim=-1) gate = gate.reshape(T, -1) q = m.q_norm(q) k = m.k_norm(m.k_proj(x).view(T, -1, hd)) v = m.v_proj(x).view(T, -1, hd) q, k = _rope(q, ctx.cos, ctx.sin), _rope(k, ctx.cos, ctx.sin) if ctx.capture: lv = ctx.tree.levels[0] ctx.captured[li] = {"k": k[:lv.end], "v": v[:lv.end]} # views; ``segment_of`` copies run = _attention_flash if ctx.attention == "flash" else _attention_sdpa out = run(q, k, v, ctx.tree, m.scaling, li) return m.o_proj(out.reshape(T, -1) * torch.sigmoid(gate)) def _deltanet(m, x: torch.Tensor, ctx: _Ctx, li: int) -> torch.Tensor: from fla.modules.conv import causal_conv1d from fla.ops.gated_delta_rule import chunk_gated_delta_rule tree, T = ctx.tree, x.shape[0] mixed = m.in_proj_qkv(x) z, b, a = m.in_proj_z(x), m.in_proj_b(x), m.in_proj_a(x) source = mixed if tree.pasts: source = torch.cat([mixed, torch.stack([p.conv[li] for p in tree.pasts]).reshape(-1, mixed.shape[-1])]) conv, _ = causal_conv1d(source[tree.conv_index][None], weight=m.conv1d.weight.squeeze(1), bias=m.conv1d.bias, activation=m.activation, cu_seqlens=tree.conv_cu) mixed = conv[0, tree.conv_keep] q, k, v = torch.split(mixed, [m.key_dim, m.key_dim, m.value_dim], dim=-1) q = q.reshape(1, T, -1, m.head_k_dim) k = k.reshape(1, T, -1, m.head_k_dim) v = v.reshape(1, T, -1, m.head_v_dim) beta = b.sigmoid()[None] g = (-m.A_log.float().exp() * F.softplus(a.float() + m.dt_bias))[None] init = None if tree.pasts: states = torch.stack([p.state[li] for p in tree.pasts]) init = torch.zeros(len(tree.levels[0].nodes), *states.shape[1:], dtype=torch.float32, device=x.device) init[tree.past_roots] = states[torch.tensor([s for s in tree.root_slot if s >= 0], device=x.device)] outs = [] for d, lv in enumerate(tree.levels): last = d == len(tree.levels) - 1 want = (not last) or (d == 0 and ctx.capture) sl = slice(lv.start, lv.end) o, final = chunk_gated_delta_rule(q[:, sl], k[:, sl], v[:, sl], g=g[:, sl], beta=beta[:, sl], use_qk_l2norm_in_kernel=True, initial_state=init, output_final_state=want, cu_seqlens=lv.cu_long) outs.append(o) if d == 0 and ctx.capture: roots = len(lv.nodes) tails = source[tree.capture_tail].reshape(roots, tree.tail, -1) ctx.captured[li] = {"conv": tails, "state": final} if not last: init = final[tree.levels[d + 1].parent_local] out = torch.cat(outs, 1) if len(outs) > 1 else outs[0] out = m.norm(out.reshape(-1, m.head_v_dim), z.reshape(-1, m.head_v_dim)) return m.out_proj(out.reshape(T, -1)) def segment_of(tree: ForkTree, captured: dict[int, dict[str, torch.Tensor]], root: int) -> Past: """The end state of root node ``root`` (input index) from ``tree_forward(..., capture=True)``, as a ``Past`` that holds only that root's own tokens' keys/values (``length`` = its token count). Tensors are copies.""" r = tree.levels[0].nodes.index(root) s, n = tree.node_start[root], tree.lengths[root] out = Past(n) for li, c in captured.items(): if "conv" in c: out.conv[li], out.state[li] = c["conv"][r].clone(), c["state"][r].clone() else: out.k[li], out.v[li] = c["k"][s:s + n].clone(), c["v"][s:s + n].clone() return out def chain_past(segments: Sequence[Past]) -> Past: """A ``Past`` for a prefix made of consecutive ``segments`` (the first one's tokens first): the last segment's conv tails and state, every segment's keys/values joined.""" last = segments[-1] out = Past(sum(s.length for s in segments), dict(last.conv), dict(last.state)) for li in segments[0].k: out.k[li] = torch.cat([s.k[li] for s in segments]) if len(segments) > 1 else segments[0].k[li] out.v[li] = torch.cat([s.v[li] for s in segments]) if len(segments) > 1 else segments[0].v[li] return out @torch.no_grad() def tree_forward(lm, tree: ForkTree, *, attention: str = "flash", capture: bool = False, readout: torch.Tensor | None = None): """Final-norm hidden states of a fork tree, [T, hidden] (or the rows ``readout`` selects). With ``capture`` also returns ``{layer: tensors}`` for each root's end state (see ``Past``): GDN layers ``conv`` [R, tail, D] and ``state`` [R, Hv, K, V]; full-attention layers ``k``/``v`` [T_roots, Hkv, D] in root stream order.""" if attention not in ATTENTION_BACKENDS: raise ValueError(f"attention must be one of {ATTENTION_BACKENDS}") hidden = lm.embed_tokens(tree.input_ids) cos, sin = lm.rotary_emb(hidden, tree.position_ids.view(1, 1, -1).expand(3, 1, -1)) ctx = _Ctx(tree, cos[0], sin[0], attention, capture, {}) for li, layer in enumerate(lm.layers): x = layer.input_layernorm(hidden) if layer.block_type == "linear_attention": x = _deltanet(layer.linear_attn, x, ctx, li) else: x = _attention(layer.self_attn, x, ctx, li) hidden = hidden + x hidden = hidden + layer.mlp(layer.post_attention_layernorm(hidden)) out = lm.norm(hidden if readout is None else hidden[readout]) return (out, ctx.captured) if capture else out