File size: 15,912 Bytes
127ebd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""Padding-free packed forward of a Qwen3.5 text backbone (``Qwen3_5TextModel``), causal attention.

A batch is one flat token stream of several sequences, ``input_ids`` [T] with cumulative lengths ``cu_seqlens``. Every
layer resets at each sequence boundary through variable-length kernels:

- full attention: flash-attn ``flash_attn_varlen_func`` (or a per-sequence SDPA loop, the reference backend);
- Gated DeltaNet: fla ``causal_conv1d`` and ``chunk_gated_delta_rule`` with ``cu_seqlens``, so no recurrent state or
  conv window crosses a boundary.

Branches: a batch built with ``owners`` holds root sequences first, then branches, each continuing one root as if
appended to it, so a root (a question's shared prefix) runs once for all its branches (its options). A branch's
positions go on from its root's length, and every layer reads what the root left behind, as a prefix cache would: full
attention sees the root's keys and values (bottom-right causal), the short convolution sees the root's last
``kernel - 1`` inputs, and the delta rule starts from the root's final recurrent state. The result is the same as one
sequence per (root + branch), up to kernel rounding.

The math is transformers' ``modeling_qwen3_5`` (same submodules, same order); only the kernels differ.
"""
from __future__ import annotations

from dataclasses import dataclass

import torch
import torch.nn.functional as F

ATTENTION_BACKENDS = ("flash", "sdpa")


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 Branches:
    """The shared-prefix layout of a packed stream: sequences ``[0, roots)`` are roots (stream tokens ``[0, tokens)``),
    the rest branches; branch j continues root ``owners[j]``."""

    roots: int
    tokens: int
    owners: list[int]
    root_lengths: list[int]
    branch_lengths: list[int]
    owner: torch.Tensor        # [N_b] long
    cu_roots: torch.Tensor     # [N_r+1] int32
    cu_branches: torch.Tensor  # [N_b+1] int32, offsets from ``tokens``
    kv_index: torch.Tensor     # stream indices of the keys/values each branch reads: its root's tokens, then its own
    cu_kv: torch.Tensor        # [N_b+1] int32
    max_root: int
    max_branch: int
    max_kv: int
    device: torch.device | str

    def __post_init__(self):
        self._conv: dict[int, tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = {}
        self._chunks: tuple | None = None
        self._chunks_ready = False

    def _make_chunks(self) -> tuple | None:
        """Contiguous branch ranges whose expanded KV rows are bounded by the logical token count (keeps the expanded
        key/value copies of many branches from growing past the batch's own size)."""
        kv_lengths = [self.root_lengths[o] + n for o, n in zip(self.owners, self.branch_lengths)]
        logical_tokens = self.tokens + sum(self.branch_lengths)
        if sum(kv_lengths) <= logical_tokens:
            return None

        raw_chunks = []
        q_at = kv_at = q_start = kv_start = expanded = 0
        q_lengths, chunk_kv_lengths = [], []
        for q_length, kv_length in zip(self.branch_lengths, kv_lengths):
            if expanded and expanded + kv_length > logical_tokens:
                raw_chunks.append((q_start, q_at, kv_start, kv_at, q_lengths, chunk_kv_lengths))
                q_start, kv_start = q_at, kv_at
                q_lengths, chunk_kv_lengths, expanded = [], [], 0
            q_at += q_length
            kv_at += kv_length
            q_lengths.append(q_length)
            chunk_kv_lengths.append(kv_length)
            expanded += kv_length
        raw_chunks.append((q_start, q_at, kv_start, kv_at, q_lengths, chunk_kv_lengths))

        return tuple(
            (q_start, q_end, kv_start, kv_end,
             _cumsum(q_lengths).to(self.device, non_blocking=True),
             _cumsum(kv_lengths).to(self.device, non_blocking=True),
             max(q_lengths), max(kv_lengths), q_lengths, kv_lengths)
            for q_start, q_end, kv_start, kv_end, q_lengths, kv_lengths in raw_chunks
        )

    def conv_layout(self, tail: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """-> (index, cu_seqlens, keep) for one short-convolution call over the whole stream: ``index`` gathers the
        conv inputs (every root, then each branch preceded by its root's last ``tail`` inputs), ``cu_seqlens`` (long)
        bounds those sequences, ``keep`` picks the outputs of the stream's own tokens, in stream order."""
        if tail not in self._conv:
            root_ends = _cumsum(self.root_lengths)[1:].tolist()
            index, lengths, keep = list(range(self.tokens)), list(self.root_lengths), list(range(self.tokens))
            at = self.tokens
            for r, n in zip(self.owners, self.branch_lengths):
                t = min(tail, self.root_lengths[r])
                start = len(index)
                index += range(root_ends[r] - t, root_ends[r])
                index += range(at, at + n)
                keep += range(start + t, start + t + n)
                lengths.append(t + n)
                at += n
            to = lambda x: torch.tensor(x, dtype=torch.long).to(self.device, non_blocking=True)  # noqa: E731
            self._conv[tail] = (to(index), _cumsum(lengths).long().to(self.device, non_blocking=True), to(keep))
        return self._conv[tail]


@dataclass
class Packed:
    """A flat token stream of sequences. ``starts[i]`` is the offset of sequence i in the stream. ``branches`` is set
    when some sequences continue others (``build(..., owners=...)``)."""

    input_ids: torch.Tensor     # [T] long
    position_ids: torch.Tensor  # [T] long, restarting at 0 per sequence (a branch: at its root's length)
    cu_seqlens: torch.Tensor    # [N+1] int32 (flash-attn); fla takes it as long
    lengths: list[int]
    max_seqlen: int
    branches: Branches | None = None

    @classmethod
    def build(cls, sequences: list[list[int]], device: torch.device | str,
              owners: list[int] | None = None) -> Packed:
        """``owners[i]``: -1 for a root sequence, else the index of the root that sequence i continues. Roots come
        first."""
        lengths = [len(s) for s in sequences]
        if not lengths or min(lengths) < 1:
            raise ValueError("a packed batch needs at least one nonempty sequence")
        ids = torch.tensor([t for s in sequences for t in s], dtype=torch.long)
        branches = None
        if owners is None or all(o < 0 for o in owners):
            pos = torch.cat([torch.arange(n) for n in lengths])
        else:
            if len(owners) != len(sequences):
                raise ValueError("owners must give one entry per sequence")
            roots = next(i for i, o in enumerate(owners) if o >= 0)
            tail = owners[roots:]
            if any(o >= 0 for o in owners[:roots]) or any(not 0 <= o < roots for o in tail):
                raise ValueError("roots must come first and every branch must continue a root")
            root_lengths, branch_lengths = lengths[:roots], lengths[roots:]
            pos = torch.cat([torch.arange(n) for n in root_lengths]
                            + [torch.arange(root_lengths[o], root_lengths[o] + n) for o, n in zip(tail, branch_lengths)])
            tokens = sum(root_lengths)
            root_starts = _cumsum(root_lengths).tolist()
            kv, kv_lengths, at = [], [], tokens
            for o, n in zip(tail, branch_lengths):
                kv += range(root_starts[o], root_starts[o + 1])
                kv += range(at, at + n)
                kv_lengths.append(root_lengths[o] + n)
                at += n
            branches = Branches(
                roots, tokens, tail, root_lengths, branch_lengths,
                torch.tensor(tail, dtype=torch.long).to(device, non_blocking=True),
                _cumsum(root_lengths).to(device, non_blocking=True),
                _cumsum(branch_lengths).to(device, non_blocking=True),
                torch.tensor(kv, dtype=torch.long).to(device, non_blocking=True),
                _cumsum(kv_lengths).to(device, non_blocking=True),
                max(root_lengths), max(branch_lengths), max(kv_lengths), device)
        return cls(ids.to(device, non_blocking=True), pos.to(device, non_blocking=True),
                   _cumsum(lengths).to(device, non_blocking=True), lengths, max(lengths), branches)

    @property
    def starts(self) -> list[int]:
        out, at = [], 0
        for n in self.lengths:
            out.append(at)
            at += n
        return out


@dataclass
class _Context:
    batch: Packed
    cos: torch.Tensor   # [T, rotary_dim]
    sin: torch.Tensor
    attention: str
    cu_long: torch.Tensor


def _deltanet(m, x: torch.Tensor, ctx: _Context) -> torch.Tensor:
    """transformers ``Qwen3_5GatedDeltaNet.forward`` on a packed stream (no cache, no padding)."""
    from fla.modules.conv import causal_conv1d
    from fla.ops.gated_delta_rule import chunk_gated_delta_rule

    T = x.shape[0]
    mixed = m.in_proj_qkv(x)
    z = m.in_proj_z(x)
    b = m.in_proj_b(x)
    a = m.in_proj_a(x)
    br = ctx.batch.branches
    weight = m.conv1d.weight.squeeze(1)
    if br is None:
        mixed, _ = causal_conv1d(mixed[None], weight=weight, bias=m.conv1d.bias, activation=m.activation,
                                 cu_seqlens=ctx.cu_long)
    else:   # each branch convolves on from its root's last inputs (the conv window a cache would hold)
        index, cu, keep = br.conv_layout(m.conv_kernel_size - 1)
        mixed, _ = causal_conv1d(mixed[index][None], weight=weight, bias=m.conv1d.bias, activation=m.activation,
                                 cu_seqlens=cu)
        mixed = mixed[:, keep]
    q, k, v = torch.split(mixed[0], [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]
    if br is None:
        out, _ = chunk_gated_delta_rule(q, k, v, g=g, beta=beta, use_qk_l2norm_in_kernel=True,
                                        cu_seqlens=ctx.cu_long)
    else:   # roots, then branches from their root's final recurrent state
        r = br.tokens
        roots, final = chunk_gated_delta_rule(q[:, :r], k[:, :r], v[:, :r], g=g[:, :r], beta=beta[:, :r],
                                              use_qk_l2norm_in_kernel=True, output_final_state=True,
                                              cu_seqlens=br.cu_roots.long())
        rest, _ = chunk_gated_delta_rule(q[:, r:], k[:, r:], v[:, r:], g=g[:, r:], beta=beta[:, r:],
                                         use_qk_l2norm_in_kernel=True, initial_state=final[br.owner],
                                         cu_seqlens=br.cu_branches.long())
        out = torch.cat([roots, rest], 1)
    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 _rotate_half(x: torch.Tensor) -> torch.Tensor:
    half = x.shape[-1] // 2
    return torch.cat((-x[..., half:], x[..., :half]), dim=-1)


def _rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """transformers' partial-rotary ``apply_rotary_pos_emb`` for x [T, H, D], cos/sin [T, R]."""
    r = cos.shape[-1]
    cos, sin = cos[:, None], sin[:, None]
    rot, keep = x[..., :r], x[..., r:]
    return torch.cat([rot * cos + _rotate_half(rot) * sin, keep], dim=-1)


def _attention(m, x: torch.Tensor, ctx: _Context) -> torch.Tensor:
    """transformers ``Qwen3_5Attention.forward`` (gated output, q/k RMSNorm, partial RoPE) on a packed stream."""
    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)
    b, br = ctx.batch, ctx.batch.branches
    if br is None:
        out = _varlen(q, k, v, b.cu_seqlens, b.cu_seqlens, b.max_seqlen, b.max_seqlen, b.lengths, b.lengths,
                      m.scaling, ctx.attention)
    else:   # roots on their own; a branch's queries see its root's keys and values, then its own (causal)
        r = br.tokens
        if not br._chunks_ready:
            br._chunks = br._make_chunks()
            br._chunks_ready = True
        root_out = _varlen(q[:r], k[:r], v[:r], br.cu_roots, br.cu_roots, br.max_root, br.max_root,
                           br.root_lengths, br.root_lengths, m.scaling, ctx.attention)
        if br._chunks is None:
            kv_lengths = [br.root_lengths[o] + n for o, n in zip(br.owners, br.branch_lengths)]
            branch_out = [_varlen(q[r:], k[br.kv_index], v[br.kv_index], br.cu_branches, br.cu_kv, br.max_branch,
                                  br.max_kv, br.branch_lengths, kv_lengths, m.scaling, ctx.attention)]
        else:
            branch_out = []
            for q_start, q_end, kv_start, kv_end, cu_q, cu_kv, max_q, max_k, q_lengths, chunk_kv_lengths in \
                    br._chunks:
                chunk_k = k[br.kv_index[kv_start:kv_end]]
                chunk_v = v[br.kv_index[kv_start:kv_end]]
                branch_out.append(_varlen(q[r + q_start:r + q_end], chunk_k, chunk_v, cu_q, cu_kv, max_q, max_k,
                                          q_lengths, chunk_kv_lengths, m.scaling, ctx.attention))
                del chunk_k, chunk_v
        out = torch.cat([root_out, *branch_out])
    out = out.reshape(T, -1) * torch.sigmoid(gate)
    return m.o_proj(out)


def _varlen(q, k, v, cu_q, cu_k, max_q, max_k, lengths_q, lengths_k, scale, attention) -> torch.Tensor:
    """Causal variable-length attention; with longer keys than queries, query i of a sequence sees keys up to
    ``len_k - len_q + i`` (bottom-right alignment: the queries are the keys' last tokens)."""
    if attention == "flash":
        from flash_attn import flash_attn_varlen_func

        return flash_attn_varlen_func(q, k, v, cu_q, cu_k, max_q, max_k, softmax_scale=scale, causal=True)
    pieces = []
    for q_i, k_i, v_i, n_q, n_k in zip(q.split(lengths_q), k.split(lengths_k), v.split(lengths_k), lengths_q,
                                       lengths_k):
        mask = None
        if n_k != n_q:
            mask = torch.ones(n_q, n_k, dtype=torch.bool, device=q.device).tril(n_k - n_q)
        o = F.scaled_dot_product_attention(q_i.transpose(0, 1)[None], k_i.transpose(0, 1)[None],
                                           v_i.transpose(0, 1)[None], attn_mask=mask, is_causal=mask is None,
                                           scale=scale, enable_gqa=True)
        pieces.append(o[0].transpose(0, 1))
    return torch.cat(pieces)


@torch.no_grad()
def packed_forward(lm, batch: Packed, *, attention: str = "flash", readout: torch.Tensor | None = None):
    """Final-norm hidden states [T, hidden] of a packed batch (or the rows ``readout`` selects)."""
    if attention not in ATTENTION_BACKENDS:
        raise ValueError(f"attention must be one of {ATTENTION_BACKENDS}")
    hidden = lm.embed_tokens(batch.input_ids)
    cos, sin = lm.rotary_emb(hidden, batch.position_ids.view(1, 1, -1).expand(3, 1, -1))
    ctx = _Context(batch, cos[0], sin[0], attention, batch.cu_seqlens.long())
    for layer in lm.layers:
        x = layer.input_layernorm(hidden)
        if layer.block_type == "linear_attention":
            x = _deltanet(layer.linear_attn, x, ctx)
        else:
            x = _attention(layer.self_attn, x, ctx)
        hidden = hidden + x
        hidden = hidden + layer.mlp(layer.post_attention_layernorm(hidden))
    return lm.norm(hidden if readout is None else hidden[readout])