hunterFormsBS 0.3.2__py3-none-any.whl
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.
- hunterFormsBS/__init__.py +30 -0
- hunterFormsBS/attend.py +570 -0
- hunterFormsBS/bandSplitRotator.py +830 -0
- hunterFormsBS/bands.py +118 -0
- hunterFormsBS/hyperACE.py +2496 -0
- hunterFormsBS/loss.py +157 -0
- hunterFormsBS/mask.py +391 -0
- hunterFormsBS/py.typed +0 -0
- hunterFormsBS/theTypes.py +313 -0
- hunterFormsBS/transform.py +305 -0
- hunterformsbs-0.3.2.dist-info/METADATA +388 -0
- hunterformsbs-0.3.2.dist-info/RECORD +17 -0
- hunterformsbs-0.3.2.dist-info/WHEEL +5 -0
- hunterformsbs-0.3.2.dist-info/licenses/LICENSE +407 -0
- hunterformsbs-0.3.2.dist-info/licenses/LICENSE-Solovyev +23 -0
- hunterformsbs-0.3.2.dist-info/licenses/LICENSE-Wang +23 -0
- hunterformsbs-0.3.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Access typed band-split source-separation modules and the primary separator.
|
|
2
|
+
|
|
3
|
+
You can use this package to assemble typed source-separation models for music and other audio
|
|
4
|
+
mixtures. You can import the primary separator model from the top-level package namespace and reach
|
|
5
|
+
the supporting attention, band-partitioning, optional segmentation-branch, and typed-configuration
|
|
6
|
+
modules through `hunterFormsBS.*` submodule imports.
|
|
7
|
+
|
|
8
|
+
Modules
|
|
9
|
+
-------
|
|
10
|
+
attend
|
|
11
|
+
Attention layers for separator models.
|
|
12
|
+
bands
|
|
13
|
+
Band projection layer and the BS-style default frequency-bin partition.
|
|
14
|
+
bandSplitRotator
|
|
15
|
+
Primary band-split separator model exposed by the package.
|
|
16
|
+
hyperACE
|
|
17
|
+
Optional segmentation-style mask-estimation branch and supporting building blocks.
|
|
18
|
+
loss
|
|
19
|
+
Multi-resolution STFT training-loss computation utilities.
|
|
20
|
+
mask
|
|
21
|
+
Mask estimation heads and band-local affine blocks.
|
|
22
|
+
theTypes
|
|
23
|
+
Typed configuration records for attention, mask estimation, STFT, transformer, and loss setup.
|
|
24
|
+
transform
|
|
25
|
+
Position-wise feedforward block and stacked attention-and-feedforward transformer.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from hunterFormsBS.bandSplitRotator import BandSplitRotator as BandSplitRotator
|
hunterFormsBS/attend.py
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
# ruff: noqa: PLC0415
|
|
2
|
+
"""Evaluate and project attention for music source separation.
|
|
3
|
+
|
|
4
|
+
You can use this module to assemble the attention core used by
|
|
5
|
+
`hunterFormsBS.bandSplitRotator.BandSplitRotator` [1]. The constructor parameter names stay aligned
|
|
6
|
+
across the stack so outer model classes can pass settings such as `attn_dropout`, `flash_attn`,
|
|
7
|
+
`sage_attention`, and `scale` without renaming fields. `Attend` evaluates attention from
|
|
8
|
+
precomputed query, key, and value arrays and can dispatch to an explicit implementation, to
|
|
9
|
+
PyTorch SDPA [2], or to SageAttention [3][4]. `Attention` projects activations into query, key,
|
|
10
|
+
and value arrays, applies RoPE [5] or PoPE [6], and then calls `Attend`. The feedforward and
|
|
11
|
+
transformer residual blocks now live in `hunterFormsBS.transform` [7].
|
|
12
|
+
|
|
13
|
+
Contents
|
|
14
|
+
--------
|
|
15
|
+
Classes
|
|
16
|
+
Attend
|
|
17
|
+
Evaluate attention output from precomputed query, key, and value arrays.
|
|
18
|
+
Attention
|
|
19
|
+
Project activations into multi-head query, key, and value arrays and return gated output.
|
|
20
|
+
|
|
21
|
+
References
|
|
22
|
+
----------
|
|
23
|
+
[1] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
|
|
24
|
+
|
|
25
|
+
[2] PyTorch.
|
|
26
|
+
https://context7.com/pytorch/pytorch
|
|
27
|
+
[3] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., and Chen, J. (2025).
|
|
28
|
+
SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
|
|
29
|
+
https://arxiv.org/abs/2410.02367
|
|
30
|
+
[4] thu-ml/SageAttention
|
|
31
|
+
https://github.com/thu-ml/SageAttention
|
|
32
|
+
[5] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu, Y. (2021).
|
|
33
|
+
RoFormer: Enhanced Transformer with Rotary Position Embedding. https://arxiv.org/abs/2104.09864
|
|
34
|
+
[6] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., and Mozer, M. C. (2025).
|
|
35
|
+
Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings.
|
|
36
|
+
https://arxiv.org/abs/2509.10534
|
|
37
|
+
[7] `hunterFormsBS.transform`
|
|
38
|
+
"""
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
from einops import rearrange
|
|
42
|
+
from hunterFormsBS.theTypes import FlashAttentionConfig
|
|
43
|
+
from operator import neg
|
|
44
|
+
from packaging import version
|
|
45
|
+
from PoPE_pytorch import flash_attn_with_pope, PoPE
|
|
46
|
+
from torch import einsum, nn, Tensor
|
|
47
|
+
from torch_einops_kit import exists, once
|
|
48
|
+
from torch_einops_kit.scaleValues import RMSNorm
|
|
49
|
+
from typing import Any, cast, TYPE_CHECKING
|
|
50
|
+
import torch
|
|
51
|
+
import torch.nn.functional as F
|
|
52
|
+
|
|
53
|
+
if TYPE_CHECKING:
|
|
54
|
+
from collections.abc import Callable
|
|
55
|
+
from rotary_embedding_torch import RotaryEmbedding
|
|
56
|
+
from torch._C import _CudaDeviceProperties
|
|
57
|
+
|
|
58
|
+
print_once: Callable[..., Any] = once(print)
|
|
59
|
+
|
|
60
|
+
class Attend(nn.Module):
|
|
61
|
+
"""Compute attention output from precomputed query, key, and value arrays.
|
|
62
|
+
|
|
63
|
+
You can use `Attend` after `Attention` [1] has already built query `Tensor` `q`, key `Tensor` `k`,
|
|
64
|
+
and value `Tensor` `v`. `Attend` compares query `Tensor` `q` against key `Tensor` `k` to build
|
|
65
|
+
attention weights and then uses the attention weights to mix value `Tensor` `v` with the standard
|
|
66
|
+
scaled dot-product rule [2]. `Attend` can compute that mapping with an explicit implementation,
|
|
67
|
+
with PyTorch SDPA [3], or with SageAttention [4][5] when the optional dependency is installed
|
|
68
|
+
manually.
|
|
69
|
+
|
|
70
|
+
Attributes
|
|
71
|
+
----------
|
|
72
|
+
nn_Dropout : nn.Dropout
|
|
73
|
+
Dropout module applied to attention weights after `softmax` in the explicit path.
|
|
74
|
+
attn_dropout : float
|
|
75
|
+
Probability used for attention-weight dropout during training.
|
|
76
|
+
cpu_config : FlashAttentionConfig
|
|
77
|
+
Backend flags passed to `torch.backends.cuda.sdp_kernel` [3] when execution remains on CPU or
|
|
78
|
+
when `cuda_config` is `None` [6].
|
|
79
|
+
cuda_config : FlashAttentionConfig | None
|
|
80
|
+
Backend flags used for CUDA execution when `flash` is enabled [6].
|
|
81
|
+
flash : bool
|
|
82
|
+
Whether `forward` may delegate to `flash_attn` when `sage_attention` is `False`.
|
|
83
|
+
sage_attention : bool
|
|
84
|
+
Whether `forward` should try `sageattention.sageattn` [4][5] before the PyTorch SDPA path or
|
|
85
|
+
the explicit path.
|
|
86
|
+
scale : float = q.shape[-1] ** -0.5
|
|
87
|
+
Attention-score multiplier used in every backend.
|
|
88
|
+
|
|
89
|
+
References
|
|
90
|
+
----------
|
|
91
|
+
[1] `Attention`
|
|
92
|
+
|
|
93
|
+
[2] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L.,
|
|
94
|
+
Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention Is All You Need.
|
|
95
|
+
https://arxiv.org/abs/1706.03762
|
|
96
|
+
[3] PyTorch.
|
|
97
|
+
https://context7.com/pytorch/pytorch
|
|
98
|
+
[4] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., and Chen, J. (2025).
|
|
99
|
+
SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
|
|
100
|
+
https://arxiv.org/abs/2410.02367
|
|
101
|
+
[5] thu-ml/SageAttention
|
|
102
|
+
https://github.com/thu-ml/SageAttention
|
|
103
|
+
[6] `hunterFormsBS.theTypes.FlashAttentionConfig`
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def __init__(self, attn_dropout: float, scale: float, *, flash: bool = False, sage_attention: bool = False) -> None:
|
|
107
|
+
"""Configure attention-score scaling and backend selection.
|
|
108
|
+
|
|
109
|
+
You can use `__init__` to set the attention-weight dropout probability, store the
|
|
110
|
+
attention-score multiplier, and select which fallback backends `forward` may use. `__init__`
|
|
111
|
+
prepares one PyTorch SDPA configuration for CPU execution and, when `flash=True` and a
|
|
112
|
+
supported CUDA device is available, one PyTorch SDPA configuration for CUDA execution [1].
|
|
113
|
+
`__init__` also stores whether `forward` should prefer SageAttention [2][3], which you must
|
|
114
|
+
install manually outside this package.
|
|
115
|
+
|
|
116
|
+
Parameters
|
|
117
|
+
----------
|
|
118
|
+
attn_dropout : float
|
|
119
|
+
Probability applied to attention weights during training.
|
|
120
|
+
scale : float
|
|
121
|
+
Attention-score multiplier used by every backend.
|
|
122
|
+
flash : bool = False
|
|
123
|
+
Whether `forward` may delegate to PyTorch SDPA [1] through `flash_attn` when
|
|
124
|
+
`sage_attention` is `False`.
|
|
125
|
+
sage_attention : bool = False
|
|
126
|
+
Whether `forward` should first try `sageattention.sageattn` [2][3]. `hunterFormsBS` does
|
|
127
|
+
not install `sageattention`.
|
|
128
|
+
|
|
129
|
+
PyTorch
|
|
130
|
+
-------
|
|
131
|
+
backend selection : implementation detail
|
|
132
|
+
`__init__` inspects the active CUDA device when `flash` is `True`. `__init__` enables the
|
|
133
|
+
flash backend only on A100 devices and keeps the math plus memory-efficient backends
|
|
134
|
+
available on other CUDA devices [1].
|
|
135
|
+
|
|
136
|
+
References
|
|
137
|
+
----------
|
|
138
|
+
[1] PyTorch.
|
|
139
|
+
https://context7.com/pytorch/pytorch
|
|
140
|
+
[2] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., and Chen, J. (2025).
|
|
141
|
+
SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
|
|
142
|
+
https://arxiv.org/abs/2410.02367
|
|
143
|
+
[3] thu-ml/SageAttention
|
|
144
|
+
https://github.com/thu-ml/SageAttention
|
|
145
|
+
""" # noqa: DOC501
|
|
146
|
+
super().__init__()
|
|
147
|
+
self.scale: float = scale
|
|
148
|
+
self.attn_dropout: float = attn_dropout
|
|
149
|
+
self.nn_Dropout: nn.Dropout = nn.Dropout(self.attn_dropout)
|
|
150
|
+
|
|
151
|
+
self.flash: bool = flash
|
|
152
|
+
if self.flash and version.parse(torch.__version__) < version.parse('2.0.0'):
|
|
153
|
+
pytorchVersion: str = torch.__version__
|
|
154
|
+
message: str = f'I received `{pytorchVersion = }`, but `flash=True` requires PyTorch 2.0.0 or above.'
|
|
155
|
+
raise RuntimeError(message)
|
|
156
|
+
|
|
157
|
+
self.sage_attention: bool = sage_attention
|
|
158
|
+
|
|
159
|
+
# determine efficient attention configs for cuda and cpu
|
|
160
|
+
|
|
161
|
+
self.cpu_config: FlashAttentionConfig = FlashAttentionConfig(enable_flash=True, enable_math=True, enable_mem_efficient=True)
|
|
162
|
+
self.cuda_config: FlashAttentionConfig | None = None
|
|
163
|
+
|
|
164
|
+
if not torch.cuda.is_available() or not self.flash:
|
|
165
|
+
return
|
|
166
|
+
|
|
167
|
+
device_properties: _CudaDeviceProperties = torch.cuda.get_device_properties(torch.device('cuda')) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
|
|
168
|
+
device_properties = cast('_CudaDeviceProperties', device_properties) # ty:ignore[redundant-cast]
|
|
169
|
+
|
|
170
|
+
if device_properties.major == 8 and device_properties.minor == 0:
|
|
171
|
+
print_once('A100 GPU detected, using flash attention if input tensor is on cuda')
|
|
172
|
+
self.cuda_config = FlashAttentionConfig(enable_flash=True, enable_math=False, enable_mem_efficient=False)
|
|
173
|
+
else:
|
|
174
|
+
print_once('Non-A100 GPU detected, using math or mem efficient attention if input tensor is on cuda')
|
|
175
|
+
self.cuda_config = FlashAttentionConfig(enable_flash=False, enable_math=True, enable_mem_efficient=True)
|
|
176
|
+
|
|
177
|
+
def flash_attn(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
|
|
178
|
+
"""Compute attention output from query, key, and value arrays with PyTorch SDPA.
|
|
179
|
+
|
|
180
|
+
You can use `flash_attn` when query `Tensor` `q`, key `Tensor` `k`, and value `Tensor` `v`
|
|
181
|
+
already share compatible batch, head, sequence, and head-feature axes. `flash_attn` is the
|
|
182
|
+
PyTorch-SDPA path selected by `forward` [1] when `sage_attention` is `False` and `flash` is
|
|
183
|
+
`True`. `flash_attn` rescales query `Tensor` `q` when `self.scale` differs from the default
|
|
184
|
+
inverse-square-root query-feature normalization [2]. `flash_attn` then selects a PyTorch SDPA
|
|
185
|
+
backend with `torch.backends.cuda.sdp_kernel` [3] and returns the attention-weighted mixture
|
|
186
|
+
of value `Tensor` `v` through `torch.nn.functional.scaled_dot_product_attention` [3]. When the
|
|
187
|
+
selected backend supports it, PyTorch may realize the computation with a flash-style kernel
|
|
188
|
+
[4].
|
|
189
|
+
|
|
190
|
+
Parameters
|
|
191
|
+
----------
|
|
192
|
+
q : Tensor
|
|
193
|
+
Query `Tensor` with shape `batch × head × query position × head feature`.
|
|
194
|
+
k : Tensor
|
|
195
|
+
Key `Tensor` with shape `batch × head × key position × head feature`.
|
|
196
|
+
v : Tensor
|
|
197
|
+
Value `Tensor` with shape `batch × head × key position × head feature`.
|
|
198
|
+
|
|
199
|
+
Returns
|
|
200
|
+
-------
|
|
201
|
+
out : Tensor
|
|
202
|
+
Attention output `Tensor` with shape `batch × head × query position × head feature`.
|
|
203
|
+
|
|
204
|
+
Mathematics
|
|
205
|
+
-----------
|
|
206
|
+
scaled scores : equation
|
|
207
|
+
```
|
|
208
|
+
Let d ≜ `q.shape[-1]`, s₀ ≜ `self.scale`, Q ≜ `q`, K ≜ `k`, V ≜ `v`,
|
|
209
|
+
s₀ ∈ ℝ ∪ {∅}
|
|
210
|
+
|
|
211
|
+
s = ⎧ s₀, s₀ ≠ ∅
|
|
212
|
+
⎨
|
|
213
|
+
⎩ d⁻¹ᐟ², s₀ = ∅
|
|
214
|
+
|
|
215
|
+
Q′ = (s / d⁻¹ᐟ²) Q
|
|
216
|
+
S[b, h, i, j] = ⟨Q′[b, h, i, :], K[b, h, j, :]⟩ · d⁻¹ᐟ² = ⟨Q[b, h, i, :], K[b, h, j, :]⟩ · s
|
|
217
|
+
A[b, h, i, j] = exp(S[b, h, i, j]) / ∑ₘ exp(S[b, h, i, m])
|
|
218
|
+
O[b, h, i, :] = ∑ⱼ A[b, h, i, j] · V[b, h, j, :]
|
|
219
|
+
|
|
220
|
+
where O ≜ `out`
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
PyTorch
|
|
224
|
+
-------
|
|
225
|
+
backend selection : implementation detail
|
|
226
|
+
`flash_attn` always enters `torch.backends.cuda.sdp_kernel` [1] before calling
|
|
227
|
+
`torch.nn.functional.scaled_dot_product_attention` [1]. `cpu_config` enables all three
|
|
228
|
+
SDPA backend families. When `q.is_cuda` is `True` and `cuda_config` is available,
|
|
229
|
+
`flash_attn` switches to the stored CUDA-specific flags. During training, `flash_attn`
|
|
230
|
+
passes `self.attn_dropout`, and during evaluation, `flash_attn` passes `0.0`.
|
|
231
|
+
|
|
232
|
+
References
|
|
233
|
+
----------
|
|
234
|
+
[1] `Attend.forward`
|
|
235
|
+
|
|
236
|
+
[2] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L.,
|
|
237
|
+
Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention Is All You Need.
|
|
238
|
+
https://arxiv.org/abs/1706.03762
|
|
239
|
+
[3] PyTorch.
|
|
240
|
+
https://context7.com/pytorch/pytorch
|
|
241
|
+
[4] Dao, T., Fu, D. Y., Ermon, S., Rudra, A., and Ré, C. (2022).
|
|
242
|
+
FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness.
|
|
243
|
+
https://arxiv.org/abs/2205.14135
|
|
244
|
+
"""
|
|
245
|
+
is_cuda: bool = q.is_cuda
|
|
246
|
+
|
|
247
|
+
q *= (self.scale / (q.shape[-1] ** neg(0.5)))
|
|
248
|
+
|
|
249
|
+
# Check if there is a compatible device for flash attention
|
|
250
|
+
config: FlashAttentionConfig = self.cpu_config
|
|
251
|
+
if is_cuda and exists(self.cuda_config):
|
|
252
|
+
config = self.cuda_config
|
|
253
|
+
|
|
254
|
+
with torch.backends.cuda.sdp_kernel(**config._asdict()): # pyright: ignore[reportDeprecated]
|
|
255
|
+
out: Tensor = F.scaled_dot_product_attention(q, k, v, dropout_p=self.attn_dropout if self.training else 0.0)
|
|
256
|
+
|
|
257
|
+
return out
|
|
258
|
+
|
|
259
|
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
|
|
260
|
+
"""Compute attention output from query, key, and value arrays.
|
|
261
|
+
|
|
262
|
+
You can use `forward` after another module has already built query `Tensor` `q`, key `Tensor`
|
|
263
|
+
`k`, and value `Tensor` `v`. `forward` compares query `Tensor` `q` against key `Tensor` `k` to
|
|
264
|
+
build attention weights and then uses those attention weights to mix value `Tensor` `v`. When
|
|
265
|
+
`sage_attention` is `True`, `forward` imports and calls `sageattention.sageattn(q, k, v,
|
|
266
|
+
tensor_layout='HND', is_causal=False)` [1][2]. When `sage_attention` is `False` and `flash` is
|
|
267
|
+
`True`, `forward` delegates to `flash_attn` [3]. Otherwise `forward` computes the standard
|
|
268
|
+
scaled dot-product attention weights explicitly with `softmax` [4].
|
|
269
|
+
|
|
270
|
+
Parameters
|
|
271
|
+
----------
|
|
272
|
+
q : Tensor
|
|
273
|
+
Query `Tensor` with shape `batch × head × query position × head feature`.
|
|
274
|
+
k : Tensor
|
|
275
|
+
Key `Tensor` with shape `batch × head × key position × head feature`.
|
|
276
|
+
v : Tensor
|
|
277
|
+
Value `Tensor` with shape `batch × head × key position × head feature`.
|
|
278
|
+
|
|
279
|
+
Returns
|
|
280
|
+
-------
|
|
281
|
+
out : Tensor
|
|
282
|
+
Attention output `Tensor` with shape `batch × head × query position × head feature`.
|
|
283
|
+
|
|
284
|
+
SageAttention
|
|
285
|
+
-------------
|
|
286
|
+
manual installation : dependency
|
|
287
|
+
`hunterFormsBS` does not install `sageattention`. Install `sageattention` manually from
|
|
288
|
+
the SageAttention project [2] before enabling `sage_attention`.
|
|
289
|
+
|
|
290
|
+
Mathematics
|
|
291
|
+
-----------
|
|
292
|
+
scaled scores : equation
|
|
293
|
+
```
|
|
294
|
+
Let d ≜ `q.shape[-1]`, s₀ ≜ `self.scale`, Q ≜ `q`, K ≜ `k`, V ≜ `v`,
|
|
295
|
+
s₀ ∈ ℝ ∪ {∅}
|
|
296
|
+
|
|
297
|
+
s = ⎧ s₀, s₀ ≠ ∅
|
|
298
|
+
⎨
|
|
299
|
+
⎩ d⁻¹ᐟ², s₀ = ∅
|
|
300
|
+
|
|
301
|
+
S[b, h, i, j] = ⟨Q[b, h, i, :], K[b, h, j, :]⟩ · s
|
|
302
|
+
A[b, h, i, j] = exp(S[b, h, i, j]) / ∑ₘ exp(S[b, h, i, m])
|
|
303
|
+
O[b, h, i, :] = ∑ⱼ A[b, h, i, j] · V[b, h, j, :]
|
|
304
|
+
|
|
305
|
+
where S ≜ `similarity`, A ≜ `attention_weights`
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
References
|
|
309
|
+
----------
|
|
310
|
+
[1] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., and Chen, J. (2025).
|
|
311
|
+
SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
|
|
312
|
+
https://arxiv.org/abs/2410.02367
|
|
313
|
+
[2] thu-ml/SageAttention
|
|
314
|
+
https://github.com/thu-ml/SageAttention
|
|
315
|
+
[3] `Attend.flash_attn`
|
|
316
|
+
|
|
317
|
+
[4] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L.,
|
|
318
|
+
Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention Is All You Need.
|
|
319
|
+
https://arxiv.org/abs/1706.03762
|
|
320
|
+
"""
|
|
321
|
+
if self.sage_attention:
|
|
322
|
+
from sageattention import sageattn # pyright: ignore[reportMissingImports, reportUnknownVariableType] # ty:ignore[unresolved-import]
|
|
323
|
+
return sageattn(q, k, v, tensor_layout='HND', is_causal=False) # pyright: ignore[reportUnknownVariableType]
|
|
324
|
+
if self.flash:
|
|
325
|
+
return self.flash_attn(q, k, v)
|
|
326
|
+
|
|
327
|
+
similarity: Tensor = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
|
|
328
|
+
|
|
329
|
+
attention_weights: Tensor = similarity.softmax(dim=-1)
|
|
330
|
+
attention_weights = self.nn_Dropout(attention_weights)
|
|
331
|
+
|
|
332
|
+
# aggregate values
|
|
333
|
+
return einsum('b h i j, b h j d -> b h i d', attention_weights, v)
|
|
334
|
+
|
|
335
|
+
class Attention(nn.Module):
|
|
336
|
+
"""Mix information across sequence positions and return updated features.
|
|
337
|
+
|
|
338
|
+
You can use `Attention` when activation `Tensor` `x` at each sequence position should gather
|
|
339
|
+
information from other sequence positions before the next block. `Attention` projects activation
|
|
340
|
+
`Tensor` `x` into query `Tensor` `q`, key `Tensor` `k`, and value `Tensor` `v`, applies PoPE
|
|
341
|
+
[1][2] or RoPE [3] when those position encoders are available, and aggregates the result through
|
|
342
|
+
`Attend` [4].
|
|
343
|
+
|
|
344
|
+
PyTorch
|
|
345
|
+
-------
|
|
346
|
+
module structure : implementation detail
|
|
347
|
+
`Attention` applies `RMSNorm` to the input activations, projects the normalized activations
|
|
348
|
+
with `to_qkv`, reshapes the projected result into head-specific query `Tensor` `q`, key
|
|
349
|
+
`Tensor` `k`, and value `Tensor` `v`, and then chooses one of three execution paths.
|
|
350
|
+
`Attention` calls `flash_attn_with_pope` [2] when `pope_embed` is available, rotates query
|
|
351
|
+
`Tensor` `q` and key `Tensor` `k` before `Attend` [4] when `rotary_embed` is available, and
|
|
352
|
+
otherwise delegates directly to `Attend` [4]. After aggregation, `Attention` multiplies each
|
|
353
|
+
head output by a sigmoid gate from `to_gates`, concatenates the gated head outputs, and
|
|
354
|
+
applies `to_out`.
|
|
355
|
+
|
|
356
|
+
Attributes
|
|
357
|
+
----------
|
|
358
|
+
attend : Attend
|
|
359
|
+
Exact attention core used when `pope_embed` is `None` [4].
|
|
360
|
+
heads : int
|
|
361
|
+
Number of attention heads.
|
|
362
|
+
norm : RMSNorm
|
|
363
|
+
Root-mean-square normalization module applied before the projections.
|
|
364
|
+
pope_embed : PoPE | None
|
|
365
|
+
Optional polar-coordinate position encoder [1][2].
|
|
366
|
+
rotary_embed : RotaryEmbedding | None
|
|
367
|
+
Optional rotary position encoder [3].
|
|
368
|
+
scale : float = dim_head ** -0.5
|
|
369
|
+
Head-feature normalization factor. `scale` is `dim_head ** -0.5` when `scale` is omitted.
|
|
370
|
+
to_gates : nn.Linear
|
|
371
|
+
Projection layer implemented with `nn.Linear` [6] to produce one gate value for each head.
|
|
372
|
+
to_out : nn.Sequential
|
|
373
|
+
Output projection and dropout submodule sequence implemented with PyTorch layers [6].
|
|
374
|
+
to_qkv : nn.Linear
|
|
375
|
+
Projection layer implemented with `nn.Linear` [6] to produce concatenated query, key, and
|
|
376
|
+
value features.
|
|
377
|
+
|
|
378
|
+
References
|
|
379
|
+
----------
|
|
380
|
+
[1] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., and Mozer, M. C. (2025).
|
|
381
|
+
Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings.
|
|
382
|
+
https://arxiv.org/abs/2509.10534
|
|
383
|
+
[2] lucidrains/PoPE-pytorch.
|
|
384
|
+
https://github.com/lucidrains/PoPE-pytorch
|
|
385
|
+
[3] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu, Y. (2021). RoFormer: Enhanced
|
|
386
|
+
Transformer with Rotary Position Embedding. https://arxiv.org/abs/2104.09864
|
|
387
|
+
[4] `Attend`
|
|
388
|
+
|
|
389
|
+
[5] `hunterFormsBS.transform.Transformer`
|
|
390
|
+
|
|
391
|
+
[6] PyTorch.
|
|
392
|
+
https://context7.com/pytorch/pytorch
|
|
393
|
+
"""
|
|
394
|
+
def __init__(
|
|
395
|
+
self
|
|
396
|
+
, dim: int
|
|
397
|
+
, dim_head: int = 64
|
|
398
|
+
, attn_dropout: float = 0.0
|
|
399
|
+
, heads: int = 8
|
|
400
|
+
, pope_embed: PoPE | None = None
|
|
401
|
+
, rotary_embed: RotaryEmbedding | None = None
|
|
402
|
+
, scale: float | None = None
|
|
403
|
+
, *
|
|
404
|
+
, flash: bool = True
|
|
405
|
+
, sage_attention: bool = False,
|
|
406
|
+
) -> None:
|
|
407
|
+
"""Set up an attention block for a chosen width and head layout.
|
|
408
|
+
|
|
409
|
+
You can use `__init__` to choose the feature width, head layout, dropout probability,
|
|
410
|
+
position-encoding path, and attention backend for the block. `__init__` stores the resulting
|
|
411
|
+
submodules so later calls to `forward` can reuse the same attention block.
|
|
412
|
+
|
|
413
|
+
PyTorch
|
|
414
|
+
-------
|
|
415
|
+
submodule construction : implementation detail
|
|
416
|
+
`__init__` computes `dim_inner = heads * dim_head`, stores `rotary_embed` and
|
|
417
|
+
`pope_embed`, creates `Attend(flash=flash, attn_dropout=attn_dropout,
|
|
418
|
+
sage_attention=sage_attention)` [1], instantiates `RMSNorm(dim)`, and constructs `to_qkv =
|
|
419
|
+
nn.Linear(dim, dim_inner * 3, bias=False)`, `to_gates = nn.Linear(dim, heads)`, and
|
|
420
|
+
`to_out = nn.Sequential(nn.Linear(dim_inner, dim, bias=False), nn.Dropout(attn_dropout))`
|
|
421
|
+
[2].
|
|
422
|
+
|
|
423
|
+
Parameters
|
|
424
|
+
----------
|
|
425
|
+
dim : int
|
|
426
|
+
Input feature width before projection and output feature width after `to_out`.
|
|
427
|
+
heads : int = 8
|
|
428
|
+
Number of attention heads.
|
|
429
|
+
dim_head : int = 64
|
|
430
|
+
Feature width of each head before concatenation.
|
|
431
|
+
attn_dropout : float = 0.0
|
|
432
|
+
Probability used by `Attend` [1] and the output dropout layer.
|
|
433
|
+
pope_embed : PoPE | None = None
|
|
434
|
+
Optional polar-coordinate position encoder [3][4]. When `pope_embed` is not `None`,
|
|
435
|
+
`forward` prefers the PoPE path over the rotary path.
|
|
436
|
+
rotary_embed : RotaryEmbedding | None = None
|
|
437
|
+
Optional rotary position encoder [5]. `forward` uses `rotary_embed` only when `pope_embed`
|
|
438
|
+
is `None`.
|
|
439
|
+
scale : float | None = None
|
|
440
|
+
Optional attention-score multiplier override. When `scale` is `None`, `__init__` stores
|
|
441
|
+
`dim_head ** -0.5`.
|
|
442
|
+
flash : bool = True
|
|
443
|
+
Whether `Attend` [1] may use PyTorch SDPA [2] when the PoPE path is not active and
|
|
444
|
+
`sage_attention` is `False`.
|
|
445
|
+
sage_attention : bool = False
|
|
446
|
+
Whether `Attend` [1] should prefer SageAttention [6][7]. `hunterFormsBS` does not install
|
|
447
|
+
`sageattention`.
|
|
448
|
+
|
|
449
|
+
References
|
|
450
|
+
----------
|
|
451
|
+
[1] `Attend`
|
|
452
|
+
|
|
453
|
+
[2] PyTorch.
|
|
454
|
+
https://context7.com/pytorch/pytorch
|
|
455
|
+
[3] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., and Mozer, M. C. (2025).
|
|
456
|
+
Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings.
|
|
457
|
+
https://arxiv.org/abs/2509.10534
|
|
458
|
+
[4] lucidrains/PoPE-pytorch.
|
|
459
|
+
https://github.com/lucidrains/PoPE-pytorch
|
|
460
|
+
[5] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu, Y. (2021). RoFormer: Enhanced
|
|
461
|
+
Transformer with Rotary Position Embedding. https://arxiv.org/abs/2104.09864
|
|
462
|
+
[6] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., and Chen, J. (2025).
|
|
463
|
+
SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
|
|
464
|
+
https://arxiv.org/abs/2410.02367
|
|
465
|
+
[7] thu-ml/SageAttention
|
|
466
|
+
https://github.com/thu-ml/SageAttention
|
|
467
|
+
"""
|
|
468
|
+
super().__init__()
|
|
469
|
+
|
|
470
|
+
self.heads: int = heads
|
|
471
|
+
self.norm: RMSNorm = RMSNorm(dim)
|
|
472
|
+
self.pope_embed: PoPE | None = pope_embed
|
|
473
|
+
self.rotary_embed: RotaryEmbedding | None = rotary_embed
|
|
474
|
+
self.scale: float = scale or dim_head ** neg(0.5)
|
|
475
|
+
|
|
476
|
+
self.attend: Attend = Attend(attn_dropout=attn_dropout, scale=self.scale, flash=flash, sage_attention=sage_attention)
|
|
477
|
+
self.to_gates: nn.Linear = nn.Linear(dim, self.heads)
|
|
478
|
+
|
|
479
|
+
dim_inner: int = self.heads * dim_head
|
|
480
|
+
|
|
481
|
+
self.to_qkv: nn.Linear = nn.Linear(in_features=dim, out_features=dim_inner * 3, bias=False)
|
|
482
|
+
self.to_out: nn.Sequential = nn.Sequential(nn.Linear(in_features=dim_inner, out_features=dim, bias=False), nn.Dropout(attn_dropout))
|
|
483
|
+
|
|
484
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
485
|
+
"""Compute gated multi-head attention output from activations `x`.
|
|
486
|
+
|
|
487
|
+
You can use `forward` to normalize activations `x`, project activation `Tensor` `x` into query
|
|
488
|
+
`Tensor` `q`, key `Tensor` `k`, and value `Tensor` `v`, inject position through
|
|
489
|
+
`pope_embed` [1][2] or `rotary_embed` [3], aggregate value `Tensor` `v` through
|
|
490
|
+
`Attend.forward` [4] or the PoPE-specific flash-attention path [2], and return the gated,
|
|
491
|
+
concatenated, projected result.
|
|
492
|
+
|
|
493
|
+
Parameters
|
|
494
|
+
----------
|
|
495
|
+
x : Tensor
|
|
496
|
+
Input activation `Tensor` with shape `batch × sequence position × feature`.
|
|
497
|
+
|
|
498
|
+
Returns
|
|
499
|
+
-------
|
|
500
|
+
out : Tensor
|
|
501
|
+
Output activation `Tensor` with shape `batch × sequence position × feature`.
|
|
502
|
+
|
|
503
|
+
Mathematics
|
|
504
|
+
-----------
|
|
505
|
+
gated multi-head attention : equation
|
|
506
|
+
```
|
|
507
|
+
Let H ≜ `self.heads`, α ≜ `self.scale`,
|
|
508
|
+
X ≜ `self.norm(x)`, Q ≜ `q`, K ≜ `k`, V ≜ `v`,
|
|
509
|
+
wₕᴳ ≜ `to_gates`.weight[h, :], h ∈ {0, …, H−1},
|
|
510
|
+
Wᴼ ≜ `to_out[0]`.weight
|
|
511
|
+
|
|
512
|
+
S[b, h, i, j] = ⟨Q[b, h, i, :], K[b, h, j, :]⟩ · α
|
|
513
|
+
A[b, h, i, j] = exp(S[b, h, i, j]) / ∑ₘ exp(S[b, h, i, m])
|
|
514
|
+
O[b, h, i, :] = ∑ⱼ A[b, h, i, j] · V[b, h, j, :]
|
|
515
|
+
G[b, i, h] = σ(⟨X[b, i, :], wₕᴳ⟩)
|
|
516
|
+
Z[b, i, hd : (h+1)d] = G[b, i, h] · O[b, h, i, :]
|
|
517
|
+
Y[b, i, :] = Z[b, i, :] Wᴼ
|
|
518
|
+
|
|
519
|
+
where G ≜ `gates`, Y ≜ `out`
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
PyTorch
|
|
523
|
+
-------
|
|
524
|
+
path selection and head gating : implementation detail
|
|
525
|
+
`forward` computes query `Tensor` `q`, key `Tensor` `k`, and value `Tensor` `v` from
|
|
526
|
+
normalized `x`. When `pope_embed` is available, `forward` calls `flash_attn_with_pope` [2]
|
|
527
|
+
with `pos_emb=self.pope_embed(x.shape[-2])` and `softmax_scale=self.scale`. When
|
|
528
|
+
`pope_embed` is absent and `rotary_embed` is available, `forward` rotates query `Tensor`
|
|
529
|
+
`q` and key `Tensor` `k` before `Attend.forward` [4]. When neither positional encoder is
|
|
530
|
+
available, `forward` passes query `Tensor` `q`, key `Tensor` `k`, and value `Tensor` `v`
|
|
531
|
+
directly to `Attend.forward` [4]. After the attention output is produced, `forward`
|
|
532
|
+
multiplies each head output by `sigmoid(self.to_gates(X))`, concatenates the gated heads,
|
|
533
|
+
and applies `to_out`.
|
|
534
|
+
|
|
535
|
+
References
|
|
536
|
+
----------
|
|
537
|
+
[1] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., and Mozer, M. C. (2025).
|
|
538
|
+
Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings.
|
|
539
|
+
https://arxiv.org/abs/2509.10534
|
|
540
|
+
[2] lucidrains/PoPE-pytorch.
|
|
541
|
+
https://github.com/lucidrains/PoPE-pytorch
|
|
542
|
+
[3] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu, Y. (2021).
|
|
543
|
+
RoFormer: Enhanced Transformer with Rotary Position Embedding.
|
|
544
|
+
https://arxiv.org/abs/2104.09864
|
|
545
|
+
[4] `Attend.forward`
|
|
546
|
+
|
|
547
|
+
[5] `hunterFormsBS.transform.Transformer`
|
|
548
|
+
|
|
549
|
+
[6] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L.,
|
|
550
|
+
Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention Is All You Need.
|
|
551
|
+
https://arxiv.org/abs/1706.03762
|
|
552
|
+
"""
|
|
553
|
+
x = self.norm(x)
|
|
554
|
+
|
|
555
|
+
q, k, v = rearrange(self.to_qkv(x), 'b n (qkv h d) -> qkv b h n d', qkv=3, h=self.heads)
|
|
556
|
+
|
|
557
|
+
if exists(self.pope_embed):
|
|
558
|
+
out: Tensor = flash_attn_with_pope(q, k, v, pos_emb=self.pope_embed(q.shape[-2]), softmax_scale=self.scale)
|
|
559
|
+
elif exists(self.rotary_embed):
|
|
560
|
+
q: Tensor = self.rotary_embed.rotate_queries_or_keys(q)
|
|
561
|
+
k: Tensor = self.rotary_embed.rotate_queries_or_keys(k)
|
|
562
|
+
out = self.attend(q, k, v)
|
|
563
|
+
else:
|
|
564
|
+
out = self.attend(q, k, v)
|
|
565
|
+
|
|
566
|
+
gates: Tensor = self.to_gates(x)
|
|
567
|
+
out *= rearrange(gates, 'b n h -> b h n 1').sigmoid()
|
|
568
|
+
|
|
569
|
+
out = rearrange(out, 'b h n d -> b n (h d)')
|
|
570
|
+
return self.to_out(out)
|