SGDF 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sgdf-0.5.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SGDF contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
sgdf-0.5.0/MANIFEST.in ADDED
@@ -0,0 +1 @@
1
+ include USAGE.md
sgdf-0.5.0/PKG-INFO ADDED
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: SGDF
3
+ Version: 0.5.0
4
+ Summary: SGDF gradient-filter optimizer: Sign, Muon, optional fused CUDA, distributed DTensor
5
+ Author: Zhipeng Yao and SGDF contributors
6
+ License-Expression: MIT
7
+ Project-URL: Source, https://github.com/ZPyAo0591/SGDF-Optimizer
8
+ Project-URL: Paper, https://arxiv.org/abs/2311.02818
9
+ Project-URL: CVPR, https://openaccess.thecvf.com/content/CVPR2026/html/Yao_Dynamic_Momentum_Recalibration_in_Online_Gradient_Learning_CVPR_2026_paper.html
10
+ Keywords: SGDF,PyTorch,optimizer,Muon,signSGD,distributed,AMP
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: torch>=2.0
18
+ Provides-Extra: triton
19
+ Requires-Dist: triton>=3.0; sys_platform == "linux" and extra == "triton"
20
+ Dynamic: license-file
21
+
22
+ # SGDF — Signal Processing Meets SGD
23
+
24
+ SGDF is a PyTorch optimizer providing three update modes in a single `torch.optim.Optimizer` interface: **SGDF**, **Sign-SGDF**, and **Muon + SGDF**.
25
+
26
+ Reference: [Signal Processing Meets SGD: From Momentum to Filter](https://arxiv.org/abs/2311.02818).
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install .
32
+ ```
33
+
34
+ Or install the distributed `.whl` directly with `pip install <wheel-file>`.
35
+
36
+ Python 3.9+ and PyTorch 2.0+ are required. Triton is an optional dependency used only with `fused=True`:
37
+
38
+ ```bash
39
+ pip install '.[triton]'
40
+ ```
41
+
42
+ ## Basic usage
43
+
44
+ ```python
45
+ from SGDF import SGDF
46
+
47
+ optimizer = SGDF(model.parameters(), lr=0.1) # SGDF
48
+ optimizer = SGDF(model.parameters(), lr=1e-3, use_sign=True) # Sign-SGDF
49
+ optimizer = SGDF(model.parameters(), lr=0.01, use_muon=True) # Muon + SGDF
50
+ ```
51
+
52
+ `use_sign` and `use_muon` are mutually exclusive. SGDF works with standard PyTorch parameter groups, learning-rate schedulers, AMP, and optimizer checkpoints (`state_dict`).
53
+
54
+ When using Muon, matrix-like parameters are orthogonalized with Newton–Schulz; vectors and scalars receive the standard SGDF update. A common configuration is:
55
+
56
+ ```python
57
+ optimizer = SGDF([
58
+ {"params": matrix_params, "use_muon": True, "lr": 0.01},
59
+ {"params": other_params, "use_muon": False, "lr": 0.001},
60
+ ])
61
+ ```
62
+
63
+ The two parameter lists must not overlap.
64
+
65
+ For detailed examples of optimizer modes, parameter groups, AMP, distributed Muon,
66
+ checkpointing, and options, see [USAGE.md](USAGE.md).
67
+
68
+ ## GPU fused update
69
+
70
+ Use `fused=True` with contiguous CUDA FP32 parameters and gradients, after installing the optional Triton dependency:
71
+
72
+ ```python
73
+ optimizer = SGDF(model.parameters(), lr=0.1, fused=True)
74
+ ```
75
+
76
+ The fused path supports standard SGDF and Sign-SGDF. Muon uses the non-fused path.
77
+
78
+ ## Single-node multi-GPU Muon
79
+
80
+ For ordinary DDP, the optimizer uses synchronized gradients just like other
81
+ PyTorch optimizers. If Muon matrices are large, `muon_ddp="shard"` balances
82
+ Newton–Schulz computations across local DDP replicas and broadcasts directions
83
+ in bounded buckets:
84
+
85
+ ```python
86
+ optimizer = SGDF(ddp_model.parameters(), lr=0.01, use_muon=True,
87
+ muon_ddp="shard")
88
+ ```
89
+
90
+ For FSDP2 / DTensor matrix sharding, `muon_distributed="auto"` is the default:
91
+
92
+ ```python
93
+ optimizer = SGDF(model.parameters(), lr=0.01, use_muon=True,
94
+ muon_distributed="auto")
95
+ ```
96
+
97
+ Auto mode chooses between reconstructing the whole matrix (`gather`) and
98
+ computing a global Gram matrix (`gram`) once, followed by local polynomial
99
+ Newton–Schulz iterations. It respects `muon_gram_max_dim` and
100
+ `muon_gather_max_bytes`. To select a specific strategy, set
101
+ `muon_distributed="gram"` or `"gather"`.
102
+
103
+ These modes target a single node with multiple GPUs. All ranks must execute
104
+ collectives in the same order. FSDP1 flattened parameter shards are unsupported
105
+ for Muon orthogonalization.
106
+
107
+ ## Configuration
108
+
109
+ Main options include `lr`, `betas`, `eps`, `gamma`, `weight_decay`, `weight_decouple`, `maximize`, `use_sign`, `use_muon`, `foreach`, `foreach_max_bytes`, `fused`, `capturable`, `ns_steps`, `muon_distributed`, `muon_gram_max_dim`, `muon_gather_max_bytes`, `muon_compute_dtype`, `muon_ddp`, `muon_ddp_min_numel`, and `muon_ddp_bucket_bytes`.
110
+
111
+ The default `gamma=None` selects 0.5 for standard/Muon SGDF and 1.0 for Sign-SGDF. Sparse gradients and differentiable optimizer steps are not supported.
112
+
113
+ License: MIT.
sgdf-0.5.0/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # SGDF — Signal Processing Meets SGD
2
+
3
+ SGDF is a PyTorch optimizer providing three update modes in a single `torch.optim.Optimizer` interface: **SGDF**, **Sign-SGDF**, and **Muon + SGDF**.
4
+
5
+ Reference: [Signal Processing Meets SGD: From Momentum to Filter](https://arxiv.org/abs/2311.02818).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install .
11
+ ```
12
+
13
+ Or install the distributed `.whl` directly with `pip install <wheel-file>`.
14
+
15
+ Python 3.9+ and PyTorch 2.0+ are required. Triton is an optional dependency used only with `fused=True`:
16
+
17
+ ```bash
18
+ pip install '.[triton]'
19
+ ```
20
+
21
+ ## Basic usage
22
+
23
+ ```python
24
+ from SGDF import SGDF
25
+
26
+ optimizer = SGDF(model.parameters(), lr=0.1) # SGDF
27
+ optimizer = SGDF(model.parameters(), lr=1e-3, use_sign=True) # Sign-SGDF
28
+ optimizer = SGDF(model.parameters(), lr=0.01, use_muon=True) # Muon + SGDF
29
+ ```
30
+
31
+ `use_sign` and `use_muon` are mutually exclusive. SGDF works with standard PyTorch parameter groups, learning-rate schedulers, AMP, and optimizer checkpoints (`state_dict`).
32
+
33
+ When using Muon, matrix-like parameters are orthogonalized with Newton–Schulz; vectors and scalars receive the standard SGDF update. A common configuration is:
34
+
35
+ ```python
36
+ optimizer = SGDF([
37
+ {"params": matrix_params, "use_muon": True, "lr": 0.01},
38
+ {"params": other_params, "use_muon": False, "lr": 0.001},
39
+ ])
40
+ ```
41
+
42
+ The two parameter lists must not overlap.
43
+
44
+ For detailed examples of optimizer modes, parameter groups, AMP, distributed Muon,
45
+ checkpointing, and options, see [USAGE.md](USAGE.md).
46
+
47
+ ## GPU fused update
48
+
49
+ Use `fused=True` with contiguous CUDA FP32 parameters and gradients, after installing the optional Triton dependency:
50
+
51
+ ```python
52
+ optimizer = SGDF(model.parameters(), lr=0.1, fused=True)
53
+ ```
54
+
55
+ The fused path supports standard SGDF and Sign-SGDF. Muon uses the non-fused path.
56
+
57
+ ## Single-node multi-GPU Muon
58
+
59
+ For ordinary DDP, the optimizer uses synchronized gradients just like other
60
+ PyTorch optimizers. If Muon matrices are large, `muon_ddp="shard"` balances
61
+ Newton–Schulz computations across local DDP replicas and broadcasts directions
62
+ in bounded buckets:
63
+
64
+ ```python
65
+ optimizer = SGDF(ddp_model.parameters(), lr=0.01, use_muon=True,
66
+ muon_ddp="shard")
67
+ ```
68
+
69
+ For FSDP2 / DTensor matrix sharding, `muon_distributed="auto"` is the default:
70
+
71
+ ```python
72
+ optimizer = SGDF(model.parameters(), lr=0.01, use_muon=True,
73
+ muon_distributed="auto")
74
+ ```
75
+
76
+ Auto mode chooses between reconstructing the whole matrix (`gather`) and
77
+ computing a global Gram matrix (`gram`) once, followed by local polynomial
78
+ Newton–Schulz iterations. It respects `muon_gram_max_dim` and
79
+ `muon_gather_max_bytes`. To select a specific strategy, set
80
+ `muon_distributed="gram"` or `"gather"`.
81
+
82
+ These modes target a single node with multiple GPUs. All ranks must execute
83
+ collectives in the same order. FSDP1 flattened parameter shards are unsupported
84
+ for Muon orthogonalization.
85
+
86
+ ## Configuration
87
+
88
+ Main options include `lr`, `betas`, `eps`, `gamma`, `weight_decay`, `weight_decouple`, `maximize`, `use_sign`, `use_muon`, `foreach`, `foreach_max_bytes`, `fused`, `capturable`, `ns_steps`, `muon_distributed`, `muon_gram_max_dim`, `muon_gather_max_bytes`, `muon_compute_dtype`, `muon_ddp`, `muon_ddp_min_numel`, and `muon_ddp_bucket_bytes`.
89
+
90
+ The default `gamma=None` selects 0.5 for standard/Muon SGDF and 1.0 for Sign-SGDF. Sparse gradients and differentiable optimizer steps are not supported.
91
+
92
+ License: MIT.
sgdf-0.5.0/USAGE.md ADDED
@@ -0,0 +1,249 @@
1
+ # SGDF Usage Guide
2
+
3
+ SGDF provides three update modes through a single PyTorch optimizer class:
4
+ standard **SGDF**, **Sign-SGDF**, and **Muon + SGDF**.
5
+
6
+ ## Installation
7
+
8
+ Install from the project directory:
9
+
10
+ ```bash
11
+ python -m pip install .
12
+ ```
13
+
14
+ Or install the prebuilt wheel:
15
+
16
+ ```bash
17
+ python -m pip install sgdf-0.5.0-py3-none-any.whl
18
+ ```
19
+
20
+ Requires Python 3.9+ and PyTorch 2.0+.
21
+
22
+ ## 1. Standard SGDF
23
+
24
+ Replace an existing PyTorch optimizer with `SGDF`:
25
+
26
+ ```python
27
+ from SGDF import SGDF
28
+
29
+ model = ...
30
+ optimizer = SGDF(model.parameters(), lr=0.1)
31
+
32
+ for inputs, targets in dataloader:
33
+ optimizer.zero_grad(set_to_none=True)
34
+ output = model(inputs)
35
+ loss = criterion(output, targets)
36
+ loss.backward()
37
+ optimizer.step()
38
+ ```
39
+
40
+ The example assumes that `model`, `dataloader`, and `criterion` have already been defined.
41
+
42
+ ## 2. Sign-SGDF
43
+
44
+ ```python
45
+ optimizer = SGDF(model.parameters(), lr=1e-3, use_sign=True)
46
+ ```
47
+
48
+ `use_sign=True` applies `sign()` to SGDF's filtered gradient direction before the update.
49
+ The default gain exponent in this mode is `gamma=1.0`.
50
+
51
+ ## 3. Muon + SGDF
52
+
53
+ ```python
54
+ optimizer = SGDF(model.parameters(), lr=0.01, use_muon=True, ns_steps=5)
55
+ ```
56
+
57
+ Muon applies Newton–Schulz orthogonalization to matrix-like (`ndim >= 2`)
58
+ parameter update directions. One-dimensional parameters and scalars use the
59
+ standard SGDF update.
60
+
61
+ You can choose Muon only for specific parameter groups:
62
+
63
+ ```python
64
+ matrix_params = [p for p in model.parameters() if p.requires_grad and p.ndim >= 2]
65
+ other_params = [p for p in model.parameters() if p.requires_grad and p.ndim < 2]
66
+
67
+ optimizer = SGDF([
68
+ {"params": matrix_params, "use_muon": True, "lr": 0.01},
69
+ {"params": other_params, "use_muon": False, "lr": 0.001},
70
+ ])
71
+ ```
72
+
73
+ Each trainable parameter must appear in at most one group.
74
+ If your model includes embeddings, output heads, or other matrices that should
75
+ not use Muon, place them in the standard SGDF group explicitly.
76
+
77
+ `use_muon=True` and `use_sign=True` cannot be enabled in the same group.
78
+
79
+ ## 4. GPU fused updates (Triton)
80
+
81
+ Install the optional Triton dependency:
82
+
83
+ ```bash
84
+ python -m pip install '.[triton]'
85
+ ```
86
+
87
+ Or install Triton separately when using the wheel. Enable the fused update:
88
+
89
+ ```python
90
+ optimizer = SGDF(model.parameters(), lr=0.1, fused=True)
91
+ ```
92
+
93
+ Fused updates require contiguous CUDA `float32` parameters and gradients.
94
+ The path is available for standard SGDF and Sign-SGDF, not Muon.
95
+ Do not set `capturable=True` together with `fused=True`.
96
+
97
+ ## 5. AMP / mixed precision
98
+
99
+ Keep the model parameters in float32, use autocast for forward computation,
100
+ and let GradScaler call the optimizer step:
101
+
102
+ ```python
103
+ from SGDF import SGDF
104
+ import torch
105
+
106
+ optimizer = SGDF(model.parameters(), lr=0.1)
107
+ scaler = torch.cuda.amp.GradScaler()
108
+
109
+ optimizer.zero_grad(set_to_none=True)
110
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
111
+ output = model(inputs)
112
+ loss = criterion(output, targets)
113
+
114
+ scaler.scale(loss).backward()
115
+ scaler.step(optimizer)
116
+ scaler.update()
117
+ ```
118
+
119
+ ## 6. Single-node multi-GPU training
120
+
121
+ Launch one process per GPU with `torchrun` and initialize `torch.distributed`
122
+ with `backend="nccl"`. On CPU, Gloo is available for development.
123
+
124
+ ### DDP (replicated parameters)
125
+
126
+ Normal DDP already synchronizes gradients; Muon can run on each replica:
127
+
128
+ ```python
129
+ optimizer = SGDF(ddp_model.parameters(), lr=0.01, use_muon=True)
130
+ ```
131
+
132
+ For larger matrix parameters, distribute Newton–Schulz computation among
133
+ DDP ranks on the same node and broadcast coalesced update directions:
134
+
135
+ ```python
136
+ optimizer = SGDF(
137
+ ddp_model.parameters(),
138
+ lr=0.01,
139
+ use_muon=True,
140
+ muon_ddp="shard",
141
+ muon_ddp_min_numel=65536,
142
+ muon_ddp_bucket_bytes=32 * 1024 * 1024,
143
+ )
144
+ ```
145
+
146
+ `muon_ddp="local"` is the default and avoids optimizer-side broadcasts.
147
+ `shard` balances large orthogonalizations across ranks by approximate matrix
148
+ cost; small matrices are computed locally on every rank. All ranks must have
149
+ matching parameters and step in the same order, with synchronized gradients.
150
+ For very small models, local computation can be faster than broadcasting.
151
+
152
+ ### FSDP2 / sharded DTensor matrices
153
+
154
+ FSDP2 preserves parameter shapes as DTensors, unlike FSDP1's flattened
155
+ parameter storage. `muon_distributed="auto"` (the default) selects one of:
156
+
157
+ - `gram`: for a 2-D parameter sharded along one axis on a 1-D DeviceMesh,
158
+ compute one global Gram matrix and run the remaining Newton–Schulz
159
+ iterations locally; full weight all-gather is not required.
160
+ - `gather`: materialize the full matrix on every participating rank before
161
+ orthogonalizing, then return the original DTensor placements.
162
+
163
+ ```python
164
+ optimizer = SGDF(
165
+ model.parameters(),
166
+ lr=0.01,
167
+ use_muon=True,
168
+ muon_distributed="auto",
169
+ muon_gram_max_dim=4096,
170
+ muon_gather_max_bytes=256 * 1024 * 1024,
171
+ )
172
+ ```
173
+
174
+ For supported one-dimensional DTensor meshes, you may force either
175
+ `muon_distributed="gram"` or `muon_distributed="gather"`. Setting
176
+ `muon_distributed="error"` rejects sharded matrices instead.
177
+
178
+ Only matrix-like parameters use Muon; scalars and vectors use standard SGDF.
179
+ Embedding and output-head matrices are best placed in a separate standard
180
+ SGDF group when your training recipe excludes them from Muon.
181
+
182
+ All participating ranks must enter collectives in the same order. FSDP1
183
+ FlatParameter shards cannot be safely orthogonalized by this optimizer.
184
+ The DDP `muon_ddp="shard"` option is for replicated local parameters and
185
+ cannot be combined with DTensor sharding for the same parameter group.
186
+
187
+ ## 7. Weight decay, foreach, and schedulers
188
+
189
+ ```python
190
+ optimizer = SGDF(
191
+ model.parameters(),
192
+ lr=0.1,
193
+ weight_decay=0.01,
194
+ weight_decouple=True,
195
+ foreach=True,
196
+ )
197
+
198
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)
199
+ ```
200
+
201
+ `weight_decouple=True` selects decoupled weight decay; the default is L2
202
+ regularization when `weight_decay` is nonzero.
203
+
204
+ ## 8. Save and restore an optimizer checkpoint
205
+
206
+ ```python
207
+ # Save
208
+ checkpoint = {
209
+ "model": model.state_dict(),
210
+ "optimizer": optimizer.state_dict(),
211
+ }
212
+ torch.save(checkpoint, "checkpoint.pt")
213
+
214
+ # Restore after rebuilding the model and optimizer
215
+ checkpoint = torch.load("checkpoint.pt", map_location="cpu", weights_only=True)
216
+ model.load_state_dict(checkpoint["model"])
217
+ optimizer.load_state_dict(checkpoint["optimizer"])
218
+ ```
219
+
220
+ After restoring an LR scheduler, follow the usual PyTorch optimizer/scheduler
221
+ load ordering to preserve the learning rates from the checkpoint.
222
+
223
+ ## 9. Main constructor parameters
224
+
225
+ | Parameter | Default | Description |
226
+ | --- | --- | --- |
227
+ | `lr` | `0.5` | Learning rate |
228
+ | `betas` | `(0.9, 0.999)` | Momentum and variance decay |
229
+ | `eps` | `1e-8` | Numerical stabilization |
230
+ | `gamma` | `None` | Gain exponent: 0.5 normally; 1.0 for Sign-SGDF |
231
+ | `weight_decay` | `0.0` | Weight decay coefficient |
232
+ | `weight_decouple` | `False` | Use decoupled decay when enabled |
233
+ | `use_sign` | `False` | Sign-SGDF update |
234
+ | `use_muon` | `False` | Muon postprocessing |
235
+ | `ns_steps` | `5` | Newton–Schulz iterations |
236
+ | `foreach` | `None` | Use grouped tensor operations when eligible |
237
+ | `foreach_max_bytes` | `16777216` | Maximum bytes per foreach batch |
238
+ | `fused` | `False` | Triton fused GPU path |
239
+ | `capturable` | `False` | CUDA graph-oriented step path |
240
+ | `maximize` | `False` | Ascend rather than descend |
241
+ | `muon_distributed` | `"auto"` | `auto`, `error`, `gather`, or `gram` |
242
+ | `muon_gram_max_dim` | `4096` | Maximum Gram dimension |
243
+ | `muon_gather_max_bytes` | `268435456` | Automatic gather memory cap |
244
+ | `muon_ddp` | `"local"` | `local` or `shard` for replicated DDP |
245
+ | `muon_ddp_min_numel` | `65536` | Minimum matrix size for DDP sharding |
246
+ | `muon_ddp_bucket_bytes` | `33554432` | Coalesced direction broadcast target |
247
+ | `muon_compute_dtype` | `"auto"` | `auto`, `float32`, `bfloat16` |
248
+
249
+ Sparse gradients and differentiable optimizer steps are not supported.
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "SGDF"
7
+ version = "0.5.0"
8
+ description = "SGDF gradient-filter optimizer: Sign, Muon, optional fused CUDA, distributed DTensor"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Zhipeng Yao and SGDF contributors"}]
14
+ dependencies = ["torch>=2.0"]
15
+ keywords = ["SGDF", "PyTorch", "optimizer", "Muon", "signSGD", "distributed", "AMP"]
16
+
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "Operating System :: OS Independent",
20
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ triton = ["triton>=3.0; sys_platform == 'linux'"]
25
+
26
+ [project.urls]
27
+ Source = "https://github.com/ZPyAo0591/SGDF-Optimizer"
28
+ Paper = "https://arxiv.org/abs/2311.02818"
29
+ CVPR = "https://openaccess.thecvf.com/content/CVPR2026/html/Yao_Dynamic_Momentum_Recalibration_in_Online_Gradient_Learning_CVPR_2026_paper.html"
30
+
31
+ [tool.setuptools]
32
+ package-dir = {"" = "src"}
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+ include = ["SGDF*"]
sgdf-0.5.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """SGDF: SGD with online gradient filtering, Muon and Sign options."""
2
+ from .optimizer import SGDF
3
+
4
+ __version__ = "0.5.0"
5
+ __all__ = ["SGDF"]
@@ -0,0 +1,61 @@
1
+ """Optional fp32 CUDA Triton fused update for standard and Sign-SGDF.
2
+
3
+ Importing this module requires Triton; main SGDF imports it only for fused=True.
4
+ This path is not graph-capturable.
5
+ """
6
+ import torch
7
+ import triton
8
+ import triton.language as tl
9
+
10
+
11
+ @triton.jit
12
+ def _sgdf_kernel(P, G, M, V, N: tl.constexpr,
13
+ LR: tl.constexpr, B1: tl.constexpr, B2: tl.constexpr,
14
+ EPS: tl.constexpr, GAMMA: tl.constexpr, WD: tl.constexpr,
15
+ DECOUPLE: tl.constexpr, MAXIMIZE: tl.constexpr,
16
+ SIGN: tl.constexpr, INVM: tl.constexpr,
17
+ SFACTOR: tl.constexpr, BLOCK: tl.constexpr):
18
+ idx = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
19
+ mask = idx < N
20
+ p = tl.load(P + idx, mask, other=0)
21
+ g = tl.load(G + idx, mask, other=0)
22
+ m = tl.load(M + idx, mask, other=0)
23
+ v = tl.load(V + idx, mask, other=0)
24
+ if MAXIMIZE:
25
+ g = -g
26
+ if not DECOUPLE:
27
+ g = g + WD * p
28
+ new_m = B1 * m + (1.0 - B1) * g
29
+ r = g - new_m
30
+ new_v = B2 * v + (1.0 - B2) * r * r
31
+ delta = g - INVM * new_m
32
+ var = SFACTOR * new_v
33
+ k = var / (var + delta * delta + EPS)
34
+ if GAMMA == 0.5:
35
+ k = tl.sqrt(k)
36
+ elif GAMMA != 1.0:
37
+ k = tl.exp(GAMMA * tl.log(k))
38
+ direction = INVM * new_m + k * delta
39
+ if SIGN:
40
+ direction = tl.where(direction > 0, 1.0, tl.where(direction < 0, -1.0, 0.0))
41
+ if DECOUPLE:
42
+ p = p * (1.0 - LR * WD)
43
+ p = p - LR * direction
44
+ tl.store(P + idx, p, mask)
45
+ tl.store(M + idx, new_m, mask)
46
+ tl.store(V + idx, new_v, mask)
47
+
48
+
49
+ def fused_sgdf_step(p: torch.Tensor, grad: torch.Tensor,
50
+ m: torch.Tensor, v: torch.Tensor, *, lr: float,
51
+ beta1: float, beta2: float, eps: float, gamma: float,
52
+ wd: float, decouple: bool, maximize: bool, sign: bool,
53
+ inv_m: float, s_factor: float) -> None:
54
+ if not (p.is_cuda and p.dtype == torch.float32 and p.is_contiguous() and
55
+ grad.is_contiguous() and m.is_contiguous() and v.is_contiguous()):
56
+ raise RuntimeError('Triton fused SGDF only supports contiguous CUDA fp32 tensors')
57
+ _sgdf_kernel[(triton.cdiv(p.numel(), 256),)](
58
+ p, grad, m, v, p.numel(), lr, beta1, beta2, eps, gamma, wd,
59
+ decouple, maximize, sign, inv_m, s_factor, BLOCK=256,
60
+ enable_fp_fusion=False, # improve agreement with the PyTorch reference
61
+ )