File size: 13,492 Bytes
b66f552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang


import torch

from fla.modules.l2norm import l2norm_bwd, l2norm_fwd
from fla.ops.common.chunk_h import chunk_bwd_dh
from fla.ops.mesa_net.chunk_cg_solver_bwd import chunk_mesa_cg_bwd
from fla.ops.mesa_net.chunk_cg_solver_fwd import chunk_mesa_cg_fwd
from fla.ops.mesa_net.chunk_h_fwd import chunk_mesa_fwd_h
from fla.ops.mesa_net.chunk_h_kk_intra_bwd import chunk_mesa_net_h_kk_bwd_intra_fn
from fla.ops.mesa_net.chunk_h_kv_intra_bwd import chunk_mesa_net_h_kv_bwd_intra_fn
from fla.ops.utils import chunk_local_cumsum
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard


def chunk_fwd_mesa_net_fwd(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    g: torch.Tensor,
    beta: torch.Tensor,
    lamb: torch.Tensor,
    cu_seqlens: torch.Tensor,
    max_CG_iteration: int = 30,
    chunk_size: int = 64,
    h_kk_init: torch.Tensor | None = None,
    h_kv_init: torch.Tensor | None = None,
    output_final_state: bool = False,
) -> torch.Tensor:

    g = chunk_local_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens) if g is not None else None
    h_kk, h_kv, h_kk_final, h_kv_final = chunk_mesa_fwd_h(
        k=k,
        v=v,
        g=g,
        beta=beta,
        h_init=h_kk_init,
        h_kv_init=h_kv_init,
        output_final_state=output_final_state,
        states_in_fp32=False,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    q_star, o = chunk_mesa_cg_fwd(
        q=q,
        k=k,
        h=h_kk,
        h_kv=h_kv,
        v=v,
        g_local_cumsum=g,
        beta=beta,
        lamb=lamb,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
        max_CG_iteration=max_CG_iteration,
    )
    return g, q_star, o, (h_kk_final, h_kv_final)


def chunk_fwd_mesa_net_bwd(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    g: torch.Tensor,
    beta: torch.Tensor,
    lamb: torch.Tensor,
    q_star: torch.Tensor,  # should be cached in the forward pass
    do: torch.Tensor,
    cu_seqlens: torch.Tensor,
    max_CG_iteration: int = 30,
    chunk_size: int = 64,
    h_kk_init: torch.Tensor | None = None,
    h_kv_init: torch.Tensor | None = None,
    dh_kv_final: torch.Tensor | None = None,
    dh_kk_final: torch.Tensor | None = None,
) -> torch.Tensor:
    # recompute the hidden states, which is quite cheap
    h_kk, h_kv, _, _ = chunk_mesa_fwd_h(
        k=k,
        v=v,
        g=g,
        beta=beta,
        h_init=h_kk_init,
        h_kv_init=h_kv_init,
        output_final_state=False,
        states_in_fp32=False,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dh_kv, dh0_kv = chunk_bwd_dh(
        q=q_star,
        k=k,
        v=v,
        g=g,
        gk=None,
        gv=None,
        do=do,
        h0=h_kv_init,
        dht=dh_kv_final,
        states_in_fp32=False,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
        scale=1,
    )
    dq, dk_beta, dv, dg = chunk_mesa_net_h_kv_bwd_intra_fn(
        q_star=q_star,
        k=k,
        v=v,
        beta=beta,
        h_kv=h_kv,
        dh_kv=dh_kv,
        g=g,
        do=do,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dq = chunk_mesa_cg_bwd(
        dq=dq,
        k=k,
        h=h_kk,
        g_local_cumsum=g,
        beta=beta,
        lamb=lamb,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
        max_CG_iteration=max_CG_iteration,
        output_dtype=torch.float16,
    )
    dh_kk, dh0_kk = chunk_bwd_dh(
        q=dq,
        k=k,
        v=k,
        g=g,
        gk=None,
        gv=None,
        do=q_star,
        h0=h_kk_init,
        dht=-dh_kk_final if dh_kk_final is not None else None,
        states_in_fp32=False,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
        scale=1,
    )
    dk, dg2, dlamb, dbeta = chunk_mesa_net_h_kk_bwd_intra_fn(
        k=k,
        g=g,
        beta=beta,
        h=h_kk,
        dh=dh_kk,
        dk_beta=dk_beta,
        q_star=q_star,
        dq=dq,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dg.add_(dg2)
    dg = chunk_local_cumsum(dg, chunk_size=chunk_size, reverse=True, cu_seqlens=cu_seqlens).to(g)
    return dq, dk, dv, dg, dbeta, dlamb, -dh0_kk if dh0_kk is not None else None, dh0_kv if dh0_kv is not None else None


class ChunkMesaNetFunction(torch.autograd.Function):
    @staticmethod
    @input_guard
    @autocast_custom_fwd
    def forward(
        ctx,
        q,
        k,
        v,
        g,
        beta,
        lamb,
        cu_seqlens,
        max_CG_iteration,
        h_kk_init,
        h_kv_init,
        output_final_state,
        use_qk_l2norm_in_kernel,
    ):
        chunk_size = 64

        if use_qk_l2norm_in_kernel:
            q, q_rstd = l2norm_fwd(q, output_dtype=torch.float16)
            k, k_rstd = l2norm_fwd(k, output_dtype=torch.float16)
        else:
            q_rstd, k_rstd = None, None
            q = q.to(torch.float16)
            k = k.to(torch.float16)

        g_cumsum, q_star, o, (h_kk_final, h_kv_final) = chunk_fwd_mesa_net_fwd(
            q=q,
            k=k,
            v=v,
            g=g,
            beta=beta,
            lamb=lamb,
            cu_seqlens=cu_seqlens,
            max_CG_iteration=max_CG_iteration,
            chunk_size=chunk_size,
            h_kk_init=h_kk_init,
            h_kv_init=h_kv_init,
            output_final_state=output_final_state,
        )
        ctx.max_CG_iteration = max_CG_iteration
        ctx.chunk_size = chunk_size
        ctx.cu_seqlens = cu_seqlens
        ctx.use_qk_l2norm_in_kernel = use_qk_l2norm_in_kernel
        ctx.save_for_backward(q, q_rstd, k, k_rstd, v, g_cumsum, beta, lamb, h_kk_init, h_kv_init, q_star, o)
        return o, h_kk_final, h_kv_final

    @staticmethod
    @input_guard
    @autocast_custom_bwd
    def backward(ctx, do, dh_kk_final=None, dh_kv_final=None):
        q, q_rstd, k, k_rstd, v, g, beta, lamb, h_kk_init, h_kv_init, q_star, o = ctx.saved_tensors

        max_CG_iteration = ctx.max_CG_iteration
        chunk_size = ctx.chunk_size
        cu_seqlens = ctx.cu_seqlens
        dq, dk, dv, dg, dbeta, dlamb, dh0_kk, dh0_kv = chunk_fwd_mesa_net_bwd(
            q=q, k=k, v=v, g=g, beta=beta, lamb=lamb, q_star=q_star, do=do,
            cu_seqlens=cu_seqlens, max_CG_iteration=max_CG_iteration, chunk_size=chunk_size,
            h_kk_init=h_kk_init, h_kv_init=h_kv_init, dh_kv_final=dh_kv_final, dh_kk_final=dh_kk_final,
        )
        if ctx.use_qk_l2norm_in_kernel:
            dq = l2norm_bwd(q, q_rstd, dq)
            dk = l2norm_bwd(k, k_rstd, dk)
        return dq, dk, dv.to(v), dg.to(g), dbeta.to(beta), dlamb.to(lamb), None, None, dh0_kk, dh0_kv, None, None


@torch.compiler.disable
def chunk_mesa_net(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    g: torch.Tensor,
    beta: torch.Tensor,
    lamb: torch.Tensor,
    h_kk_init: torch.Tensor | None = None,
    h_kv_init: torch.Tensor | None = None,
    output_final_state: bool = False,
    max_CG_iteration: int = 30,
    use_qk_l2norm_in_kernel: bool = False,
    cu_seqlens: torch.LongTensor | None = None,
):
    r"""
    Args:
        q (torch.Tensor):
            queries of shape `[B, T, H, K]`
        k (torch.Tensor):
            keys of shape `[B, T, H, K]`. Should be l2-normalized before passing in.
        v (torch.Tensor):
            values of shape `[B, T, H, V]`.
        g (torch.Tensor):
            decay factors of shape `[B, T, H]`. Note that `g` should be in log space, that is, `g = log(decay_factor) < 0`.
            Recommended input dtype: `torch.float32`.
        beta (torch.Tensor):
            betas of shape `[B, T, H]`. Recommended input dtype: `torch.float32`.
        lamb (torch.Tensor):
            lambdas of shape `[B, T, H]`. Recommended input dtype: `torch.float32`.
        h_kk_init (Optional[torch.Tensor]):
            Initial state of shape `[N, H, K, V]` for `N` input sequences.
            For equal-length input sequences, `N` equals the batch size `B`.
            Default: `None`.
        h_kv_init (Optional[torch.Tensor]):
            Initial state of shape `[N, H, K, V]` for `N` input sequences.
            For equal-length input sequences, `N` equals the batch size `B`.
            Default: `None`.
        max_CG_iteration (int):
            Maximum number of conjugate gradient iterations for solving the linear system. Default: `30`.
        output_final_state (Optional[bool]):
            Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
        use_qk_l2norm_in_kernel (bool):
            Do l2 normalization on Q and K in the kernel for saving GPU memory. Default: `False`.
        cu_seqlens (torch.LongTensor):
            Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
            consistent with the FlashAttention API.

    Returns:
        o (torch.Tensor):
            Outputs of shape `[B, T, H, V]`.
        (final_states_kk, final_states_kv) (Tuple[torch.Tensor, torch.Tensor]):
            Final states of shape `[N, H, K, K]` and `[N, H, K, V]` if `output_final_state=True` else `(None, None)`.
            Recall that MesaNet has two states, `h_kk` and `h_kv`!

    Examples::
        >>> import torch
        >>> import torch.nn.functional as F
        >>> from einops import rearrange
        >>> from fla.ops.mesa_net import chunk_mesa_net
        # inputs with equal lengths
        >>> B, T, H, K, V = 4, 2048, 16, 128, 128
        >>> q = torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda')
        >>> k = torch.randn(B, T, H, K, dtype=torch.bfloat16, device='cuda')
        >>> v = torch.randn(B, T, H, V, dtype=torch.bfloat16, device='cuda')
        >>> g = F.logsigmoid(torch.randn(B, T, H, dtype=torch.float32, device='cuda'))
        >>> beta = torch.rand(B, T, H, dtype=torch.float32, device='cuda').sigmoid()
        # lower bound is 0.25 for numerical stability
        >>> lamb = F.softplus(torch.rand(H, K, dtype=torch.float32, device='cuda')) + 0.25
        >>> init_state_kk = torch.randn(B, H, K, V, dtype=torch.float32, device='cuda')
        >>> init_state_kv = torch.randn(B, H, K, V, dtype=torch.float32, device='cuda')
        >>> o, (final_state_kk, final_state_kv) = chunk_mesa_net(
            q, k, v, beta, lamb,
            h_kk_init=init_state_kk,
            h_kv_init=init_state_kv,
            max_CG_iteration=30,
            output_final_state=True
        )
        # for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
        >>> q, k, v, beta = map(lambda x: rearrange(x, 'b t ... -> 1 (b t) ...'), (q, k, v, beta))
        # for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
        >>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
        >>> o_var, (final_state_kk_var, final_state_kv_var) = chunk_mesa_net(
            q, k, v, beta, lamb,
            h_kk_init=init_state_kk,
            h_kv_init=init_state_kv,
            max_CG_iteration=30,
            output_final_state=True,
            cu_seqlens=cu_seqlens
        )
    """
    B, T, H, K = q.shape
    assert k.shape == (B, T, H, K), "k must be of shape (batch size, seq len, num head, head dim)."
    assert v.shape == (B, T, H, K), "v must be of shape (batch size, seq len, num head, head dim)."
    assert g.shape == (B, T, H), "g must be of shape (batch size, seq len, num head)."
    assert beta.shape == (B, T, H), "beta must be of shape (batch size, seq len, num head)."
    assert lamb.shape == (H, K), "lamb must be of shape (num head, key dim)."

    if h_kv_init is not None:
        assert h_kv_init.dtype == torch.float32, "h_kv_init must be in float32."
        if cu_seqlens is None:
            assert h_kv_init.shape == (B, H, K, K), "h_kv_init must be of shape (batch size, num head, head dim, head dim)."
    if h_kk_init is not None:
        assert h_kk_init.dtype == torch.float32, "h_kk_init must be in float32."
        if cu_seqlens is None:
            assert h_kk_init.shape == (B, H, K, K), "h_kk_init must be of shape (batch size, num head, head dim, head dim)."

    if cu_seqlens is not None:
        if q.shape[0] != 1:
            raise ValueError(
                f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
                f"Please flatten variable-length inputs before processing.",
            )
        if h_kk_init is not None and h_kk_init.shape[0] != len(cu_seqlens) - 1:
            raise ValueError(
                f"The number of initial states is expected to be equal to the number of input sequences, "
                f"i.e., {len(cu_seqlens) - 1} rather than {h_kk_init.shape[0]}.",
            )
        if h_kv_init is not None and h_kv_init.shape[0] != len(cu_seqlens) - 1:
            raise ValueError(
                f"The number of initial states is expected to be equal to the number of input sequences, "
                f"i.e., {len(cu_seqlens) - 1} rather than {h_kv_init.shape[0]}.",
            )
    o, final_state_kk, final_state_kv = ChunkMesaNetFunction.apply(
        q,
        k,
        v,
        g,
        beta,
        lamb,
        cu_seqlens,
        max_CG_iteration,
        h_kk_init,
        h_kv_init,
        output_final_state,
        use_qk_l2norm_in_kernel,
    )
    return o, final_state_kk, final_state_kv