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
 
 
 
 
 
 
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""GLA / RetNet decoder layer.

Pre-norm residual:
  attn_norm -> GatedLinearAttention -> residual
  mlp_norm  -> GLAMLP -> residual

Forward signature mirrors FLA's ``GLABlock.forward`` (returns a tuple of
``(hidden_states, attentions, past_key_values)``) so that the same L3
block backs both GLA and RetNet — RetNet just uses ``decay_mode="fixed_per_head"``
and ``use_rotary=True`` in the attention layer.
"""

from __future__ import annotations

import torch
import torch.nn as nn
import triton
import triton.language as tl

from ..L1.rms_norm import RMSNorm
from ..L1 import chunk_gla as _chunk_gla
from ..L2 import gla_attention as _gla_attention
from ..L2.gla_attention import GatedLinearAttention
from ..L2.gla_mlp import GLAMLP


@triton.jit
def _accurate_rms_silu_gate(
    x,
    gate,
    weight,
    out,
    n_rows,
    N: tl.constexpr,
    eps: tl.constexpr,
    BLOCK_M: tl.constexpr,
    BLOCK_N: tl.constexpr,
):
    rows = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M)
    cols = tl.arange(0, BLOCK_N)
    offsets = rows[:, None] * N + cols[None, :]
    mask = (rows[:, None] < n_rows) & (cols[None, :] < N)

    values = tl.load(x + offsets, mask=mask, other=0.0).to(tl.float32)
    variance = tl.sum(values * values, axis=1) / N
    inv_rms = tl.rsqrt(variance + eps)
    scales = tl.load(
        weight + cols[None, :],
        mask=cols[None, :] < N,
        other=0.0,
    ).to(tl.float32)
    normalized = (values * inv_rms[:, None] * scales).to(tl.bfloat16)

    gates = tl.load(gate + offsets, mask=mask, other=0.0).to(tl.float32)
    activated = (gates * tl.sigmoid(gates)).to(tl.bfloat16)
    tl.store(out + offsets, normalized * activated, mask=mask)


_gla_attention._rms_silu_gate = _accurate_rms_silu_gate


@triton.jit
def _accurate_log_sigmoid_kernel(
    x,
    out,
    n_elements: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
):
    offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
    mask = offsets < n_elements
    values = tl.load(x + offsets, mask=mask, other=0.0).to(tl.float32)
    result = tl.minimum(values, 0.0) - tl.log(1.0 + tl.exp(-tl.abs(values)))
    tl.store(out + offsets, result, mask=mask)


class _AccurateLogSigmoid(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        out = torch.empty_like(x)
        n_elements = x.numel()
        block_size = 2048 if n_elements <= 2048 else 4096
        _accurate_log_sigmoid_kernel[(triton.cdiv(n_elements, block_size),)](
            x,
            out,
            n_elements,
            BLOCK_SIZE=block_size,
            num_warps=8,
        )
        return out


@triton.jit
def _dense_states_no_final(
    k,
    v,
    gc,
    states,
    T: tl.constexpr,
    H: tl.constexpr,
    K: tl.constexpr,
    V: tl.constexpr,
    NT: tl.constexpr,
    BK: tl.constexpr,
    BV: tl.constexpr,
):
    i_k = tl.program_id(0)
    i_v = tl.program_id(1)
    i_bh = tl.program_id(2)
    i_b, i_h = i_bh // H, i_bh % H
    o_k = i_k * BK + tl.arange(0, BK)
    o_v = i_v * BV + tl.arange(0, BV)
    mask_kv = (o_k[:, None] < K) & (o_v[None, :] < V)
    state = tl.zeros((BK, BV), tl.float32)

    for chunk in range(NT):
        state_ptrs = (
            states
            + ((i_b * NT + chunk) * H + i_h) * K * V
            + o_k[:, None] * V
            + o_v[None, :]
        )
        tl.store(state_ptrs, state.to(tl.bfloat16), mask=mask_kv)
        tokens = chunk * 64 + tl.arange(0, 64)
        mask_kt = (o_k[:, None] < K) & (tokens[None, :] < T)
        mask_tv = (tokens[:, None] < T) & (o_v[None, :] < V)
        last = tl.minimum((chunk + 1) * 64, T) - 1
        base_k = i_b * T * H * K + i_h * K
        base_v = i_b * T * H * V + i_h * V
        last_gate = tl.load(
            gc + base_k + last * H * K + o_k,
            mask=o_k < K,
            other=0.0,
        )
        gates = tl.load(
            gc + base_k + tokens[None, :] * H * K + o_k[:, None],
            mask=mask_kt,
            other=0.0,
        )
        keys = tl.load(
            k + base_k + tokens[None, :] * H * K + o_k[:, None],
            mask=mask_kt,
            other=0.0,
        )
        values = tl.load(
            v + base_v + tokens[:, None] * H * V + o_v[None, :],
            mask=mask_tv,
            other=0.0,
        )
        state *= tl.exp2(last_gate)[:, None]
        gated_keys = (
            keys * tl.exp2(last_gate[:, None] - gates)
        ).to(tl.bfloat16)
        state += tl.dot(gated_keys, values)


@triton.jit
def _dense_score_offdiagonal(
    q,
    k,
    gc,
    scores,
    T: tl.constexpr,
    H: tl.constexpr,
    K: tl.constexpr,
    BC: tl.constexpr,
    BK: tl.constexpr,
):
    i_t = tl.program_id(0)
    i_pair = tl.program_id(1)
    i_bh = tl.program_id(2)
    i_b, i_h = i_bh // H, i_bh % H
    i_i, i_j = i_pair + 1, i_pair
    o_i = tl.arange(0, BC)
    o_j = tl.arange(0, BC)
    t_i = i_t * 64 + i_i * BC + o_i
    t_j = i_t * 64 + i_j * BC + o_j
    score_ptrs = (
        scores
        + (i_b * T + t_i[:, None]) * H * 64
        + i_h * 64
        + i_j * BC
        + o_j[None, :]
    )
    valid = (t_i[:, None] < T) & (t_j[None, :] < T)

    values = tl.zeros((BC, BC), tl.float32)
    base = i_b * T * H * K + i_h * K
    for block in range(tl.cdiv(K, BK)):
        o_k = block * BK + tl.arange(0, BK)
        mask_i = (t_i[:, None] < T) & (o_k[None, :] < K)
        mask_j = (o_k[:, None] < K) & (t_j[None, :] < T)
        mask_k = o_k < K
        anchor = tl.load(
            gc + base + (i_t * 64 + i_i * BC) * H * K + o_k,
            mask=mask_k,
            other=0.0,
        )
        queries = tl.load(
            q + base + t_i[:, None] * H * K + o_k[None, :],
            mask=mask_i,
            other=0.0,
        )
        query_gates = tl.load(
            gc + base + t_i[:, None] * H * K + o_k[None, :],
            mask=mask_i,
            other=0.0,
        )
        keys = tl.load(
            k + base + t_j[None, :] * H * K + o_k[:, None],
            mask=mask_j,
            other=0.0,
        )
        key_gates = tl.load(
            gc + base + t_j[None, :] * H * K + o_k[:, None],
            mask=mask_j,
            other=0.0,
        )
        gated_queries = (
            queries * tl.exp2(query_gates - anchor[None, :]) * 0.0625
        )
        gated_keys = keys * tl.exp2(anchor[:, None] - key_gates)
        values += tl.dot(gated_queries, gated_keys)

    tl.store(score_ptrs, values, mask=valid)


@triton.jit
def _dense_score_diagonal(
    q,
    k,
    gc,
    scores,
    T: tl.constexpr,
    H: tl.constexpr,
    K: tl.constexpr,
    BC: tl.constexpr,
    BK: tl.constexpr,
):
    i_t = tl.program_id(0)
    i_c = tl.program_id(1)
    i_bh = tl.program_id(2)
    i_b, i_h = i_bh // H, i_bh % H
    o_i = tl.arange(0, BC)
    o_k = tl.arange(0, BK)
    t_i = i_t * 64 + i_c * BC + o_i
    mask_i = (t_i[:, None] < T) & (o_k[None, :] < K)
    base = i_b * T * H * K + i_h * K
    queries = tl.load(
        q + base + t_i[:, None] * H * K + o_k[None, :],
        mask=mask_i,
        other=0.0,
    )
    query_gates = tl.load(
        gc + base + t_i[:, None] * H * K + o_k[None, :],
        mask=mask_i,
        other=0.0,
    )

    for j in range(BC):
        t_j = i_t * 64 + i_c * BC + j
        mask_j = (o_k < K) & (t_j < T)
        keys = tl.load(
            k + base + t_j * H * K + o_k,
            mask=mask_j,
            other=0.0,
        ).to(tl.float32)
        key_gates = tl.load(
            gc + base + t_j * H * K + o_k,
            mask=mask_j,
            other=0.0,
        ).to(tl.float32)
        values = tl.sum(
            queries
            * keys[None, :]
            * tl.exp2(query_gates - key_gates[None, :]),
            axis=1,
        ) * 0.0625
        score_ptrs = (
            scores
            + (i_b * T + t_i) * H * 64
            + i_h * 64
            + i_c * BC
            + j
        )
        tl.store(
            score_ptrs,
            tl.where(o_i >= j, values, 0.0),
            mask=t_i < T,
        )


class _AccurateChunkGLA(nn.Module):
    def __init__(self, fallback: nn.Module):
        super().__init__()
        self.fallback = fallback

    def forward(
        self,
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
        scale: float | None = None,
        initial_state: torch.Tensor | None = None,
        output_final_state: bool = False,
        cu_seqlens: torch.Tensor | None = None,
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        total_t, heads, key_dim, value_dim = (
            q.shape[1],
            q.shape[2],
            q.shape[3],
            v.shape[3],
        )
        if cu_seqlens is not None or initial_state is not None or total_t <= 65:
            return self.fallback(
                q,
                k,
                v,
                g,
                scale,
                initial_state,
                output_final_state,
                cu_seqlens,
            )

        batch = q.shape[0]
        chunks = triton.cdiv(total_t, 64)
        scanned_gates = torch.empty_like(g, dtype=torch.float32)
        states = torch.empty(
            (batch, chunks, heads, key_dim, value_dim),
            device=q.device,
            dtype=torch.bfloat16,
        )
        scores = torch.empty(
            (batch, total_t, heads, 64),
            device=q.device,
            dtype=torch.float32,
        )
        out = torch.empty_like(v)
        _chunk_gla._dense_gate_scan[
            (triton.cdiv(key_dim, 64), chunks, batch * heads)
        ](
            g,
            scanned_gates,
            total_t,
            heads,
            key_dim,
            BK=64,
            num_warps=2,
        )
        state_grid = (
            triton.cdiv(key_dim, 64),
            triton.cdiv(value_dim, 32),
            batch * heads,
        )
        if output_final_state:
            final_state = torch.empty(
                (batch, heads, key_dim, value_dim),
                device=q.device,
                dtype=torch.float32,
            )
            _chunk_gla._dense_states[state_grid](
                k,
                v,
                scanned_gates,
                states,
                final_state,
                total_t,
                heads,
                key_dim,
                value_dim,
                chunks,
                BK=64,
                BV=32,
                num_warps=2,
                num_stages=2,
            )
        else:
            final_state = None
            _dense_states_no_final[state_grid](
                k,
                v,
                scanned_gates,
                states,
                total_t,
                heads,
                key_dim,
                value_dim,
                chunks,
                BK=64,
                BV=32,
                num_warps=2,
                num_stages=2,
            )
        _chunk_gla._dense_scores[(chunks, batch * heads)](
            q,
            k,
            scanned_gates,
            scores,
            total_t,
            heads,
            key_dim,
            BK=32,
            num_warps=8,
            num_stages=2,
        )
        _dense_score_offdiagonal[(chunks, 1, batch * heads)](
            q,
            k,
            scanned_gates,
            scores,
            total_t,
            heads,
            key_dim,
            BC=16,
            BK=64,
            num_warps=4,
            num_stages=2,
        )
        _dense_score_diagonal[(chunks, 4, batch * heads)](
            q,
            k,
            scanned_gates,
            scores,
            total_t,
            heads,
            key_dim,
            BC=16,
            BK=256,
            num_warps=8,
        )
        _chunk_gla._dense_output[
            (triton.cdiv(value_dim, 128), chunks, batch * heads)
        ](
            q,
            v,
            scanned_gates,
            states,
            scores,
            out,
            total_t,
            heads,
            key_dim,
            value_dim,
            chunks,
            BK=64,
            BV=128,
            num_warps=8,
            num_stages=2,
        )
        return out, final_state if output_final_state else None


class GLADecoderLayer(nn.Module):
    def __init__(self, config, layer_idx: int):
        super().__init__()
        self.layer_idx = layer_idx
        self.attn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
        self.attn = GatedLinearAttention(
            hidden_size=config.hidden_size,
            num_heads=config.num_heads,
            expand_k=config.expand_k,
            expand_v=config.expand_v,
            decay_mode=getattr(config, "decay_mode", "learned_low_rank"),
            gate_low_rank_dim=getattr(config, "gate_low_rank_dim", 16),
            gate_logit_normalizer=getattr(config, "gate_logit_normalizer", 16),
            use_rotary=getattr(config, "use_rotary", False),
            rotary_base=getattr(config, "rotary_base", 10000.0),
            rotary_max_position=getattr(config, "max_position_embeddings", 8192),
            norm_eps=config.norm_eps,
        )
        if self.attn.decay_mode == "learned_low_rank":
            self.attn.log_sigmoid = _AccurateLogSigmoid()
            self.attn.chunk = _AccurateChunkGLA(self.attn.chunk)
        self.mlp_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
        self.mlp = GLAMLP(config.hidden_size, config.intermediate_size)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: torch.Tensor | None = None,
        past_key_values=None,
        use_cache: bool = False,
        **kwargs,
    ) -> tuple[torch.Tensor, None, object | None]:
        residual = hidden_states
        h = self.attn_norm(
            hidden_states.reshape(-1, hidden_states.size(-1))
        ).reshape_as(hidden_states)
        if (
            hidden_states.shape[0] == 1
            and kwargs.get("cu_seqlens") is not None
            and kwargs["cu_seqlens"].numel() == 2
        ):
            kwargs = dict(kwargs)
            kwargs.pop("cu_seqlens")

        h, attentions, past_key_values = self.attn(
            hidden_states=h,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            use_cache=use_cache and past_key_values is not None,
            **kwargs,
        )
        h, residual = self.mlp_norm(
            h.reshape(-1, h.size(-1)),
            residual.reshape(-1, residual.size(-1)),
        )
        h = h.reshape_as(hidden_states)
        residual = residual.reshape_as(hidden_states)
        hidden_states = residual.add_(self.mlp(h))
        return hidden_states, attentions, past_key_values