stackformers 3.9.0__tar.gz → 3.9.2__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.
- stackformers-3.9.2/CHANGELOG.md +219 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/PKG-INFO +1 -1
- {stackformers-3.9.0 → stackformers-3.9.2}/pyproject.toml +1 -1
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/README.md +4 -2
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/ops.py +8 -57
- stackformers-3.9.2/stackformers/attention/varlen_backend.py +88 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/rope2d.py +15 -5
- stackformers-3.9.2/tests/attention/test_varlen_backend.py +122 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/positional/test_rope.py +163 -8
- {stackformers-3.9.0 → stackformers-3.9.2}/uv.lock +1 -1
- {stackformers-3.9.0 → stackformers-3.9.2}/.claudeignore +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/.gitignore +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/.python-version +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/.vscode/settings.json +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/CLAUDE.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/Justfile +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/LICENSE +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/PLAN.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/README.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/bias.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/config.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/cross_attn.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/protocols.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/attention/self_attn.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/config.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/cross_attender.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/decoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/encoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/README.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/config.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/factory.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/geglu.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/protocols.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/relu_squared.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/feedforward/swiglu.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/layers.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/norm/README.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/norm/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/norm/config.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/norm/factory.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/norm/protocols.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/README.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/config.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/factory.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/learned.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/none.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/protocols.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/positional/rope1d.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/presets/README.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/presets/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/presets/cross_attender.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/presets/decoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/presets/encoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/presets/pyramid_vision.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/sequence.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/README.md +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/config.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/factory.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/input.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/kv_reduction.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/layer.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/patch_merging.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/protocols.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/spatial_reduction.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/stackformers/spatial/window.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/attention/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/attention/test_cross_attn.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/attention/test_kernels.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/attention/test_ops.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/attention/test_self_attn.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/conftest.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/feedforward/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/feedforward/test_geglu.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/feedforward/test_relu_squared.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/feedforward/test_swiglu.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/positional/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/positional/test_learned_pos.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/presets/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/presets/test_cross_attender.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/presets/test_decoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/presets/test_encoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/presets/test_pyramid_vision.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/__init__.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/test_input.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/test_kv_reduction.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/test_layer.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/test_patch_merging.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/test_spatial_reduction.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/spatial/test_window.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/test_cross_attender.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/test_decoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/test_encoder.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/test_layers.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/test_norm.py +0 -0
- {stackformers-3.9.0 → stackformers-3.9.2}/tests/test_sequence.py +0 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here.
|
|
4
|
+
|
|
5
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
|
|
6
|
+
adheres to [Semantic Versioning](https://semver.org/): MAJOR for breaking public API changes,
|
|
7
|
+
MINOR for backwards-compatible features, PATCH for bug fixes and internal changes.
|
|
8
|
+
|
|
9
|
+
## [3.9.2] — 2026-07-14
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **`RotaryEmbedding2D` was not computing a rotation.** The frequency vector was laid out as
|
|
14
|
+
`[row | row | col | col]`, but `_rotate_half` pairs channel `i` with channel `i + dh/2`, so a
|
|
15
|
+
row angle was paired against a column angle. The resulting 2×2 map had
|
|
16
|
+
`det = cos((row − col) · ωᵢ)` and singular values `√(1 ± |sin D|)` — a squeeze, not a rotation.
|
|
17
|
+
It was therefore non-orthogonal, annihilated high-frequency channels wherever the determinant
|
|
18
|
+
reached zero, and produced attention scores that leaked absolute position instead of depending
|
|
19
|
+
only on relative offset. Frequencies are now built as `[row | col | row | col]`.
|
|
20
|
+
- `RotaryEmbedding2D` now casts positions and `inv_freq` to float32 for the outer product,
|
|
21
|
+
matching `RotaryEmbedding1D`. A `.half()`-ed module previously lost position precision.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- **Numerics of `RotaryEmbedding2D` change.** Any checkpoint trained against the previous
|
|
26
|
+
encoding is tuned to the broken position code and requires retraining or finetuning.
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
|
|
30
|
+
- Math tests for `RotaryEmbedding2D` on a genuine row-major grid: a definition-first reference
|
|
31
|
+
oracle, orthogonality (norms and inner products), relative-offset invariance, per-axis
|
|
32
|
+
sensitivity, distinct-offset separation, and packed/padded agreement. The previous test used a
|
|
33
|
+
`row == col` position grid — the main diagonal, the one locus where the row and column angles
|
|
34
|
+
coincide and the broken layout is indistinguishable from a correct one.
|
|
35
|
+
|
|
36
|
+
## [3.9.1] — 2026-06-30
|
|
37
|
+
|
|
38
|
+
### Fixed
|
|
39
|
+
|
|
40
|
+
- Make the experimental `varlen_attn` import and call robust across PyTorch versions.
|
|
41
|
+
|
|
42
|
+
## [3.9.0] — 2026-06-17
|
|
43
|
+
|
|
44
|
+
### Added
|
|
45
|
+
|
|
46
|
+
- 2-D grid attention (`spatial`) and the pyramid vision backbone preset.
|
|
47
|
+
|
|
48
|
+
## [3.8.2] — 2026-05-29
|
|
49
|
+
|
|
50
|
+
### Fixed
|
|
51
|
+
|
|
52
|
+
- Force absolute positions to float32 in `sequence`.
|
|
53
|
+
|
|
54
|
+
## [3.8.1] — 2026-05-29
|
|
55
|
+
|
|
56
|
+
### Fixed
|
|
57
|
+
|
|
58
|
+
- Keep batch size as a `SymInt` in the packed attention fallback, preserving `torch.export`
|
|
59
|
+
compatibility.
|
|
60
|
+
|
|
61
|
+
## [3.8.0] — 2026-05-27
|
|
62
|
+
|
|
63
|
+
### Fixed
|
|
64
|
+
|
|
65
|
+
- Replace `.tolist()` loops in `sequence` and `ops` with tensor operations, making them
|
|
66
|
+
`torch.export`-compatible.
|
|
67
|
+
|
|
68
|
+
### Added
|
|
69
|
+
|
|
70
|
+
- PyPI publish metadata in `pyproject.toml`.
|
|
71
|
+
|
|
72
|
+
## [3.7.0] — 2026-05-21
|
|
73
|
+
|
|
74
|
+
### Changed
|
|
75
|
+
|
|
76
|
+
- Introduce abstract generic base classes for all presets.
|
|
77
|
+
|
|
78
|
+
## [3.6.0] — 2026-05-21
|
|
79
|
+
|
|
80
|
+
### Added
|
|
81
|
+
|
|
82
|
+
- `AttnBias` protocol and the `NoAttnBias` null object on `SelfAttention`.
|
|
83
|
+
|
|
84
|
+
## [3.5.2] — 2026-05-21
|
|
85
|
+
|
|
86
|
+
### Fixed
|
|
87
|
+
|
|
88
|
+
- Warn and fall back to SDPA when `varlen_attn` raises.
|
|
89
|
+
|
|
90
|
+
## [3.5.1] — 2026-05-18
|
|
91
|
+
|
|
92
|
+
### Changed
|
|
93
|
+
|
|
94
|
+
- Move attention dropout to the output projection.
|
|
95
|
+
|
|
96
|
+
## [3.5.0] — 2026-05-18
|
|
97
|
+
|
|
98
|
+
### Added
|
|
99
|
+
|
|
100
|
+
- Packed→padded SDPA fallback; extract `ops.py`.
|
|
101
|
+
|
|
102
|
+
## [3.4.2] — 2026-05-18
|
|
103
|
+
|
|
104
|
+
### Added
|
|
105
|
+
|
|
106
|
+
- `padded_to_packed` and `packed_to_padded` helpers.
|
|
107
|
+
|
|
108
|
+
## [3.4.1] — 2026-05-18
|
|
109
|
+
|
|
110
|
+
### Removed
|
|
111
|
+
|
|
112
|
+
- Packed-attention CPU fallback; warn on dropout instead.
|
|
113
|
+
|
|
114
|
+
## [3.4.0] — 2026-05-17
|
|
115
|
+
|
|
116
|
+
### Added
|
|
117
|
+
|
|
118
|
+
- ReLU² feed-forward network.
|
|
119
|
+
|
|
120
|
+
## [3.3.0] — 2026-05-17
|
|
121
|
+
|
|
122
|
+
### Added
|
|
123
|
+
|
|
124
|
+
- QK-norm in attention; all config fields documented.
|
|
125
|
+
|
|
126
|
+
## [3.2.0] — 2026-05-17
|
|
127
|
+
|
|
128
|
+
### Changed
|
|
129
|
+
|
|
130
|
+
- Eliminate layout-specific duplicates in positional encoding implementations.
|
|
131
|
+
|
|
132
|
+
## [3.1.0] — 2026-05-17
|
|
133
|
+
|
|
134
|
+
### Changed
|
|
135
|
+
|
|
136
|
+
- Replace `forward()` on positional encodings with `forward_padded` / `forward_packed`, so
|
|
137
|
+
callers pick the path for the layout they already know.
|
|
138
|
+
|
|
139
|
+
## [3.0.1] — 2026-05-17
|
|
140
|
+
|
|
141
|
+
### Fixed
|
|
142
|
+
|
|
143
|
+
- Use the GELU tanh approximation in GEGLU.
|
|
144
|
+
|
|
145
|
+
## [3.0.0] — 2026-05-16
|
|
146
|
+
|
|
147
|
+
### Changed
|
|
148
|
+
|
|
149
|
+
- **Breaking:** remove the kernel abstraction; padded and packed dispatch are unified.
|
|
150
|
+
|
|
151
|
+
## [2.0.2] — 2026-05-16
|
|
152
|
+
|
|
153
|
+
### Removed
|
|
154
|
+
|
|
155
|
+
- The unused local-attention package.
|
|
156
|
+
|
|
157
|
+
## [2.0.1] — 2026-05-16
|
|
158
|
+
|
|
159
|
+
### Changed
|
|
160
|
+
|
|
161
|
+
- Store feed-forward activations as `nn.Module` attributes.
|
|
162
|
+
|
|
163
|
+
## [2.0.0] — 2026-05-16
|
|
164
|
+
|
|
165
|
+
### Removed
|
|
166
|
+
|
|
167
|
+
- **Breaking:** the `attn_bias` / ALiBi system.
|
|
168
|
+
|
|
169
|
+
## [1.1.0] — 2026-05-16
|
|
170
|
+
|
|
171
|
+
### Added
|
|
172
|
+
|
|
173
|
+
- `LearnedPosEncoding` with absolute position embeddings.
|
|
174
|
+
|
|
175
|
+
## [1.0.1] — 2026-05-16
|
|
176
|
+
|
|
177
|
+
### Added
|
|
178
|
+
|
|
179
|
+
- `LayerNorm` wrapper.
|
|
180
|
+
|
|
181
|
+
## [1.0.0] — 2026-05-16
|
|
182
|
+
|
|
183
|
+
### Added
|
|
184
|
+
|
|
185
|
+
- GEGLU feed-forward variant.
|
|
186
|
+
|
|
187
|
+
### Changed
|
|
188
|
+
|
|
189
|
+
- **Breaking:** feed-forward config becomes a discriminated union.
|
|
190
|
+
|
|
191
|
+
## [0.5.0] — 2026-05-16
|
|
192
|
+
|
|
193
|
+
### Added
|
|
194
|
+
|
|
195
|
+
- Unfold mode for the windowed SDPA kernel.
|
|
196
|
+
|
|
197
|
+
## [0.4.0] — 2026-05-15
|
|
198
|
+
|
|
199
|
+
### Added
|
|
200
|
+
|
|
201
|
+
- `RotaryEmbedding2D` and the packed cross-attender.
|
|
202
|
+
|
|
203
|
+
## [0.3.0] — 2026-05-14
|
|
204
|
+
|
|
205
|
+
### Changed
|
|
206
|
+
|
|
207
|
+
- Establish the semantic versioning convention.
|
|
208
|
+
|
|
209
|
+
## [0.2.0] — 2026-05-13
|
|
210
|
+
|
|
211
|
+
### Changed
|
|
212
|
+
|
|
213
|
+
- Remove the `v1` namespace; add the `presets` package.
|
|
214
|
+
|
|
215
|
+
## [0.1.0] — 2026-05-13
|
|
216
|
+
|
|
217
|
+
### Added
|
|
218
|
+
|
|
219
|
+
- Initial library scaffold.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: stackformers
|
|
3
|
-
Version: 3.9.
|
|
3
|
+
Version: 3.9.2
|
|
4
4
|
Summary: Typed, composable, SOLID transformer library for PyTorch
|
|
5
5
|
Project-URL: Homepage, https://github.com/Red-Eyed/stackformers
|
|
6
6
|
Project-URL: Repository, https://github.com/Red-Eyed/stackformers
|
|
@@ -8,9 +8,11 @@ Multi-head self-attention and cross-attention.
|
|
|
8
8
|
|
|
9
9
|
**Static vs runtime dispatch.** The attention *type* (global vs sliding-window) is determined at construction time via `window_size: int | None` in `SelfAttentionConfig`. The *backend* (padded vs packed) is determined at runtime: `SelfAttention.forward` and `CrossAttention.forward` dispatch on `SequenceInput` via `match`. This means one model handles both training (packed) and inference (padded) without swapping classes.
|
|
10
10
|
|
|
11
|
-
**Kernel ops in `ops.py`.** All low-level attention math lives in `attention/ops.py`: mask builders, `
|
|
11
|
+
**Kernel ops in `ops.py`.** All low-level attention math lives in `attention/ops.py`: mask builders, `padded_sdpa`, the packed↔padded scatter/gather helpers, and `packed_attn_or_fallback`. The modules stay thin dispatchers.
|
|
12
12
|
|
|
13
|
-
**
|
|
13
|
+
**Experimental kernel behind one interface function.** `torch.nn.attention.varlen` is an experimental API — the symbol is absent in some torch builds and its signature is not stable. Everything that touches it lives in `varlen_backend.py` behind a single function, `try_varlen_attn(...) -> Tensor | None`: the guarded import, the eligibility/bias checks, and the call itself. The rest of the package depends only on that function and never on the volatile import path, so an absent or renamed symbol degrades to the fallback instead of breaking the whole package at import time.
|
|
14
|
+
|
|
15
|
+
**Packed attention with automatic fallback.** `PackedInput` normally routes to `varlen_attn`, which requires CUDA and `float16`/`bfloat16`. `packed_attn_or_fallback` calls `try_varlen_attn`; a `None` result means take the padded path — scatter q/k/v to padded layout, run `F.scaled_dot_product_attention`, and gather the result back to packed (same weights, same output shape `(nt, h, d)`). The fallback runs **silently** for the expected CPU/float32/`torch.export` route, and **with a `UserWarning` explaining why** when the kernel was eligible but unusable: it failed to import, an attention bias is present (no bias slot), or the call raised a runtime/signature error (unsupported GPU or a changed experimental API). Dropout works on the fallback path; it is silently skipped only when `varlen_attn` is used (which does not accept a dropout argument).
|
|
14
16
|
|
|
15
17
|
**`torch.export` and `torch.compile` compatibility.** All scatter/gather helpers in `ops.py` (`_cu_to_indices`, `_packed_heads_to_padded`, `_padded_heads_to_packed`) are fully export-compatible. The key design constraint is that per-document length iteration must never use Python-side loops over data-dependent values (i.e., no `.tolist()` followed by a list comprehension). Instead, `_cu_to_indices` uses `torch.repeat_interleave` to produce `batch_idx` and derives `pos_idx` via the identity `arange(nt) - cu[batch_idx]`. This keeps the computation graph purely symbolic even when `nt` (total tokens) is a data-dependent unbacked symbol.
|
|
16
18
|
|
|
@@ -1,19 +1,13 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
import warnings
|
|
4
|
-
|
|
5
3
|
import torch
|
|
6
4
|
import torch.nn.functional as F
|
|
7
5
|
from torch import Tensor
|
|
8
|
-
from torch.nn.attention.varlen import varlen_attn as _varlen_attn
|
|
9
6
|
|
|
7
|
+
from stackformers.attention.varlen_backend import try_varlen_attn
|
|
10
8
|
from stackformers.sequence import PackedSequence
|
|
11
9
|
|
|
12
10
|
|
|
13
|
-
def varlen_supported(q: Tensor) -> bool:
|
|
14
|
-
return q.is_cuda and q.dtype in (torch.float16, torch.bfloat16)
|
|
15
|
-
|
|
16
|
-
|
|
17
11
|
def padding_mask(mask: Tensor, dtype: torch.dtype) -> Tensor:
|
|
18
12
|
bias = torch.zeros(mask.shape, dtype=dtype, device=mask.device)
|
|
19
13
|
bias.masked_fill_(~mask, torch.finfo(dtype).min)
|
|
@@ -34,12 +28,6 @@ def window_mask(n: int, s: int, window_size: int, causal: bool, device: torch.de
|
|
|
34
28
|
return mask
|
|
35
29
|
|
|
36
30
|
|
|
37
|
-
def varlen_window(causal: bool, window_size: int | None) -> tuple[int, int]:
|
|
38
|
-
if window_size is None:
|
|
39
|
-
return (-1, 0) if causal else (-1, -1)
|
|
40
|
-
return (window_size, 0) if causal else (window_size // 2, window_size // 2)
|
|
41
|
-
|
|
42
|
-
|
|
43
31
|
def padded_sdpa(
|
|
44
32
|
q: Tensor,
|
|
45
33
|
k: Tensor,
|
|
@@ -101,30 +89,6 @@ def _padded_heads_to_packed(x: Tensor, mask: Tensor) -> Tensor:
|
|
|
101
89
|
return x.permute(0, 2, 1, 3)[mask]
|
|
102
90
|
|
|
103
91
|
|
|
104
|
-
def packed_attn(
|
|
105
|
-
q: Tensor,
|
|
106
|
-
k: Tensor,
|
|
107
|
-
v: Tensor,
|
|
108
|
-
q_seq: PackedSequence,
|
|
109
|
-
k_seq: PackedSequence,
|
|
110
|
-
causal: bool,
|
|
111
|
-
window_size: int | None,
|
|
112
|
-
) -> Tensor:
|
|
113
|
-
win = varlen_window(causal, window_size)
|
|
114
|
-
result = _varlen_attn(
|
|
115
|
-
query=q,
|
|
116
|
-
key=k,
|
|
117
|
-
value=v,
|
|
118
|
-
cu_seq_q=q_seq.cu_seqlens.to(torch.int32),
|
|
119
|
-
cu_seq_k=k_seq.cu_seqlens.to(torch.int32),
|
|
120
|
-
max_q=q_seq.max_seqlen,
|
|
121
|
-
max_k=k_seq.max_seqlen,
|
|
122
|
-
window_size=win,
|
|
123
|
-
)
|
|
124
|
-
assert isinstance(result, Tensor)
|
|
125
|
-
return result
|
|
126
|
-
|
|
127
|
-
|
|
128
92
|
def packed_attn_or_fallback(
|
|
129
93
|
q: Tensor,
|
|
130
94
|
k: Tensor,
|
|
@@ -135,29 +99,16 @@ def packed_attn_or_fallback(
|
|
|
135
99
|
window_size: int | None,
|
|
136
100
|
bias: Tensor | None,
|
|
137
101
|
) -> Tensor:
|
|
138
|
-
"""Run varlen attention; fall back to padded SDPA when unavailable.
|
|
102
|
+
"""Run varlen attention; fall back to padded SDPA when it is unavailable.
|
|
139
103
|
|
|
140
104
|
Inputs and output are all packed: q/k/v are (nt, h, d), result is (nt_q, h, d).
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
warning
|
|
144
|
-
that do not support varlen_attn (e.g. compute capability < 8.0).
|
|
105
|
+
``try_varlen_attn`` owns the experimental kernel and its warnings; ``None`` from it means
|
|
106
|
+
take the padded SDPA path — silently for the expected CPU/float32/export route, or after
|
|
107
|
+
a warning when the kernel was eligible but unavailable.
|
|
145
108
|
"""
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
"Performance may be lower.",
|
|
150
|
-
stacklevel=2,
|
|
151
|
-
)
|
|
152
|
-
elif varlen_supported(q):
|
|
153
|
-
try:
|
|
154
|
-
return packed_attn(q, k, v, q_seq, k_seq, causal, window_size)
|
|
155
|
-
except RuntimeError as exc:
|
|
156
|
-
warnings.warn(
|
|
157
|
-
f"varlen_attn is not supported on this device ({exc}); "
|
|
158
|
-
"falling back to padded SDPA. Performance may be lower.",
|
|
159
|
-
stacklevel=2,
|
|
160
|
-
)
|
|
109
|
+
out = try_varlen_attn(q, k, v, q_seq, k_seq, causal, window_size, bias)
|
|
110
|
+
if out is not None:
|
|
111
|
+
return out
|
|
161
112
|
|
|
162
113
|
# Keep b as SymInt-friendly: int(SymInt) forces specialization under torch.export.
|
|
163
114
|
# Downstream consumers (_packed_heads_to_padded) accept SymInt for shape args.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""The experimental ``varlen_attn`` kernel behind one interface function.
|
|
2
|
+
|
|
3
|
+
``torch.nn.attention.varlen`` is an experimental API: the symbol is absent in some torch
|
|
4
|
+
builds, and its call signature is not yet stable. Everything that touches it lives here —
|
|
5
|
+
the guarded import, the eligibility/bias checks, and the call itself — so the rest of the
|
|
6
|
+
package depends only on :func:`try_varlen_attn` and never on the volatile import path.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import warnings
|
|
12
|
+
|
|
13
|
+
import torch
|
|
14
|
+
from torch import Tensor
|
|
15
|
+
|
|
16
|
+
from stackformers.sequence import PackedSequence
|
|
17
|
+
|
|
18
|
+
_FALLBACK_NOTE = " Falling back to padded SDPA; performance may be lower."
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _load():
|
|
22
|
+
try:
|
|
23
|
+
from torch.nn.attention.varlen import varlen_attn
|
|
24
|
+
except ImportError as exc:
|
|
25
|
+
return None, f"varlen_attn could not be imported ({exc})"
|
|
26
|
+
return varlen_attn, None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
_varlen_attn, _import_error = _load()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _eligible(q: Tensor) -> bool:
|
|
33
|
+
"""Whether this query's device/dtype is one ``varlen_attn`` would handle at all."""
|
|
34
|
+
return q.is_cuda and q.dtype in (torch.float16, torch.bfloat16)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _window(causal: bool, window_size: int | None) -> tuple[int, int]:
|
|
38
|
+
if window_size is None:
|
|
39
|
+
return (-1, 0) if causal else (-1, -1)
|
|
40
|
+
return (window_size, 0) if causal else (window_size // 2, window_size // 2)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _skip(reason: str) -> None:
|
|
44
|
+
warnings.warn(reason + _FALLBACK_NOTE, stacklevel=3)
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def try_varlen_attn(
|
|
49
|
+
q: Tensor,
|
|
50
|
+
k: Tensor,
|
|
51
|
+
v: Tensor,
|
|
52
|
+
q_seq: PackedSequence,
|
|
53
|
+
k_seq: PackedSequence,
|
|
54
|
+
causal: bool,
|
|
55
|
+
window_size: int | None,
|
|
56
|
+
bias: Tensor | None,
|
|
57
|
+
) -> Tensor | None:
|
|
58
|
+
"""Attempt varlen attention for a packed batch; return ``None`` to use the SDPA fallback.
|
|
59
|
+
|
|
60
|
+
q/k/v are ``(nt, h, d)``; the result is the packed ``(nt_q, h, d)`` tensor. ``None`` means
|
|
61
|
+
the caller should run the padded SDPA path instead. When varlen *would* apply (CUDA +
|
|
62
|
+
float16/bfloat16) but cannot, a ``UserWarning`` explains why: an absent kernel, an
|
|
63
|
+
attention bias (varlen_attn has no bias slot), or a runtime/signature error from the call
|
|
64
|
+
(an unsupported GPU or a changed experimental API). The expected CPU/float32/export route
|
|
65
|
+
returns ``None`` silently — that is normal, not a failure.
|
|
66
|
+
"""
|
|
67
|
+
if not _eligible(q):
|
|
68
|
+
return None
|
|
69
|
+
if _varlen_attn is None:
|
|
70
|
+
return _skip(f"varlen_attn is unavailable ({_import_error}).")
|
|
71
|
+
if bias is not None:
|
|
72
|
+
return _skip("varlen_attn does not support attention bias.")
|
|
73
|
+
try:
|
|
74
|
+
result = _varlen_attn(
|
|
75
|
+
query=q,
|
|
76
|
+
key=k,
|
|
77
|
+
value=v,
|
|
78
|
+
cu_seq_q=q_seq.cu_seqlens.to(torch.int32),
|
|
79
|
+
cu_seq_k=k_seq.cu_seqlens.to(torch.int32),
|
|
80
|
+
max_q=q_seq.max_seqlen,
|
|
81
|
+
max_k=k_seq.max_seqlen,
|
|
82
|
+
window_size=_window(causal, window_size),
|
|
83
|
+
)
|
|
84
|
+
except (RuntimeError, TypeError) as exc:
|
|
85
|
+
return _skip(f"varlen_attn call failed ({type(exc).__name__}: {exc}).")
|
|
86
|
+
if not isinstance(result, Tensor):
|
|
87
|
+
return _skip(f"varlen_attn returned {type(result).__name__}, expected Tensor.")
|
|
88
|
+
return result
|
|
@@ -25,12 +25,22 @@ class RotaryEmbedding2D(nn.Module):
|
|
|
25
25
|
|
|
26
26
|
@torch.no_grad()
|
|
27
27
|
def _freqs_from_positions(self, positions: Tensor) -> Tensor:
|
|
28
|
-
"""positions: (..., 2) → freqs: (..., dh)
|
|
28
|
+
"""positions: (..., 2) → freqs: (..., dh), laid out as [row | col | row | col].
|
|
29
|
+
|
|
30
|
+
_rotate_half pairs channel i with channel i + dh/2, so both members of a pair must
|
|
31
|
+
carry the same angle for the map to be a rotation. Duplicating the *concatenated*
|
|
32
|
+
half-vector satisfies that; concatenating the *duplicated* row and col blocks
|
|
33
|
+
([row | row | col | col]) would pair a row angle against a col angle and yield a
|
|
34
|
+
squeeze instead — non-orthogonal, and not a function of relative position.
|
|
35
|
+
|
|
36
|
+
float32 cast ensures half-precision inputs don't lose precision in the outer product.
|
|
37
|
+
"""
|
|
29
38
|
inv: Tensor = self.inv_freq # type: ignore[assignment]
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
39
|
+
pos = positions.to(dtype=torch.float32)
|
|
40
|
+
row = pos[..., 0].unsqueeze(-1) * inv.float() # (..., dh//4)
|
|
41
|
+
col = pos[..., 1].unsqueeze(-1) * inv.float() # (..., dh//4)
|
|
42
|
+
half = torch.cat([row, col], dim=-1) # (..., dh//2)
|
|
43
|
+
return torch.cat([half, half], dim=-1) # (..., dh)
|
|
34
44
|
|
|
35
45
|
def _encode(
|
|
36
46
|
self, q: Tensor, k: Tensor, q_positions: Tensor, k_positions: Tensor
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Tests for stackformers/attention/varlen_backend.py.
|
|
2
|
+
|
|
3
|
+
Covers the fallback contract of ``try_varlen_attn``: it returns the kernel's tensor on the
|
|
4
|
+
happy path and ``None`` (with a reason-bearing ``UserWarning`` when the kernel was eligible
|
|
5
|
+
but unusable) on every degraded path — absent symbol, attention bias, a runtime/signature
|
|
6
|
+
error from the call, or a non-Tensor return. The experimental kernel is faked via monkeypatch
|
|
7
|
+
so the logic is exercised without CUDA or the real (possibly-absent) ``varlen_attn``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import warnings
|
|
13
|
+
|
|
14
|
+
import pytest
|
|
15
|
+
import torch
|
|
16
|
+
|
|
17
|
+
from stackformers.attention import varlen_backend as vb
|
|
18
|
+
from stackformers.sequence import PackedSequence
|
|
19
|
+
|
|
20
|
+
NT, H, DH = 5, 2, 8
|
|
21
|
+
|
|
22
|
+
Packed = tuple[torch.Tensor, torch.Tensor, torch.Tensor, PackedSequence]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.fixture
|
|
26
|
+
def packed() -> Packed:
|
|
27
|
+
"""Two packed sequences (lengths 3 and 2) of (nt, h, d) q/k/v plus their PackedSequence."""
|
|
28
|
+
seq = PackedSequence(cu_seqlens=torch.tensor([0, 3, 5], dtype=torch.long), max_seqlen=3)
|
|
29
|
+
q = torch.randn(NT, H, DH)
|
|
30
|
+
k = torch.randn(NT, H, DH)
|
|
31
|
+
v = torch.randn(NT, H, DH)
|
|
32
|
+
return q, k, v, seq
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@pytest.fixture
|
|
36
|
+
def force_eligible(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
37
|
+
"""Pretend the query is CUDA + float16 so the eligibility guard does not short-circuit."""
|
|
38
|
+
monkeypatch.setattr(vb, "_eligible", lambda q: True)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _attempt(packed: Packed, bias: torch.Tensor | None = None) -> torch.Tensor | None:
|
|
42
|
+
q, k, v, seq = packed
|
|
43
|
+
return vb.try_varlen_attn(q, k, v, seq, seq, causal=False, window_size=None, bias=bias)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_ineligible_falls_back_silently(packed: Packed, recwarn: pytest.WarningsRecorder) -> None:
|
|
47
|
+
"""A plain CPU/float32 query is the expected fallback route — None, and no warning."""
|
|
48
|
+
out = _attempt(packed)
|
|
49
|
+
assert out is None
|
|
50
|
+
assert len(recwarn) == 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_unavailable_kernel_warns(
|
|
54
|
+
packed: Packed, force_eligible: None, monkeypatch: pytest.MonkeyPatch
|
|
55
|
+
) -> None:
|
|
56
|
+
"""An eligible query with no imported kernel falls back and reports the import reason."""
|
|
57
|
+
monkeypatch.setattr(vb, "_varlen_attn", None)
|
|
58
|
+
monkeypatch.setattr(vb, "_import_error", "varlen_attn could not be imported (no module)")
|
|
59
|
+
with pytest.warns(UserWarning, match="unavailable"):
|
|
60
|
+
out = _attempt(packed)
|
|
61
|
+
assert out is None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_attention_bias_warns(
|
|
65
|
+
packed: Packed, force_eligible: None, monkeypatch: pytest.MonkeyPatch
|
|
66
|
+
) -> None:
|
|
67
|
+
"""varlen_attn has no bias slot: an eligible query with a bias falls back with a warning."""
|
|
68
|
+
monkeypatch.setattr(vb, "_varlen_attn", lambda **kw: torch.zeros(NT, H, DH))
|
|
69
|
+
bias = torch.zeros(1, 1, NT, NT)
|
|
70
|
+
with pytest.warns(UserWarning, match="attention bias"):
|
|
71
|
+
out = _attempt(packed, bias=bias)
|
|
72
|
+
assert out is None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_signature_error_warns(
|
|
76
|
+
packed: Packed, force_eligible: None, monkeypatch: pytest.MonkeyPatch
|
|
77
|
+
) -> None:
|
|
78
|
+
"""A changed experimental signature raises TypeError, which is caught and falls back."""
|
|
79
|
+
|
|
80
|
+
def renamed_kwarg(**kw: object) -> torch.Tensor:
|
|
81
|
+
raise TypeError("unexpected keyword argument 'cu_seq_q'")
|
|
82
|
+
|
|
83
|
+
monkeypatch.setattr(vb, "_varlen_attn", renamed_kwarg)
|
|
84
|
+
with pytest.warns(UserWarning, match="call failed"):
|
|
85
|
+
out = _attempt(packed)
|
|
86
|
+
assert out is None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_runtime_error_warns(
|
|
90
|
+
packed: Packed, force_eligible: None, monkeypatch: pytest.MonkeyPatch
|
|
91
|
+
) -> None:
|
|
92
|
+
"""An unsupported-GPU RuntimeError from the call is caught and falls back."""
|
|
93
|
+
|
|
94
|
+
def unsupported(**kw: object) -> torch.Tensor:
|
|
95
|
+
raise RuntimeError("varlen_attn requires compute capability >= 8.0")
|
|
96
|
+
|
|
97
|
+
monkeypatch.setattr(vb, "_varlen_attn", unsupported)
|
|
98
|
+
with pytest.warns(UserWarning, match="call failed"):
|
|
99
|
+
out = _attempt(packed)
|
|
100
|
+
assert out is None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_non_tensor_return_warns(
|
|
104
|
+
packed: Packed, force_eligible: None, monkeypatch: pytest.MonkeyPatch
|
|
105
|
+
) -> None:
|
|
106
|
+
"""A changed return contract (non-Tensor) falls back rather than propagating bad data."""
|
|
107
|
+
monkeypatch.setattr(vb, "_varlen_attn", lambda **kw: ("not", "a", "tensor"))
|
|
108
|
+
with pytest.warns(UserWarning, match="expected Tensor"):
|
|
109
|
+
out = _attempt(packed)
|
|
110
|
+
assert out is None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_success_returns_kernel_tensor(
|
|
114
|
+
packed: Packed, force_eligible: None, monkeypatch: pytest.MonkeyPatch
|
|
115
|
+
) -> None:
|
|
116
|
+
"""The happy path returns the kernel's tensor unchanged and emits no warning."""
|
|
117
|
+
expected = torch.randn(NT, H, DH)
|
|
118
|
+
monkeypatch.setattr(vb, "_varlen_attn", lambda **kw: expected)
|
|
119
|
+
with warnings.catch_warnings():
|
|
120
|
+
warnings.simplefilter("error")
|
|
121
|
+
out = _attempt(packed)
|
|
122
|
+
assert out is expected
|
|
@@ -125,21 +125,176 @@ def test_rope1d_preserves_norms(
|
|
|
125
125
|
assert torch.allclose(k.norm(dim=-1), k_out.norm(dim=-1), atol=tol)
|
|
126
126
|
|
|
127
127
|
|
|
128
|
+
# --- RoPE-2D ---
|
|
129
|
+
#
|
|
130
|
+
# A row-major GH x GW grid, never row == col. On the diagonal (row == col) the row and column
|
|
131
|
+
# angles coincide, which makes a broken frequency layout indistinguishable from a correct one.
|
|
132
|
+
|
|
133
|
+
GH, GW = 3, 5
|
|
134
|
+
GN = GH * GW
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _grid_positions(b: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
|
138
|
+
"""Row-major (row, col) positions over a GH x GW grid, as (b, GN, 2)."""
|
|
139
|
+
rows = torch.arange(GH, device=device, dtype=dtype).repeat_interleave(GW)
|
|
140
|
+
cols = torch.arange(GW, device=device, dtype=dtype).repeat(GH)
|
|
141
|
+
return torch.stack([rows, cols], dim=-1).unsqueeze(0).expand(b, -1, -1).clone()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _reference_rope2d(t: torch.Tensor, positions: torch.Tensor, base: int = 10_000) -> torch.Tensor:
|
|
145
|
+
"""Axial 2-D RoPE written directly from the definition, independent of the implementation.
|
|
146
|
+
|
|
147
|
+
Rotates channel pair (i, i + dh/2) by row * w_i for the first dh/4 pairs and by col * w_i
|
|
148
|
+
for the rest. t: (b, h, n, dh), positions: (b, n, 2).
|
|
149
|
+
"""
|
|
150
|
+
dh = t.shape[-1]
|
|
151
|
+
half, quarter = dh // 2, dh // 4
|
|
152
|
+
inv = 1.0 / (base ** (torch.arange(0, half, 2, dtype=torch.float32) / half))
|
|
153
|
+
inv = inv.to(device=t.device)
|
|
154
|
+
|
|
155
|
+
out = torch.zeros_like(t, dtype=torch.float32)
|
|
156
|
+
src = t.float()
|
|
157
|
+
for i in range(half):
|
|
158
|
+
axis = 0 if i < quarter else 1
|
|
159
|
+
freq = inv[i if i < quarter else i - quarter]
|
|
160
|
+
angle = positions[..., axis].float() * freq # (b, n)
|
|
161
|
+
cos, sin = angle.cos().unsqueeze(1), angle.sin().unsqueeze(1) # (b, 1, n)
|
|
162
|
+
x, y = src[..., i], src[..., i + half]
|
|
163
|
+
out[..., i] = x * cos - y * sin
|
|
164
|
+
out[..., i + half] = x * sin + y * cos
|
|
165
|
+
return out.to(t.dtype)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@pytest.fixture
|
|
169
|
+
def grid_qk(device_dtype: tuple[torch.device, torch.dtype]) -> tuple[torch.Tensor, torch.Tensor]:
|
|
170
|
+
device, dtype = device_dtype
|
|
171
|
+
return (
|
|
172
|
+
torch.randn(B, H, GN, DH, device=device, dtype=dtype),
|
|
173
|
+
torch.randn(B, H, GN, DH, device=device, dtype=dtype),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@pytest.fixture
|
|
178
|
+
def grid_pos(device_dtype: tuple[torch.device, torch.dtype]) -> torch.Tensor:
|
|
179
|
+
device, dtype = device_dtype
|
|
180
|
+
return _grid_positions(B, device, dtype)
|
|
181
|
+
|
|
182
|
+
|
|
128
183
|
def test_rope2d_output_shape(
|
|
129
184
|
rope2d: RotaryEmbedding2D,
|
|
130
|
-
|
|
185
|
+
grid_qk: tuple[torch.Tensor, torch.Tensor],
|
|
186
|
+
grid_pos: torch.Tensor,
|
|
131
187
|
) -> None:
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
k = torch.randn(B, H, N, DH, device=device, dtype=dtype)
|
|
135
|
-
row_ids = torch.arange(N, dtype=dtype, device=device)
|
|
136
|
-
col_ids = torch.arange(N, dtype=dtype, device=device)
|
|
137
|
-
pos = torch.stack([row_ids, col_ids], dim=-1).unsqueeze(0).expand(B, -1, -1) # b n 2
|
|
138
|
-
q_out, k_out = rope2d.forward_padded(q, k, pos, pos)
|
|
188
|
+
q, k = grid_qk
|
|
189
|
+
q_out, k_out = rope2d.forward_padded(q, k, grid_pos, grid_pos)
|
|
139
190
|
assert q_out.shape == q.shape
|
|
140
191
|
assert k_out.shape == k.shape
|
|
141
192
|
|
|
142
193
|
|
|
194
|
+
def test_rope2d_matches_reference_rotation(
|
|
195
|
+
rope2d: RotaryEmbedding2D,
|
|
196
|
+
grid_qk: tuple[torch.Tensor, torch.Tensor],
|
|
197
|
+
grid_pos: torch.Tensor,
|
|
198
|
+
device_dtype: tuple[torch.device, torch.dtype],
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Pins the exact rotation against a definition-first oracle, not just its properties."""
|
|
201
|
+
_, dtype = device_dtype
|
|
202
|
+
q, k = grid_qk
|
|
203
|
+
q_out, k_out = rope2d.forward_padded(q, k, grid_pos, grid_pos)
|
|
204
|
+
assert torch.allclose(q_out, _reference_rope2d(q, grid_pos), atol=atol(dtype))
|
|
205
|
+
assert torch.allclose(k_out, _reference_rope2d(k, grid_pos), atol=atol(dtype))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def test_rope2d_is_orthogonal(
|
|
209
|
+
rope2d: RotaryEmbedding2D,
|
|
210
|
+
grid_qk: tuple[torch.Tensor, torch.Tensor],
|
|
211
|
+
grid_pos: torch.Tensor,
|
|
212
|
+
device_dtype: tuple[torch.device, torch.dtype],
|
|
213
|
+
) -> None:
|
|
214
|
+
"""A rotation preserves norms and inner products; a squeeze or reflection does not."""
|
|
215
|
+
_, dtype = device_dtype
|
|
216
|
+
q, k = grid_qk
|
|
217
|
+
q_out, k_out = rope2d.forward_padded(q, k, grid_pos, grid_pos)
|
|
218
|
+
tol = atol(dtype)
|
|
219
|
+
assert torch.allclose(q.norm(dim=-1), q_out.norm(dim=-1), atol=tol)
|
|
220
|
+
assert torch.allclose(k.norm(dim=-1), k_out.norm(dim=-1), atol=tol)
|
|
221
|
+
# Same position for q and k, so the shared rotation must cancel in the inner product.
|
|
222
|
+
before = (q.float() * k.float()).sum(dim=-1)
|
|
223
|
+
after = (q_out.float() * k_out.float()).sum(dim=-1)
|
|
224
|
+
assert torch.allclose(before, after, atol=tol * DH)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@pytest.mark.parametrize("offset", [(0, 1), (1, 0), (2, 3), (-1, 2)], ids=str)
|
|
228
|
+
def test_rope2d_score_depends_only_on_relative_offset(
|
|
229
|
+
device: torch.device,
|
|
230
|
+
offset: tuple[int, int],
|
|
231
|
+
) -> None:
|
|
232
|
+
"""The defining property: sliding a query/key pair across the grid must not move the score."""
|
|
233
|
+
rope = RotaryEmbedding2D(RoPE2DConfig(dim_head=DH)).to(device=device)
|
|
234
|
+
q = torch.randn(1, H, 1, DH, device=device)
|
|
235
|
+
k = torch.randn(1, H, 1, DH, device=device)
|
|
236
|
+
d_row, d_col = offset
|
|
237
|
+
|
|
238
|
+
def score(row: int, col: int) -> torch.Tensor:
|
|
239
|
+
q_pos = torch.tensor([[[float(row), float(col)]]], device=device)
|
|
240
|
+
k_pos = torch.tensor([[[float(row + d_row), float(col + d_col)]]], device=device)
|
|
241
|
+
q_out, k_out = rope.forward_padded(q, k, q_pos, k_pos)
|
|
242
|
+
return (q_out @ k_out.transpose(-1, -2))[0, :, 0, 0]
|
|
243
|
+
|
|
244
|
+
anchor = score(0, 0)
|
|
245
|
+
for row, col in [(2, 3), (5, 9), (11, 4), (7, 7)]:
|
|
246
|
+
assert torch.allclose(anchor, score(row, col), atol=atol(torch.float32) * 10)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def test_rope2d_distinct_offsets_give_distinct_scores(device: torch.device) -> None:
|
|
250
|
+
"""Guards the degenerate fix where every offset collapses to the same score."""
|
|
251
|
+
rope = RotaryEmbedding2D(RoPE2DConfig(dim_head=DH)).to(device=device)
|
|
252
|
+
q = torch.randn(1, H, 1, DH, device=device)
|
|
253
|
+
k = torch.randn(1, H, 1, DH, device=device)
|
|
254
|
+
|
|
255
|
+
def score(k_row: float, k_col: float) -> torch.Tensor:
|
|
256
|
+
q_pos = torch.zeros(1, 1, 2, device=device)
|
|
257
|
+
k_pos = torch.tensor([[[k_row, k_col]]], device=device)
|
|
258
|
+
q_out, k_out = rope.forward_padded(q, k, q_pos, k_pos)
|
|
259
|
+
return (q_out @ k_out.transpose(-1, -2))[0, :, 0, 0]
|
|
260
|
+
|
|
261
|
+
# A row-offset and the matching col-offset must not be conflated: the axes are separate.
|
|
262
|
+
assert not torch.allclose(score(2.0, 0.0), score(0.0, 2.0))
|
|
263
|
+
assert not torch.allclose(score(0.0, 0.0), score(1.0, 1.0))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@pytest.mark.parametrize("axis", [0, 1], ids=["row", "col"])
|
|
267
|
+
def test_rope2d_each_axis_changes_the_encoding(
|
|
268
|
+
rope2d: RotaryEmbedding2D,
|
|
269
|
+
device_dtype: tuple[torch.device, torch.dtype],
|
|
270
|
+
axis: int,
|
|
271
|
+
) -> None:
|
|
272
|
+
"""Moving along either axis alone must change the output — neither axis may be ignored."""
|
|
273
|
+
device, dtype = device_dtype
|
|
274
|
+
q = torch.randn(1, H, 1, DH, device=device, dtype=dtype)
|
|
275
|
+
base_pos = torch.full((1, 1, 2), 2.0, device=device, dtype=dtype)
|
|
276
|
+
moved_pos = base_pos.clone()
|
|
277
|
+
moved_pos[..., axis] += 3.0
|
|
278
|
+
base_out, _ = rope2d.forward_padded(q, q, base_pos, base_pos)
|
|
279
|
+
moved_out, _ = rope2d.forward_padded(q, q, moved_pos, moved_pos)
|
|
280
|
+
assert not torch.allclose(base_out, moved_out, atol=atol(dtype))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def test_rope2d_packed_matches_padded(
|
|
284
|
+
rope2d: RotaryEmbedding2D,
|
|
285
|
+
device_dtype: tuple[torch.device, torch.dtype],
|
|
286
|
+
) -> None:
|
|
287
|
+
"""Both layouts are the same per-token operation and must agree token for token."""
|
|
288
|
+
device, dtype = device_dtype
|
|
289
|
+
q = torch.randn(1, H, GN, DH, device=device, dtype=dtype)
|
|
290
|
+
pos = _grid_positions(1, device, dtype)
|
|
291
|
+
padded, _ = rope2d.forward_padded(q, q, pos, pos)
|
|
292
|
+
|
|
293
|
+
packed_q = q[0].transpose(0, 1).contiguous() # (nt, h, dh)
|
|
294
|
+
packed_out, _ = rope2d.forward_packed(packed_q, packed_q, pos[0], pos[0])
|
|
295
|
+
assert torch.allclose(packed_out, padded[0].transpose(0, 1), atol=atol(dtype))
|
|
296
|
+
|
|
297
|
+
|
|
143
298
|
# --- YaRN scaling ---
|
|
144
299
|
|
|
145
300
|
_YARN = YaRNConfig(scale=4.0, original_max_seq_len=512)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|