SGDF 0.5.0__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.
- SGDF/__init__.py +5 -0
- SGDF/_triton.py +61 -0
- SGDF/muon.py +193 -0
- SGDF/optimizer.py +631 -0
- sgdf-0.5.0.dist-info/METADATA +113 -0
- sgdf-0.5.0.dist-info/RECORD +9 -0
- sgdf-0.5.0.dist-info/WHEEL +5 -0
- sgdf-0.5.0.dist-info/licenses/LICENSE +21 -0
- sgdf-0.5.0.dist-info/top_level.txt +1 -0
SGDF/__init__.py
ADDED
SGDF/_triton.py
ADDED
|
@@ -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
|
+
)
|
SGDF/muon.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Newton-Schulz postprocessing of SGDF filtered gradients.
|
|
2
|
+
|
|
3
|
+
Distributed Muon chooses either all-gather or a single-all-reduce Gram
|
|
4
|
+
polynomial path for a sharded DTensor, never treating a shard as a full matrix.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
_COEFF = (3.4445, -4.7750, 2.0315)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _dtype(matrix: torch.Tensor, compute_dtype: str) -> torch.dtype:
|
|
15
|
+
if matrix.dtype == torch.float64:
|
|
16
|
+
# Never silently demote high-precision training to bf16.
|
|
17
|
+
return torch.float64
|
|
18
|
+
if compute_dtype == 'float32':
|
|
19
|
+
return torch.float32
|
|
20
|
+
if compute_dtype == 'bfloat16':
|
|
21
|
+
if matrix.device.type != 'cuda' or not torch.cuda.is_bf16_supported():
|
|
22
|
+
raise RuntimeError('muon_compute_dtype="bfloat16" requires bf16 CUDA support')
|
|
23
|
+
return torch.bfloat16
|
|
24
|
+
if compute_dtype != 'auto':
|
|
25
|
+
raise ValueError('Invalid Muon compute dtype')
|
|
26
|
+
return (torch.bfloat16 if matrix.device.type == 'cuda' and
|
|
27
|
+
torch.cuda.is_bf16_supported() else torch.float32)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def zeropower_via_newtonschulz5(matrix: torch.Tensor, steps: int = 5,
|
|
31
|
+
compute_dtype: str = 'auto') -> torch.Tensor:
|
|
32
|
+
"""Muon quintic Newton-Schulz, on a complete 2-D *local* matrix."""
|
|
33
|
+
if matrix.ndim != 2:
|
|
34
|
+
raise ValueError('Newton-Schulz expects a 2D matrix')
|
|
35
|
+
if steps < 2:
|
|
36
|
+
raise ValueError('steps must be >=2')
|
|
37
|
+
x = matrix.to(dtype=_dtype(matrix, compute_dtype))
|
|
38
|
+
flipped = x.shape[0] > x.shape[1]
|
|
39
|
+
if flipped:
|
|
40
|
+
x = x.T
|
|
41
|
+
acc_dtype = torch.float64 if x.dtype == torch.float64 else torch.float32
|
|
42
|
+
x = x / (torch.linalg.vector_norm(x.to(acc_dtype)) + 1e-7)
|
|
43
|
+
a, b, c = _COEFF
|
|
44
|
+
for _ in range(steps):
|
|
45
|
+
gram = x @ x.T
|
|
46
|
+
x = a * x + (b * gram + c * (gram @ gram)) @ x
|
|
47
|
+
if flipped:
|
|
48
|
+
x = x.T
|
|
49
|
+
return x.to(dtype=matrix.dtype)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _local_postprocess(update: torch.Tensor, ns_steps: int,
|
|
53
|
+
compute_dtype: str) -> torch.Tensor:
|
|
54
|
+
if update.ndim < 2:
|
|
55
|
+
return update
|
|
56
|
+
mat = update.reshape(update.shape[0], -1)
|
|
57
|
+
rows, cols = mat.shape
|
|
58
|
+
orthogonal = zeropower_via_newtonschulz5(mat, steps=ns_steps,
|
|
59
|
+
compute_dtype=compute_dtype)
|
|
60
|
+
return (orthogonal * math.sqrt(max(1.0, rows / cols))).reshape_as(update)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _gram_layout(update: torch.Tensor, gram_max_dim: int):
|
|
64
|
+
"""Return the shard axis and Gram dimension for a supported 1-D mesh."""
|
|
65
|
+
from torch.distributed.tensor import Shard
|
|
66
|
+
|
|
67
|
+
mesh, places = update.device_mesh, update.placements
|
|
68
|
+
if (update.ndim != 2 or mesh.ndim != 1 or len(places) != 1 or
|
|
69
|
+
not isinstance(places[0], Shard)):
|
|
70
|
+
return None
|
|
71
|
+
axis = places[0].dim
|
|
72
|
+
if axis not in (0, 1):
|
|
73
|
+
return None
|
|
74
|
+
dim = update.shape[1 - axis]
|
|
75
|
+
return (axis, dim) if dim <= gram_max_dim else None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _gram_postprocess(update: torch.Tensor, ns_steps: int, gram_max_dim: int,
|
|
79
|
+
compute_dtype: str) -> torch.Tensor:
|
|
80
|
+
"""Single-all-reduce distributed Muon for a row- or column-sharded matrix.
|
|
81
|
+
|
|
82
|
+
Newton-Schulz is a matrix polynomial: X_{k+1} = X_k P(G_k) when
|
|
83
|
+
G_k=X_k.T@X_k (or P(G_k)@X_k for G_k=X_k@X_k.T). Hence
|
|
84
|
+
G_{k+1}=P(G_k)G_kP(G_k), and we can accumulate P(G_k) on each rank.
|
|
85
|
+
Only the initial Gram matrix requires an all-reduce. Its trace also
|
|
86
|
+
supplies the global Frobenius norm, avoiding a separate norm reduce.
|
|
87
|
+
"""
|
|
88
|
+
import torch.distributed as dist
|
|
89
|
+
from torch.distributed.tensor import DTensor
|
|
90
|
+
|
|
91
|
+
layout = _gram_layout(update, gram_max_dim)
|
|
92
|
+
if layout is None:
|
|
93
|
+
raise RuntimeError('muon_distributed="gram" requires a 2D DTensor on '
|
|
94
|
+
'a 1-D Shard(0)/Shard(1) mesh with a small enough '
|
|
95
|
+
'unsharded dimension; try muon_distributed="gather"')
|
|
96
|
+
axis, dim = layout
|
|
97
|
+
local = update.to_local()
|
|
98
|
+
compute = local.to(dtype=_dtype(local, compute_dtype))
|
|
99
|
+
# Tiny Gram matrices benefit from fp64 recurrence: the quintic NS
|
|
100
|
+
# coefficients amplify rounding in the Gram's null-space. Larger
|
|
101
|
+
# matrices retain fp32 matmul throughput on GPUs.
|
|
102
|
+
acc_dtype = (torch.float64 if compute.dtype == torch.float64 or dim <= 64
|
|
103
|
+
else torch.float32)
|
|
104
|
+
x = compute.to(dtype=acc_dtype)
|
|
105
|
+
|
|
106
|
+
# The all-reduced Gram gives both the global norm and the starting
|
|
107
|
+
# polynomial, including when shards have unequal or zero local rows.
|
|
108
|
+
gram = x.T @ x if axis == 0 else x @ x.T
|
|
109
|
+
dist.all_reduce(gram, op=dist.ReduceOp.SUM, group=update.device_mesh.get_group())
|
|
110
|
+
norm = torch.diagonal(gram).sum().clamp_min(0).sqrt() + 1e-7
|
|
111
|
+
gram = gram / (norm * norm)
|
|
112
|
+
|
|
113
|
+
a, b, c = _COEFF
|
|
114
|
+
identity = torch.eye(dim, dtype=acc_dtype, device=x.device)
|
|
115
|
+
transform = identity
|
|
116
|
+
for step in range(ns_steps):
|
|
117
|
+
polynomial = a * identity + b * gram + c * (gram @ gram)
|
|
118
|
+
transform = transform @ polynomial
|
|
119
|
+
if step + 1 < ns_steps:
|
|
120
|
+
gram = polynomial @ gram @ polynomial
|
|
121
|
+
# Counter small floating point asymmetry without communication.
|
|
122
|
+
gram = (gram + gram.T) * 0.5
|
|
123
|
+
|
|
124
|
+
# One local matrix multiplication applies the accumulated orthogonalizer.
|
|
125
|
+
# Accumulate in fp32 even when auto chooses bf16 for the input. This
|
|
126
|
+
# prevents repeated low-precision rounding in the Gram recurrence.
|
|
127
|
+
output = (x @ transform if axis == 0 else transform @ x) / norm
|
|
128
|
+
rows, cols = update.shape
|
|
129
|
+
output = (output * math.sqrt(max(1.0, rows / cols))).to(dtype=update.dtype)
|
|
130
|
+
return DTensor.from_local(output, device_mesh=update.device_mesh,
|
|
131
|
+
placements=update.placements,
|
|
132
|
+
shape=update.shape, stride=update.stride())
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _automatic_mode(update: torch.Tensor, gram_max_dim: int,
|
|
136
|
+
gather_max_bytes: int) -> str:
|
|
137
|
+
"""Use the cheaper communication layout, with an all-gather memory cap."""
|
|
138
|
+
nbytes = update.numel() * update.element_size()
|
|
139
|
+
layout = _gram_layout(update, gram_max_dim)
|
|
140
|
+
if layout is not None:
|
|
141
|
+
_, dim = layout
|
|
142
|
+
# One all-reduced Gram costs ~2*dim**2 elements of network traffic;
|
|
143
|
+
# gathering the full matrix costs roughly its total element count.
|
|
144
|
+
# Favor Gram when it is smaller, or when gathering would exceed cap.
|
|
145
|
+
if 2 * dim * dim <= update.numel() or nbytes > gather_max_bytes:
|
|
146
|
+
return 'gram'
|
|
147
|
+
if nbytes <= gather_max_bytes:
|
|
148
|
+
return 'gather'
|
|
149
|
+
raise RuntimeError(
|
|
150
|
+
'Muon automatic distributed selection cannot safely gather this '
|
|
151
|
+
f'{nbytes}-byte matrix (muon_gather_max_bytes={gather_max_bytes}) '
|
|
152
|
+
'and Gram is unavailable. Increase the limit, muon_gram_max_dim, '
|
|
153
|
+
'or adjust the sharding layout.'
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def muon_postprocess(update: torch.Tensor, ns_steps: int = 5,
|
|
157
|
+
distributed: str = 'auto', gram_max_dim: int = 4096,
|
|
158
|
+
compute_dtype: str = 'auto',
|
|
159
|
+
gather_max_bytes: int = 256 * 1024 * 1024) -> torch.Tensor:
|
|
160
|
+
"""Orthogonalize a full matrix, or explicitly gather/Gram-reduce DTensor.
|
|
161
|
+
|
|
162
|
+
Ordinary torch.Tensor is always treated as full: caller must reject FSDP1
|
|
163
|
+
flat parameter views or other manually sharded raw tensors.
|
|
164
|
+
"""
|
|
165
|
+
if update.ndim < 2:
|
|
166
|
+
return update
|
|
167
|
+
try:
|
|
168
|
+
from torch.distributed.tensor import DTensor, Replicate, Shard, Partial
|
|
169
|
+
except ImportError:
|
|
170
|
+
DTensor = None
|
|
171
|
+
if DTensor is None or not isinstance(update, DTensor):
|
|
172
|
+
return _local_postprocess(update, ns_steps, compute_dtype)
|
|
173
|
+
if any(isinstance(p, Partial) for p in update.placements):
|
|
174
|
+
raise RuntimeError('Muon does not support DTensor Partial placements')
|
|
175
|
+
if not any(isinstance(p, Shard) for p in update.placements):
|
|
176
|
+
local = _local_postprocess(update.to_local(), ns_steps, compute_dtype)
|
|
177
|
+
return DTensor.from_local(local, device_mesh=update.device_mesh,
|
|
178
|
+
placements=update.placements,
|
|
179
|
+
shape=update.shape, stride=update.stride())
|
|
180
|
+
if distributed == 'auto':
|
|
181
|
+
distributed = _automatic_mode(update, gram_max_dim, gather_max_bytes)
|
|
182
|
+
if distributed == 'error':
|
|
183
|
+
raise RuntimeError('Muon on sharded DTensor requires auto, gather or gram mode')
|
|
184
|
+
if distributed == 'gram':
|
|
185
|
+
return _gram_postprocess(update, ns_steps, gram_max_dim, compute_dtype)
|
|
186
|
+
if distributed != 'gather':
|
|
187
|
+
raise ValueError('Muon distributed mode must be auto, error, gather, or gram')
|
|
188
|
+
replicate = (Replicate(),) * update.device_mesh.ndim
|
|
189
|
+
whole = update.redistribute(placements=replicate)
|
|
190
|
+
local_out = _local_postprocess(whole.to_local(), ns_steps, compute_dtype)
|
|
191
|
+
full = DTensor.from_local(local_out, device_mesh=update.device_mesh,
|
|
192
|
+
placements=replicate)
|
|
193
|
+
return full.redistribute(placements=update.placements)
|
SGDF/optimizer.py
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
"""SGDF optimizer for PyTorch (Algorithm 1, CVPR 2026).
|
|
2
|
+
|
|
3
|
+
Single torch.optim.Optimizer subclass with optional sign or Muon update directions.
|
|
4
|
+
The two moment states always use torch.zeros_like(parameter), as torch.optim.Adam
|
|
5
|
+
normally does. Thus fp16/bfloat16 parameters have fp16/bfloat16 states; standard
|
|
6
|
+
AMP with fp32 model parameters keeps fp32 states, just as torch.optim.Adam.
|
|
7
|
+
|
|
8
|
+
K = (s_hat / (s_hat + (grad - m_hat)**2 + eps)) ** gamma.
|
|
9
|
+
Epsilon is INSIDE the denominator. An optional Triton fused CUDA path and explicit distributed Muon modes are available.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
from typing import Optional
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
from torch.optim import Optimizer
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
from torch.distributed.tensor import DTensor, Shard, Partial
|
|
22
|
+
except ImportError: # Older PyTorch versions may not expose DTensor.
|
|
23
|
+
DTensor = None
|
|
24
|
+
Shard = None
|
|
25
|
+
Partial = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_dtensor(p: torch.Tensor) -> bool:
|
|
29
|
+
return DTensor is not None and isinstance(p, DTensor)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_DEFAULT_FOREACH_BYTES = 16 * 1024 * 1024
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _validate_group(g: dict) -> None:
|
|
36
|
+
try:
|
|
37
|
+
b1, b2 = g['betas']
|
|
38
|
+
except (TypeError, ValueError) as exc:
|
|
39
|
+
raise ValueError('betas must have two values') from exc
|
|
40
|
+
if not (math.isfinite(float(g['lr'])) and g['lr'] >= 0):
|
|
41
|
+
raise ValueError('lr must be finite and >= 0')
|
|
42
|
+
if not (0 <= b1 < 1 and 0 <= b2 < 1):
|
|
43
|
+
raise ValueError('betas must be in [0, 1)')
|
|
44
|
+
if not (math.isfinite(float(g['eps'])) and g['eps'] > 0):
|
|
45
|
+
raise ValueError('eps must be finite and > 0')
|
|
46
|
+
if g['gamma'] is not None and not (math.isfinite(float(g['gamma'])) and g['gamma'] > 0):
|
|
47
|
+
raise ValueError('gamma must be None or finite and > 0')
|
|
48
|
+
if not (math.isfinite(float(g['weight_decay'])) and g['weight_decay'] >= 0):
|
|
49
|
+
raise ValueError('weight_decay must be finite and >= 0')
|
|
50
|
+
if g['foreach'] not in (None, True, False):
|
|
51
|
+
raise ValueError('foreach must be None, True or False')
|
|
52
|
+
if type(g['foreach_max_bytes']) is not int or g['foreach_max_bytes'] < 1024:
|
|
53
|
+
raise ValueError('foreach_max_bytes must be an integer >= 1024')
|
|
54
|
+
if type(g['ns_steps']) is not int or g['ns_steps'] < 2:
|
|
55
|
+
raise ValueError('ns_steps must be an integer >= 2')
|
|
56
|
+
if not isinstance(g['use_sign'], bool) or not isinstance(g['use_muon'], bool):
|
|
57
|
+
raise ValueError('use_sign and use_muon must be bool')
|
|
58
|
+
if g['use_sign'] and g['use_muon']:
|
|
59
|
+
raise ValueError('use_sign and use_muon cannot both be enabled')
|
|
60
|
+
if g['capturable'] not in (True, False):
|
|
61
|
+
raise ValueError('capturable must be bool')
|
|
62
|
+
if g['maximize'] not in (True, False):
|
|
63
|
+
raise ValueError('maximize must be bool')
|
|
64
|
+
if not isinstance(g['weight_decouple'], bool):
|
|
65
|
+
raise ValueError('weight_decouple must be bool')
|
|
66
|
+
if not isinstance(g['fused'], bool):
|
|
67
|
+
raise ValueError('fused must be bool')
|
|
68
|
+
if g['muon_distributed'] not in ('auto', 'error', 'gather', 'gram'):
|
|
69
|
+
raise ValueError('muon_distributed must be auto, error, gather, or gram')
|
|
70
|
+
if type(g['muon_gram_max_dim']) is not int or g['muon_gram_max_dim'] < 1:
|
|
71
|
+
raise ValueError('muon_gram_max_dim must be a positive integer')
|
|
72
|
+
if type(g['muon_gather_max_bytes']) is not int or g['muon_gather_max_bytes'] < 1024:
|
|
73
|
+
raise ValueError('muon_gather_max_bytes must be >= 1024')
|
|
74
|
+
if type(g['muon_ddp_bucket_bytes']) is not int or g['muon_ddp_bucket_bytes'] < 1024:
|
|
75
|
+
raise ValueError('muon_ddp_bucket_bytes must be >= 1024')
|
|
76
|
+
if g['muon_ddp'] not in ('local', 'shard'):
|
|
77
|
+
raise ValueError('muon_ddp must be local or shard')
|
|
78
|
+
if type(g['muon_ddp_min_numel']) is not int or g['muon_ddp_min_numel'] < 1:
|
|
79
|
+
raise ValueError('muon_ddp_min_numel must be a positive integer')
|
|
80
|
+
if g['muon_ddp'] == 'shard' and not g['use_muon']:
|
|
81
|
+
raise ValueError('muon_ddp=shard requires use_muon=True')
|
|
82
|
+
if g['muon_compute_dtype'] not in ('auto', 'float32', 'bfloat16'):
|
|
83
|
+
raise ValueError('muon_compute_dtype must be auto, float32 or bfloat16')
|
|
84
|
+
if g['fused'] and g['use_muon']:
|
|
85
|
+
raise ValueError('fused=True is only supported for standard/Sign-SGDF, not Muon')
|
|
86
|
+
if g['fused'] and g['capturable']:
|
|
87
|
+
raise ValueError('fused=True and capturable=True cannot be combined')
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _step_as_int(step) -> int:
|
|
91
|
+
return int(step.item()) if isinstance(step, torch.Tensor) else int(step)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _effective_gamma(group: dict) -> float:
|
|
95
|
+
# Paper Sec. 4.2 uses an unscaled gain for Sign-SGDF.
|
|
96
|
+
if group['gamma'] is None:
|
|
97
|
+
return 1.0 if group['use_sign'] else 0.5
|
|
98
|
+
return float(group['gamma'])
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _ensure_step_tensor(state: dict, p: torch.Tensor, capturable: bool) -> torch.Tensor:
|
|
102
|
+
"""Use Adam-style scalar tensor steps (CPU normally; device for graphs)."""
|
|
103
|
+
step = state.get('step', 0)
|
|
104
|
+
device = p.device if capturable else torch.device('cpu')
|
|
105
|
+
if isinstance(step, torch.Tensor):
|
|
106
|
+
if step.device == device and step.dtype == torch.float32:
|
|
107
|
+
return step
|
|
108
|
+
step = step.to(device=device, dtype=torch.float32)
|
|
109
|
+
else:
|
|
110
|
+
step = torch.tensor(float(step), dtype=torch.float32, device=device)
|
|
111
|
+
state['step'] = step
|
|
112
|
+
return step
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _gain_power_(gain: torch.Tensor, gamma: float) -> None:
|
|
116
|
+
if gamma == 0.5:
|
|
117
|
+
gain.sqrt_()
|
|
118
|
+
elif gamma != 1.0:
|
|
119
|
+
gain.pow_(gamma)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _corrections(beta1: float, beta2: float, t):
|
|
123
|
+
"""Return 1/(1-beta1**t) and factor in paper's s_hat definition."""
|
|
124
|
+
inv_m = 1.0 / (1.0 - beta1 ** t)
|
|
125
|
+
s_factor = ((1.0 - beta1) * (1.0 - beta1 ** (2 * t)) /
|
|
126
|
+
((1.0 + beta1) * (1.0 - beta2 ** t)))
|
|
127
|
+
return inv_m, s_factor
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class SGDF(Optimizer):
|
|
131
|
+
"""PyTorch SGDF, with optional Sign-SGDF or Muon-SGDF update directions.
|
|
132
|
+
|
|
133
|
+
Paper Algorithm 1 (elementwise), with t counted per parameter:
|
|
134
|
+
m <- beta1 * m + (1-beta1) * grad
|
|
135
|
+
s <- beta2 * s + (1-beta2) * (grad-m)**2
|
|
136
|
+
m_hat <- m / (1-beta1**t)
|
|
137
|
+
s_hat <- ((1-beta1)*(1-beta1**(2*t)) /
|
|
138
|
+
((1+beta1)*(1-beta2**t))) * s
|
|
139
|
+
K <- (s_hat / (s_hat + (grad-m_hat)**2 + eps))**gamma
|
|
140
|
+
direction <- m_hat + K*(grad-m_hat)
|
|
141
|
+
p <- p - lr*direction
|
|
142
|
+
|
|
143
|
+
Optional mutually exclusive flags transform *only* direction:
|
|
144
|
+
use_sign: direction <- sign(direction)
|
|
145
|
+
use_muon: direction <- Newton-Schulz(direction) for >=2-D weights;
|
|
146
|
+
1-D weights and scalars use normal SGDF.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
gamma: None selects 0.5 for standard/Muon SGDF, 1.0 for Sign-SGDF
|
|
150
|
+
(matching the sign extension in Sec. 4.2). Otherwise use the provided value.
|
|
151
|
+
foreach: None (small CUDA batches automatically), True (bounded CUDA/CPU
|
|
152
|
+
tensor-list operations), False (lowest peak temporary allocation).
|
|
153
|
+
foreach_max_bytes: maximum total parameter bytes per foreach batch. Large
|
|
154
|
+
individual tensors use memory-efficient elementwise PyTorch operations.
|
|
155
|
+
capturable: CUDA graph per-tensor path (requires static gradients).
|
|
156
|
+
For DDP, let PyTorch synchronize gradients; no optimizer-side all-reduce.
|
|
157
|
+
Elementwise SGDF works with FSDP local/sharded parameter tensors; Muon
|
|
158
|
+
orthogonalization requires complete matrices and cannot act on shards.
|
|
159
|
+
muon_distributed: 'auto' selects Gram or gather by matrix shape and
|
|
160
|
+
communication size; 'error' rejects shards; 'gather' reconstructs a
|
|
161
|
+
DTensor matrix; 'gram' performs single-reduce polynomial Newton-Schulz
|
|
162
|
+
on a 2-D matrix sharded on a 1-D mesh.
|
|
163
|
+
muon_gram_max_dim: upper bound on the unsharded Gram matrix dimension.
|
|
164
|
+
muon_gather_max_bytes: avoid automatically gathering enormous matrices.
|
|
165
|
+
muon_ddp: 'local' computes Muon on every DDP replica; 'shard' assigns
|
|
166
|
+
expensive complete matrices across ranks and broadcasts directions.
|
|
167
|
+
All ranks must call optimizer.step() in the same order with matching
|
|
168
|
+
parameter groups, synchronized gradients, and equal grad presence.
|
|
169
|
+
muon_ddp_min_numel: avoid broadcasting small Muon matrices.
|
|
170
|
+
muon_ddp_bucket_bytes: maximum coalesced direction broadcast size.
|
|
171
|
+
muon_compute_dtype: 'auto' (bf16 on supported CUDA, fp32 elsewhere),
|
|
172
|
+
'float32' or 'bfloat16' (requires CUDA). fp64 input retains fp64.
|
|
173
|
+
fused: use optional Triton fused CUDA kernel for contiguous fp32
|
|
174
|
+
standard/Sign-SGDF. Explicit opt-in; incompatible configurations error.
|
|
175
|
+
weight_decouple: False = L2 regularization; True = decoupled weight decay.
|
|
176
|
+
maximize: ascend rather than descend the objective.
|
|
177
|
+
|
|
178
|
+
Sparse gradients and differentiable optimizer steps are not supported.
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
def __init__(
|
|
182
|
+
self, params, lr: float = 0.5, betas=(0.9, 0.999),
|
|
183
|
+
eps: float = 1e-8, gamma: Optional[float] = None, weight_decay: float = 0.0,
|
|
184
|
+
weight_decouple: bool = False, use_sign: bool = False,
|
|
185
|
+
use_muon: bool = False, ns_steps: int = 5,
|
|
186
|
+
foreach: Optional[bool] = None,
|
|
187
|
+
foreach_max_bytes: int = _DEFAULT_FOREACH_BYTES,
|
|
188
|
+
capturable: bool = False, maximize: bool = False,
|
|
189
|
+
fused: bool = False, muon_distributed: str = 'auto',
|
|
190
|
+
muon_gram_max_dim: int = 4096, muon_compute_dtype: str = 'auto',
|
|
191
|
+
muon_gather_max_bytes: int = 256 * 1024 * 1024,
|
|
192
|
+
muon_ddp: str = 'local', muon_ddp_min_numel: int = 65536,
|
|
193
|
+
muon_ddp_bucket_bytes: int = 32 * 1024 * 1024,
|
|
194
|
+
):
|
|
195
|
+
defaults = dict(lr=lr, betas=tuple(betas), eps=eps, gamma=gamma,
|
|
196
|
+
weight_decay=weight_decay, weight_decouple=weight_decouple,
|
|
197
|
+
use_sign=use_sign, use_muon=use_muon, ns_steps=ns_steps,
|
|
198
|
+
foreach=foreach, foreach_max_bytes=foreach_max_bytes,
|
|
199
|
+
capturable=capturable, maximize=maximize, fused=fused,
|
|
200
|
+
muon_distributed=muon_distributed,
|
|
201
|
+
muon_gram_max_dim=muon_gram_max_dim,
|
|
202
|
+
muon_compute_dtype=muon_compute_dtype,
|
|
203
|
+
muon_gather_max_bytes=muon_gather_max_bytes,
|
|
204
|
+
muon_ddp=muon_ddp, muon_ddp_min_numel=muon_ddp_min_numel,
|
|
205
|
+
muon_ddp_bucket_bytes=muon_ddp_bucket_bytes)
|
|
206
|
+
_validate_group(defaults)
|
|
207
|
+
super().__init__(params, defaults)
|
|
208
|
+
|
|
209
|
+
def add_param_group(self, param_group):
|
|
210
|
+
# Optimizer.__init__ calls this method, after self.defaults is initialized.
|
|
211
|
+
if hasattr(self, 'defaults'):
|
|
212
|
+
merged = {**self.defaults, **param_group}
|
|
213
|
+
_validate_group(merged)
|
|
214
|
+
super().add_param_group(param_group)
|
|
215
|
+
|
|
216
|
+
def __setstate__(self, state):
|
|
217
|
+
super().__setstate__(state)
|
|
218
|
+
# Allow restoring checkpoints created by earlier SGDF releases.
|
|
219
|
+
for group in self.param_groups:
|
|
220
|
+
for key, default in self.defaults.items():
|
|
221
|
+
group.setdefault(key, default)
|
|
222
|
+
|
|
223
|
+
def _init_param(self, p: torch.Tensor, group: dict):
|
|
224
|
+
if p.grad.layout != torch.strided:
|
|
225
|
+
raise RuntimeError('SGDF does not support sparse/non-strided gradients')
|
|
226
|
+
if p.is_complex() or not p.is_floating_point():
|
|
227
|
+
raise TypeError('SGDF expects real floating-point parameters')
|
|
228
|
+
if p.dtype == torch.float16 and group['eps'] < 2 ** -24:
|
|
229
|
+
raise ValueError(
|
|
230
|
+
'SGDF eps underflows to zero with float16 parameters; '
|
|
231
|
+
'use standard AMP with float32 parameters, or eps >= 2**-24'
|
|
232
|
+
)
|
|
233
|
+
if group['use_muon'] and getattr(p, '_is_flat_param', False):
|
|
234
|
+
raise RuntimeError(
|
|
235
|
+
'Muon requires complete weight matrices. FSDP FlatParameter / '
|
|
236
|
+
'sharded flat tensors cannot be orthogonalized independently; '
|
|
237
|
+
'use SGDF(use_muon=False) for FSDP or Muon with DDP.'
|
|
238
|
+
)
|
|
239
|
+
if _is_dtensor(p) and not _is_dtensor(p.grad):
|
|
240
|
+
raise RuntimeError('DTensor parameter requires a DTensor gradient')
|
|
241
|
+
if group['use_muon'] and p.ndim >= 2 and _is_dtensor(p):
|
|
242
|
+
if any(isinstance(place, Partial) for place in p.placements):
|
|
243
|
+
raise RuntimeError('Muon does not support DTensor Partial placements')
|
|
244
|
+
if (group['muon_distributed'] == 'error' and
|
|
245
|
+
any(isinstance(place, Shard) for place in p.placements)):
|
|
246
|
+
raise RuntimeError(
|
|
247
|
+
'Muon on sharded DTensor needs muon_distributed="gather" or "gram"; '
|
|
248
|
+
'local-shard Newton-Schulz is mathematically incorrect.'
|
|
249
|
+
)
|
|
250
|
+
if group['fused']:
|
|
251
|
+
if (p.device.type != 'cuda' or _is_dtensor(p) or p.dtype != torch.float32 or
|
|
252
|
+
p.grad.dtype != torch.float32 or not p.is_contiguous() or
|
|
253
|
+
not p.grad.is_contiguous()):
|
|
254
|
+
raise RuntimeError(
|
|
255
|
+
'fused=True requires contiguous non-DTensor CUDA float32 '
|
|
256
|
+
'parameters and gradients; use fused=False otherwise'
|
|
257
|
+
)
|
|
258
|
+
if p.grad.device != p.device or p.grad.shape != p.shape:
|
|
259
|
+
raise RuntimeError('Parameter and gradient must share shape and device')
|
|
260
|
+
if group['capturable'] and p.device.type != 'cuda':
|
|
261
|
+
raise ValueError('capturable=True requires CUDA tensors')
|
|
262
|
+
st = self.state[p]
|
|
263
|
+
if not st:
|
|
264
|
+
# Match torch.optim.Adam: moment dtype and device follow parameters.
|
|
265
|
+
st['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
|
266
|
+
st['exp_var'] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
|
267
|
+
st['step'] = torch.zeros((), dtype=torch.float32,
|
|
268
|
+
device=(p.device if group['capturable'] else 'cpu'))
|
|
269
|
+
else:
|
|
270
|
+
# torch.optim.Optimizer.load_state_dict normally restores state
|
|
271
|
+
# to the current parameter device/dtype, like Adam.
|
|
272
|
+
for key in ('exp_avg', 'exp_var'):
|
|
273
|
+
if key not in st:
|
|
274
|
+
raise RuntimeError(f'Incomplete SGDF optimizer state: {key} missing')
|
|
275
|
+
if st[key].device != p.device:
|
|
276
|
+
raise RuntimeError('SGDF state device mismatch; reload state_dict')
|
|
277
|
+
_ensure_step_tensor(st, p, group['capturable'])
|
|
278
|
+
|
|
279
|
+
@staticmethod
|
|
280
|
+
def _muon_ddp_owners(group: dict, ps: list[torch.Tensor]) -> dict[int, int]:
|
|
281
|
+
"""Assign high-cost 2-D+ Muon updates to single-node DDP ranks."""
|
|
282
|
+
import torch.distributed as dist
|
|
283
|
+
|
|
284
|
+
if not dist.is_available() or not dist.is_initialized():
|
|
285
|
+
return {}
|
|
286
|
+
if not group['params']:
|
|
287
|
+
return {}
|
|
288
|
+
world = dist.get_world_size()
|
|
289
|
+
if world <= 1:
|
|
290
|
+
return {}
|
|
291
|
+
if any(_is_dtensor(p) for p in group['params']):
|
|
292
|
+
raise RuntimeError('muon_ddp="shard" requires replicated local tensors; '
|
|
293
|
+
'for FSDP2/DTensor use muon_distributed="auto"')
|
|
294
|
+
if len({p.device for p in group['params']}) != 1:
|
|
295
|
+
raise RuntimeError('muon_ddp="shard" requires parameters on one device per rank')
|
|
296
|
+
|
|
297
|
+
# Catch mismatched gradient availability before entering a per-layer
|
|
298
|
+
# broadcast, which would otherwise risk a multi-rank deadlock.
|
|
299
|
+
backend = str(dist.get_backend()).lower()
|
|
300
|
+
first = ps[0] if ps else group['params'][0]
|
|
301
|
+
dev = first.device if 'nccl' in backend else torch.device('cpu')
|
|
302
|
+
num_params = len(group['params'])
|
|
303
|
+
local_count = torch.tensor([num_params], device=dev, dtype=torch.int64)
|
|
304
|
+
counts = [torch.empty_like(local_count) for _ in range(world)]
|
|
305
|
+
dist.all_gather(counts, local_count)
|
|
306
|
+
if any(int(v.item()) != num_params for v in counts):
|
|
307
|
+
raise RuntimeError('Muon DDP shards require identical parameter groups on all ranks')
|
|
308
|
+
flags = torch.tensor([int(p.grad is not None) for p in group['params']],
|
|
309
|
+
dtype=torch.uint8, device=dev)
|
|
310
|
+
flags_all = [torch.empty_like(flags) for _ in range(world)]
|
|
311
|
+
dist.all_gather(flags_all, flags)
|
|
312
|
+
if any(not torch.equal(v, flags) for v in flags_all):
|
|
313
|
+
raise RuntimeError('Muon DDP shards require matching gradient presence '
|
|
314
|
+
'on every rank; synchronize gradients before step')
|
|
315
|
+
|
|
316
|
+
# Greedy balancing by approximate Newton-Schulz work, not by layer
|
|
317
|
+
# count. The sorted shapes are identical on all DDP replicas.
|
|
318
|
+
jobs = []
|
|
319
|
+
for i, p in enumerate(group['params']):
|
|
320
|
+
if (p.grad is None or p.ndim < 2 or
|
|
321
|
+
p.numel() < group['muon_ddp_min_numel']):
|
|
322
|
+
continue
|
|
323
|
+
rows, cols = p.shape[0], p.numel() // p.shape[0]
|
|
324
|
+
lo, hi = min(rows, cols), max(rows, cols)
|
|
325
|
+
jobs.append((hi * lo * lo, i, p))
|
|
326
|
+
jobs.sort(key=lambda item: (-item[0], item[1]))
|
|
327
|
+
loads = [0] * world
|
|
328
|
+
owners = {}
|
|
329
|
+
for cost, _, p in jobs:
|
|
330
|
+
owner = min(range(world), key=lambda idx: loads[idx])
|
|
331
|
+
owners[id(p)] = owner
|
|
332
|
+
loads[owner] += cost
|
|
333
|
+
return owners
|
|
334
|
+
|
|
335
|
+
@staticmethod
|
|
336
|
+
def _finish_muon_ddp(
|
|
337
|
+
pending: list[tuple[torch.Tensor, int, Optional[torch.Tensor], float]],
|
|
338
|
+
group: dict,
|
|
339
|
+
) -> None:
|
|
340
|
+
"""Broadcast all shard owners' ready updates in bounded flat buckets.
|
|
341
|
+
|
|
342
|
+
Newton-Schulz work has already run concurrently on different ranks.
|
|
343
|
+
Packing updates by owner and dtype avoids one collective per layer.
|
|
344
|
+
"""
|
|
345
|
+
import torch.distributed as dist
|
|
346
|
+
|
|
347
|
+
if not pending:
|
|
348
|
+
return
|
|
349
|
+
rank = dist.get_rank()
|
|
350
|
+
world = dist.get_world_size()
|
|
351
|
+
max_bytes = group['muon_ddp_bucket_bytes']
|
|
352
|
+
for owner in range(world):
|
|
353
|
+
for dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):
|
|
354
|
+
items = [entry for entry in pending
|
|
355
|
+
if entry[1] == owner and entry[0].dtype == dtype]
|
|
356
|
+
if not items:
|
|
357
|
+
continue
|
|
358
|
+
buckets = []
|
|
359
|
+
bucket, used = [], 0
|
|
360
|
+
for entry in items:
|
|
361
|
+
size = entry[0].numel() * entry[0].element_size()
|
|
362
|
+
if bucket and used + size > max_bytes:
|
|
363
|
+
buckets.append(bucket)
|
|
364
|
+
bucket, used = [], 0
|
|
365
|
+
bucket.append(entry)
|
|
366
|
+
used += size
|
|
367
|
+
if bucket:
|
|
368
|
+
buckets.append(bucket)
|
|
369
|
+
for batch in buckets:
|
|
370
|
+
count = sum(p.numel() for p, _, _, _ in batch)
|
|
371
|
+
if rank == owner:
|
|
372
|
+
flat = torch.cat([direction.reshape(-1)
|
|
373
|
+
for _, _, direction, _ in batch])
|
|
374
|
+
else:
|
|
375
|
+
flat = torch.empty(count, dtype=dtype,
|
|
376
|
+
device=batch[0][0].device)
|
|
377
|
+
dist.broadcast(flat, src=owner)
|
|
378
|
+
offset = 0
|
|
379
|
+
for p, _, _, lr in batch:
|
|
380
|
+
num = p.numel()
|
|
381
|
+
p.add_(flat[offset:offset + num].reshape(p.shape), alpha=-lr)
|
|
382
|
+
offset += num
|
|
383
|
+
|
|
384
|
+
@torch.no_grad()
|
|
385
|
+
def step(self, closure=None):
|
|
386
|
+
loss = None
|
|
387
|
+
if closure is not None:
|
|
388
|
+
with torch.enable_grad():
|
|
389
|
+
loss = closure()
|
|
390
|
+
for group in self.param_groups:
|
|
391
|
+
# Legacy SGDF checkpoint groups may lack newer options.
|
|
392
|
+
for key, default in self.defaults.items():
|
|
393
|
+
group.setdefault(key, default)
|
|
394
|
+
_validate_group(group)
|
|
395
|
+
ps = [p for p in group['params'] if p.grad is not None]
|
|
396
|
+
owners = (self._muon_ddp_owners(group, ps)
|
|
397
|
+
if group['muon_ddp'] == 'shard' else {})
|
|
398
|
+
if not ps:
|
|
399
|
+
continue
|
|
400
|
+
for p in ps:
|
|
401
|
+
self._init_param(p, group)
|
|
402
|
+
|
|
403
|
+
if group['fused']:
|
|
404
|
+
for p in ps:
|
|
405
|
+
self._step_fused(p, group)
|
|
406
|
+
continue
|
|
407
|
+
|
|
408
|
+
# Foreach can consume O(num_params) extra memory. Group by state
|
|
409
|
+
# step and use fixed-byte chunks; large matrices use the loop.
|
|
410
|
+
want_foreach = (group['foreach'] is True or
|
|
411
|
+
(group['foreach'] is None and ps[0].device.type == 'cuda'))
|
|
412
|
+
if (not want_foreach or group['capturable'] or group['use_muon'] or
|
|
413
|
+
not all(hasattr(torch, op) for op in (
|
|
414
|
+
'_foreach_add_', '_foreach_addcmul_', '_foreach_mul_',
|
|
415
|
+
'_foreach_sub', '_foreach_reciprocal_', '_foreach_mul')) or
|
|
416
|
+
(group['use_sign'] and not hasattr(torch, '_foreach_sign_'))):
|
|
417
|
+
deferred = []
|
|
418
|
+
for p in ps:
|
|
419
|
+
self._step_one(p, group, muon_owner=owners.get(id(p)),
|
|
420
|
+
muon_deferred=deferred)
|
|
421
|
+
if deferred:
|
|
422
|
+
self._finish_muon_ddp(deferred, group)
|
|
423
|
+
continue
|
|
424
|
+
|
|
425
|
+
buckets = defaultdict(list)
|
|
426
|
+
max_bytes = group['foreach_max_bytes']
|
|
427
|
+
for p in ps:
|
|
428
|
+
st = self.state[p]
|
|
429
|
+
eligible = (
|
|
430
|
+
not _is_dtensor(p) and not _is_dtensor(p.grad)
|
|
431
|
+
and p.is_contiguous() and p.grad.is_contiguous()
|
|
432
|
+
and p.dtype in (torch.float32, torch.float64)
|
|
433
|
+
and st['exp_avg'].dtype == p.dtype
|
|
434
|
+
and st['exp_var'].dtype == p.dtype
|
|
435
|
+
and st['step'].device.type == 'cpu'
|
|
436
|
+
and p.numel() * p.element_size() <= max_bytes
|
|
437
|
+
)
|
|
438
|
+
if not eligible:
|
|
439
|
+
self._step_one(p, group)
|
|
440
|
+
continue
|
|
441
|
+
key = (p.device, p.dtype, _step_as_int(st['step']))
|
|
442
|
+
buckets[key].append(p)
|
|
443
|
+
|
|
444
|
+
for bucket in buckets.values():
|
|
445
|
+
batch, batch_bytes = [], 0
|
|
446
|
+
for p in bucket:
|
|
447
|
+
b = p.numel() * p.element_size()
|
|
448
|
+
if batch and batch_bytes + b > max_bytes:
|
|
449
|
+
self._step_foreach(batch, group)
|
|
450
|
+
batch, batch_bytes = [], 0
|
|
451
|
+
batch.append(p)
|
|
452
|
+
batch_bytes += b
|
|
453
|
+
if batch:
|
|
454
|
+
self._step_foreach(batch, group)
|
|
455
|
+
return loss
|
|
456
|
+
|
|
457
|
+
def _step_one(self, p: torch.Tensor, group: dict,
|
|
458
|
+
muon_owner: Optional[int] = None,
|
|
459
|
+
muon_deferred: Optional[list] = None) -> None:
|
|
460
|
+
b1, b2 = group['betas']
|
|
461
|
+
lr, eps, gamma = group['lr'], group['eps'], _effective_gamma(group)
|
|
462
|
+
wd, decouple = group['weight_decay'], group['weight_decouple']
|
|
463
|
+
st = self.state[p]
|
|
464
|
+
m, v = st['exp_avg'], st['exp_var']
|
|
465
|
+
grad = p.grad.detach()
|
|
466
|
+
if grad.dtype != m.dtype:
|
|
467
|
+
grad = grad.to(dtype=m.dtype)
|
|
468
|
+
if group['maximize']:
|
|
469
|
+
grad = grad.neg()
|
|
470
|
+
if wd and not decouple:
|
|
471
|
+
# Creates working gradient; NEVER modifies p.grad.
|
|
472
|
+
grad = grad.add(p.detach().to(dtype=m.dtype), alpha=wd)
|
|
473
|
+
elif wd and decouple:
|
|
474
|
+
p.mul_(1 - lr * wd)
|
|
475
|
+
|
|
476
|
+
m.mul_(b1).add_(grad, alpha=1 - b1)
|
|
477
|
+
# r: first (grad-m), then reuse SAME buffer as (grad-m_hat).
|
|
478
|
+
r = grad - m
|
|
479
|
+
v.mul_(b2).addcmul_(r, r, value=1 - b2)
|
|
480
|
+
|
|
481
|
+
if group['capturable']:
|
|
482
|
+
counter = _ensure_step_tensor(st, p, capturable=True)
|
|
483
|
+
counter.add_(1)
|
|
484
|
+
t = counter
|
|
485
|
+
else:
|
|
486
|
+
counter = _ensure_step_tensor(st, p, capturable=False)
|
|
487
|
+
counter.add_(1)
|
|
488
|
+
t = _step_as_int(counter)
|
|
489
|
+
inv_m, s_factor = _corrections(b1, b2, t)
|
|
490
|
+
r.add_(m, alpha=1.0 - inv_m) if isinstance(inv_m, float) else r.add_(m * (1 - inv_m))
|
|
491
|
+
|
|
492
|
+
# EXACT paper formula, written in two full-size temporaries (r, K):
|
|
493
|
+
# K = (s_hat / (s_hat + r*r + eps))**gamma
|
|
494
|
+
# s_hat = s_factor * v
|
|
495
|
+
# eps is added to the DENOMINATOR, never outside K.
|
|
496
|
+
# Match torch.optim.Adam's ordinary tensor-dtype arithmetic: no
|
|
497
|
+
# special fp32 promotion for half-precision parameters. As in Adam,
|
|
498
|
+
# eps=1e-8 may round to zero when the denominator is float16.
|
|
499
|
+
k = r.square()
|
|
500
|
+
if isinstance(s_factor, float):
|
|
501
|
+
k.add_(v, alpha=s_factor).add_(eps)
|
|
502
|
+
torch.div(v, k, out=k).mul_(s_factor)
|
|
503
|
+
else: # CUDA-graph device scalar
|
|
504
|
+
k.add_(v * s_factor).add_(eps)
|
|
505
|
+
torch.div(v, k, out=k).mul_(s_factor)
|
|
506
|
+
_gain_power_(k, gamma)
|
|
507
|
+
|
|
508
|
+
if group['use_sign'] or (group['use_muon'] and p.ndim >= 2):
|
|
509
|
+
k.mul_(r)
|
|
510
|
+
if isinstance(inv_m, float):
|
|
511
|
+
k.add_(m, alpha=inv_m)
|
|
512
|
+
else:
|
|
513
|
+
k.add_(m * inv_m)
|
|
514
|
+
if group['use_sign']:
|
|
515
|
+
k.sign_()
|
|
516
|
+
direction = k
|
|
517
|
+
else:
|
|
518
|
+
from .muon import muon_postprocess
|
|
519
|
+
if muon_owner is None:
|
|
520
|
+
direction = muon_postprocess(
|
|
521
|
+
k, ns_steps=group['ns_steps'],
|
|
522
|
+
distributed=group['muon_distributed'],
|
|
523
|
+
gram_max_dim=group['muon_gram_max_dim'],
|
|
524
|
+
compute_dtype=group['muon_compute_dtype'],
|
|
525
|
+
gather_max_bytes=group['muon_gather_max_bytes'],
|
|
526
|
+
)
|
|
527
|
+
else:
|
|
528
|
+
import torch.distributed as dist
|
|
529
|
+
if dist.get_rank() == muon_owner:
|
|
530
|
+
direction = muon_postprocess(
|
|
531
|
+
k, ns_steps=group['ns_steps'],
|
|
532
|
+
distributed='error',
|
|
533
|
+
compute_dtype=group['muon_compute_dtype'],
|
|
534
|
+
).to(dtype=p.dtype).contiguous()
|
|
535
|
+
else:
|
|
536
|
+
direction = None
|
|
537
|
+
if muon_deferred is not None:
|
|
538
|
+
muon_deferred.append((p, muon_owner, direction, lr))
|
|
539
|
+
return
|
|
540
|
+
if direction is None:
|
|
541
|
+
direction = torch.empty(p.shape, dtype=p.dtype, device=p.device)
|
|
542
|
+
dist.broadcast(direction, src=muon_owner)
|
|
543
|
+
p.add_(direction.to(dtype=p.dtype), alpha=-lr)
|
|
544
|
+
elif p.dtype == m.dtype and isinstance(inv_m, float):
|
|
545
|
+
# No third full-size update tensor.
|
|
546
|
+
p.add_(m, alpha=-lr * inv_m)
|
|
547
|
+
p.addcmul_(k, r, value=-lr)
|
|
548
|
+
else:
|
|
549
|
+
# CUDA graph capture and dtype-mismatched updates use a temporary direction.
|
|
550
|
+
k.mul_(r)
|
|
551
|
+
if isinstance(inv_m, float):
|
|
552
|
+
k.add_(m, alpha=inv_m)
|
|
553
|
+
else:
|
|
554
|
+
k.add_(m * inv_m)
|
|
555
|
+
p.add_(k.to(dtype=p.dtype), alpha=-lr)
|
|
556
|
+
|
|
557
|
+
def _step_foreach(self, ps: list[torch.Tensor], group: dict) -> None:
|
|
558
|
+
b1, b2 = group['betas']
|
|
559
|
+
lr, eps, gamma = group['lr'], group['eps'], _effective_gamma(group)
|
|
560
|
+
wd, decouple = group['weight_decay'], group['weight_decouple']
|
|
561
|
+
ms = [self.state[p]['exp_avg'] for p in ps]
|
|
562
|
+
vs = [self.state[p]['exp_var'] for p in ps]
|
|
563
|
+
gs = [p.grad.detach() for p in ps]
|
|
564
|
+
if group['maximize']:
|
|
565
|
+
gs = torch._foreach_neg(gs)
|
|
566
|
+
if wd:
|
|
567
|
+
if decouple:
|
|
568
|
+
torch._foreach_mul_(ps, 1 - lr * wd)
|
|
569
|
+
else:
|
|
570
|
+
gs = torch._foreach_add(gs, ps, alpha=wd)
|
|
571
|
+
|
|
572
|
+
torch._foreach_mul_(ms, b1)
|
|
573
|
+
torch._foreach_add_(ms, gs, alpha=1 - b1)
|
|
574
|
+
r = torch._foreach_sub(gs, ms)
|
|
575
|
+
torch._foreach_mul_(vs, b2)
|
|
576
|
+
torch._foreach_addcmul_(vs, r, r, value=1 - b2)
|
|
577
|
+
t = _step_as_int(self.state[ps[0]]['step']) + 1
|
|
578
|
+
for p in ps:
|
|
579
|
+
self.state[p]['step'].add_(1)
|
|
580
|
+
inv_m, s_factor = _corrections(b1, b2, t)
|
|
581
|
+
torch._foreach_add_(r, ms, alpha=1 - inv_m)
|
|
582
|
+
# Epsilon is added only to the gain denominator.
|
|
583
|
+
gains = torch._foreach_mul(r, r)
|
|
584
|
+
torch._foreach_add_(gains, vs, alpha=s_factor)
|
|
585
|
+
torch._foreach_add_(gains, eps)
|
|
586
|
+
torch._foreach_reciprocal_(gains)
|
|
587
|
+
torch._foreach_mul_(gains, vs)
|
|
588
|
+
torch._foreach_mul_(gains, s_factor)
|
|
589
|
+
if gamma == 0.5:
|
|
590
|
+
torch._foreach_sqrt_(gains)
|
|
591
|
+
elif gamma != 1.0:
|
|
592
|
+
torch._foreach_pow_(gains, gamma)
|
|
593
|
+
if group['use_sign']:
|
|
594
|
+
torch._foreach_mul_(gains, r)
|
|
595
|
+
torch._foreach_add_(gains, ms, alpha=inv_m)
|
|
596
|
+
torch._foreach_sign_(gains)
|
|
597
|
+
torch._foreach_add_(ps, gains, alpha=-lr)
|
|
598
|
+
else:
|
|
599
|
+
# In-place 2-term update: no direction tensors allocated.
|
|
600
|
+
torch._foreach_add_(ps, ms, alpha=-lr * inv_m)
|
|
601
|
+
torch._foreach_addcmul_(ps, gains, r, value=-lr)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _step_fused(self, p: torch.Tensor, group: dict) -> None:
|
|
605
|
+
"""Optional fused fp32 CUDA path; Triton is imported only on demand.
|
|
606
|
+
|
|
607
|
+
Persistent moment buffers remain identical to v0.4.1. The kernel merges
|
|
608
|
+
every elementwise SGDF operation into a single launch per parameter.
|
|
609
|
+
The step counter is CPU-hosted to avoid CUDA synchronization; this
|
|
610
|
+
implementation is intentionally not CUDA-graph-capturable.
|
|
611
|
+
"""
|
|
612
|
+
try:
|
|
613
|
+
from ._triton import fused_sgdf_step
|
|
614
|
+
except ImportError as exc:
|
|
615
|
+
raise RuntimeError(
|
|
616
|
+
'fused=True requires a CUDA-enabled PyTorch and Triton. '
|
|
617
|
+
'Install SGDF[triton] or set fused=False.'
|
|
618
|
+
) from exc
|
|
619
|
+
state = self.state[p]
|
|
620
|
+
counter = _ensure_step_tensor(state, p, capturable=False)
|
|
621
|
+
counter.add_(1)
|
|
622
|
+
t = _step_as_int(counter)
|
|
623
|
+
b1, b2 = group['betas']
|
|
624
|
+
inv_m, s_factor = _corrections(b1, b2, t)
|
|
625
|
+
fused_sgdf_step(
|
|
626
|
+
p, p.grad.detach(), state['exp_avg'], state['exp_var'],
|
|
627
|
+
lr=group['lr'], beta1=b1, beta2=b2, eps=group['eps'],
|
|
628
|
+
gamma=_effective_gamma(group), wd=group['weight_decay'],
|
|
629
|
+
decouple=group['weight_decouple'], maximize=group['maximize'],
|
|
630
|
+
sign=group['use_sign'], inv_m=inv_m, s_factor=s_factor,
|
|
631
|
+
)
|
|
@@ -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.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
SGDF/__init__.py,sha256=CZjRL7m_xjPKw-GTVqwt6sto5ld1BmxrFvimLIZV-fg,141
|
|
2
|
+
SGDF/_triton.py,sha256=o7OeBVIKvL9qHT7xTWus5oB6t1OT0BKNuKPRcwGQ6qc,2410
|
|
3
|
+
SGDF/muon.py,sha256=k8CCoMrtBD_AGdmoS9ZBLZ5ENU75P-mylyiBYDrJ_S4,8872
|
|
4
|
+
SGDF/optimizer.py,sha256=SFVXv1qWVjw4fRZJ13iydfwJGgchD-Oy065Bp1jH4tY,30038
|
|
5
|
+
sgdf-0.5.0.dist-info/licenses/LICENSE,sha256=5xdXMvQcKb5_6Bkwbc16nC6tuDo9FtSmvxjEj8Q-VSU,1074
|
|
6
|
+
sgdf-0.5.0.dist-info/METADATA,sha256=SP9Vs1BUeVj6VbF94L8LVNU_I3wy4qdp7hYq0Np3BPk,4376
|
|
7
|
+
sgdf-0.5.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
8
|
+
sgdf-0.5.0.dist-info/top_level.txt,sha256=UswYzV4h9nt17_ZkM5VR3orBfZ_uWxOZCD7-98Dilc0,5
|
|
9
|
+
sgdf-0.5.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
SGDF
|