flashgdn 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flashgdn-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michelangelo Di Nicola / BranchingNLP
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: flashgdn
3
+ Version: 0.1.0
4
+ Summary: Gated DeltaNet written from scratch in C and CUDA: recurrent and chunked forms, forward and backward
5
+ Author: Michelangelo Di Nicola
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/BranchingNLP/FlashGDN
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: torch>=2.1
12
+ Requires-Dist: ninja
13
+ Dynamic: license-file
14
+
15
+ # FlashGDN
16
+
17
+ **Gated DeltaNet written from scratch** — first in plain C, then in CUDA, packaged as a PyTorch library.
18
+ Built for [Grace](https://huggingface.co/BranchingNLP), BranchingNLP's family of small hybrid language models.
19
+
20
+ ```python
21
+ from flashgdn import gdn_chunk, gdn_recurrent
22
+
23
+ # training: chunked form, fused CUDA kernels (forward + backward)
24
+ o, state = gdn_chunk(q, k, v, beta, g, initial_state=None, output_final_state=True)
25
+ o.sum().backward()
26
+
27
+ # inference / decoding: recurrent form, state kept in registers
28
+ o, state = gdn_recurrent(q, k, v, beta, g, initial_state=state, output_final_state=True)
29
+ ```
30
+
31
+ Shapes: `q, k: [B, T, H, K]` (L2-normalised), `v: [B, T, H, V]`, `beta, g: [B, T, H]`
32
+ (`beta ∈ (0, 1)`, `g ≤ 0` is the log-decay). Same convention as
33
+ [flash-linear-attention](https://github.com/fla-org/flash-linear-attention).
34
+
35
+ ## The gated delta rule
36
+
37
+ ```
38
+ S_t = α_t S_{t-1} + β_t k_t (v_t − α_t S_{t-1}ᵀ k_t)ᵀ α_t = e^{g_t}
39
+ o_t = scale · S_tᵀ q_t
40
+ ```
41
+
42
+ The chunked form (blocks of C = 64 tokens) turns this into dense matrix products inside each block,
43
+ plus a short sequential pass of the state between blocks:
44
+
45
+ ```
46
+ γ = cumsum(g) L_ij = e^{γ_i − γ_j} A = −(diag(β) k kᵀ) ⊙ L (strictly lower) T = (I − A)⁻¹
47
+ u = T diag(β) v w = T diag(β e^γ) k
48
+ v_new = u − w S o = (q ⊙ e^γ) S + ((q kᵀ) ⊙ L) v_new S ← e^{γ_last} S + (k ⊙ e^{γ_last − γ})ᵀ v_new
49
+ ```
50
+
51
+ ## What's inside
52
+
53
+ | file | what |
54
+ |---|---|
55
+ | `reference/flashgdn.c` | recurrent and chunked forms in plain C — they match to 4.5e-8 |
56
+ | `reference/flashgdn_bwd.c` | recurrent backward in C, checked with finite differences |
57
+ | `flashgdn/flashgdn_kernel.cuh` | recurrent inference kernel (one thread per state column, state in registers) |
58
+ | `flashgdn/flashgdn_opt.cuh` | recurrent training kernels: forward with checkpoints every 64 tokens + backward |
59
+ | `flashgdn/flashgdn_chunk.cuh` | chunked form: state-passing kernel (forward/backward), `cp.async` pipelined |
60
+ | `flashgdn/flashgdn_fused.cuh` | chunked form: all intra-chunk work fused (3 kernels forward, 6 backward), TF32 tensor cores |
61
+ | `flashgdn/chunk.py` | `gdn_chunk` + a PyTorch fallback for shapes the fused kernels don't cover |
62
+ | `tests/` | correctness against a naive PyTorch reference + benchmarks |
63
+
64
+ The backward of the fused chunked form (through the triangular inverse, the decays and the state pass)
65
+ is derived by hand; every kernel's math was first checked against autograd in float64 (error ~1e-15).
66
+
67
+ ## Speed
68
+
69
+ One GDN layer of Grace (batch 4 × 2048 tokens, 12 heads, K = 64, V = 128), forward + backward, RTX 3070:
70
+
71
+ | implementation | inputs | forward | forward + backward |
72
+ |---|---|---:|---:|
73
+ | **FlashGDN fused, `MODE="bf16"`** | bf16 | 1.4 ms | **4.8 ms** |
74
+ | fla `chunk_gated_delta_rule` (Triton) | bf16 | 1.0 ms | 3.6 ms |
75
+ | FlashGDN fused, `MODE="bf16"` | fp32 | 1.6 ms | 5.5 ms |
76
+ | FlashGDN fused, `MODE="tf32"` | fp32 | 2.0 ms | 8.2 ms |
77
+ | fla `chunk_gated_delta_rule` (Triton) | fp32 | 2.2 ms | 8.9 ms |
78
+ | FlashGDN fused, `MODE="fp32"` (exact) | fp32 | 2.8 ms | 10.6 ms |
79
+ | FlashGDN chunked, PyTorch + `torch.compile` + state kernel | fp32 | 4.5 ms | 13.4 ms |
80
+ | FlashGDN recurrent | fp32 | 2.6 ms | 44.9 ms |
81
+
82
+ Recurrent decoding: 8.7 µs per token per layer.
83
+
84
+ How it got there: hand-derived chunked backward → fused kernels → blocked triangular inverse →
85
+ bank-conflict-free shared memory (padded rows, warp-per-row reductions) → bf16 intermediates →
86
+ bf16 tensor cores via hand-written `mma.sync` fragments → register accumulators → bf16 operand tiles.
87
+
88
+ ## Install and test
89
+
90
+ ```bash
91
+ pip install -e . # or just put the repo on PYTHONPATH
92
+ python3 tests/test_flashgdn_chunk.py
93
+ python3 tests/test_flashgdn_bwd.py
94
+ python3 tests/test_flashgdn.py
95
+ ```
96
+
97
+ The CUDA code is compiled on first import with `torch.utils.cpp_extension` (needs `nvcc` and `ninja`)
98
+ and cached afterwards.
99
+
100
+ Options:
101
+ - `flashgdn.chunk.MODE` — what the fused kernels multiply with:
102
+ `"bf16"` (default) bf16 tensor cores via `mma.sync`, like fla; `"tf32"` TF32 tensor cores via `wmma`;
103
+ `"fp32"` no tensor cores and fp32 intermediates (slow, exact to ~1e-7, for checking).
104
+ With `"bf16"`/`"tf32"` the large intermediates (u, w, T, attn, per-chunk states) are stored in bf16;
105
+ all accumulation inside the kernels, and the recurrent state, stay in fp32.
106
+ - Inputs `q, k, v` can be fp32, bf16 or fp16: the kernels read them directly and `o, dq, dk, dv` come back in the same dtype.
107
+ - `FLASHGDN_FUSED=0` — use the PyTorch + state-kernel path instead of the fused kernels
108
+ - `FLASHGDN_COMPILE=0` — disable `torch.compile` on that path
109
+
110
+ ## Limits
111
+
112
+ - Fused chunked kernels: `K = 64`, `V` multiple of 32. Other shapes use the PyTorch path (`K ≤ 64`).
113
+ - Recurrent kernels: `K ≤ 128` (optimised path for `V ≤ 128`).
114
+ - Computation is in fp32 (inputs in bf16/fp16 are converted; the output keeps the input dtype).
115
+ - Tested on sm_86 (RTX 3070).
116
+
117
+ ## License
118
+
119
+ MIT
@@ -0,0 +1,105 @@
1
+ # FlashGDN
2
+
3
+ **Gated DeltaNet written from scratch** — first in plain C, then in CUDA, packaged as a PyTorch library.
4
+ Built for [Grace](https://huggingface.co/BranchingNLP), BranchingNLP's family of small hybrid language models.
5
+
6
+ ```python
7
+ from flashgdn import gdn_chunk, gdn_recurrent
8
+
9
+ # training: chunked form, fused CUDA kernels (forward + backward)
10
+ o, state = gdn_chunk(q, k, v, beta, g, initial_state=None, output_final_state=True)
11
+ o.sum().backward()
12
+
13
+ # inference / decoding: recurrent form, state kept in registers
14
+ o, state = gdn_recurrent(q, k, v, beta, g, initial_state=state, output_final_state=True)
15
+ ```
16
+
17
+ Shapes: `q, k: [B, T, H, K]` (L2-normalised), `v: [B, T, H, V]`, `beta, g: [B, T, H]`
18
+ (`beta ∈ (0, 1)`, `g ≤ 0` is the log-decay). Same convention as
19
+ [flash-linear-attention](https://github.com/fla-org/flash-linear-attention).
20
+
21
+ ## The gated delta rule
22
+
23
+ ```
24
+ S_t = α_t S_{t-1} + β_t k_t (v_t − α_t S_{t-1}ᵀ k_t)ᵀ α_t = e^{g_t}
25
+ o_t = scale · S_tᵀ q_t
26
+ ```
27
+
28
+ The chunked form (blocks of C = 64 tokens) turns this into dense matrix products inside each block,
29
+ plus a short sequential pass of the state between blocks:
30
+
31
+ ```
32
+ γ = cumsum(g) L_ij = e^{γ_i − γ_j} A = −(diag(β) k kᵀ) ⊙ L (strictly lower) T = (I − A)⁻¹
33
+ u = T diag(β) v w = T diag(β e^γ) k
34
+ v_new = u − w S o = (q ⊙ e^γ) S + ((q kᵀ) ⊙ L) v_new S ← e^{γ_last} S + (k ⊙ e^{γ_last − γ})ᵀ v_new
35
+ ```
36
+
37
+ ## What's inside
38
+
39
+ | file | what |
40
+ |---|---|
41
+ | `reference/flashgdn.c` | recurrent and chunked forms in plain C — they match to 4.5e-8 |
42
+ | `reference/flashgdn_bwd.c` | recurrent backward in C, checked with finite differences |
43
+ | `flashgdn/flashgdn_kernel.cuh` | recurrent inference kernel (one thread per state column, state in registers) |
44
+ | `flashgdn/flashgdn_opt.cuh` | recurrent training kernels: forward with checkpoints every 64 tokens + backward |
45
+ | `flashgdn/flashgdn_chunk.cuh` | chunked form: state-passing kernel (forward/backward), `cp.async` pipelined |
46
+ | `flashgdn/flashgdn_fused.cuh` | chunked form: all intra-chunk work fused (3 kernels forward, 6 backward), TF32 tensor cores |
47
+ | `flashgdn/chunk.py` | `gdn_chunk` + a PyTorch fallback for shapes the fused kernels don't cover |
48
+ | `tests/` | correctness against a naive PyTorch reference + benchmarks |
49
+
50
+ The backward of the fused chunked form (through the triangular inverse, the decays and the state pass)
51
+ is derived by hand; every kernel's math was first checked against autograd in float64 (error ~1e-15).
52
+
53
+ ## Speed
54
+
55
+ One GDN layer of Grace (batch 4 × 2048 tokens, 12 heads, K = 64, V = 128), forward + backward, RTX 3070:
56
+
57
+ | implementation | inputs | forward | forward + backward |
58
+ |---|---|---:|---:|
59
+ | **FlashGDN fused, `MODE="bf16"`** | bf16 | 1.4 ms | **4.8 ms** |
60
+ | fla `chunk_gated_delta_rule` (Triton) | bf16 | 1.0 ms | 3.6 ms |
61
+ | FlashGDN fused, `MODE="bf16"` | fp32 | 1.6 ms | 5.5 ms |
62
+ | FlashGDN fused, `MODE="tf32"` | fp32 | 2.0 ms | 8.2 ms |
63
+ | fla `chunk_gated_delta_rule` (Triton) | fp32 | 2.2 ms | 8.9 ms |
64
+ | FlashGDN fused, `MODE="fp32"` (exact) | fp32 | 2.8 ms | 10.6 ms |
65
+ | FlashGDN chunked, PyTorch + `torch.compile` + state kernel | fp32 | 4.5 ms | 13.4 ms |
66
+ | FlashGDN recurrent | fp32 | 2.6 ms | 44.9 ms |
67
+
68
+ Recurrent decoding: 8.7 µs per token per layer.
69
+
70
+ How it got there: hand-derived chunked backward → fused kernels → blocked triangular inverse →
71
+ bank-conflict-free shared memory (padded rows, warp-per-row reductions) → bf16 intermediates →
72
+ bf16 tensor cores via hand-written `mma.sync` fragments → register accumulators → bf16 operand tiles.
73
+
74
+ ## Install and test
75
+
76
+ ```bash
77
+ pip install -e . # or just put the repo on PYTHONPATH
78
+ python3 tests/test_flashgdn_chunk.py
79
+ python3 tests/test_flashgdn_bwd.py
80
+ python3 tests/test_flashgdn.py
81
+ ```
82
+
83
+ The CUDA code is compiled on first import with `torch.utils.cpp_extension` (needs `nvcc` and `ninja`)
84
+ and cached afterwards.
85
+
86
+ Options:
87
+ - `flashgdn.chunk.MODE` — what the fused kernels multiply with:
88
+ `"bf16"` (default) bf16 tensor cores via `mma.sync`, like fla; `"tf32"` TF32 tensor cores via `wmma`;
89
+ `"fp32"` no tensor cores and fp32 intermediates (slow, exact to ~1e-7, for checking).
90
+ With `"bf16"`/`"tf32"` the large intermediates (u, w, T, attn, per-chunk states) are stored in bf16;
91
+ all accumulation inside the kernels, and the recurrent state, stay in fp32.
92
+ - Inputs `q, k, v` can be fp32, bf16 or fp16: the kernels read them directly and `o, dq, dk, dv` come back in the same dtype.
93
+ - `FLASHGDN_FUSED=0` — use the PyTorch + state-kernel path instead of the fused kernels
94
+ - `FLASHGDN_COMPILE=0` — disable `torch.compile` on that path
95
+
96
+ ## Limits
97
+
98
+ - Fused chunked kernels: `K = 64`, `V` multiple of 32. Other shapes use the PyTorch path (`K ≤ 64`).
99
+ - Recurrent kernels: `K ≤ 128` (optimised path for `V ≤ 128`).
100
+ - Computation is in fp32 (inputs in bf16/fp16 are converted; the output keeps the input dtype).
101
+ - Tested on sm_86 (RTX 3070).
102
+
103
+ ## License
104
+
105
+ MIT
@@ -0,0 +1,70 @@
1
+ """
2
+ flashgdn — Gated DeltaNet in CUDA, scritto da zero. Forma ricorrente: forward (inferenza) e backward (training).
3
+
4
+ from flashgdn import gdn_recurrent
5
+ o, state = gdn_recurrent(q, k, v, beta, g, initial_state=None, output_final_state=True)
6
+ o.sum().backward() # funziona: i gradienti arrivano a q, k, v, beta, g (e allo stato iniziale)
7
+
8
+ q, k: [B, T, H, K] (già normalizzate L2, come nel modello) v: [B, T, H, V]
9
+ beta: [B, T, H] in (0, 1) g: [B, T, H] log del decadimento (≤ 0)
10
+ ritorna o: [B, T, H, V] (stesso dtype di v) e lo stato finale [B, H, K, V] in float32 (o None)
11
+
12
+ Se nessun input richiede gradienti si usa il kernel di sola inferenza (più leggero); altrimenti quello di training,
13
+ che salva lo stato ogni 64 token e nel backward ricalcola il resto.
14
+ La prima importazione compila il codice CUDA (~1-2 minuti); poi resta in cache.
15
+ """
16
+ import os
17
+
18
+ import torch
19
+
20
+ _ext = None
21
+
22
+
23
+ def _load():
24
+ global _ext
25
+ if _ext is None:
26
+ import glob
27
+ import hashlib
28
+ from torch.utils.cpp_extension import load
29
+ here = os.path.dirname(os.path.abspath(__file__))
30
+ # torch ricompila solo se cambia flashgdn_ext.cu, non gli header inclusi: il nome contiene l'hash di TUTTI
31
+ # i sorgenti, così ogni modifica a un .cuh produce un'estensione nuova
32
+ h = hashlib.sha1()
33
+ for f in sorted(glob.glob(os.path.join(here, "*.cu")) + glob.glob(os.path.join(here, "*.cuh"))):
34
+ h.update(open(f, "rb").read())
35
+ _ext = load(name=f"flashgdn_ext_{h.hexdigest()[:10]}", sources=[os.path.join(here, "flashgdn_ext.cu")],
36
+ extra_cuda_cflags=["-O3", "--use_fast_math"], verbose=False)
37
+ return _ext
38
+
39
+
40
+ class _GDNRecurrent(torch.autograd.Function):
41
+ @staticmethod
42
+ def forward(ctx, q, k, v, beta, g, s0, scale):
43
+ o, s_out, ckpt = _load().recurrent_fwd_train(q, k, v, beta, g, s0, scale)
44
+ ctx.save_for_backward(q, k, v, beta, g, ckpt)
45
+ ctx.scale, ctx.has_s0 = scale, s0 is not None
46
+ return o, s_out
47
+
48
+ @staticmethod
49
+ def backward(ctx, do, ds_out):
50
+ q, k, v, beta, g, ckpt = ctx.saved_tensors
51
+ dq, dk, dv, dbeta, dg, ds0 = _load().recurrent_bwd(
52
+ q, k, v, beta, g, ckpt, do.float().contiguous(),
53
+ None if ds_out is None else ds_out.float().contiguous(), ctx.scale)
54
+ return dq, dk, dv, dbeta, dg, (ds0 if ctx.has_s0 else None), None
55
+
56
+
57
+ def gdn_recurrent(q, k, v, beta, g, scale=None, initial_state=None, output_final_state=False):
58
+ dtype = v.dtype
59
+ f = lambda x: x.float().contiguous()
60
+ scale = q.shape[-1] ** -0.5 if scale is None else float(scale)
61
+ s0 = f(initial_state) if initial_state is not None else None
62
+ ins = [q, k, v, beta, g] + ([initial_state] if initial_state is not None else [])
63
+ if torch.is_grad_enabled() and any(x.requires_grad for x in ins):
64
+ o, s = _GDNRecurrent.apply(f(q), f(k), f(v), f(beta), f(g), s0, scale)
65
+ else:
66
+ o, s = _load().recurrent_fwd(f(q), f(k), f(v), f(beta), f(g), s0, scale, bool(output_final_state))
67
+ return o.to(dtype), (s if output_final_state else None)
68
+
69
+
70
+ from .chunk import gdn_chunk # noqa: E402 forma a blocchi (training veloce)
@@ -0,0 +1,143 @@
1
+ """
2
+ chunk.py — Gated DeltaNet in forma A BLOCCHI (per il training veloce): PyTorch + un kernel CUDA nostro.
3
+
4
+ - le parti parallele (dentro ogni blocco di 64 token: γ, L, A, T = (I − A)⁻¹, u, w, attn, output)
5
+ sono moltiplicazioni tra matrici su tutti i blocchi insieme (_prep e _post);
6
+ - il passaggio di stato da un blocco al successivo (l'unica parte in sequenza) è il kernel statepass,
7
+ con il suo backward. L'autograd di PyTorch fa il resto.
8
+
9
+ _prep e _post passano da torch.compile (le decine di piccole operazioni elemento per elemento diventano
10
+ pochi kernel fusi). FLASHGDN_COMPILE=0 per disattivarlo (es. per fare debug).
11
+ Con K = 64 e V multiplo di 32 (Grace) si usa la versione FUSA (flashgdn_fused.cuh): anche le parti parallele
12
+ sono kernel nostri, con i tensor core (MODE = "bf16" | "tf32" | "fp32"). FLASHGDN_FUSED=0 per disattivarla.
13
+ Limiti del kernel di stato: K ≤ 64.
14
+ """
15
+ import os
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+
20
+ C = 64
21
+ _TI = (torch.float32, torch.bfloat16, torch.float16)
22
+ MODE = "bf16" # kernel fusi: "bf16" tensor core bf16 (come fla) | "tf32" tensor core TF32 | "fp32" esatto, per i controlli
23
+ _MODES = {"fp32": 0, "tf32": 1, "bf16": 2}
24
+
25
+
26
+ class _StatePass(torch.autograd.Function):
27
+ @staticmethod
28
+ def forward(ctx, u, w, kd, last, s0):
29
+ from . import _load
30
+ vnew, sst, sfin = _load().statepass_forward(u, w, kd, last, s0)
31
+ ctx.save_for_backward(w, kd, last, vnew, sst)
32
+ ctx.has_s0 = s0 is not None
33
+ return vnew, sst, sfin
34
+
35
+ @staticmethod
36
+ def backward(ctx, dvnew, dsst, dsfin):
37
+ from . import _load
38
+ w, kd, last, vnew, sst = ctx.saved_tensors
39
+ f = lambda x: None if x is None else x.float().contiguous()
40
+ dvnew = torch.zeros_like(vnew) if dvnew is None else f(dvnew)
41
+ dvt, dsnext, ds0 = _load().statepass_backward(w, kd, last, dvnew, f(dsst), f(dsfin))
42
+ # v_new = u − w·S → du = dvt, dw = −dvt · Sᵀ
43
+ # S' = last·S + kdᵀ·v_new → dkd = v_new · dS'ᵀ, dlast = Σ dS' ⊙ S
44
+ du = dvt
45
+ dw = -(dvt @ sst.transpose(-1, -2))
46
+ dkd = vnew @ dsnext.transpose(-1, -2)
47
+ dlast = (dsnext * sst).sum((-1, -2))
48
+ return du, dw, dkd, dlast, (ds0 if ctx.has_s0 else None)
49
+
50
+
51
+ class _Fused(torch.autograd.Function):
52
+ @staticmethod
53
+ def forward(ctx, q, k, v, beta, g, s0, scale, mode):
54
+ from . import _load
55
+ o, sfin, Tm, gcs, attn, sst, vnew, w, kd, last = _load().fused_forward(q, k, v, beta, g, s0, scale, mode)
56
+ ctx.save_for_backward(q, k, v, beta, Tm, gcs, attn, sst, vnew, w, kd, last)
57
+ ctx.scale, ctx.mode, ctx.has_s0 = scale, mode, s0 is not None
58
+ return o, sfin
59
+
60
+ @staticmethod
61
+ def backward(ctx, dO, dsfin):
62
+ from . import _load
63
+ saved = ctx.saved_tensors
64
+ f = lambda x: None if x is None else x.float().contiguous()
65
+ dO = torch.zeros_like(saved[2]) if dO is None else dO.to(saved[0].dtype).contiguous()
66
+ dq, dk, dv, db, dg, ds0 = _load().fused_backward(*saved, dO, f(dsfin), ctx.scale, ctx.mode)
67
+ return dq, dk, dv, db, dg, (ds0 if ctx.has_s0 else None), None, None
68
+
69
+
70
+ def _prep(q, k, v, beta, g, scale: float):
71
+ """[B,T,H,·] → tutto quello che serve al passaggio di stato e agli output, per blocchi [B·H, N, C, ·]."""
72
+ B, T, H, K = q.shape
73
+ V = v.shape[-1]
74
+ q, k, v, g, beta = (x.transpose(1, 2).float() for x in (q, k, v, g, beta)) # [B, H, T, ...]
75
+ pad = (C - T % C) % C
76
+ if pad: # token finti: non cambiano niente
77
+ q, k, v = (F.pad(x, (0, 0, 0, pad)) for x in (q, k, v))
78
+ g, beta = F.pad(g, (0, pad)), F.pad(beta, (0, pad))
79
+ N = q.shape[2] // C
80
+ q, k, v = (x.reshape(B * H, N, C, -1) for x in (q, k, v))
81
+ g, beta = g.reshape(B * H, N, C), beta.reshape(B * H, N, C)
82
+
83
+ q = q * scale
84
+ gc = g.cumsum(-1) # γ
85
+ tril = torch.ones(C, C, dtype=torch.bool, device=q.device).tril()
86
+ diff = gc[..., :, None] - gc[..., None, :]
87
+ L = torch.where(tril, diff, torch.full_like(diff, -float("inf"))).exp() # e^(γi−γj) sotto la diagonale
88
+ k_beta = k * beta[..., None]
89
+ A = (-(k_beta @ k.transpose(-1, -2)) * L).masked_fill(~tril.tril(-1), 0.0) # strettamente inferiore
90
+ eye = torch.eye(C, device=q.device, dtype=q.dtype)
91
+ Tm = torch.linalg.solve_triangular(eye - A, eye.expand_as(A), upper=False, unitriangular=True)
92
+ eg = gc.exp()[..., None]
93
+ u = Tm @ (v * beta[..., None])
94
+ w = Tm @ (k_beta * eg)
95
+ attn = (q @ k.transpose(-1, -2)) * L
96
+ q_dec = q * eg
97
+ k_dec = k * (gc[..., -1:] - gc).exp()[..., None]
98
+ last = gc[..., -1].exp()
99
+ return u.contiguous(), w.contiguous(), k_dec.contiguous(), last.contiguous(), q_dec, attn
100
+
101
+
102
+ def _post(q_dec, sst, attn, vnew, B: int, T: int, H: int):
103
+ o = q_dec @ sst + attn @ vnew # [B·H, N, C, V]
104
+ V = o.shape[-1]
105
+ return o.reshape(B, H, -1, V)[:, :, :T].transpose(1, 2)
106
+
107
+
108
+ _compiled = {}
109
+
110
+
111
+ def _fn(name):
112
+ f = {"prep": _prep, "post": _post}[name]
113
+ if os.environ.get("FLASHGDN_COMPILE", "1") == "0":
114
+ return f
115
+ if name not in _compiled:
116
+ try:
117
+ _compiled[name] = torch.compile(f, dynamic=False)
118
+ except Exception:
119
+ _compiled[name] = f
120
+ return _compiled[name]
121
+
122
+
123
+ def gdn_chunk(q, k, v, beta, g, scale=None, initial_state=None, output_final_state=False):
124
+ """Stessa interfaccia di gdn_recurrent: q, k [B,T,H,K], v [B,T,H,V], beta, g [B,T,H]."""
125
+ B, T, H, K = q.shape
126
+ V = v.shape[-1]
127
+ dtype = v.dtype
128
+ scale = K ** -0.5 if scale is None else float(scale)
129
+
130
+ if K == 64 and V % 32 == 0 and os.environ.get("FLASHGDN_FUSED", "1") != "0":
131
+ # q, k, v restano nel loro tipo (bf16/fp16 letti direttamente dai kernel, convertiti in memoria condivisa)
132
+ ti = q.dtype if (q.dtype in _TI and k.dtype == q.dtype and v.dtype == q.dtype) else torch.float32
133
+ t = lambda x: x.to(ti).contiguous()
134
+ f = lambda x: x.float().contiguous()
135
+ s0 = None if initial_state is None else f(initial_state)
136
+ o, sfin = _Fused.apply(t(q), t(k), t(v), f(beta), f(g), s0, scale, _MODES[MODE])
137
+ return o.to(dtype), (sfin if output_final_state else None)
138
+
139
+ u, w, k_dec, last, q_dec, attn = _fn("prep")(q, k, v, beta, g, scale)
140
+ s0 = None if initial_state is None else initial_state.float().reshape(B * H, K, V).contiguous()
141
+ vnew, sst, sfin = _StatePass.apply(u, w, k_dec, last, s0)
142
+ o = _fn("post")(q_dec, sst, attn, vnew, B, T, H)
143
+ return o.to(dtype), (sfin.view(B, H, K, V) if output_final_state else None)