Metadata-Version: 2.4
Name: flashgdn
Version: 0.2.1
Summary: Gated DeltaNet written from scratch in C and CUDA: recurrent and chunked forms, forward and backward
Author: Michelangelo Di Nicola
License: MIT
Project-URL: Homepage, https://github.com/BranchingNLP/FlashGDN
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.1
Requires-Dist: ninja
Dynamic: license-file

# FlashGDN

[![PyPI](https://img.shields.io/pypi/v/flashgdn)](https://pypi.org/project/flashgdn/) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/BranchingNLP/FlashGDN/blob/main/notebooks/flashgdn_colab.ipynb)

**Gated DeltaNet written from scratch** — first in plain C, then in CUDA, packaged as a PyTorch library.
Built for [Grace](https://huggingface.co/BranchingNLP), BranchingNLP's family of small hybrid language models.

```python
from flashgdn import gdn_chunk, gdn_recurrent

# training: chunked form, fused CUDA kernels (forward + backward)
o, state = gdn_chunk(q, k, v, beta, g, initial_state=None, output_final_state=True)
o.sum().backward()

# inference / decoding: recurrent form, state kept in registers
o, state = gdn_recurrent(q, k, v, beta, g, initial_state=state, output_final_state=True)
```

### Drop-in for fla

Already using [fla](https://github.com/fla-org/flash-linear-attention)? One line swaps its Gated DeltaNet kernels
for FlashGDN's, everything else in your model stays the same:

```python
import flashgdn
flashgdn.patch_fla()        # fla.layers.GatedDeltaNet now runs on FlashGDN kernels
# flashgdn.unpatch_fla()    # back to fla's Triton kernels
```

`flashgdn.chunk_gated_delta_rule` also takes fla's exact arguments (in-kernel gate, beta sigmoid, q/k L2 norm,
`state_v_first`), with or without fla installed. Packed sequences (`cu_seqlens`) fall back to fla.

Shapes: `q, k: [B, T, H, K]` (L2-normalised), `v: [B, T, H, V]`, `beta, g: [B, T, H]`
(`beta ∈ (0, 1)`, `g ≤ 0` is the log-decay). Same convention as
[flash-linear-attention](https://github.com/fla-org/flash-linear-attention).

## The gated delta rule

```
S_t = α_t S_{t-1} + β_t k_t (v_t − α_t S_{t-1}ᵀ k_t)ᵀ      α_t = e^{g_t}
o_t = scale · S_tᵀ q_t
```

The chunked form (blocks of C = 64 tokens) turns this into dense matrix products inside each block,
plus a short sequential pass of the state between blocks:

```
γ = cumsum(g)    L_ij = e^{γ_i − γ_j}    A = −(diag(β) k kᵀ) ⊙ L  (strictly lower)    T = (I − A)⁻¹
u = T diag(β) v        w = T diag(β e^γ) k
v_new = u − w S        o = (q ⊙ e^γ) S + ((q kᵀ) ⊙ L) v_new        S ← e^{γ_last} S + (k ⊙ e^{γ_last − γ})ᵀ v_new
```

## What's inside

| file | what |
|---|---|
| `reference/flashgdn.c` | recurrent and chunked forms in plain C — they match to 4.5e-8 |
| `reference/flashgdn_bwd.c` | recurrent backward in C, checked with finite differences |
| `flashgdn/flashgdn_kernel.cuh` | recurrent inference kernel (one thread per state column, state in registers) |
| `flashgdn/flashgdn_opt.cuh` | recurrent training kernels: forward with checkpoints every 64 tokens + backward |
| `flashgdn/flashgdn_chunk.cuh` | chunked form: state-passing kernel (forward/backward), `cp.async` pipelined |
| `flashgdn/flashgdn_fused.cuh` | chunked form: all intra-chunk work fused (3 kernels forward, 6 backward), TF32 tensor cores |
| `flashgdn/chunk.py` | `gdn_chunk` + a PyTorch fallback for shapes the fused kernels don't cover |
| `tests/` | correctness against a naive PyTorch reference + benchmarks |

The backward of the fused chunked form (through the triangular inverse, the decays and the state pass)
is derived by hand; every kernel's math was first checked against autograd in float64 (error ~1e-15).

## Speed

One GDN layer of Grace (batch 4 × 2048 tokens, 12 heads, K = 64, V = 128), RTX 3070:

| implementation | inputs | forward | forward + backward |
|---|---|---:|---:|
| **FlashGDN fused, `MODE="bf16"`** | bf16 | 1.1 ms | **3.5 ms** |
| fla `chunk_gated_delta_rule` (Triton) | bf16 | 1.0 ms | 3.6 ms |
| FlashGDN fused, `MODE="bf16"` | fp32 | 1.4 ms | 4.4 ms |
| FlashGDN fused, `MODE="tf32"` | bf16 | 1.8 ms | 7.6 ms |
| FlashGDN fused, `MODE="tf32"` | fp32 | 2.0 ms | 8.6 ms |
| fla `chunk_gated_delta_rule` (Triton) | fp32 | 2.2 ms | 8.9 ms |
| FlashGDN fused, `MODE="fp32"` (exact) | fp32 | 2.9 ms | 10.7 ms |
| FlashGDN chunked, PyTorch + `torch.compile` + state kernel | fp32 | 4.6 ms | 13.4 ms |
| FlashGDN recurrent | fp32 | 2.6 ms | 45.2 ms |

Tesla T4 (Colab free tier, sm_75, fp16 inputs; FlashGDN runs in exact fp32 mode on Turing):

| implementation | forward | forward + backward |
|---|---:|---:|
| **FlashGDN** | 17.7 ms | **32.0 ms** |
| fla (Triton) | 30.4 ms | 74.0 ms |

Recurrent decoding: 8.7 µs per token per layer.

How it got there: hand-derived chunked backward → fused kernels → blocked triangular inverse →
bank-conflict-free shared memory (padded rows, warp-per-row reductions) → bf16 intermediates →
bf16 tensor cores via hand-written `mma.sync` fragments → register accumulators → bf16 operand tiles.

## Install and test

```bash
pip install -e .            # or just put the repo on PYTHONPATH
python3 tests/test_flashgdn_chunk.py
python3 tests/test_flashgdn_bwd.py
python3 tests/test_flashgdn.py
```

The CUDA code is compiled on first import with `torch.utils.cpp_extension` (needs `nvcc` and `ninja`)
and cached afterwards.

Options:
- `flashgdn.chunk.MODE` — what the fused kernels multiply with:
  `"bf16"` (default) bf16 tensor cores via `mma.sync`, like fla; `"tf32"` TF32 tensor cores via `wmma`;
  `"fp32"` no tensor cores and fp32 intermediates (slow, exact to ~1e-7, for checking).
  With `"bf16"`/`"tf32"` the large intermediates (u, w, T, attn, per-chunk states) are stored in bf16;
  all accumulation inside the kernels, and the recurrent state, stay in fp32.
- 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.
- `FLASHGDN_FUSED=0` — use the PyTorch + state-kernel path instead of the fused kernels
- `FLASHGDN_COMPILE=0` — disable `torch.compile` on that path

## Limits

- Fused chunked kernels: `K = 64`, `V` multiple of 32. Other shapes use the PyTorch path (`K ≤ 64`).
- Recurrent kernels: `K ≤ 128` (optimised path for `V ≤ 128`).
- Computation is in fp32 (inputs in bf16/fp16 are converted; the output keeps the input dtype).
- GPUs: compute capability 7.5+ (T4 and newer). Tensor-core modes (`bf16`, `tf32`) need 8.0+ (Ampere: A100, L4, RTX 30/40/50);
  on older GPUs the fused kernels automatically run in exact `fp32` mode. Benchmarked on sm_86 (RTX 3070);
  numbers from other GPUs are very welcome (see the Colab notebook).

## License

MIT
