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,313 @@
|
|
|
1
|
+
"""Define shared typed configuration records for `hunterFormsBS`.
|
|
2
|
+
|
|
3
|
+
You can use this module to access the small record classes that group related keyword arguments and
|
|
4
|
+
pass those keyword arguments through several constructor layers without renaming fields. The records
|
|
5
|
+
keep the attention stack, the mask-estimation heads, the optional segmentation branch, the STFT
|
|
6
|
+
helpers, and the separator model aligned when one outer model configures several downstream classes.
|
|
7
|
+
The records are consumed by `hunterFormsBS.attend` [1], `hunterFormsBS.bands` [2],
|
|
8
|
+
`hunterFormsBS.loss` [3], `hunterFormsBS.mask` [4],
|
|
9
|
+
`hunterFormsBS.bandSplitRotator.BandSplitRotator` [5], and `hunterFormsBS.hyperACE` [6].
|
|
10
|
+
|
|
11
|
+
Contents
|
|
12
|
+
--------
|
|
13
|
+
Classes
|
|
14
|
+
FlashAttentionConfig
|
|
15
|
+
Store one scaled-dot-product-attention backend selection record.
|
|
16
|
+
ParametersAttention
|
|
17
|
+
Collect one attention-block keyword record.
|
|
18
|
+
ParametersComputeLoss
|
|
19
|
+
Collect one multi-resolution STFT loss keyword record.
|
|
20
|
+
ParametersMaskEstimator
|
|
21
|
+
Collect one mask-estimator keyword record.
|
|
22
|
+
ParametersSTFT
|
|
23
|
+
Collect one forward-and-inverse STFT keyword record.
|
|
24
|
+
ParametersTransformer
|
|
25
|
+
Collect one transformer-block keyword record.
|
|
26
|
+
|
|
27
|
+
References
|
|
28
|
+
----------
|
|
29
|
+
[1] `hunterFormsBS.attend`
|
|
30
|
+
|
|
31
|
+
[2] `hunterFormsBS.bands`
|
|
32
|
+
|
|
33
|
+
[3] `hunterFormsBS.loss`
|
|
34
|
+
|
|
35
|
+
[4] `hunterFormsBS.mask`
|
|
36
|
+
|
|
37
|
+
[5] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
|
|
38
|
+
|
|
39
|
+
[6] `hunterFormsBS.hyperACE`
|
|
40
|
+
"""
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
from typing import NamedTuple, TYPE_CHECKING, TypedDict
|
|
44
|
+
|
|
45
|
+
if TYPE_CHECKING:
|
|
46
|
+
from collections.abc import Callable
|
|
47
|
+
from PoPE_pytorch import PoPE
|
|
48
|
+
from rotary_embedding_torch import RotaryEmbedding
|
|
49
|
+
from torch import nn, Tensor
|
|
50
|
+
|
|
51
|
+
class FlashAttentionConfig(NamedTuple):
|
|
52
|
+
"""Store one scaled-dot-product-attention backend selection record.
|
|
53
|
+
|
|
54
|
+
You can use `FlashAttentionConfig` to keep the backend-enable flags together when one attention
|
|
55
|
+
block selects which scaled-dot-product-attention backend may run on CPU or CUDA.
|
|
56
|
+
|
|
57
|
+
Attributes
|
|
58
|
+
----------
|
|
59
|
+
enable_flash : bool
|
|
60
|
+
Whether the flash backend may run.
|
|
61
|
+
enable_math : bool
|
|
62
|
+
Whether the math backend may run.
|
|
63
|
+
enable_mem_efficient : bool
|
|
64
|
+
Whether the memory-efficient backend may run.
|
|
65
|
+
"""
|
|
66
|
+
enable_flash: bool
|
|
67
|
+
enable_math: bool
|
|
68
|
+
enable_mem_efficient: bool
|
|
69
|
+
|
|
70
|
+
class ParametersAttention(TypedDict):
|
|
71
|
+
"""Collect one attention-block keyword record.
|
|
72
|
+
|
|
73
|
+
You can use `ParametersAttention` to keep one attention-block configuration together while outer
|
|
74
|
+
model classes forward stable field names through several constructor layers. The record stores head
|
|
75
|
+
geometry, dropout, positional-encoder objects, backend toggles, and attention-score scaling.
|
|
76
|
+
|
|
77
|
+
Attributes
|
|
78
|
+
----------
|
|
79
|
+
attn_dropout : float
|
|
80
|
+
Dropout probability applied inside the attention block.
|
|
81
|
+
dim_head : int
|
|
82
|
+
Feature width of each attention head before concatenation.
|
|
83
|
+
dim : int
|
|
84
|
+
Input and output feature width of the attention block.
|
|
85
|
+
flash : bool
|
|
86
|
+
Whether the attention block may use the optimized scaled-dot-product-attention backend path.
|
|
87
|
+
heads : int
|
|
88
|
+
Number of attention heads.
|
|
89
|
+
pope_embed : PoPE | None
|
|
90
|
+
Optional polar-coordinate positional encoder object. `pope_embed` is mutually exclusive with
|
|
91
|
+
`rotary_embed`.
|
|
92
|
+
rotary_embed : RotaryEmbedding | None
|
|
93
|
+
Optional rotary positional encoder object. `rotary_embed` is mutually exclusive with
|
|
94
|
+
`pope_embed`.
|
|
95
|
+
sage_attention : bool
|
|
96
|
+
Whether the attention block may try the optional `SageAttention` backend [1]. `SageAttention`
|
|
97
|
+
is not installed automatically with `hunterFormsBS`, so you must install `SageAttention`
|
|
98
|
+
separately [1].
|
|
99
|
+
scale : float | None
|
|
100
|
+
Optional override for the default inverse-square-root attention-score scale.
|
|
101
|
+
|
|
102
|
+
References
|
|
103
|
+
----------
|
|
104
|
+
[1] thu-ml/SageAttention
|
|
105
|
+
https://github.com/thu-ml/SageAttention
|
|
106
|
+
"""
|
|
107
|
+
attn_dropout: float
|
|
108
|
+
dim_head: int
|
|
109
|
+
dim: int
|
|
110
|
+
flash: bool
|
|
111
|
+
heads: int
|
|
112
|
+
pope_embed: PoPE | None
|
|
113
|
+
rotary_embed: RotaryEmbedding | None
|
|
114
|
+
sage_attention: bool
|
|
115
|
+
scale: float | None
|
|
116
|
+
|
|
117
|
+
class ParametersComputeLoss(TypedDict):
|
|
118
|
+
"""Collect one multi-resolution STFT loss keyword record.
|
|
119
|
+
|
|
120
|
+
You can use `ParametersComputeLoss` to keep the shared short-time Fourier transform (STFT) loss
|
|
121
|
+
settings together. The record stores the hop size, each evaluation window size, the minimum FFT
|
|
122
|
+
size, the normalization flag, the loss weight, and the window-construction callable.
|
|
123
|
+
|
|
124
|
+
Attributes
|
|
125
|
+
----------
|
|
126
|
+
hop_length : int
|
|
127
|
+
Hop size between adjacent STFT frames.
|
|
128
|
+
loss_weight : float
|
|
129
|
+
Multiplier for the multi-resolution STFT loss term.
|
|
130
|
+
window_sizes : tuple[int, ...]
|
|
131
|
+
Each STFT windowing-function size evaluated by the multi-resolution loss.
|
|
132
|
+
n_fft : int
|
|
133
|
+
Lower bound on the FFT size used for each STFT resolution.
|
|
134
|
+
normalized : bool
|
|
135
|
+
Whether each STFT uses normalized scaling.
|
|
136
|
+
window_fn : Callable[..., Tensor]
|
|
137
|
+
Callable that builds the STFT ***window***ing function for a requested size.
|
|
138
|
+
"""
|
|
139
|
+
hop_length: int
|
|
140
|
+
loss_weight: float
|
|
141
|
+
window_sizes: tuple[int, ...]
|
|
142
|
+
n_fft: int
|
|
143
|
+
normalized: bool
|
|
144
|
+
window_fn: Callable[..., Tensor]
|
|
145
|
+
|
|
146
|
+
class ParametersMaskEstimator(TypedDict):
|
|
147
|
+
"""Collect one mask-estimator keyword record.
|
|
148
|
+
|
|
149
|
+
You can use `ParametersMaskEstimator` to keep the full `MaskEstimator` keyword family together
|
|
150
|
+
while `BandSplitRotator` forwards stable field names into each mask-estimator head [1]. The
|
|
151
|
+
record stores the shared band-local MLP settings, the `use_hyperACE` switch, and the `segm_*`
|
|
152
|
+
parameter families for the optional segmentation-style branch [2].
|
|
153
|
+
|
|
154
|
+
Attributes
|
|
155
|
+
----------
|
|
156
|
+
activation : type[nn.Module]
|
|
157
|
+
Activation class instantiated inside each band-local `MLP` head.
|
|
158
|
+
dim : int
|
|
159
|
+
Feature width of each input band token.
|
|
160
|
+
depth : int
|
|
161
|
+
Number of hidden-width repeats inside each band-local `MLP` head.
|
|
162
|
+
mlp_expansion_factor : int
|
|
163
|
+
Hidden-width multiplier relative to `dim` for each band-local `MLP` head.
|
|
164
|
+
use_hyperACE : bool
|
|
165
|
+
Whether each mask-estimator head adds the optional segmentation-style branch [2].
|
|
166
|
+
|
|
167
|
+
Other Parameters
|
|
168
|
+
----------------
|
|
169
|
+
segmentation output geometry : forwarded parameter family
|
|
170
|
+
See `hunterFormsBS.hyperACE.SegmModel.__init__` [2]. `ParametersMaskEstimator` stores
|
|
171
|
+
`segm_out_bins` and `segm_out_channels`.
|
|
172
|
+
backbone parameters : forwarded parameter family
|
|
173
|
+
See `hunterFormsBS.hyperACE.Backbone.__init__` [3]. `ParametersMaskEstimator` stores
|
|
174
|
+
`segm_base_channels`, `segm_base_depth`, and `segm_backbone_channels`.
|
|
175
|
+
hypergraph size and branch parameters : forwarded parameter family
|
|
176
|
+
See `hunterFormsBS.hyperACE.HyperACE.__init__` [4]. `ParametersMaskEstimator` stores
|
|
177
|
+
`segm_num_hyperedges`, `segm_num_heads`, and the `segm_hyperace_*` family.
|
|
178
|
+
decoder parameters : forwarded parameter family
|
|
179
|
+
See `hunterFormsBS.hyperACE.Decoder.__init__` [5]. `ParametersMaskEstimator` stores
|
|
180
|
+
`segm_decoder_channels`, `segm_decoder_block_depth`, `segm_decoder_block_kernel`, and
|
|
181
|
+
`segm_decoder_block_expansion`.
|
|
182
|
+
upsample and shared layer settings : forwarded parameter family
|
|
183
|
+
See `hunterFormsBS.hyperACE.ProgressiveUpsampleHead.__init__` [6].
|
|
184
|
+
`ParametersMaskEstimator` stores `segm_upsample_scales`, `segm_upsample_tfc_tdf_depth`,
|
|
185
|
+
`segm_upsample_tfc_tdf_bn`, `segm_activation`, `segm_norm_eps`, `segm_norm_affine`,
|
|
186
|
+
`segm_conv_bias`, and `segm_linear_bias`.
|
|
187
|
+
|
|
188
|
+
References
|
|
189
|
+
----------
|
|
190
|
+
[1] `hunterFormsBS.bandSplit.MaskEstimator`
|
|
191
|
+
|
|
192
|
+
[2] `hunterFormsBS.hyperACE.SegmModel.__init__`
|
|
193
|
+
|
|
194
|
+
[3] `hunterFormsBS.hyperACE.Backbone.__init__`
|
|
195
|
+
|
|
196
|
+
[4] `hunterFormsBS.hyperACE.HyperACE.__init__`
|
|
197
|
+
|
|
198
|
+
[5] `hunterFormsBS.hyperACE.Decoder.__init__`
|
|
199
|
+
|
|
200
|
+
[6] `hunterFormsBS.hyperACE.ProgressiveUpsampleHead.__init__`
|
|
201
|
+
"""
|
|
202
|
+
activation: type[nn.Module]
|
|
203
|
+
dim: int
|
|
204
|
+
depth: int
|
|
205
|
+
mlp_expansion_factor: int
|
|
206
|
+
segm_out_bins: int | None
|
|
207
|
+
segm_out_channels: int
|
|
208
|
+
segm_base_channels: int
|
|
209
|
+
segm_base_depth: int
|
|
210
|
+
segm_num_hyperedges: int
|
|
211
|
+
segm_num_heads: int
|
|
212
|
+
segm_backbone_channels: tuple[int, int, int, int, int] | None
|
|
213
|
+
segm_hyperace_k: int
|
|
214
|
+
segm_hyperace_l: int
|
|
215
|
+
segm_hyperace_c_h: float
|
|
216
|
+
segm_hyperace_c_l: float
|
|
217
|
+
segm_hyperace_c3ah_expansion: float
|
|
218
|
+
segm_hyperace_low_order_depth: int
|
|
219
|
+
segm_hyperace_low_order_kernel: int
|
|
220
|
+
segm_hyperace_low_order_expansion: float
|
|
221
|
+
segm_hyperace_out_channels: int | None
|
|
222
|
+
segm_decoder_channels: list[int] | tuple[int, int, int, int] | None
|
|
223
|
+
segm_decoder_block_depth: int
|
|
224
|
+
segm_decoder_block_kernel: int
|
|
225
|
+
segm_decoder_block_expansion: float
|
|
226
|
+
segm_upsample_scales: tuple[int, int, int, int]
|
|
227
|
+
segm_upsample_tfc_tdf_depth: int
|
|
228
|
+
segm_upsample_tfc_tdf_bn: int
|
|
229
|
+
segm_activation: type[nn.Module]
|
|
230
|
+
segm_norm_eps: float
|
|
231
|
+
segm_norm_affine: bool
|
|
232
|
+
segm_conv_bias: bool
|
|
233
|
+
segm_linear_bias: bool
|
|
234
|
+
use_hyperACE: bool
|
|
235
|
+
|
|
236
|
+
class ParametersSTFT(TypedDict):
|
|
237
|
+
"""Collect one forward-and-inverse STFT keyword record.
|
|
238
|
+
|
|
239
|
+
You can use `ParametersSTFT` to keep one short-time Fourier transform (STFT) configuration
|
|
240
|
+
together. The same record can be forwarded to the forward STFT call and the inverse STFT call so
|
|
241
|
+
both operations use the same FFT size, hop size, windowing-function length, and normalization
|
|
242
|
+
rule.
|
|
243
|
+
|
|
244
|
+
Attributes
|
|
245
|
+
----------
|
|
246
|
+
hop_length : int
|
|
247
|
+
Hop size between adjacent STFT frames.
|
|
248
|
+
n_fft : int
|
|
249
|
+
FFT size used by the STFT.
|
|
250
|
+
normalized : bool
|
|
251
|
+
Whether the STFT uses normalized scaling.
|
|
252
|
+
win_length : int
|
|
253
|
+
Length of the STFT windowing function.
|
|
254
|
+
"""
|
|
255
|
+
hop_length: int
|
|
256
|
+
n_fft: int
|
|
257
|
+
normalized: bool
|
|
258
|
+
win_length: int
|
|
259
|
+
|
|
260
|
+
class ParametersTransformer(TypedDict):
|
|
261
|
+
"""Collect one transformer-block keyword record.
|
|
262
|
+
|
|
263
|
+
You can use `ParametersTransformer` to keep one transformer-block configuration together while
|
|
264
|
+
separator models forward stable field names to the shared attention stack. The record stores
|
|
265
|
+
attention geometry, feedforward settings, backend toggles, optional multi-stream residual
|
|
266
|
+
settings, and compatibility fields kept for older configuration files.
|
|
267
|
+
|
|
268
|
+
Attributes
|
|
269
|
+
----------
|
|
270
|
+
attn_dropout : float
|
|
271
|
+
Dropout probability passed to each attention sublayer.
|
|
272
|
+
dim : int
|
|
273
|
+
Input and output feature width of the transformer block.
|
|
274
|
+
dim_head : int
|
|
275
|
+
Feature width of each attention head.
|
|
276
|
+
ff_dropout : float
|
|
277
|
+
Dropout probability in the feedforward sublayer.
|
|
278
|
+
ff_mult : float | None
|
|
279
|
+
Hidden-width expansion factor for each feedforward sublayer. `None` asks the feedforward
|
|
280
|
+
sublayer to use its default expansion factor.
|
|
281
|
+
flash_attn : bool
|
|
282
|
+
Whether attention sublayers may use the optimized scaled-dot-product-attention backend path.
|
|
283
|
+
heads : int
|
|
284
|
+
Number of attention heads.
|
|
285
|
+
linear_attn : bool
|
|
286
|
+
Legacy compatibility flag preserved for older configuration files. The current shared
|
|
287
|
+
transformer stack keeps only the standard attention path, so `linear_attn` is forwarded as
|
|
288
|
+
metadata rather than selecting a separate linear-attention implementation.
|
|
289
|
+
norm_output : bool
|
|
290
|
+
Whether to normalize after the last layer.
|
|
291
|
+
sage_attention : bool
|
|
292
|
+
Whether attention sublayers may try the optional `SageAttention` backend [1]. `SageAttention`
|
|
293
|
+
is not installed automatically with `hunterFormsBS`, so you must install `SageAttention`
|
|
294
|
+
separately [1].
|
|
295
|
+
scale : float | None
|
|
296
|
+
Optional override for the default inverse-square-root attention-score scale.
|
|
297
|
+
|
|
298
|
+
References
|
|
299
|
+
----------
|
|
300
|
+
[1] thu-ml/SageAttention
|
|
301
|
+
https://github.com/thu-ml/SageAttention
|
|
302
|
+
"""
|
|
303
|
+
attn_dropout: float
|
|
304
|
+
dim_head: int
|
|
305
|
+
dim: int
|
|
306
|
+
ff_dropout: float
|
|
307
|
+
ff_mult: float
|
|
308
|
+
flash_attn: bool
|
|
309
|
+
heads: int
|
|
310
|
+
linear_attn: bool
|
|
311
|
+
norm_output: bool
|
|
312
|
+
sage_attention: bool
|
|
313
|
+
scale: float | None
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Apply feedforward and transformer residual blocks for music source separation.
|
|
2
|
+
|
|
3
|
+
You can use this module to build the shared position-wise feedforward block and the stacked
|
|
4
|
+
attention-and-feedforward transformer used by
|
|
5
|
+
`hunterFormsBS.bandSplitRotator.BandSplitRotator` [1]. `FeedForward` applies a configurable
|
|
6
|
+
width-expansion nonlinear transform to every sequence position independently. `Transformer`
|
|
7
|
+
stacks repeated `Attention` [2] and `FeedForward` pairs into a residual sequence and
|
|
8
|
+
optionally normalizes the result.
|
|
9
|
+
|
|
10
|
+
Contents
|
|
11
|
+
--------
|
|
12
|
+
Classes
|
|
13
|
+
FeedForward
|
|
14
|
+
Apply a position-wise expansion-and-projection nonlinear block.
|
|
15
|
+
Transformer
|
|
16
|
+
Stack repeated `Attention` and `FeedForward` pairs into a residual sequence.
|
|
17
|
+
|
|
18
|
+
References
|
|
19
|
+
----------
|
|
20
|
+
[1] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
|
|
21
|
+
|
|
22
|
+
[2] `hunterFormsBS.attend.Attention`
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from hunterFormsBS.attend import Attention
|
|
27
|
+
from hunterFormsBS.theTypes import ParametersAttention
|
|
28
|
+
from more_itertools import loops
|
|
29
|
+
from torch import nn, Tensor
|
|
30
|
+
from torch.nn import Module, ModuleList
|
|
31
|
+
from torch_einops_kit.scaleValues import RMSNorm
|
|
32
|
+
from typing import cast, TYPE_CHECKING
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from PoPE_pytorch import PoPE
|
|
36
|
+
from rotary_embedding_torch import RotaryEmbedding
|
|
37
|
+
|
|
38
|
+
class FeedForward(Module):
|
|
39
|
+
"""Transform activations with a position-wise expansion-and-projection block.
|
|
40
|
+
|
|
41
|
+
You can use `FeedForward` after `Attention` [1] inside `Transformer` [2] when activation `Tensor`
|
|
42
|
+
`x` at each sequence position should pass through the same nonlinear feature transform.
|
|
43
|
+
`FeedForward` preserves the batch axis, sequence axis, and feature axis of activation `Tensor` `x`
|
|
44
|
+
while expanding the feature width internally before projecting back to the original width. The
|
|
45
|
+
shared `BandSplitRotator` stack uses one `FeedForward` block after every attention block [3].
|
|
46
|
+
|
|
47
|
+
Attributes
|
|
48
|
+
----------
|
|
49
|
+
net : nn.Sequential
|
|
50
|
+
Position-wise submodule sequence containing root-mean-square normalization, width expansion,
|
|
51
|
+
`nn.GELU`, `ff_dropout`, width projection, and output `ff_dropout` [4].
|
|
52
|
+
|
|
53
|
+
References
|
|
54
|
+
----------
|
|
55
|
+
[1] `Attention`
|
|
56
|
+
|
|
57
|
+
[2] `Transformer`
|
|
58
|
+
|
|
59
|
+
[3] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
|
|
60
|
+
|
|
61
|
+
[4] PyTorch.
|
|
62
|
+
https://context7.com/pytorch/pytorch
|
|
63
|
+
"""
|
|
64
|
+
def __init__(self, dim: int, ff_mult: float = 4.0, ff_dropout: float = 0.0) -> None:
|
|
65
|
+
"""Set up a position-wise feedforward block for feature width `dim`.
|
|
66
|
+
|
|
67
|
+
You can use `__init__` to choose the input and output feature width `dim`, the internal width
|
|
68
|
+
expansion factor `ff_mult`, and the `ff_dropout` probability for the shared feedforward
|
|
69
|
+
sublayer inside `Transformer` [1]. `__init__` stores the resulting normalization, linear,
|
|
70
|
+
activation, and `ff_dropout` layers in `net` for reuse by later calls to `forward`.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
dim : int
|
|
75
|
+
Input feature width before expansion and output feature width after projection.
|
|
76
|
+
ff_mult : float | None = 4.0
|
|
77
|
+
Multiplicative factor used to compute the hidden feature width `int(dim * ff_mult)`. When
|
|
78
|
+
`ff_mult` is `None`, `__init__` uses `4.0`.
|
|
79
|
+
ff_dropout : float = 0.0
|
|
80
|
+
Dropout probability applied after the hidden activation and after the output projection.
|
|
81
|
+
|
|
82
|
+
PyTorch
|
|
83
|
+
-------
|
|
84
|
+
submodule construction : implementation detail
|
|
85
|
+
`__init__` computes `dim_inner = int(dim * ff_mult)` and stores `net` as a six-stage
|
|
86
|
+
`nn.Sequential` with root-mean-square normalization, `nn.Linear(dim, dim_inner)`,
|
|
87
|
+
`nn.GELU`, `nn.Dropout(ff_dropout)`, `nn.Linear(dim_inner, dim)`, and a second
|
|
88
|
+
`nn.Dropout(ff_dropout)` [2].
|
|
89
|
+
|
|
90
|
+
References
|
|
91
|
+
----------
|
|
92
|
+
[1] `Transformer`
|
|
93
|
+
|
|
94
|
+
[2] PyTorch.
|
|
95
|
+
https://context7.com/pytorch/pytorch
|
|
96
|
+
"""
|
|
97
|
+
super().__init__()
|
|
98
|
+
dim_inner: int = int(dim * ff_mult)
|
|
99
|
+
self.net: nn.Sequential = nn.Sequential(
|
|
100
|
+
RMSNorm(dim), nn.Linear(dim, dim_inner), nn.GELU(), nn.Dropout(ff_dropout), nn.Linear(dim_inner, dim), nn.Dropout(ff_dropout)
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
104
|
+
"""Transform activations `x` with the position-wise feedforward block.
|
|
105
|
+
|
|
106
|
+
You can use `forward` when `x` already has batch axis, sequence axis, and feature axis.
|
|
107
|
+
`forward` applies the same nonlinear feature transform to every position independently, reuses
|
|
108
|
+
the submodule sequence configured by `__init__`, and returns an activation `Tensor` with the
|
|
109
|
+
same outer shape as `x`. `forward` supplies the position-wise branch used by `Transformer`
|
|
110
|
+
[1].
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
x : Tensor
|
|
115
|
+
Input activation `Tensor` with shape `batch × sequence position × feature`.
|
|
116
|
+
|
|
117
|
+
Returns
|
|
118
|
+
-------
|
|
119
|
+
out : Tensor
|
|
120
|
+
Output activation `Tensor` with shape `batch × sequence position × feature`.
|
|
121
|
+
|
|
122
|
+
Shape Transformation
|
|
123
|
+
--------------------
|
|
124
|
+
position-wise mapping : implementation detail
|
|
125
|
+
`forward` preserves the outer shape `B×N×D`. `forward` applies the same feedforward map to
|
|
126
|
+
each position vector `x[b, n, :]` independently of every other position.
|
|
127
|
+
|
|
128
|
+
References
|
|
129
|
+
----------
|
|
130
|
+
[1] `Transformer`
|
|
131
|
+
"""
|
|
132
|
+
return self.net(x)
|
|
133
|
+
|
|
134
|
+
class Transformer(Module):
|
|
135
|
+
"""Refine activations with repeated attention-and-feedforward blocks.
|
|
136
|
+
|
|
137
|
+
You can use `Transformer` as the shared sequence stack inside `BandSplitRotator` [1].
|
|
138
|
+
`Transformer` takes activation `Tensor` `x`, repeats `depth` pairs of `Attention` [2] and
|
|
139
|
+
`FeedForward` [3], and optionally normalizes the result. `Transformer`
|
|
140
|
+
preserves the batch axis, sequence axis, and feature axis of activation `Tensor` `x`. The
|
|
141
|
+
constructor still accepts several compatibility parameters, but the stack itself no longer
|
|
142
|
+
contains `LinearAttention`.
|
|
143
|
+
|
|
144
|
+
Attributes
|
|
145
|
+
----------
|
|
146
|
+
layers : ModuleList
|
|
147
|
+
Sequence of per-depth `[attention, feedforward]` pairs, where the attention entry is
|
|
148
|
+
`Attention` [2] and the feedforward entry is `FeedForward` [3].
|
|
149
|
+
norm : RMSNorm | nn.Identity
|
|
150
|
+
Final output normalization module applied after the last residual block when `norm_output` is
|
|
151
|
+
`True`, or `nn.Identity` otherwise.
|
|
152
|
+
|
|
153
|
+
References
|
|
154
|
+
----------
|
|
155
|
+
[1] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
|
|
156
|
+
|
|
157
|
+
[2] `Attention`
|
|
158
|
+
|
|
159
|
+
[3] `FeedForward`
|
|
160
|
+
"""
|
|
161
|
+
def __init__(
|
|
162
|
+
self
|
|
163
|
+
, *
|
|
164
|
+
, depth: int
|
|
165
|
+
, attn_dropout: float = 0.0
|
|
166
|
+
, dim_head: int = 64
|
|
167
|
+
, dim: int
|
|
168
|
+
, ff_dropout: float = 0.0
|
|
169
|
+
, ff_mult: float = 4
|
|
170
|
+
, flash_attn: bool = True
|
|
171
|
+
, heads: int = 8
|
|
172
|
+
, linear_attn: bool = False # noqa: ARG002
|
|
173
|
+
, norm_output: bool = True
|
|
174
|
+
, pope_embed: PoPE | None = None
|
|
175
|
+
, rotary_embed: RotaryEmbedding | None = None
|
|
176
|
+
, sage_attention: bool = False
|
|
177
|
+
, scale: float | None = None
|
|
178
|
+
) -> None:
|
|
179
|
+
"""Set up a transformer stack for feature width `dim` and layer count `depth`.
|
|
180
|
+
|
|
181
|
+
You can use `__init__` to choose the stack depth, model width, attention-head layout, dropout
|
|
182
|
+
probabilities, attention backend, and position-encoding path for a
|
|
183
|
+
shared transformer block. `__init__` stores `depth` pairs of `Attention` [1] and `FeedForward`
|
|
184
|
+
[2] in `layers`, forwards the downstream attention parameters without renaming through
|
|
185
|
+
`ParametersAttention` [3], and configures optional output normalization in `norm`. `__init__`
|
|
186
|
+
retains `linear_attn` only for configuration compatibility with earlier versions.
|
|
187
|
+
|
|
188
|
+
Parameters
|
|
189
|
+
----------
|
|
190
|
+
attn_dropout : float = 0.0
|
|
191
|
+
Dropout probability passed to each attention sublayer.
|
|
192
|
+
depth : int
|
|
193
|
+
Number of repeated attention-plus-feedforward residual blocks.
|
|
194
|
+
dim_head : int = 64
|
|
195
|
+
Feature width of each attention head.
|
|
196
|
+
dim : int
|
|
197
|
+
Input and output feature width of the stack.
|
|
198
|
+
ff_dropout : float = 0.0
|
|
199
|
+
Dropout probability passed to each `FeedForward` block [2].
|
|
200
|
+
ff_mult : float | None = 4
|
|
201
|
+
Hidden-width expansion factor passed to each `FeedForward` block [2].
|
|
202
|
+
flash_attn : bool = True
|
|
203
|
+
Whether each attention sublayer may use PyTorch SDPA (scaled dot-product attention)
|
|
204
|
+
backends [4].
|
|
205
|
+
heads : int = 8
|
|
206
|
+
Number of attention heads in each attention sublayer.
|
|
207
|
+
linear_attn : bool = False
|
|
208
|
+
Vestigial flag retained for configuration compatibility passthrough. This unified implementation
|
|
209
|
+
ignores `linear_attn` because `LinearAttention` was removed.
|
|
210
|
+
norm_output : bool = True
|
|
211
|
+
Whether to apply final output normalization after the last residual block.
|
|
212
|
+
pope_embed : PoPE | None = None
|
|
213
|
+
Optional polar-coordinate position encoder passed to each `Attention` [1] [5][6]. When
|
|
214
|
+
both positional encoders are present, `Attention.forward` prefers `pope_embed`.
|
|
215
|
+
rotary_embed : RotaryEmbedding | None = None
|
|
216
|
+
Optional rotary positional encoder passed to each `Attention` [1] [7].
|
|
217
|
+
sage_attention : bool = False
|
|
218
|
+
Whether each `Attention` should prefer SageAttention [8][9]. `hunterFormsBS` does not
|
|
219
|
+
install `sageattention`.
|
|
220
|
+
scale : float | None = None
|
|
221
|
+
Optional attention-score multiplier override passed to each `Attention` [1].
|
|
222
|
+
|
|
223
|
+
PyTorch
|
|
224
|
+
-------
|
|
225
|
+
layer construction : implementation detail
|
|
226
|
+
`__init__` first builds `ParametersAttention` [3] with the downstream attention arguments.
|
|
227
|
+
`__init__` then creates `depth` `ModuleList` pairs, each containing one
|
|
228
|
+
`Attention(**parametersAttention)` [1] and one `FeedForward(dim=dim, ff_mult=ff_mult,
|
|
229
|
+
ff_dropout=ff_dropout)` [2]. `norm` becomes `RMSNorm(dim)` when
|
|
230
|
+
`norm_output` is `True` and `nn.Identity()` otherwise [4].
|
|
231
|
+
|
|
232
|
+
References
|
|
233
|
+
----------
|
|
234
|
+
[1] `Attention`
|
|
235
|
+
|
|
236
|
+
[2] `FeedForward`
|
|
237
|
+
|
|
238
|
+
[3] `hunterFormsBS.theTypes.ParametersAttention`
|
|
239
|
+
|
|
240
|
+
[4] PyTorch.
|
|
241
|
+
https://context7.com/pytorch/pytorch
|
|
242
|
+
[5] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., and Mozer, M. C. (2025).
|
|
243
|
+
Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings.
|
|
244
|
+
https://arxiv.org/abs/2509.10534
|
|
245
|
+
[6] lucidrains/PoPE-pytorch.
|
|
246
|
+
https://github.com/lucidrains/PoPE-pytorch
|
|
247
|
+
[7] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu, Y. (2021).
|
|
248
|
+
RoFormer: Enhanced Transformer with Rotary Position Embedding.
|
|
249
|
+
https://arxiv.org/abs/2104.09864
|
|
250
|
+
[8] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., and Chen, J. (2025).
|
|
251
|
+
SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
|
|
252
|
+
https://arxiv.org/abs/2410.02367
|
|
253
|
+
[9] thu-ml/SageAttention
|
|
254
|
+
https://github.com/thu-ml/SageAttention
|
|
255
|
+
"""
|
|
256
|
+
super().__init__()
|
|
257
|
+
|
|
258
|
+
parametersAttention = ParametersAttention(
|
|
259
|
+
attn_dropout=attn_dropout
|
|
260
|
+
, dim_head=dim_head
|
|
261
|
+
, dim=dim
|
|
262
|
+
, flash=flash_attn
|
|
263
|
+
, heads=heads
|
|
264
|
+
, pope_embed=pope_embed
|
|
265
|
+
, rotary_embed=rotary_embed
|
|
266
|
+
, sage_attention=sage_attention
|
|
267
|
+
, scale=scale
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
self.layers = ModuleList(
|
|
271
|
+
ModuleList([Attention(**parametersAttention)
|
|
272
|
+
, FeedForward(dim=dim, ff_mult=ff_mult, ff_dropout=ff_dropout)])
|
|
273
|
+
for _layer in loops(depth)
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
self.norm: RMSNorm | nn.Identity = RMSNorm(dim) if norm_output else nn.Identity()
|
|
277
|
+
|
|
278
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
279
|
+
"""Transform activations `x` through the residual stack.
|
|
280
|
+
|
|
281
|
+
You can use `forward` when `x` already has batch axis, sequence axis, and feature axis.
|
|
282
|
+
|
|
283
|
+
Parameters
|
|
284
|
+
----------
|
|
285
|
+
x : Tensor
|
|
286
|
+
Input activation `Tensor` with shape `batch × sequence position × feature`.
|
|
287
|
+
|
|
288
|
+
Returns
|
|
289
|
+
-------
|
|
290
|
+
result : Tensor
|
|
291
|
+
Output activation `Tensor` with shape `batch × sequence position × feature`.
|
|
292
|
+
|
|
293
|
+
References
|
|
294
|
+
----------
|
|
295
|
+
[1] `Attention.forward`
|
|
296
|
+
|
|
297
|
+
[2] `FeedForward.forward`
|
|
298
|
+
"""
|
|
299
|
+
for sherpa in self.layers:
|
|
300
|
+
attn: Attention = cast('Attention', cast('ModuleList', sherpa)[0])
|
|
301
|
+
ff: FeedForward = cast('FeedForward', cast('ModuleList', sherpa)[1])
|
|
302
|
+
x = attn(x) + x
|
|
303
|
+
x = ff(x) + x
|
|
304
|
+
|
|
305
|
+
return self.norm(x)
|