cofrgenet-torch 0.2.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.
- cofrgenet_torch-0.2.0/LICENSE +21 -0
- cofrgenet_torch-0.2.0/PKG-INFO +206 -0
- cofrgenet_torch-0.2.0/README.md +177 -0
- cofrgenet_torch-0.2.0/cofrgenet_fng/__init__.py +32 -0
- cofrgenet_torch-0.2.0/cofrgenet_fng/layers.py +114 -0
- cofrgenet_torch-0.2.0/cofrgenet_fng/py.typed +0 -0
- cofrgenet_torch-0.2.0/cofrgenet_fng/triton_ladder.py +257 -0
- cofrgenet_torch-0.2.0/cofrgenet_torch.egg-info/PKG-INFO +206 -0
- cofrgenet_torch-0.2.0/cofrgenet_torch.egg-info/SOURCES.txt +13 -0
- cofrgenet_torch-0.2.0/cofrgenet_torch.egg-info/dependency_links.txt +1 -0
- cofrgenet_torch-0.2.0/cofrgenet_torch.egg-info/requires.txt +7 -0
- cofrgenet_torch-0.2.0/cofrgenet_torch.egg-info/top_level.txt +1 -0
- cofrgenet_torch-0.2.0/pyproject.toml +49 -0
- cofrgenet_torch-0.2.0/setup.cfg +4 -0
- cofrgenet_torch-0.2.0/tests/test_layers.py +163 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tpoisonooo
|
|
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,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cofrgenet-torch
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: PyTorch implementation of CoFrGeNet-FNG: non-expanding gated continued-fraction feed-forward layers (arXiv:2611.26835) with fused Triton fwd/bwd kernels
|
|
5
|
+
Author: tpoisonooo
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/tpoisonooo/fng
|
|
8
|
+
Project-URL: Issues, https://github.com/tpoisonooo/fng/issues
|
|
9
|
+
Project-URL: Paper, https://arxiv.org/abs/2611.26835
|
|
10
|
+
Keywords: continued-fraction,cofrgenet,cofrnet,ffn,transformer,pytorch,triton
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: torch>=2.0
|
|
24
|
+
Provides-Extra: triton
|
|
25
|
+
Requires-Dist: triton>=3.0; extra == "triton"
|
|
26
|
+
Provides-Extra: test
|
|
27
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# CoFrGeNet-FNG (unofficial PyTorch implementation)
|
|
31
|
+
|
|
32
|
+
English | [简体中文](README.zh-CN.md)
|
|
33
|
+
|
|
34
|
+
Unofficial PyTorch implementation of **CoFrGeNet-FNG** — the *Non-Expanding
|
|
35
|
+
Gated Continued Fraction* feed-forward layer from IBM Research's paper
|
|
36
|
+
[Non-Expanding Gated Continued Fraction Architecture for Feedforward Layers
|
|
37
|
+
in Language Models](https://arxiv.org/abs/2611.26835) (NeurIPS 2026) — plus
|
|
38
|
+
classic FFN baselines and a fused Triton kernel for the continued-fraction
|
|
39
|
+
ladders.
|
|
40
|
+
|
|
41
|
+
> **Note:** This is an independent, from-the-paper implementation. The
|
|
42
|
+
> authors' official repository, [IBM/CoFrNets](https://github.com/IBM/CoFrNets),
|
|
43
|
+
> had not published code at the time of writing.
|
|
44
|
+
|
|
45
|
+
## What is CoFrGeNet-FNG?
|
|
46
|
+
|
|
47
|
+
A drop-in replacement for the FFN sublayer of transformer (and SSM/MoE)
|
|
48
|
+
blocks with the same `(…, p) -> (…, p)` API, but ~4x fewer parameters:
|
|
49
|
+
|
|
50
|
+
1. **Non-expanding gated projection**: `x ∈ R^p → z ∈ R^p` (expansion
|
|
51
|
+
factor α = 1), computed as `z = a ⊙ silu(b)` where `[a, b]` is a split
|
|
52
|
+
of one linear map — 2p² parameters.
|
|
53
|
+
2. **L continued-fraction ladders of depth d**: each ladder has d+1 learned
|
|
54
|
+
coefficient vectors, a_k = w_kᵀz, and evaluates the rational function
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
f~(a_1..a_d) = 1/(a_1 + 1/(a_2 + ... + 1/a_d))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
via the continuant recursion (paper eqs. 3–6), needing only **one**
|
|
61
|
+
division per ladder instead of d.
|
|
62
|
+
3. **log/exp division** (paper eq. 8): the remaining division is rewritten
|
|
63
|
+
as `sgn·sgn·exp(log|num| − log max(|den|, ε))`, which stabilizes training
|
|
64
|
+
of deep ladders (d > 1) **without** the incremental training schedule
|
|
65
|
+
required by the original CoFrGeNet.
|
|
66
|
+
4. A linear projection `R^L → R^p`.
|
|
67
|
+
|
|
68
|
+
Parameter count: `2p² + L·p·(d+1) + L·p` vs. `2αp²` for a vanilla FFN or
|
|
69
|
+
`3αp²` for SwiGLU (α ≥ 2).
|
|
70
|
+
|
|
71
|
+
## Install
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
# from PyPI
|
|
75
|
+
pip install cofrgenet-torch # torch is the only hard dependency
|
|
76
|
+
pip install "cofrgenet-torch[triton]" # optional: fused Triton fwd+bwd (GPU)
|
|
77
|
+
|
|
78
|
+
# or from source (this repo)
|
|
79
|
+
pip install -e .
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Optional, for the fused Triton ladder kernels:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
# GPU
|
|
86
|
+
pip install triton
|
|
87
|
+
# CPU (experimental triton-cpu backend, pick your platform/python)
|
|
88
|
+
pip install "https://github.com/triton-lang/triton-cpu/releases/download/v3.8.0/triton-3.8.0%2Bcpu-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Note: install the triton-cpu wheel **last**. torch pins its own triton
|
|
92
|
+
build, so a later `pip install` that touches torch's dependencies may
|
|
93
|
+
replace the `+cpu` wheel with mainline triton (which has no CPU backend).
|
|
94
|
+
|
|
95
|
+
## Quickstart
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import torch
|
|
99
|
+
from cofrgenet_fng import CoFrGeNetFNG
|
|
100
|
+
|
|
101
|
+
ffn = CoFrGeNetFNG(p=768, n_ladders=5, depth=5) # same API as an FFN
|
|
102
|
+
x = torch.randn(2, 128, 768)
|
|
103
|
+
y = ffn(x) # (2, 128, 768)
|
|
104
|
+
|
|
105
|
+
sum(t.numel() for t in ffn.parameters()) # 1,208,862 (vs 4.7M vanilla FFN)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Examples
|
|
109
|
+
|
|
110
|
+
Run from the repo root.
|
|
111
|
+
|
|
112
|
+
### `fng_vs_ffn.py` — FNG vs. FFN baselines
|
|
113
|
+
|
|
114
|
+
Verifies the continuant math, then compares parameters, speed, and learning
|
|
115
|
+
on a teacher-student task. Measured on an 8-core CPU (torch 2.9.1):
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
module params vs FFN fwd+bwd
|
|
119
|
+
VanillaFFN (alpha=4) 4,722,432 1.00x 259.90 ms
|
|
120
|
+
SwiGLUFFN (alpha=8/3) 4,723,456 1.00x 234.54 ms
|
|
121
|
+
CoFrGeNetFNG (L=5, d=5) 1,208,862 0.26x 69.60 ms
|
|
122
|
+
CoFrGeNetFNG (L=8, d=8) 1,243,464 0.26x 74.09 ms
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
On the toy fitting task the FNG block uses 3x fewer parameters but converges
|
|
126
|
+
slower than a full-size FFN — consistent with the paper, whose parity/better
|
|
127
|
+
results are at language-model pre-training scale, not tiny regression tasks.
|
|
128
|
+
|
|
129
|
+
### `fng_triton.py` — fused Triton ladder kernel
|
|
130
|
+
|
|
131
|
+
The ladder is a serial loop of tiny elementwise ops in eager PyTorch; the
|
|
132
|
+
kernel fuses **both forward and backward** into pointwise passes (forward:
|
|
133
|
+
continuant recursion + one log/exp division; backward: analytic adjoint,
|
|
134
|
+
also division-free, exposed via `ladder_apply` / `CoFrGeNetFNGTriton`).
|
|
135
|
+
Measured with the triton-cpu backend (forward; numbers on a shared CPU vary
|
|
136
|
+
run to run; the ladder-only speedup is the consistent part — at whole-block
|
|
137
|
+
level the p→2p GEMM dominates and the difference is within noise):
|
|
138
|
+
|
|
139
|
+
```
|
|
140
|
+
(B=16, S=256, L=8, d=8) N=32,768 ladders: eager 0.679 ms | triton 0.164 ms (4.13x)
|
|
141
|
+
(B=64, S=1024, L=16, d=8) N=1,048,576 ladders: eager 16.262 ms | triton 5.945 ms (2.74x)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Run it with `TRITON_DEFAULT_BACKEND=cpu python fng_triton.py` (or on a GPU,
|
|
145
|
+
plain `python fng_triton.py`).
|
|
146
|
+
|
|
147
|
+
### `mnist_train.py` — MNIST forward + backward training test
|
|
148
|
+
|
|
149
|
+
End-to-end training on CPU (8 epochs, batch 256, AdamW lr=5e-4, grad clip 1.0)
|
|
150
|
+
of the same tiny residual classifier with the three FFN-style blocks swapped.
|
|
151
|
+
Data is fetched directly from the MNIST IDX mirrors (no torchvision needed).
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
block params test_acc @8 step
|
|
155
|
+
ffn 233,738 97.66% 5.0 ms
|
|
156
|
+
fng-eager 149,610 93.76% 5.9 ms
|
|
157
|
+
fng-triton 149,610 93.23% 5.1 ms
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`fng-triton` uses the fused Triton forward + backward kernels in the ladder
|
|
161
|
+
and tracks `fng-eager` to within small floating-point drift. With
|
|
162
|
+
`depth=5, L=16` the FNG block reaches ~93–94% at 0.64x the parameters of the
|
|
163
|
+
FFN; `depth=8` is noticeably harder to optimize at this small scale.
|
|
164
|
+
|
|
165
|
+
Run it with `TRITON_DEFAULT_BACKEND=cpu python mnist_train.py`.
|
|
166
|
+
|
|
167
|
+
## Tests
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
pip install pytest
|
|
171
|
+
pytest -v # triton tests are skipped automatically if unavailable
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Repository layout
|
|
175
|
+
|
|
176
|
+
```
|
|
177
|
+
cofrgenet_fng/ the package
|
|
178
|
+
layers.py VanillaFFN, SwiGLUFFN, CoFrGeNetFNG, continuant_fraction
|
|
179
|
+
triton_ladder.py fused Triton fwd+bwd kernels (optional), CoFrGeNetFNGTriton
|
|
180
|
+
fng_vs_ffn.py example: FNG vs. FFN baselines
|
|
181
|
+
fng_triton.py example: Triton kernel correctness + benchmarks
|
|
182
|
+
mnist_train.py example: MNIST forward + backward training test
|
|
183
|
+
tests/ pytest suite
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
## Citation
|
|
187
|
+
|
|
188
|
+
```bibtex
|
|
189
|
+
@article{dhurandhar2026cofrgenetfng,
|
|
190
|
+
title = {Non-Expanding Gated Continued Fraction Architecture for Feedforward Layers in Language Models},
|
|
191
|
+
author = {Dhurandhar, Amit and Chenthamarakshan, Vijil and Ramamurthy, Karthikeyan Natesan and Wei, Dennis and Nair, Rahul},
|
|
192
|
+
journal = {arXiv:2611.26835},
|
|
193
|
+
year = {2026}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
@inproceedings{dhurandhar2026cofrgenet,
|
|
197
|
+
title = {CoFrGeNet: Continued Fraction Architectures for Language Generation},
|
|
198
|
+
author = {Dhurandhar, A. and Chenthamarakshan, V. and Wei, D. and Pedapati, T. and Ramamurthy, K. N. and Nair, R.},
|
|
199
|
+
booktitle = {Proceedings of the 43rd International Conference on Machine Learning (ICML)},
|
|
200
|
+
year = {2026}
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# CoFrGeNet-FNG (unofficial PyTorch implementation)
|
|
2
|
+
|
|
3
|
+
English | [简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
Unofficial PyTorch implementation of **CoFrGeNet-FNG** — the *Non-Expanding
|
|
6
|
+
Gated Continued Fraction* feed-forward layer from IBM Research's paper
|
|
7
|
+
[Non-Expanding Gated Continued Fraction Architecture for Feedforward Layers
|
|
8
|
+
in Language Models](https://arxiv.org/abs/2611.26835) (NeurIPS 2026) — plus
|
|
9
|
+
classic FFN baselines and a fused Triton kernel for the continued-fraction
|
|
10
|
+
ladders.
|
|
11
|
+
|
|
12
|
+
> **Note:** This is an independent, from-the-paper implementation. The
|
|
13
|
+
> authors' official repository, [IBM/CoFrNets](https://github.com/IBM/CoFrNets),
|
|
14
|
+
> had not published code at the time of writing.
|
|
15
|
+
|
|
16
|
+
## What is CoFrGeNet-FNG?
|
|
17
|
+
|
|
18
|
+
A drop-in replacement for the FFN sublayer of transformer (and SSM/MoE)
|
|
19
|
+
blocks with the same `(…, p) -> (…, p)` API, but ~4x fewer parameters:
|
|
20
|
+
|
|
21
|
+
1. **Non-expanding gated projection**: `x ∈ R^p → z ∈ R^p` (expansion
|
|
22
|
+
factor α = 1), computed as `z = a ⊙ silu(b)` where `[a, b]` is a split
|
|
23
|
+
of one linear map — 2p² parameters.
|
|
24
|
+
2. **L continued-fraction ladders of depth d**: each ladder has d+1 learned
|
|
25
|
+
coefficient vectors, a_k = w_kᵀz, and evaluates the rational function
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
f~(a_1..a_d) = 1/(a_1 + 1/(a_2 + ... + 1/a_d))
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
via the continuant recursion (paper eqs. 3–6), needing only **one**
|
|
32
|
+
division per ladder instead of d.
|
|
33
|
+
3. **log/exp division** (paper eq. 8): the remaining division is rewritten
|
|
34
|
+
as `sgn·sgn·exp(log|num| − log max(|den|, ε))`, which stabilizes training
|
|
35
|
+
of deep ladders (d > 1) **without** the incremental training schedule
|
|
36
|
+
required by the original CoFrGeNet.
|
|
37
|
+
4. A linear projection `R^L → R^p`.
|
|
38
|
+
|
|
39
|
+
Parameter count: `2p² + L·p·(d+1) + L·p` vs. `2αp²` for a vanilla FFN or
|
|
40
|
+
`3αp²` for SwiGLU (α ≥ 2).
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# from PyPI
|
|
46
|
+
pip install cofrgenet-torch # torch is the only hard dependency
|
|
47
|
+
pip install "cofrgenet-torch[triton]" # optional: fused Triton fwd+bwd (GPU)
|
|
48
|
+
|
|
49
|
+
# or from source (this repo)
|
|
50
|
+
pip install -e .
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Optional, for the fused Triton ladder kernels:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
# GPU
|
|
57
|
+
pip install triton
|
|
58
|
+
# CPU (experimental triton-cpu backend, pick your platform/python)
|
|
59
|
+
pip install "https://github.com/triton-lang/triton-cpu/releases/download/v3.8.0/triton-3.8.0%2Bcpu-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl"
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Note: install the triton-cpu wheel **last**. torch pins its own triton
|
|
63
|
+
build, so a later `pip install` that touches torch's dependencies may
|
|
64
|
+
replace the `+cpu` wheel with mainline triton (which has no CPU backend).
|
|
65
|
+
|
|
66
|
+
## Quickstart
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import torch
|
|
70
|
+
from cofrgenet_fng import CoFrGeNetFNG
|
|
71
|
+
|
|
72
|
+
ffn = CoFrGeNetFNG(p=768, n_ladders=5, depth=5) # same API as an FFN
|
|
73
|
+
x = torch.randn(2, 128, 768)
|
|
74
|
+
y = ffn(x) # (2, 128, 768)
|
|
75
|
+
|
|
76
|
+
sum(t.numel() for t in ffn.parameters()) # 1,208,862 (vs 4.7M vanilla FFN)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Examples
|
|
80
|
+
|
|
81
|
+
Run from the repo root.
|
|
82
|
+
|
|
83
|
+
### `fng_vs_ffn.py` — FNG vs. FFN baselines
|
|
84
|
+
|
|
85
|
+
Verifies the continuant math, then compares parameters, speed, and learning
|
|
86
|
+
on a teacher-student task. Measured on an 8-core CPU (torch 2.9.1):
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
module params vs FFN fwd+bwd
|
|
90
|
+
VanillaFFN (alpha=4) 4,722,432 1.00x 259.90 ms
|
|
91
|
+
SwiGLUFFN (alpha=8/3) 4,723,456 1.00x 234.54 ms
|
|
92
|
+
CoFrGeNetFNG (L=5, d=5) 1,208,862 0.26x 69.60 ms
|
|
93
|
+
CoFrGeNetFNG (L=8, d=8) 1,243,464 0.26x 74.09 ms
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
On the toy fitting task the FNG block uses 3x fewer parameters but converges
|
|
97
|
+
slower than a full-size FFN — consistent with the paper, whose parity/better
|
|
98
|
+
results are at language-model pre-training scale, not tiny regression tasks.
|
|
99
|
+
|
|
100
|
+
### `fng_triton.py` — fused Triton ladder kernel
|
|
101
|
+
|
|
102
|
+
The ladder is a serial loop of tiny elementwise ops in eager PyTorch; the
|
|
103
|
+
kernel fuses **both forward and backward** into pointwise passes (forward:
|
|
104
|
+
continuant recursion + one log/exp division; backward: analytic adjoint,
|
|
105
|
+
also division-free, exposed via `ladder_apply` / `CoFrGeNetFNGTriton`).
|
|
106
|
+
Measured with the triton-cpu backend (forward; numbers on a shared CPU vary
|
|
107
|
+
run to run; the ladder-only speedup is the consistent part — at whole-block
|
|
108
|
+
level the p→2p GEMM dominates and the difference is within noise):
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
(B=16, S=256, L=8, d=8) N=32,768 ladders: eager 0.679 ms | triton 0.164 ms (4.13x)
|
|
112
|
+
(B=64, S=1024, L=16, d=8) N=1,048,576 ladders: eager 16.262 ms | triton 5.945 ms (2.74x)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Run it with `TRITON_DEFAULT_BACKEND=cpu python fng_triton.py` (or on a GPU,
|
|
116
|
+
plain `python fng_triton.py`).
|
|
117
|
+
|
|
118
|
+
### `mnist_train.py` — MNIST forward + backward training test
|
|
119
|
+
|
|
120
|
+
End-to-end training on CPU (8 epochs, batch 256, AdamW lr=5e-4, grad clip 1.0)
|
|
121
|
+
of the same tiny residual classifier with the three FFN-style blocks swapped.
|
|
122
|
+
Data is fetched directly from the MNIST IDX mirrors (no torchvision needed).
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
block params test_acc @8 step
|
|
126
|
+
ffn 233,738 97.66% 5.0 ms
|
|
127
|
+
fng-eager 149,610 93.76% 5.9 ms
|
|
128
|
+
fng-triton 149,610 93.23% 5.1 ms
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`fng-triton` uses the fused Triton forward + backward kernels in the ladder
|
|
132
|
+
and tracks `fng-eager` to within small floating-point drift. With
|
|
133
|
+
`depth=5, L=16` the FNG block reaches ~93–94% at 0.64x the parameters of the
|
|
134
|
+
FFN; `depth=8` is noticeably harder to optimize at this small scale.
|
|
135
|
+
|
|
136
|
+
Run it with `TRITON_DEFAULT_BACKEND=cpu python mnist_train.py`.
|
|
137
|
+
|
|
138
|
+
## Tests
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
pip install pytest
|
|
142
|
+
pytest -v # triton tests are skipped automatically if unavailable
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Repository layout
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
cofrgenet_fng/ the package
|
|
149
|
+
layers.py VanillaFFN, SwiGLUFFN, CoFrGeNetFNG, continuant_fraction
|
|
150
|
+
triton_ladder.py fused Triton fwd+bwd kernels (optional), CoFrGeNetFNGTriton
|
|
151
|
+
fng_vs_ffn.py example: FNG vs. FFN baselines
|
|
152
|
+
fng_triton.py example: Triton kernel correctness + benchmarks
|
|
153
|
+
mnist_train.py example: MNIST forward + backward training test
|
|
154
|
+
tests/ pytest suite
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Citation
|
|
158
|
+
|
|
159
|
+
```bibtex
|
|
160
|
+
@article{dhurandhar2026cofrgenetfng,
|
|
161
|
+
title = {Non-Expanding Gated Continued Fraction Architecture for Feedforward Layers in Language Models},
|
|
162
|
+
author = {Dhurandhar, Amit and Chenthamarakshan, Vijil and Ramamurthy, Karthikeyan Natesan and Wei, Dennis and Nair, Rahul},
|
|
163
|
+
journal = {arXiv:2611.26835},
|
|
164
|
+
year = {2026}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
@inproceedings{dhurandhar2026cofrgenet,
|
|
168
|
+
title = {CoFrGeNet: Continued Fraction Architectures for Language Generation},
|
|
169
|
+
author = {Dhurandhar, A. and Chenthamarakshan, V. and Wei, D. and Pedapati, T. and Ramamurthy, K. N. and Nair, R.},
|
|
170
|
+
booktitle = {Proceedings of the 43rd International Conference on Machine Learning (ICML)},
|
|
171
|
+
year = {2026}
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Unofficial PyTorch implementation of CoFrGeNet-FNG.
|
|
2
|
+
|
|
3
|
+
Non-Expanding Gated Continued Fraction feed-forward layers for language
|
|
4
|
+
models (arXiv:2611.26835), plus classic FFN baselines and fused Triton
|
|
5
|
+
forward/backward kernels for the continued-fraction ladders.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .layers import CoFrGeNetFNG, SwiGLUFFN, VanillaFFN, continuant_fraction
|
|
9
|
+
from .triton_ladder import (
|
|
10
|
+
HAS_TRITON,
|
|
11
|
+
CoFrGeNetFNGTriton,
|
|
12
|
+
ladder_apply,
|
|
13
|
+
ladder_backward,
|
|
14
|
+
ladder_forward,
|
|
15
|
+
triton_backend,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__version__ = "0.2.0"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"CoFrGeNetFNG",
|
|
22
|
+
"CoFrGeNetFNGTriton",
|
|
23
|
+
"SwiGLUFFN",
|
|
24
|
+
"VanillaFFN",
|
|
25
|
+
"continuant_fraction",
|
|
26
|
+
"HAS_TRITON",
|
|
27
|
+
"ladder_apply",
|
|
28
|
+
"ladder_backward",
|
|
29
|
+
"ladder_forward",
|
|
30
|
+
"triton_backend",
|
|
31
|
+
"__version__",
|
|
32
|
+
]
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Feed-forward layers: classic FFN baselines and the CoFrGeNet-FNG block.
|
|
2
|
+
|
|
3
|
+
CoFrGeNet-FNG ("Non-Expanding Gated Continued Fraction" FFN replacement,
|
|
4
|
+
arXiv:2611.26835) replaces the transformer FFN sublayer with:
|
|
5
|
+
|
|
6
|
+
1. a non-expanding gated projection x in R^p -> z in R^p (alpha = 1),
|
|
7
|
+
z = a * silu(b) where [a, b] = split(Linear(x)) (2p^2 params)
|
|
8
|
+
2. L continued-fraction "ladders" of depth d. Each ladder has d+1 learned
|
|
9
|
+
coefficient vectors; a_k = w_k^T z. The fractional part
|
|
10
|
+
|
|
11
|
+
f~(a_1..a_d) = 1/(a_1 + 1/(a_2 + ... + 1/a_d))
|
|
12
|
+
|
|
13
|
+
is evaluated with the continuant recursion (paper eqs. 3-6), so a depth-d
|
|
14
|
+
ladder needs only ONE division instead of d.
|
|
15
|
+
3. that division replaced by the log/exp form (paper eq. 8), which is what
|
|
16
|
+
makes d > 1 trainable without incremental training:
|
|
17
|
+
|
|
18
|
+
f~ = sgn(K_{d-1}) * sgn(K_d)
|
|
19
|
+
* exp( log|K_{d-1}| - log(max(|K_d|, eps)) )
|
|
20
|
+
4. a linear projection R^L -> R^p.
|
|
21
|
+
|
|
22
|
+
All modules share the same API: (..., p) -> (..., p), i.e. they are drop-in
|
|
23
|
+
replacements for the FFN sublayer of a transformer block.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
import torch.nn as nn
|
|
28
|
+
import torch.nn.functional as F
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"VanillaFFN",
|
|
32
|
+
"SwiGLUFFN",
|
|
33
|
+
"CoFrGeNetFNG",
|
|
34
|
+
"continuant_fraction",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class VanillaFFN(nn.Module):
|
|
39
|
+
"""GPT-2 style feed-forward network. Params ~= 2 * alpha * p^2."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, p: int, alpha: float = 4.0):
|
|
42
|
+
super().__init__()
|
|
43
|
+
self.up = nn.Linear(p, int(alpha * p))
|
|
44
|
+
self.down = nn.Linear(int(alpha * p), p)
|
|
45
|
+
|
|
46
|
+
def forward(self, x):
|
|
47
|
+
return self.down(F.gelu(self.up(x)))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class SwiGLUFFN(nn.Module):
|
|
51
|
+
"""Llama style gated FFN. Params ~= 3 * alpha * p^2."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, p: int, alpha: float = 8 / 3):
|
|
54
|
+
super().__init__()
|
|
55
|
+
hidden = int(alpha * p)
|
|
56
|
+
self.gate = nn.Linear(p, hidden)
|
|
57
|
+
self.up = nn.Linear(p, hidden)
|
|
58
|
+
self.down = nn.Linear(hidden, p)
|
|
59
|
+
|
|
60
|
+
def forward(self, x):
|
|
61
|
+
return self.down(F.silu(self.gate(x)) * self.up(x))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def continuant_fraction(A: torch.Tensor, eps: float = 0.1) -> torch.Tensor:
|
|
65
|
+
"""
|
|
66
|
+
Evaluate f~(a_1, ..., a_d) = 1/(a_1 + 1/(a_2 + ... + 1/a_d)) stably.
|
|
67
|
+
|
|
68
|
+
Uses the continuant recursion K_0 = 1, K_1 = a_d,
|
|
69
|
+
K_k = a_{d-k+1} * K_{k-1} + K_{k-2}, which gives f~ = K_{d-1} / K_d
|
|
70
|
+
with a single division, then rewrites that division in log/exp form
|
|
71
|
+
(paper eq. 8) to avoid poles during training.
|
|
72
|
+
|
|
73
|
+
A: (..., d) tensor of partial denominators a_1..a_d. Returns (...,).
|
|
74
|
+
"""
|
|
75
|
+
d = A.shape[-1]
|
|
76
|
+
Km2 = torch.ones_like(A[..., 0]) # K_0 = 1
|
|
77
|
+
Km1 = A[..., -1] # K_1 = a_d
|
|
78
|
+
for k in range(2, d + 1):
|
|
79
|
+
K = A[..., d - k] * Km1 + Km2 # K_k = a_{d-k+1} K_{k-1} + K_{k-2}
|
|
80
|
+
Km2, Km1 = Km1, K
|
|
81
|
+
# after the loop: Km1 = K_d(a_1..a_d), Km2 = K_{d-1}(a_2..a_d)
|
|
82
|
+
num, den = Km2, Km1
|
|
83
|
+
return (
|
|
84
|
+
torch.sign(num)
|
|
85
|
+
* torch.sign(den)
|
|
86
|
+
* torch.exp(
|
|
87
|
+
torch.log(num.abs().clamp_min(1e-12))
|
|
88
|
+
- torch.log(den.abs().clamp_min(eps))
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class CoFrGeNetFNG(nn.Module):
|
|
94
|
+
"""
|
|
95
|
+
Non-Expanding Gated continued-fraction FFN replacement.
|
|
96
|
+
|
|
97
|
+
Params: 2*p^2 (gate) + L*p*(d+1) (ladder coefficients) + L*p (down proj).
|
|
98
|
+
With p=768, L=5, d=5 that is ~1.2M vs ~4.7M for a vanilla FFN (alpha=4).
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, p: int, n_ladders: int = 5, depth: int = 5, eps: float = 0.1):
|
|
102
|
+
super().__init__()
|
|
103
|
+
self.p, self.L, self.d, self.eps = p, n_ladders, depth, eps
|
|
104
|
+
self.gate_up = nn.Linear(p, 2 * p) # non-expanding gated projection
|
|
105
|
+
self.coeffs = nn.Linear(p, (depth + 1) * n_ladders) # a_0..a_d per ladder
|
|
106
|
+
self.down = nn.Linear(n_ladders, p)
|
|
107
|
+
|
|
108
|
+
def forward(self, x):
|
|
109
|
+
a, b = self.gate_up(x).chunk(2, dim=-1)
|
|
110
|
+
z = a * F.silu(b) # gated, still p-dim (expansion factor alpha = 1)
|
|
111
|
+
c = self.coeffs(z).unflatten(-1, (self.L, self.d + 1))
|
|
112
|
+
a0, A = c[..., 0], c[..., 1:] # (..., L) and (..., L, d)
|
|
113
|
+
ladder_out = a0 + continuant_fraction(A, self.eps) # (..., L)
|
|
114
|
+
return self.down(ladder_out)
|
|
File without changes
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Fused Triton forward + backward kernels for CoFrGeNet-FNG ladders.
|
|
2
|
+
|
|
3
|
+
The ladder part of the FNG block is a poor fit for eager PyTorch: a serial
|
|
4
|
+
loop of d tiny elementwise kernels plus a chain of sign/abs/log/exp ops.
|
|
5
|
+
Each (batch, seq) position is independent, so both directions fuse into
|
|
6
|
+
single pointwise kernels.
|
|
7
|
+
|
|
8
|
+
Forward: out = a0 + frac, where frac = K_{d-1} / K_d evaluated by the
|
|
9
|
+
continuant recursion (1 division, paper eqs. 3-6) with the log/exp division
|
|
10
|
+
and clamped denominator (paper eq. 8):
|
|
11
|
+
|
|
12
|
+
frac = num / den_c, num = K_{d-1}, den = K_d,
|
|
13
|
+
den_c = sgn(den) * max(|den|, eps)
|
|
14
|
+
|
|
15
|
+
Backward (analytic adjoint, also division-free):
|
|
16
|
+
|
|
17
|
+
dnum = g * sgn(den) * exp(-log max(|den|, eps))
|
|
18
|
+
dden = -g * frac * sgn(den) * exp(-log max(|den|, eps)) if |den| >= eps
|
|
19
|
+
0 otherwise
|
|
20
|
+
|
|
21
|
+
then backprop through K_k = a_{d-k+1} K_{k-1} + K_{k-2} in reverse:
|
|
22
|
+
for k = d .. 2:
|
|
23
|
+
d a_{d-k+1} = A1 * km1_old
|
|
24
|
+
(A2, A1) = (A1, A1 * a + A2)
|
|
25
|
+
d a_d = A1, d a_0 = g
|
|
26
|
+
|
|
27
|
+
Since Triton jit has no register arrays, km1_old is recomputed per step
|
|
28
|
+
(O(d^2) scalar ops in registers; d <= 8, negligible next to exp/log).
|
|
29
|
+
|
|
30
|
+
Backend selection (at import time):
|
|
31
|
+
* CUDA available -> kernels launch on GPU
|
|
32
|
+
* triton-cpu backend -> set TRITON_DEFAULT_BACKEND=cpu, or it is picked
|
|
33
|
+
automatically when no GPU backend exists.
|
|
34
|
+
Prebuilt wheels: github.com/triton-lang/triton-cpu/releases
|
|
35
|
+
* neither -> falls back to TRITON_INTERPRET=1 (slow, for
|
|
36
|
+
correctness checks only)
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
import os
|
|
40
|
+
|
|
41
|
+
import torch
|
|
42
|
+
import torch.nn.functional as F
|
|
43
|
+
|
|
44
|
+
from .layers import CoFrGeNetFNG
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
import triton
|
|
48
|
+
import triton.language as tl
|
|
49
|
+
|
|
50
|
+
HAS_TRITON = True
|
|
51
|
+
except ImportError: # pragma: no cover - depends on environment
|
|
52
|
+
triton = None
|
|
53
|
+
tl = None
|
|
54
|
+
HAS_TRITON = False
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"HAS_TRITON",
|
|
58
|
+
"triton_backend",
|
|
59
|
+
"ladder_forward",
|
|
60
|
+
"ladder_backward",
|
|
61
|
+
"ladder_apply",
|
|
62
|
+
"CoFrGeNetFNGTriton",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def triton_backend() -> str:
|
|
67
|
+
"""'cuda', 'cpu', 'interpreter', or 'unavailable'."""
|
|
68
|
+
if not HAS_TRITON:
|
|
69
|
+
return "unavailable"
|
|
70
|
+
if torch.cuda.is_available():
|
|
71
|
+
return "cuda"
|
|
72
|
+
if os.environ.get("TRITON_INTERPRET") == "1":
|
|
73
|
+
return "interpreter"
|
|
74
|
+
return "cpu"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _no_triton(*args, **kwargs):
|
|
78
|
+
raise ImportError(
|
|
79
|
+
"triton is not installed. Install it (GPU: pip install triton; "
|
|
80
|
+
"CPU: wheel from github.com/triton-lang/triton-cpu/releases), "
|
|
81
|
+
"or use cofrgenet_fng.CoFrGeNetFNG instead of CoFrGeNetFNGTriton."
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if HAS_TRITON:
|
|
86
|
+
_INTERPRET = False
|
|
87
|
+
if not torch.cuda.is_available():
|
|
88
|
+
# Prefer the triton-cpu backend; fall back to the numpy interpreter.
|
|
89
|
+
try:
|
|
90
|
+
triton.runtime.driver.set_active_to_cpu()
|
|
91
|
+
except (AttributeError, RuntimeError):
|
|
92
|
+
os.environ["TRITON_INTERPRET"] = "1"
|
|
93
|
+
_INTERPRET = True
|
|
94
|
+
|
|
95
|
+
@triton.jit
|
|
96
|
+
def _sign(x):
|
|
97
|
+
# torch.sign semantics: 0 -> 0 (tl.where keeps it branch-free)
|
|
98
|
+
return tl.where(x > 0, 1.0, tl.where(x < 0, -1.0, 0.0))
|
|
99
|
+
|
|
100
|
+
@triton.jit
|
|
101
|
+
def _frac_logexp(num, den, eps):
|
|
102
|
+
# frac = num / (sgn(den) * max(|den|, eps)), via log/exp (paper eq. 8)
|
|
103
|
+
return (
|
|
104
|
+
_sign(num)
|
|
105
|
+
* _sign(den)
|
|
106
|
+
* tl.exp(
|
|
107
|
+
tl.log(tl.maximum(tl.abs(num), 1e-12))
|
|
108
|
+
- tl.log(tl.maximum(tl.abs(den), eps))
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
@triton.jit
|
|
113
|
+
def _ladder_kernel(
|
|
114
|
+
c_ptr, # (N, D1) fp32: per ladder [a0, a_1, ..., a_d]
|
|
115
|
+
out_ptr, # (N,) fp32
|
|
116
|
+
eps,
|
|
117
|
+
N,
|
|
118
|
+
D1: tl.constexpr, # d + 1
|
|
119
|
+
BLOCK: tl.constexpr,
|
|
120
|
+
):
|
|
121
|
+
rows = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
|
|
122
|
+
mask = rows < N
|
|
123
|
+
base = c_ptr + rows * D1
|
|
124
|
+
|
|
125
|
+
a0 = tl.load(base + 0, mask=mask, other=0.0)
|
|
126
|
+
|
|
127
|
+
# continuant recursion K_k = a_{d-k+1} * K_{k-1} + K_{k-2}, from a_d up
|
|
128
|
+
Km2 = tl.full((BLOCK,), 1.0, tl.float32) # K_0
|
|
129
|
+
Km1 = tl.load(base + (D1 - 1), mask=mask, other=0.0) # K_1 = a_d
|
|
130
|
+
for k in tl.static_range(2, D1):
|
|
131
|
+
a = tl.load(base + (D1 - k), mask=mask, other=0.0)
|
|
132
|
+
Km2, Km1 = Km1, a * Km1 + Km2
|
|
133
|
+
# Km1 = K_d(a_1..a_d), Km2 = K_{d-1}(a_2..a_d)
|
|
134
|
+
|
|
135
|
+
tl.store(out_ptr + rows, a0 + _frac_logexp(Km2, Km1, eps), mask=mask)
|
|
136
|
+
|
|
137
|
+
@triton.jit
|
|
138
|
+
def _ladder_bwd_kernel(
|
|
139
|
+
c_ptr, # (N, D1) fp32: forward coefficients [a0, a_1, ..., a_d]
|
|
140
|
+
g_ptr, # (N,) fp32: upstream grad w.r.t. ladder output
|
|
141
|
+
dc_ptr, # (N, D1) fp32: output grads w.r.t. c
|
|
142
|
+
eps,
|
|
143
|
+
N,
|
|
144
|
+
D1: tl.constexpr,
|
|
145
|
+
BLOCK: tl.constexpr,
|
|
146
|
+
):
|
|
147
|
+
rows = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
|
|
148
|
+
mask = rows < N
|
|
149
|
+
base = c_ptr + rows * D1
|
|
150
|
+
g = tl.load(g_ptr + rows, mask=mask, other=0.0)
|
|
151
|
+
|
|
152
|
+
# 1) recompute forward to get num, den, frac (d <= 8: cheap recompute,
|
|
153
|
+
# saves storing O(d) activations)
|
|
154
|
+
Km2 = tl.full((BLOCK,), 1.0, tl.float32)
|
|
155
|
+
Km1 = tl.load(base + (D1 - 1), mask=mask, other=0.0) # K_1 = a_d
|
|
156
|
+
for k in tl.static_range(2, D1):
|
|
157
|
+
a = tl.load(base + (D1 - k), mask=mask, other=0.0)
|
|
158
|
+
Km2, Km1 = Km1, a * Km1 + Km2
|
|
159
|
+
num, den = Km2, Km1
|
|
160
|
+
frac = _frac_logexp(num, den, eps) # frac = num / den_c
|
|
161
|
+
|
|
162
|
+
# 2) adjoint of frac = num / den_c, without explicit divisions
|
|
163
|
+
log_cap = tl.log(tl.maximum(tl.abs(den), eps))
|
|
164
|
+
sgn_den = _sign(den)
|
|
165
|
+
d_num = g * sgn_den * tl.exp(-log_cap) # g / den_c
|
|
166
|
+
d_den = tl.where(
|
|
167
|
+
tl.abs(den) >= eps,
|
|
168
|
+
-g * frac * sgn_den * tl.exp(-log_cap), # -g * frac / den_c
|
|
169
|
+
0.0,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
tl.store(dc_ptr + rows * D1 + 0, g, mask=mask) # d a_0
|
|
173
|
+
|
|
174
|
+
if D1 == 2:
|
|
175
|
+
# d = 1: num = K_0 = 1 is constant, den = a_1
|
|
176
|
+
tl.store(dc_ptr + rows * D1 + 1, d_den, mask=mask)
|
|
177
|
+
else:
|
|
178
|
+
# 3) reverse adjoint of Km2, Km1 = Km1, a * Km1 + Km2
|
|
179
|
+
A2, A1 = d_num, d_den
|
|
180
|
+
for i in range(0, D1 - 2):
|
|
181
|
+
rev_k = (D1 - 1) - i # reverse step: d, d-1, ..., 2
|
|
182
|
+
a = tl.load(base + (D1 - rev_k), mask=mask, other=0.0)
|
|
183
|
+
|
|
184
|
+
# recompute state (v2, v1) before step rev_k (steps 2 .. rev_k-1)
|
|
185
|
+
v2 = tl.full((BLOCK,), 1.0, tl.float32)
|
|
186
|
+
v1 = tl.load(base + (D1 - 1), mask=mask, other=0.0)
|
|
187
|
+
for jj in range(0, rev_k - 2):
|
|
188
|
+
aj = tl.load(base + (D1 - jj - 2), mask=mask, other=0.0)
|
|
189
|
+
v2, v1 = v1, aj * v1 + v2
|
|
190
|
+
|
|
191
|
+
d_a = A1 * v1 # grad w.r.t. the coefficient consumed at step rev_k
|
|
192
|
+
tl.store(dc_ptr + rows * D1 + (D1 - rev_k), d_a, mask=mask)
|
|
193
|
+
A2, A1 = A1, A1 * a + A2
|
|
194
|
+
tl.store(dc_ptr + rows * D1 + (D1 - 1), A1, mask=mask) # d a_d
|
|
195
|
+
|
|
196
|
+
def ladder_forward(c: torch.Tensor, eps: float = 0.1) -> torch.Tensor:
|
|
197
|
+
"""c: (..., L, d+1) coefficients [a0, a_1..a_d] -> (..., L) outputs."""
|
|
198
|
+
shape = c.shape
|
|
199
|
+
c2 = c.reshape(-1, shape[-1]).contiguous().float()
|
|
200
|
+
n = c2.shape[0]
|
|
201
|
+
out = torch.empty(n, device=c2.device, dtype=torch.float32)
|
|
202
|
+
block = 256
|
|
203
|
+
_ladder_kernel[(triton.cdiv(n, block),)](
|
|
204
|
+
c2, out, eps, n, D1=shape[-1], BLOCK=block
|
|
205
|
+
)
|
|
206
|
+
return out.reshape(shape[:-1])
|
|
207
|
+
|
|
208
|
+
def ladder_backward(
|
|
209
|
+
c: torch.Tensor, grad_out: torch.Tensor, eps: float = 0.1
|
|
210
|
+
) -> torch.Tensor:
|
|
211
|
+
"""Gradient w.r.t. c for ladder_forward; grad_out has shape (..., L)."""
|
|
212
|
+
shape = c.shape
|
|
213
|
+
c2 = c.reshape(-1, shape[-1]).contiguous().float()
|
|
214
|
+
g2 = grad_out.reshape(-1).contiguous().float()
|
|
215
|
+
dc = torch.empty_like(c2)
|
|
216
|
+
block = 256
|
|
217
|
+
_ladder_bwd_kernel[(triton.cdiv(c2.shape[0], block),)](
|
|
218
|
+
c2, g2, dc, eps, c2.shape[0], D1=shape[-1], BLOCK=block
|
|
219
|
+
)
|
|
220
|
+
return dc.reshape(shape)
|
|
221
|
+
|
|
222
|
+
class _LadderTritonFn(torch.autograd.Function):
|
|
223
|
+
@staticmethod
|
|
224
|
+
def forward(ctx, c, eps: float):
|
|
225
|
+
ctx.save_for_backward(c)
|
|
226
|
+
ctx.eps = float(eps)
|
|
227
|
+
return ladder_forward(c, eps)
|
|
228
|
+
|
|
229
|
+
@staticmethod
|
|
230
|
+
def backward(ctx, grad_out):
|
|
231
|
+
(c,) = ctx.saved_tensors
|
|
232
|
+
return ladder_backward(c, grad_out, ctx.eps), None
|
|
233
|
+
|
|
234
|
+
def ladder_apply(c: torch.Tensor, eps: float = 0.1) -> torch.Tensor:
|
|
235
|
+
"""Differentiable continued-fraction ladder (fused fwd + bwd)."""
|
|
236
|
+
return _LadderTritonFn.apply(c, eps)
|
|
237
|
+
|
|
238
|
+
class CoFrGeNetFNGTriton(CoFrGeNetFNG):
|
|
239
|
+
"""CoFrGeNetFNG whose ladder runs the fused Triton fwd+bwd kernels.
|
|
240
|
+
|
|
241
|
+
Same parameters / state_dict as CoFrGeNetFNG; input/output are fp32
|
|
242
|
+
(the surrounding gate_up, coeffs and down layers stay in autograd)."""
|
|
243
|
+
|
|
244
|
+
def forward(self, x):
|
|
245
|
+
a, b = self.gate_up(x).chunk(2, dim=-1)
|
|
246
|
+
z = a * F.silu(b)
|
|
247
|
+
c = self.coeffs(z).unflatten(-1, (self.L, self.d + 1))
|
|
248
|
+
return self.down(ladder_apply(c, self.eps))
|
|
249
|
+
|
|
250
|
+
else:
|
|
251
|
+
ladder_forward = _no_triton
|
|
252
|
+
ladder_backward = _no_triton
|
|
253
|
+
ladder_apply = _no_triton
|
|
254
|
+
|
|
255
|
+
class CoFrGeNetFNGTriton(CoFrGeNetFNG):
|
|
256
|
+
def forward(self, x):
|
|
257
|
+
_no_triton()
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cofrgenet-torch
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: PyTorch implementation of CoFrGeNet-FNG: non-expanding gated continued-fraction feed-forward layers (arXiv:2611.26835) with fused Triton fwd/bwd kernels
|
|
5
|
+
Author: tpoisonooo
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/tpoisonooo/fng
|
|
8
|
+
Project-URL: Issues, https://github.com/tpoisonooo/fng/issues
|
|
9
|
+
Project-URL: Paper, https://arxiv.org/abs/2611.26835
|
|
10
|
+
Keywords: continued-fraction,cofrgenet,cofrnet,ffn,transformer,pytorch,triton
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: torch>=2.0
|
|
24
|
+
Provides-Extra: triton
|
|
25
|
+
Requires-Dist: triton>=3.0; extra == "triton"
|
|
26
|
+
Provides-Extra: test
|
|
27
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# CoFrGeNet-FNG (unofficial PyTorch implementation)
|
|
31
|
+
|
|
32
|
+
English | [简体中文](README.zh-CN.md)
|
|
33
|
+
|
|
34
|
+
Unofficial PyTorch implementation of **CoFrGeNet-FNG** — the *Non-Expanding
|
|
35
|
+
Gated Continued Fraction* feed-forward layer from IBM Research's paper
|
|
36
|
+
[Non-Expanding Gated Continued Fraction Architecture for Feedforward Layers
|
|
37
|
+
in Language Models](https://arxiv.org/abs/2611.26835) (NeurIPS 2026) — plus
|
|
38
|
+
classic FFN baselines and a fused Triton kernel for the continued-fraction
|
|
39
|
+
ladders.
|
|
40
|
+
|
|
41
|
+
> **Note:** This is an independent, from-the-paper implementation. The
|
|
42
|
+
> authors' official repository, [IBM/CoFrNets](https://github.com/IBM/CoFrNets),
|
|
43
|
+
> had not published code at the time of writing.
|
|
44
|
+
|
|
45
|
+
## What is CoFrGeNet-FNG?
|
|
46
|
+
|
|
47
|
+
A drop-in replacement for the FFN sublayer of transformer (and SSM/MoE)
|
|
48
|
+
blocks with the same `(…, p) -> (…, p)` API, but ~4x fewer parameters:
|
|
49
|
+
|
|
50
|
+
1. **Non-expanding gated projection**: `x ∈ R^p → z ∈ R^p` (expansion
|
|
51
|
+
factor α = 1), computed as `z = a ⊙ silu(b)` where `[a, b]` is a split
|
|
52
|
+
of one linear map — 2p² parameters.
|
|
53
|
+
2. **L continued-fraction ladders of depth d**: each ladder has d+1 learned
|
|
54
|
+
coefficient vectors, a_k = w_kᵀz, and evaluates the rational function
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
f~(a_1..a_d) = 1/(a_1 + 1/(a_2 + ... + 1/a_d))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
via the continuant recursion (paper eqs. 3–6), needing only **one**
|
|
61
|
+
division per ladder instead of d.
|
|
62
|
+
3. **log/exp division** (paper eq. 8): the remaining division is rewritten
|
|
63
|
+
as `sgn·sgn·exp(log|num| − log max(|den|, ε))`, which stabilizes training
|
|
64
|
+
of deep ladders (d > 1) **without** the incremental training schedule
|
|
65
|
+
required by the original CoFrGeNet.
|
|
66
|
+
4. A linear projection `R^L → R^p`.
|
|
67
|
+
|
|
68
|
+
Parameter count: `2p² + L·p·(d+1) + L·p` vs. `2αp²` for a vanilla FFN or
|
|
69
|
+
`3αp²` for SwiGLU (α ≥ 2).
|
|
70
|
+
|
|
71
|
+
## Install
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
# from PyPI
|
|
75
|
+
pip install cofrgenet-torch # torch is the only hard dependency
|
|
76
|
+
pip install "cofrgenet-torch[triton]" # optional: fused Triton fwd+bwd (GPU)
|
|
77
|
+
|
|
78
|
+
# or from source (this repo)
|
|
79
|
+
pip install -e .
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Optional, for the fused Triton ladder kernels:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
# GPU
|
|
86
|
+
pip install triton
|
|
87
|
+
# CPU (experimental triton-cpu backend, pick your platform/python)
|
|
88
|
+
pip install "https://github.com/triton-lang/triton-cpu/releases/download/v3.8.0/triton-3.8.0%2Bcpu-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Note: install the triton-cpu wheel **last**. torch pins its own triton
|
|
92
|
+
build, so a later `pip install` that touches torch's dependencies may
|
|
93
|
+
replace the `+cpu` wheel with mainline triton (which has no CPU backend).
|
|
94
|
+
|
|
95
|
+
## Quickstart
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import torch
|
|
99
|
+
from cofrgenet_fng import CoFrGeNetFNG
|
|
100
|
+
|
|
101
|
+
ffn = CoFrGeNetFNG(p=768, n_ladders=5, depth=5) # same API as an FFN
|
|
102
|
+
x = torch.randn(2, 128, 768)
|
|
103
|
+
y = ffn(x) # (2, 128, 768)
|
|
104
|
+
|
|
105
|
+
sum(t.numel() for t in ffn.parameters()) # 1,208,862 (vs 4.7M vanilla FFN)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Examples
|
|
109
|
+
|
|
110
|
+
Run from the repo root.
|
|
111
|
+
|
|
112
|
+
### `fng_vs_ffn.py` — FNG vs. FFN baselines
|
|
113
|
+
|
|
114
|
+
Verifies the continuant math, then compares parameters, speed, and learning
|
|
115
|
+
on a teacher-student task. Measured on an 8-core CPU (torch 2.9.1):
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
module params vs FFN fwd+bwd
|
|
119
|
+
VanillaFFN (alpha=4) 4,722,432 1.00x 259.90 ms
|
|
120
|
+
SwiGLUFFN (alpha=8/3) 4,723,456 1.00x 234.54 ms
|
|
121
|
+
CoFrGeNetFNG (L=5, d=5) 1,208,862 0.26x 69.60 ms
|
|
122
|
+
CoFrGeNetFNG (L=8, d=8) 1,243,464 0.26x 74.09 ms
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
On the toy fitting task the FNG block uses 3x fewer parameters but converges
|
|
126
|
+
slower than a full-size FFN — consistent with the paper, whose parity/better
|
|
127
|
+
results are at language-model pre-training scale, not tiny regression tasks.
|
|
128
|
+
|
|
129
|
+
### `fng_triton.py` — fused Triton ladder kernel
|
|
130
|
+
|
|
131
|
+
The ladder is a serial loop of tiny elementwise ops in eager PyTorch; the
|
|
132
|
+
kernel fuses **both forward and backward** into pointwise passes (forward:
|
|
133
|
+
continuant recursion + one log/exp division; backward: analytic adjoint,
|
|
134
|
+
also division-free, exposed via `ladder_apply` / `CoFrGeNetFNGTriton`).
|
|
135
|
+
Measured with the triton-cpu backend (forward; numbers on a shared CPU vary
|
|
136
|
+
run to run; the ladder-only speedup is the consistent part — at whole-block
|
|
137
|
+
level the p→2p GEMM dominates and the difference is within noise):
|
|
138
|
+
|
|
139
|
+
```
|
|
140
|
+
(B=16, S=256, L=8, d=8) N=32,768 ladders: eager 0.679 ms | triton 0.164 ms (4.13x)
|
|
141
|
+
(B=64, S=1024, L=16, d=8) N=1,048,576 ladders: eager 16.262 ms | triton 5.945 ms (2.74x)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Run it with `TRITON_DEFAULT_BACKEND=cpu python fng_triton.py` (or on a GPU,
|
|
145
|
+
plain `python fng_triton.py`).
|
|
146
|
+
|
|
147
|
+
### `mnist_train.py` — MNIST forward + backward training test
|
|
148
|
+
|
|
149
|
+
End-to-end training on CPU (8 epochs, batch 256, AdamW lr=5e-4, grad clip 1.0)
|
|
150
|
+
of the same tiny residual classifier with the three FFN-style blocks swapped.
|
|
151
|
+
Data is fetched directly from the MNIST IDX mirrors (no torchvision needed).
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
block params test_acc @8 step
|
|
155
|
+
ffn 233,738 97.66% 5.0 ms
|
|
156
|
+
fng-eager 149,610 93.76% 5.9 ms
|
|
157
|
+
fng-triton 149,610 93.23% 5.1 ms
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`fng-triton` uses the fused Triton forward + backward kernels in the ladder
|
|
161
|
+
and tracks `fng-eager` to within small floating-point drift. With
|
|
162
|
+
`depth=5, L=16` the FNG block reaches ~93–94% at 0.64x the parameters of the
|
|
163
|
+
FFN; `depth=8` is noticeably harder to optimize at this small scale.
|
|
164
|
+
|
|
165
|
+
Run it with `TRITON_DEFAULT_BACKEND=cpu python mnist_train.py`.
|
|
166
|
+
|
|
167
|
+
## Tests
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
pip install pytest
|
|
171
|
+
pytest -v # triton tests are skipped automatically if unavailable
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Repository layout
|
|
175
|
+
|
|
176
|
+
```
|
|
177
|
+
cofrgenet_fng/ the package
|
|
178
|
+
layers.py VanillaFFN, SwiGLUFFN, CoFrGeNetFNG, continuant_fraction
|
|
179
|
+
triton_ladder.py fused Triton fwd+bwd kernels (optional), CoFrGeNetFNGTriton
|
|
180
|
+
fng_vs_ffn.py example: FNG vs. FFN baselines
|
|
181
|
+
fng_triton.py example: Triton kernel correctness + benchmarks
|
|
182
|
+
mnist_train.py example: MNIST forward + backward training test
|
|
183
|
+
tests/ pytest suite
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
## Citation
|
|
187
|
+
|
|
188
|
+
```bibtex
|
|
189
|
+
@article{dhurandhar2026cofrgenetfng,
|
|
190
|
+
title = {Non-Expanding Gated Continued Fraction Architecture for Feedforward Layers in Language Models},
|
|
191
|
+
author = {Dhurandhar, Amit and Chenthamarakshan, Vijil and Ramamurthy, Karthikeyan Natesan and Wei, Dennis and Nair, Rahul},
|
|
192
|
+
journal = {arXiv:2611.26835},
|
|
193
|
+
year = {2026}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
@inproceedings{dhurandhar2026cofrgenet,
|
|
197
|
+
title = {CoFrGeNet: Continued Fraction Architectures for Language Generation},
|
|
198
|
+
author = {Dhurandhar, A. and Chenthamarakshan, V. and Wei, D. and Pedapati, T. and Ramamurthy, K. N. and Nair, R.},
|
|
199
|
+
booktitle = {Proceedings of the 43rd International Conference on Machine Learning (ICML)},
|
|
200
|
+
year = {2026}
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
cofrgenet_fng/__init__.py
|
|
5
|
+
cofrgenet_fng/layers.py
|
|
6
|
+
cofrgenet_fng/py.typed
|
|
7
|
+
cofrgenet_fng/triton_ladder.py
|
|
8
|
+
cofrgenet_torch.egg-info/PKG-INFO
|
|
9
|
+
cofrgenet_torch.egg-info/SOURCES.txt
|
|
10
|
+
cofrgenet_torch.egg-info/dependency_links.txt
|
|
11
|
+
cofrgenet_torch.egg-info/requires.txt
|
|
12
|
+
cofrgenet_torch.egg-info/top_level.txt
|
|
13
|
+
tests/test_layers.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cofrgenet_fng
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cofrgenet-torch"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "PyTorch implementation of CoFrGeNet-FNG: non-expanding gated continued-fraction feed-forward layers (arXiv:2611.26835) with fused Triton fwd/bwd kernels"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "tpoisonooo" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"continued-fraction",
|
|
15
|
+
"cofrgenet",
|
|
16
|
+
"cofrnet",
|
|
17
|
+
"ffn",
|
|
18
|
+
"transformer",
|
|
19
|
+
"pytorch",
|
|
20
|
+
"triton",
|
|
21
|
+
]
|
|
22
|
+
classifiers = [
|
|
23
|
+
"Development Status :: 3 - Alpha",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Intended Audience :: Science/Research",
|
|
26
|
+
"Programming Language :: Python :: 3",
|
|
27
|
+
"Programming Language :: Python :: 3.10",
|
|
28
|
+
"Programming Language :: Python :: 3.11",
|
|
29
|
+
"Programming Language :: Python :: 3.12",
|
|
30
|
+
"Programming Language :: Python :: 3.13",
|
|
31
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
32
|
+
]
|
|
33
|
+
requires-python = ">=3.10"
|
|
34
|
+
dependencies = ["torch>=2.0"]
|
|
35
|
+
|
|
36
|
+
[project.optional-dependencies]
|
|
37
|
+
triton = ["triton>=3.0"]
|
|
38
|
+
test = ["pytest>=7"]
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Repository = "https://github.com/tpoisonooo/fng"
|
|
42
|
+
Issues = "https://github.com/tpoisonooo/fng/issues"
|
|
43
|
+
Paper = "https://arxiv.org/abs/2611.26835"
|
|
44
|
+
|
|
45
|
+
[tool.setuptools]
|
|
46
|
+
packages = ["cofrgenet_fng"]
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.package-data]
|
|
49
|
+
cofrgenet_fng = ["py.typed"]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
from cofrgenet_fng import (
|
|
5
|
+
HAS_TRITON,
|
|
6
|
+
CoFrGeNetFNG,
|
|
7
|
+
CoFrGeNetFNGTriton,
|
|
8
|
+
SwiGLUFFN,
|
|
9
|
+
VanillaFFN,
|
|
10
|
+
continuant_fraction,
|
|
11
|
+
ladder_apply,
|
|
12
|
+
ladder_forward,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def naive_fraction(A: torch.Tensor) -> torch.Tensor:
|
|
17
|
+
"""Direct recursive evaluation of f~ (d divisions, for checking only)."""
|
|
18
|
+
f = A[..., -1]
|
|
19
|
+
for k in range(A.shape[-1] - 1, 0, -1):
|
|
20
|
+
f = A[..., k - 1] + 1.0 / f
|
|
21
|
+
return 1.0 / f
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.mark.parametrize("d", [1, 2, 3, 5, 8])
|
|
25
|
+
def test_continuant_matches_naive(d):
|
|
26
|
+
torch.manual_seed(0)
|
|
27
|
+
# float64: verifies the math exactly (fp32 near a pole is ill-conditioned)
|
|
28
|
+
A = torch.randn(10000, d, dtype=torch.float64) * 2
|
|
29
|
+
ref = naive_fraction(A)
|
|
30
|
+
fast = continuant_fraction(A, eps=1e-9)
|
|
31
|
+
# near a pole the two parameterizations legitimately differ; skip those
|
|
32
|
+
mask = ref.abs() < 50
|
|
33
|
+
assert mask.sum() > 9000
|
|
34
|
+
err = (ref[mask] - fast[mask]).abs().max().item()
|
|
35
|
+
assert err < 1e-8
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_depth1_is_clamped_reciprocal():
|
|
39
|
+
a1 = torch.tensor([0.05, -0.05, 2.0, -2.0]).unsqueeze(-1) # (4, d=1)
|
|
40
|
+
out = continuant_fraction(a1, eps=0.1) # (..., d) -> (...,)
|
|
41
|
+
expected = torch.tensor([10.0, -10.0, 0.5, -0.5])
|
|
42
|
+
assert out.shape == (4,)
|
|
43
|
+
assert torch.allclose(out, expected)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.mark.parametrize("module", [VanillaFFN(32), SwiGLUFFN(32), CoFrGeNetFNG(32, 4, 5)])
|
|
47
|
+
def test_module_api(module):
|
|
48
|
+
x = torch.randn(2, 3, 32)
|
|
49
|
+
y = module(x)
|
|
50
|
+
assert y.shape == x.shape
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_fng_param_count():
|
|
54
|
+
p, L, d = 768, 5, 5
|
|
55
|
+
m = CoFrGeNetFNG(p, L, d)
|
|
56
|
+
expected = (
|
|
57
|
+
(2 * p * p + 2 * p) # gate_up weight + bias
|
|
58
|
+
+ ((d + 1) * L * p + (d + 1) * L) # coeffs weight + bias
|
|
59
|
+
+ (L * p + p) # down weight + bias
|
|
60
|
+
)
|
|
61
|
+
assert sum(t.numel() for t in m.parameters()) == expected
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@pytest.mark.parametrize("d", [2, 5, 8])
|
|
65
|
+
def test_deep_ladder_gradients_finite(d):
|
|
66
|
+
"""The log/exp division (paper eq. 8) is what makes d > 1 trainable
|
|
67
|
+
without the incremental training schedule of the original CoFrGeNet."""
|
|
68
|
+
torch.manual_seed(0)
|
|
69
|
+
m = CoFrGeNetFNG(64, n_ladders=8, depth=d)
|
|
70
|
+
x = torch.randn(32, 64)
|
|
71
|
+
m(x).pow(2).mean().backward()
|
|
72
|
+
for name, t in m.named_parameters():
|
|
73
|
+
assert t.grad is not None, name
|
|
74
|
+
assert torch.isfinite(t.grad).all(), name
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@pytest.mark.skipif(not HAS_TRITON, reason="triton not installed")
|
|
78
|
+
@pytest.mark.parametrize("d", [1, 2, 5, 8])
|
|
79
|
+
def test_triton_ladder_matches_eager(d):
|
|
80
|
+
torch.manual_seed(0)
|
|
81
|
+
c = torch.randn(4096, 8, d + 1) * 2
|
|
82
|
+
ref = c[..., 0] + continuant_fraction(c[..., 1:], eps=0.1)
|
|
83
|
+
got = ladder_forward(c, eps=0.1)
|
|
84
|
+
# near a pole |f~| is huge and both fp32 evaluations carry ~1e-4 noise,
|
|
85
|
+
# so judge by relative error with a depth-tolerant bound
|
|
86
|
+
err = ((ref - got).abs() / ref.abs().clamp_min(1.0)).max().item()
|
|
87
|
+
assert err < 1e-3
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@pytest.mark.skipif(not HAS_TRITON, reason="triton not installed")
|
|
91
|
+
@pytest.mark.parametrize("d", [1, 2, 5, 8])
|
|
92
|
+
@pytest.mark.parametrize("eps", [0.1, 2.0]) # 2.0 exercises the clamped branch
|
|
93
|
+
def test_triton_backward_matches_eager(d, eps):
|
|
94
|
+
torch.manual_seed(0)
|
|
95
|
+
c = (torch.randn(64, 8, d + 1) * 1.5).requires_grad_(True)
|
|
96
|
+
c_ref = c.detach().clone().requires_grad_(True)
|
|
97
|
+
g = torch.randn(64, 8)
|
|
98
|
+
|
|
99
|
+
# eager reference (autograd through continuant recursion + log/exp)
|
|
100
|
+
out_ref = c_ref[..., 0] + continuant_fraction(c_ref[..., 1:], eps=eps)
|
|
101
|
+
out_ref.backward(g)
|
|
102
|
+
|
|
103
|
+
# fused triton forward + backward
|
|
104
|
+
out = ladder_apply(c, eps=eps)
|
|
105
|
+
assert torch.allclose(out, out_ref, rtol=1e-3, atol=1e-3)
|
|
106
|
+
out.backward(g)
|
|
107
|
+
|
|
108
|
+
assert torch.isfinite(c.grad).all()
|
|
109
|
+
err = ((c.grad - c_ref.grad).abs() / c_ref.grad.abs().clamp_min(1.0)).max()
|
|
110
|
+
assert err < 1e-3, err
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@pytest.mark.skipif(not HAS_TRITON, reason="triton not installed")
|
|
114
|
+
@pytest.mark.parametrize("d", [1, 2, 5, 8])
|
|
115
|
+
def test_triton_backward_clamped_denominator(d):
|
|
116
|
+
"""Tiny nonzero coefficients: |den| << eps exercises the clamp branch."""
|
|
117
|
+
c = torch.randn(128, 4, d + 1).requires_grad_(True)
|
|
118
|
+
with torch.no_grad():
|
|
119
|
+
c[..., 1:] *= 1e-6
|
|
120
|
+
c_ref = c.detach().clone().requires_grad_(True)
|
|
121
|
+
g = torch.randn(128, 4)
|
|
122
|
+
|
|
123
|
+
(c_ref[..., 0] + continuant_fraction(c_ref[..., 1:], eps=0.1)).backward(g)
|
|
124
|
+
ladder_apply(c, eps=0.1).backward(g)
|
|
125
|
+
|
|
126
|
+
assert torch.isfinite(c.grad).all()
|
|
127
|
+
assert torch.allclose(c.grad, c_ref.grad, rtol=1e-3, atol=1e-3)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@pytest.mark.skipif(not HAS_TRITON, reason="triton not installed")
|
|
131
|
+
def test_triton_backward_at_zero_numerator():
|
|
132
|
+
"""d=2, a1=a2=0 -> num=a2=0, den=1, so frac=a2 and d frac/d a2 = 1.
|
|
133
|
+
(eager autograd returns 0 at a2=0 only because torch.abs(0).grad == 0;
|
|
134
|
+
the analytic adjoint gives the true derivative of num / den_c.)"""
|
|
135
|
+
c = torch.zeros(16, 4, 3, requires_grad=True)
|
|
136
|
+
g = torch.randn(16, 4)
|
|
137
|
+
ladder_apply(c, eps=0.1).backward(g)
|
|
138
|
+
assert torch.allclose(c.grad[..., 0], g)
|
|
139
|
+
assert torch.allclose(c.grad[..., 1], torch.zeros_like(g))
|
|
140
|
+
assert torch.allclose(c.grad[..., 2], g)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@pytest.mark.skipif(not HAS_TRITON, reason="triton not installed")
|
|
144
|
+
def test_triton_module_matches_eager_module():
|
|
145
|
+
torch.manual_seed(0)
|
|
146
|
+
eager = CoFrGeNetFNG(64, n_ladders=8, depth=5)
|
|
147
|
+
fast = CoFrGeNetFNGTriton(64, n_ladders=8, depth=5)
|
|
148
|
+
fast.load_state_dict(eager.state_dict())
|
|
149
|
+
|
|
150
|
+
x = torch.randn(16, 7, 64)
|
|
151
|
+
y_ref = eager(x)
|
|
152
|
+
y = fast(x)
|
|
153
|
+
assert torch.allclose(y, y_ref, rtol=1e-3, atol=1e-3)
|
|
154
|
+
|
|
155
|
+
y_ref.pow(2).mean().backward()
|
|
156
|
+
y.pow(2).mean().backward()
|
|
157
|
+
for (n1, p1), (n2, p2) in zip(eager.named_parameters(), fast.named_parameters()):
|
|
158
|
+
assert n1 == n2
|
|
159
|
+
assert p1.grad is not None and p2.grad is not None, n1
|
|
160
|
+
assert torch.allclose(p1.grad, p2.grad, rtol=1e-2, atol=1e-4), (
|
|
161
|
+
n1,
|
|
162
|
+
(p1.grad - p2.grad).abs().max().item(),
|
|
163
|
+
)
|