Metadata-Version: 2.4
Name: flashgdn
Version: 0.3.0
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

<div align="center">

# ⚡ FlashGDN

[![PyPI](https://img.shields.io/pypi/v/flashgdn?style=flat-square)](https://pypi.org/project/flashgdn/) [![Open In Colab](https://img.shields.io/badge/Colab-T4%20demo-F9AB00?logo=googlecolab&logoColor=white&style=flat-square)](https://colab.research.google.com/github/BranchingNLP/FlashGDN/blob/main/notebooks/flashgdn_colab.ipynb) [![Models](https://img.shields.io/badge/-Grace%20models-gray.svg?logo=huggingface&style=flat-square)](https://huggingface.co/BranchingNLP) [![License: MIT](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](LICENSE)

</div>

<p>
FlashGDN is <b>Gated DeltaNet written from scratch</b>: first in plain C, then in hand-written CUDA, packaged as a
PyTorch library. It provides the chunked (training) and recurrent (decoding) kernels with hand-derived backward passes,
a complete <code>GatedDeltaNet</code> layer that needs nothing but PyTorch, packed variable-length sequences, and a
one-line drop-in for <a href="https://github.com/fla-org/flash-linear-attention">fla</a>.
It was built for <a href="https://huggingface.co/BranchingNLP">Grace</a>, BranchingNLP's family of small hybrid
language models, where it runs both training and chat serving.
</p>

--------

* [News](#news)
* [Highlights](#highlights)
* [Installation](#installation)
* [Usage](#usage)
  * [Kernels](#kernels)
  * [The `GatedDeltaNet` layer](#the-gateddeltanet-layer)
  * [Packed sequences (`cu_seqlens`)](#packed-sequences-cu_seqlens)
  * [Generation with a cache](#generation-with-a-cache)
  * [Drop-in for fla](#drop-in-for-fla)
  * [Options](#options)
* [Benchmarks](#benchmarks)
* [How it works](#how-it-works)
* [How it got there](#how-it-got-there)
* [What's inside](#whats-inside)
* [Testing](#testing)
* [Limits and roadmap](#limits-and-roadmap)
* [Citation](#citation)
* [Acknowledgements](#acknowledgements)

## News

- [2026-12] 🧩 **v0.3.0**: `flashgdn.nn.GatedDeltaNet`, a complete layer with fla-compatible weights and no fla dependency, plus **packed variable-length sequences** (`cu_seqlens`) in the fused kernels, forward and backward.
- [2026-11] 🚀 **v0.2.1**: the backward is fused from 6 kernels to 3; with bf16 inputs on an RTX 3070, forward + backward runs in **3.0 ms vs 3.4 ms for fla**.
- [2026-11] 🔌 `flashgdn.patch_fla()`: fla's `GatedDeltaNet` layers run on FlashGDN kernels with one line.

## Highlights

- **Hand-written CUDA**: fused chunked kernels, bf16 tensor cores through raw `mma.sync` fragments, a tensor-core state pass, 16-byte vectorised loads. No Triton.
- **Hand-derived backward** through the triangular inverse, the decays and the state pass, checked against autograd in float64 (error ~1e-15).
- **Faster than fla on the op** with bf16 inputs on Ampere (3.0 vs 3.4 ms fwd+bwd), and on par for a whole layer.
- **Runs on Turing (T4)** in exact fp32 mode: 32 ms vs 74 ms for fla on a free Colab T4.
- **A complete layer without fla**: same parameter names as `fla.layers.GatedDeltaNet`, so checkpoints trained with fla load as they are.
- **Packed sequences** for padding-free training, with per-sequence initial and final states.
- **Reference implementations in C** of both forms, plus a recurrent backward checked with finite differences: readable code to learn the algorithm from.

## Installation

```sh
pip install flashgdn
```

Requirements: PyTorch ≥ 2.1 with CUDA, `nvcc` and `ninja`. The CUDA code is compiled on first use (about 1–2
minutes), cached, and rebuilt automatically when the sources change. GPUs: compute capability 7.5+ (T4 and newer).

From a clone:

```sh
git clone https://github.com/BranchingNLP/FlashGDN && cd FlashGDN
pip install -e .
```

## Usage

### Kernels

Two forms of the same recurrence, with the same interface. Shapes follow fla (sequence first):
`q, k: [B, T, H, K]` (L2-normalised), `v: [B, T, H, V]`, `beta, g: [B, T, H]` with `beta ∈ (0, 1)` and `g ≤ 0` the log-decay.

```py
>>> import torch, torch.nn.functional as F
>>> from flashgdn import gdn_chunk, gdn_recurrent
>>> B, T, H, K, V = 4, 2048, 12, 64, 128
>>> dev, dt = "cuda", torch.bfloat16
>>> q = F.normalize(torch.randn(B, T, H, K, device=dev), dim=-1).to(dt).requires_grad_()
>>> k = F.normalize(torch.randn(B, T, H, K, device=dev), dim=-1).to(dt).requires_grad_()
>>> v = torch.randn(B, T, H, V, device=dev, dtype=dt, requires_grad=True)
>>> beta = torch.rand(B, T, H, device=dev).requires_grad_()
>>> g = (-torch.rand(B, T, H, device=dev) * 0.1).requires_grad_()

# 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.shape, state.shape
(torch.Size([4, 2048, 12, 128]), torch.Size([4, 12, 64, 128]))
>>> o.sum().backward()

# decoding: recurrent form, state kept in registers
>>> o1, state = gdn_recurrent(q[:, :1], k[:, :1], v[:, :1], beta[:, :1], g[:, :1],
...                           initial_state=state, output_final_state=True)
```

The recurrent state is always float32; `o` comes back in the dtype of `v`.

### The `GatedDeltaNet` layer

`flashgdn.nn.GatedDeltaNet` is the full token mixer (projections, short convolutions, gates, output norm) built on the
kernels above. It needs only PyTorch, and its parameters have **the same names as `fla.layers.GatedDeltaNet`**
(`q_proj`, `k_proj`, `v_proj`, `a_proj`, `b_proj`, `g_proj`, `o_proj`, `A_log`, `dt_bias`, `q/k/v_conv1d`, `o_norm`).

```py
>>> from flashgdn.nn import GatedDeltaNet
>>> layer = GatedDeltaNet(hidden_size=1024, num_heads=12, head_dim=64, expand_v=2).to("cuda", torch.bfloat16)
>>> x = torch.randn(4, 2048, 1024, device="cuda", dtype=torch.bfloat16)
>>> y, *_ = layer(x)
>>> y.shape
torch.Size([4, 2048, 1024])
```

<details>
<summary>Click to expand the layer structure</summary>

```py
>>> layer
GatedDeltaNet(
  (q_proj): Linear(in_features=1024, out_features=768, bias=False)
  (k_proj): Linear(in_features=1024, out_features=768, bias=False)
  (v_proj): Linear(in_features=1024, out_features=1536, bias=False)
  (a_proj): Linear(in_features=1024, out_features=12, bias=False)
  (b_proj): Linear(in_features=1024, out_features=12, bias=False)
  (q_conv1d): ShortConvolution(768, 768, kernel_size=(4,), stride=(1,), padding=(3,), groups=768, bias=False)
  (k_conv1d): ShortConvolution(768, 768, kernel_size=(4,), stride=(1,), padding=(3,), groups=768, bias=False)
  (v_conv1d): ShortConvolution(1536, 1536, kernel_size=(4,), stride=(1,), padding=(3,), groups=1536, bias=False)
  (g_proj): Linear(in_features=1024, out_features=1536, bias=False)
  (o_norm): RMSNormGated()
  (o_proj): Linear(in_features=1536, out_features=1024, bias=False)
)
```

</details>

Arguments: `hidden_size`, `num_heads`, `head_dim`, `expand_v` (value head size = `head_dim · expand_v`), `use_gate`,
`use_short_conv`, `conv_size`, `conv_bias`, `allow_neg_eigval` (β ∈ (0, 2)), `norm_eps`.
The call returns `(y, None, state)`, the same 3-tuple shape as fla.

During training the element-wise parts (short convolutions, SiLU, L2 norm, β, decay, gated RMSNorm) go through
`torch.compile`, so they become a few fused kernels instead of dozens of small ones. During generation they stay
eager, so prompts of different lengths don't trigger recompilation.

Kernel choice is automatic: the chunked form for sequences, the recurrent form for a single token (and for `K > 64`),
and a slow but exact PyTorch reference on CPU.

### Packed sequences (`cu_seqlens`)

Several sequences of different lengths can be packed into one row with no padding. `cu_seqlens` holds their
boundaries, `[0, l1, l1+l2, …, T]`, exactly as in fla. No information crosses from one sequence to the next, in the
recurrence or in the short convolutions.

```py
>>> cu = torch.tensor([0, 300, 1100, 1500])                  # 3 sequences: 300, 800 and 400 tokens
>>> x = torch.randn(1, 1500, 1024, device="cuda", dtype=torch.bfloat16)
>>> y, *_ = layer(x, cu_seqlens=cu)

# kernel level: inputs are [1, 1500, H, ·]; initial and final states are per sequence, [3, H, K, V]
>>> o, states = gdn_chunk(q, k, v, beta, g, initial_state=s0, output_final_state=True, cu_seqlens=cu)
```

Each sequence is moved so that it starts on a 64-token chunk boundary, and the gaps are filled with neutral tokens
(`q = k = v = 0`, `β = 0`, `g = 0`, which leave the state untouched). No chunk ever holds two sequences, so the
intra-chunk kernels are unchanged; only the state pass restarts at each sequence (and, in the backward, hands the
gradient of each initial state back). The waste is at most 63 tokens per sequence, and the result is identical,
bit for bit, to running every sequence on its own.

### Generation with a cache

```py
>>> y, _, st = layer(prompt, use_cache=True)                  # prefill: chunked kernels
>>> for _ in range(n_new):
...     y, _, st = layer(next_x, state=st, use_cache=True)    # one token: recurrent kernel
```

The cache is a dict with the recurrent state `S` `[B, H, K, V]` and the last `conv_size − 1` inputs of each short
convolution. Prefill followed by token-by-token decoding gives the same output as a single full forward.

### Drop-in for fla

Already using fla? There are three ways in, from the lightest to the most complete:

```py
>>> import flashgdn

# 1. fla's layers keep running, on FlashGDN kernels
>>> flashgdn.patch_fla()          # flashgdn.unpatch_fla() goes back to fla's Triton kernels

# 2. replace every fla GatedDeltaNet inside a model with flashgdn.nn.GatedDeltaNet (weights copied)
>>> flashgdn.nn.replace_fla(model)

# 3. the op alone, with fla's exact signature, with or without fla installed
>>> from flashgdn import chunk_gated_delta_rule
>>> o, final_state = chunk_gated_delta_rule(q, k, v, g, beta, use_qk_l2norm_in_kernel=True, cu_seqlens=cu)
```

`chunk_gated_delta_rule` accepts fla's arguments: in-kernel gate (`use_gate_in_kernel` with `A_log` / `dt_bias`),
`use_beta_sigmoid_in_kernel`, `allow_neg_eigval`, `use_qk_l2norm_in_kernel`, `state_v_first`, `cu_seqlens`.
Cases FlashGDN doesn't cover (context parallel, `head_first`, `K > 64`, CPU tensors) fall back to fla when it is installed.

### Options

| setting | values | effect |
|---|---|---|
| `flashgdn.chunk.MODE` | `"bf16"` (default), `"tf32"`, `"fp32"` | what the fused kernels multiply with: bf16 tensor cores via `mma.sync` (like fla), TF32 tensor cores via `wmma`, or no tensor cores and fp32 intermediates (slower, exact to ~1e-7, for checking) |
| `FLASHGDN_FUSED=0` | env | use the PyTorch + state-kernel path instead of the fused kernels |
| `FLASHGDN_COMPILE=0` | env | disable `torch.compile` everywhere (useful for debugging) |

With `"bf16"` and `"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. On GPUs older than Ampere the fused
kernels automatically run in exact `"fp32"` mode.

## Benchmarks

All times are forward + backward after warm-up, from the scripts in `tests/`.
Numbers from other GPUs are very welcome: run the Colab notebook or the tests and open an issue.

**One GDN op** (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.0 ms** |
| fla `chunk_gated_delta_rule` (Triton) | bf16 | 1.1 ms | 3.4 ms |
| FlashGDN fused, `MODE="bf16"` | fp32 | 1.4 ms | 3.4 ms |
| FlashGDN fused, `MODE="tf32"` | bf16 | 1.8 ms | 7.2 ms |
| fla `chunk_gated_delta_rule` (Triton) | fp32 | 2.2 ms | 8.5 ms |
| FlashGDN fused, `MODE="fp32"` (exact) | fp32 | 2.8 ms | 9.9 ms |
| FlashGDN chunked, PyTorch + `torch.compile` + state kernel | fp32 | 4.5 ms | 12.6 ms |
| FlashGDN recurrent | fp32 | 2.6 ms | 44.2 ms |

**Tesla T4** (Colab free tier, sm_75, fp16 inputs). On Turing FlashGDN runs in exact fp32 mode, and fla's Triton
kernels are not tuned for this generation, so read this as "FlashGDN runs well on a free T4" rather than as a
like-for-like comparison:

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

**A whole layer** (`GatedDeltaNet`, hidden 1024, same shapes, bf16), RTX 3070:

| implementation | forward + backward |
|---|---:|
| fla `fla.layers.GatedDeltaNet` | 15.3 ms |
| FlashGDN `flashgdn.nn.GatedDeltaNet` | 15.9 ms |

At the layer level about half of the time is the dense projections (cuBLAS, already near the GPU's peak), so the two
are on par; the remaining gap comes from fla doing the L2 norm of q and k inside its kernel (see the roadmap).

**Packed sequences**: 7 sequences of random length, 7469 tokens in total, bf16, RTX 3070:

| implementation | forward + backward |
|---|---:|
| **packed, one call with `cu_seqlens`** | **5.2 ms** |
| one call per sequence | 7.7 ms |

**Decoding**: 8.7 µs per token per layer with the recurrent kernel.

End to end, training a 64M hybrid Grace model on the RTX 3070 runs at the same tokens/s with FlashGDN inside fla as
with fla's own kernels, with matching validation loss; the loss also matches fla on Blackwell (sm_120).

## How it works

The gated delta rule keeps a matrix state `S` per head and, at every token, decays it and corrects it toward the
new key–value pair:

```
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 **recurrent form** runs this token by token: one CUDA thread per state column, with the state in registers.
It is the right tool for decoding, but training through it is sequential in T.

The **chunked form** (blocks of C = 64 tokens) turns everything inside a block into dense matrix products,
and leaves only 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
```

In FlashGDN the forward is three kernels: `prep` (γ, A, the blocked 16×16 triangular inverse, u, w), the
tensor-core state pass, and `out` (the outputs). The backward is three more, derived by hand: output gradients with
per-chunk state gradients, the reverse state pass, and everything that flows back through T, the decays and β,
without the per-chunk gradients ever leaving the SM.

## How it got there

Recurrent form in C → chunked form in C (matching to 4.5e-8) → recurrent backward checked with finite differences →
CUDA recurrent kernels → hand-derived chunked backward → fused kernels → blocked 16×16 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 →
backward fused from 6 kernels to 3 → 16-byte vectorised tile loads →
`k` staged once in shared memory instead of re-read from global memory → a complete layer → packed sequences.

From 60.8 ms (first CUDA backward) to 3.0 ms, profiling every step with Nsight Compute.

## 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: fp32 state-pass kernel (forward / backward, packed sequences), `cp.async` pipelined |
| `flashgdn/flashgdn_fused.cuh` | chunked form, all intra-chunk work fused: 3 kernels forward, 3 backward in bf16 mode, plus the tensor-core state pass |
| `flashgdn/flashgdn_ext.cu` | PyTorch bindings |
| `flashgdn/chunk.py` | `gdn_chunk`, the packed-sequence layout, and a PyTorch fallback for shapes the fused kernels don't cover |
| `flashgdn/nn.py` | `GatedDeltaNet` layer, `ShortConvolution`, `RMSNormGated`, `replace_fla` |
| `flashgdn/fla_compat.py` | fla-compatible `chunk_gated_delta_rule`, `patch_fla()` / `unpatch_fla()` |
| `tests/` | correctness against references and fla, packed sequences, benchmarks |
| `notebooks/flashgdn_colab.ipynb` | correctness + benchmark vs fla + decoding + `patch_fla()`, one click on Colab |
| `examples/grace/` | how Grace uses it: fla patch for training, cached generation for serving |

## Testing

```sh
python3 tests/test_flashgdn_chunk.py   # chunked form vs a naive PyTorch reference, all modes, + benchmark vs fla
python3 tests/test_varlen.py           # packed sequences vs one sequence at a time (outputs, states, all gradients)
python3 tests/test_nn.py               # GatedDeltaNet layer vs fla's (same weights), cache vs full forward
python3 tests/test_fla_compat.py       # fla API compatibility (needs fla)
python3 tests/test_flashgdn_bwd.py     # recurrent backward
python3 tests/test_flashgdn.py         # recurrent forward
```

Expected errors: ~1e-7 in `"fp32"` mode, ~1e-2 relative with bf16 tensor cores (the same as fla, whose kernels are
also bf16).

## Limits and roadmap

Current limits:
- Fused chunked kernels: `K = 64`, `V` a multiple of 32. Other shapes use the PyTorch path (`K ≤ 64`).
- Recurrent kernels: `K ≤ 128` (optimised path for `V ≤ 128`).
- NVIDIA only, compute capability 7.5+, tuned on sm_86 (RTX 3070). Tensor-core modes need 8.0+.
- The layer doesn't support grouped value heads (`num_v_heads ≠ num_heads`) or padding masks yet.

Next:
- L2 norm of q and k inside the kernels, forward and backward (closes the layer-level gap with fla).
- A fused linear + cross-entropy loss, to avoid materialising the logits.

## Citation

If FlashGDN is useful in your work, please cite it together with the Gated DeltaNet paper:

```bib
@software{dinicola2026flashgdn,
  title  = {FlashGDN: Gated DeltaNet Written from Scratch in C and CUDA},
  author = {Di Nicola, Michelangelo},
  url    = {https://github.com/BranchingNLP/FlashGDN},
  year   = {2026}
}

@inproceedings{yang2024gdn,
  title     = {Gated Delta Networks: Improving Mamba2 with Delta Rule},
  author    = {Yang, Songlin and Kautz, Jan and Hatamizadeh, Ali},
  booktitle = {Proceedings of ICLR},
  year      = {2025}
}
```

## Acknowledgements

The chunked algorithm follows the Gated DeltaNet paper and the parallel delta-rule formulation by Songlin Yang and
co-authors. [fla](https://github.com/fla-org/flash-linear-attention) is the reference every FlashGDN kernel was
checked and benchmarked against, and the API FlashGDN mirrors.

MIT License.
