adv-optm 1.2.dev19__py3-none-any.whl → 2.dev3__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.

Potentially problematic release.


This version of adv-optm might be problematic. Click here for more details.

adv_optm/__init__.py CHANGED
@@ -20,4 +20,4 @@ __all__ = [
20
20
  "AdaMuon_adv",
21
21
  ]
22
22
 
23
- __version__ = "1.2.dev19"
23
+ __version__ = "2.dev3"
@@ -46,7 +46,6 @@ class AdaMuon_adv(torch.optim.Optimizer):
46
46
  (default: (3.4445, -4.7750, 2.0315)).
47
47
  stochastic_rounding (bool): whether to use stochastic rounding for
48
48
  BF16 parameter updates (default: True).
49
- orthogonal_gradient (bool): whether to use OrthoGrad. (default: False)
50
49
  nesterov (bool): enables Nesterov momentum (default: False).
51
50
  use_atan2 (bool): whether to use the atan2 update rule. (default: False)
52
51
  Simplified_AdEMAMix (bool): whether to use the Simplified AdEMAMix update rule.
@@ -96,7 +95,6 @@ class AdaMuon_adv(torch.optim.Optimizer):
96
95
  ns_eps: float = 1e-7,
97
96
  ns_coeffs: tuple[float, float, float] = (3.4445, -4.7750, 2.0315),
98
97
  stochastic_rounding: bool = False,
99
- orthogonal_gradient: bool = False,
100
98
  use_atan2: bool = False,
101
99
  nesterov: bool = False,
102
100
  Simplified_AdEMAMix: bool = False,
@@ -149,7 +147,7 @@ class AdaMuon_adv(torch.optim.Optimizer):
149
147
  "vector_reshape": vector_reshape,
150
148
  "nesterov":nesterov, "use_atan2":use_atan2,
151
149
  "Simplified_AdEMAMix": Simplified_AdEMAMix, "alpha_grad": alpha_grad,
152
- "normuon_variant": normuon_variant, "orthogonal_gradient": orthogonal_gradient,
150
+ "normuon_variant": normuon_variant,
153
151
  # Low-rank Ortho
154
152
  "low_rank_ortho": low_rank_ortho, "ortho_rank": ortho_rank,
155
153
  "compiled_optimizer":compiled_optimizer,
@@ -284,10 +282,6 @@ class AdaMuon_adv(torch.optim.Optimizer):
284
282
  nesterov = group['nesterov']
285
283
  Simplified_AdEMAMix = group['Simplified_AdEMAMix']
286
284
  alpha_grad = group['alpha_grad']
287
- if grad.dtype != torch.float32 and state.get('factored', False):
288
- grad = grad.float()
289
- if group.get("orthogonal_gradient"):
290
- grad = _orthogonalize_gradient(p, grad)
291
285
 
292
286
  if state['factored']: # Factored AdaMuon
293
287
 
@@ -351,7 +345,11 @@ class AdaMuon_adv(torch.optim.Optimizer):
351
345
  mean_squared_update = torch.mean(update.square(), dim=1)
352
346
  v_t.mul_(beta2).add_(mean_squared_update, alpha=1 - beta2)
353
347
  # Normalize update
354
- update.div_(v_t.sqrt().unsqueeze(1).add_(group['eps']))
348
+ if group['use_atan2']:
349
+ a = 1.2732395
350
+ update.atan2_(v_t.sqrt().unsqueeze(1)).mul_(a)
351
+ else:
352
+ update.div_(v_t.sqrt().unsqueeze(1).add_(group['eps']))
355
353
  # Scale learning rate
356
354
  update_norm = torch.linalg.vector_norm(update)
357
355
  scaled_lr = group['rms_target'] * lr * (p.numel()**0.5) / update_norm.add_(group['eps'])
@@ -456,7 +454,11 @@ class AdaMuon_adv(torch.optim.Optimizer):
456
454
  mean_squared_update = torch.mean(update.square(), dim=1)
457
455
  v_t.mul_(beta2).add_(mean_squared_update, alpha=1 - beta2)
458
456
  # Normalize update
459
- update.div_(v_t.sqrt().unsqueeze(1).add_(group['eps']))
457
+ if group['use_atan2']:
458
+ a = 1.2732395
459
+ update.atan2_(v_t.sqrt().unsqueeze(1)).mul_(a)
460
+ else:
461
+ update.div_(v_t.sqrt().unsqueeze(1).add_(group['eps']))
460
462
  # Scale learning rate
461
463
  update_norm = torch.linalg.vector_norm(update)
462
464
  scaled_lr = group['rms_target'] * lr * (p.numel()**0.5) / update_norm.add_(group['eps'])
@@ -49,14 +49,12 @@ class AdamW_adv(torch.optim.Optimizer):
49
49
  before it is added to the fast momentum term (`update = mt + alpha * mt_slow`).
50
50
  A higher value increases the stabilizing influence of the slow
51
51
  momentum. (default: 5.0)
52
- t_alpha (Optional[int]): The number of steps for a linear warmup of the
53
- `alpha` parameter (only used when `use_AdEMAMix` is `True`). This is
54
- highly recommended to prevent instability at the beginning of training,
55
- as it gradually introduces the stabilizing slow momentum term. During
56
- the warmup, `alpha` ramps from 0 to its target value. If `None`,
57
- the scheduler is disabled. (default: None)
58
52
  kourkoutas_beta (bool): whether to enable the layer-wise dynamic β₂ logic.
59
53
  If `False`, the optimizer behaves as standard AdamW. (default: False)
54
+ layer_key_fn (Optional[Callable]): A function that takes a parameter `p`
55
+ and returns a unique, hashable key representing its "layer" or "bucket".
56
+ If `None`, parameters are bucketed by their shape.
57
+ (default: None)
60
58
  beta2_min (float): The minimum value for dynamic β₂, used during periods of
61
59
  high gradient variance ("sunspikes"). Must be less than `betas[1]`.
62
60
  (default: 0.88)
@@ -72,11 +70,7 @@ class AdamW_adv(torch.optim.Optimizer):
72
70
  k_logging (int): if > 0 and kourkoutas_beta=True, enables periodic console
73
71
  logging of Kourkoutas-β statistics (min, max, mean of `β₂` across layers)
74
72
  every logging steps. Useful for debugging and tuning. Set to 0 to disable
75
- logging (default: 0).
76
- layer_key_fn (Optional[Callable]): A function that takes a parameter `p`
77
- and returns a unique, hashable key representing its "layer" or "bucket".
78
- If `None`, parameters are bucketed by their memory ID (tensor-wise).
79
- (default: None)
73
+ logging (default: 0).
80
74
  nnmf_factor (bool): whether to use the factorization or disable it to use
81
75
  the uncompressed optimizer. (default: False)
82
76
  """
@@ -89,7 +83,7 @@ class AdamW_adv(torch.optim.Optimizer):
89
83
  eps: float = 1e-8,
90
84
  weight_decay: float = 0.0,
91
85
  use_bias_correction: bool = True,
92
- vector_reshape: bool = True,
86
+ vector_reshape: bool = False,
93
87
  stochastic_rounding: bool = True,
94
88
  use_atan2: bool = False,
95
89
  cautious_mask: bool = False,
@@ -98,15 +92,16 @@ class AdamW_adv(torch.optim.Optimizer):
98
92
  use_AdEMAMix: bool = False,
99
93
  beta3_ema: float = 0.9999,
100
94
  alpha: float = 5.0,
101
- t_alpha: int | None = None,
102
95
  kourkoutas_beta: bool = False,
96
+ layer_key_fn: Optional[Callable] = None,
103
97
  beta2_min: float = 0.9,
104
98
  ema_alpha: float = 0.95,
105
99
  tiny_spike: float = 1e-9,
106
100
  k_warmup_steps: int = 0,
107
101
  k_logging: int = 0,
108
- layer_key_fn: Optional[Callable] = None,
109
102
  nnmf_factor: bool = False,
103
+ # Compiled
104
+ compiled_optimizer: bool = False,
110
105
  ):
111
106
  if not (lr >= 0.0):
112
107
  raise ValueError(f"Learning-rate should be >= 0.0. Got {lr}")
@@ -116,7 +111,8 @@ class AdamW_adv(torch.optim.Optimizer):
116
111
  raise ValueError(f"Epsilon should be >= 0.0. Got {eps}")
117
112
  if not (weight_decay >= 0.0):
118
113
  raise ValueError(f"Weight-decay should be >= 0.0. Got {weight_decay}")
119
- if kourkoutas_beta and not (betas[1] > beta2_min): raise ValueError(f"For Kourkoutas-β, betas[1] (as beta2_max) must be > beta2_min. Got {betas[1]} and {beta2_min}")
114
+ if kourkoutas_beta and not (betas[1] > beta2_min):
115
+ raise ValueError(f"For Kourkoutas-β, betas[1] (as beta2_max) must be > beta2_min. Got {betas[1]} and {beta2_min}")
120
116
 
121
117
  if cautious_mask and grams_moment:
122
118
  print("Warning: cautious is incompatible with grams, Disabling cautious.")
@@ -126,22 +122,30 @@ class AdamW_adv(torch.optim.Optimizer):
126
122
  "lr": lr, "betas": betas, "eps": eps, "weight_decay": weight_decay,
127
123
  "vector_reshape": vector_reshape, "use_atan2": use_atan2,
128
124
  "orthogonal_gradient": orthogonal_gradient, "use_bias_correction": use_bias_correction,
129
- "beta3_ema": beta3_ema, "alpha": alpha, "t_alpha": t_alpha,
125
+ "beta3_ema": beta3_ema, "alpha": alpha,
130
126
  "kourkoutas_beta": kourkoutas_beta, "beta2_min": beta2_min, "ema_alpha": ema_alpha,
131
127
  "tiny_spike": tiny_spike, "k_warmup_steps": k_warmup_steps, "k_logging": k_logging,
128
+ "compiled_optimizer": compiled_optimizer,
132
129
  }
133
130
  self.stochastic_rounding = stochastic_rounding
134
131
  self.cautious_mask = cautious_mask
135
132
  self.grams_moment = grams_moment
136
133
  self.use_AdEMAMix = use_AdEMAMix
137
134
  self.factored = nnmf_factor
138
- self.kourkoutas_beta = kourkoutas_beta
139
135
  self.layer_key_fn = layer_key_fn
136
+ self.kourkoutas_beta = kourkoutas_beta
137
+
140
138
  super().__init__(params, defaults)
141
139
 
140
+ self.init_step()
141
+
142
142
  if self.kourkoutas_beta:
143
143
  self.kourkoutas_helper = KourkoutasHelper(self)
144
144
 
145
+ if compiled_optimizer:
146
+ torch._dynamo.config.cache_size_limit = 8192
147
+ self.compile(fullgraph=True)
148
+
145
149
  @property
146
150
  def supports_fused_back_pass(self):
147
151
  return True
@@ -154,29 +158,24 @@ class AdamW_adv(torch.optim.Optimizer):
154
158
  def supports_flat_params(self):
155
159
  return False
156
160
 
157
- @torch.no_grad()
158
- def step_parameter(self, p: torch.Tensor, group: dict, i: int | None = None):
159
- if p.grad is None:
160
- return
161
+ def init_step(self):
162
+ for group in self.param_groups:
163
+ for p in group['params']:
164
+ self.__init_state(p, group)
161
165
 
162
- grad = p.grad
163
- if grad.dtype != torch.float32 and self.factored:
164
- grad = grad.float()
165
- if group["orthogonal_gradient"]:
166
- grad = _orthogonalize_gradient(p, grad)
166
+ @torch.no_grad()
167
+ def __init_state(self, p, group):
167
168
  state = self.state[p]
168
169
 
169
- # State Initialization
170
- if 'step' not in state:
170
+ if len(state) == 0:
171
+
171
172
  state['step'] = 0
172
173
 
173
- should_factor = (
174
+ state['factored'] = (
174
175
  self.factored and
175
176
  not (len(p.shape) == 1 and not group['vector_reshape'])
176
177
  )
177
178
 
178
- state['factored'] = should_factor
179
-
180
179
  dtype = torch.float32 if self.factored else p.dtype
181
180
  device = p.device
182
181
 
@@ -186,18 +185,18 @@ class AdamW_adv(torch.optim.Optimizer):
186
185
 
187
186
  # First moment (m)
188
187
  if group['betas'][0] > 0:
189
- state['mu_m_nmf'] = torch.zeros(d1, device=device, dtype=dtype)
188
+ state['mu_m_nmf'] = torch.zeros(d1, device=device, dtype=dtype)
190
189
  state['mv_m_nmf'] = torch.zeros(d2, device=device, dtype=dtype)
191
190
  if not self.grams_moment:
192
191
  packed_d2 = (d2 + 7) // 8
193
192
  state['sign'] = torch.zeros((d1, packed_d2), dtype=torch.uint8, device=device)
194
193
  if self.use_AdEMAMix:
195
- state['mu_m_slow_nmf'] = torch.zeros(d1, device=p.device, dtype=dtype)
194
+ state['mu_m_slow_nmf'] = torch.zeros(d1, device=p.device, dtype=dtype)
196
195
  state['mv_m_slow_nmf'] = torch.zeros(d2, device=p.device, dtype=dtype)
197
196
  packed_d2 = (d2 + 7) // 8
198
197
  state['sign_slow'] = torch.zeros((d1, packed_d2), dtype=torch.uint8, device=p.device)
199
198
  # Second moment (v)
200
- state['mu_v_nmf'] = torch.zeros(d1, device=device, dtype=dtype)
199
+ state['mu_v_nmf'] = torch.zeros(d1, device=device, dtype=dtype)
201
200
  state['mv_v_nmf'] = torch.zeros(d2, device=device, dtype=dtype)
202
201
  else: # Fallback to standard AdamW for non-factored tensors
203
202
  if group['betas'][0] > 0:
@@ -206,37 +205,32 @@ class AdamW_adv(torch.optim.Optimizer):
206
205
  state['exp_avg_slow'] = torch.zeros_like(p, device=device, dtype=dtype)
207
206
  state['exp_avg_sq'] = torch.zeros_like(p, device=device, dtype=dtype)
208
207
 
208
+ @torch.no_grad()
209
+ def __step_parameter(self, p: torch.Tensor, group: dict, lr: torch.Tensor | float, bias_correction1: torch.Tensor | float, bias_correction2: torch.Tensor | float):
210
+ if p.grad is None:
211
+ return
212
+
213
+ grad = p.grad
214
+ if grad.dtype != torch.float32 and self.factored:
215
+ grad = grad.float()
216
+ if group["orthogonal_gradient"]:
217
+ grad = _orthogonalize_gradient(p, grad)
218
+ state = self.state[p]
219
+
220
+
209
221
  beta1, beta2 = group['betas']
210
222
 
211
- current_step = state['step']
212
223
  if group.get('kourkoutas_beta', False):
213
- # Call prepare_step() once at the beginning of the step for all params
214
- self.kourkoutas_helper.maybe_prepare_step(current_step)
215
224
  # Accumulate current grad's norm for the *next* step
216
225
  self.kourkoutas_helper.accumulate_gradient_sq_norm(p, grad)
217
226
  # Get the dynamic beta2 calculated in prepare_step()
218
- beta2 = self.kourkoutas_helper.get_beta2(p, group, current_step)
227
+ beta2 = self.kourkoutas_helper.get_beta2(p, group)
219
228
 
220
- step = state['step'] + 1
221
- if group['use_bias_correction']:
222
- bias_correction1 = 1.0 - beta1 ** step
223
- if group.get('kourkoutas_beta', False):
224
- bias_correction2 = 1.0 - group['betas'][1] ** step
225
- # Use beta2_max for bias correction
226
- else:
227
- bias_correction2 = 1.0 - beta2 ** step
228
- else:
229
- bias_correction1 = 1
230
- bias_correction2 = 1
231
- step_size = group['lr'] / bias_correction1
229
+ step_size = lr / bias_correction1
232
230
 
233
231
  if self.use_AdEMAMix:
234
232
  beta3_ema = group['beta3_ema']
235
233
  alpha = group['alpha']
236
- t_alpha = group['t_alpha']
237
- alpha_t = alpha
238
- if t_alpha is not None and t_alpha > 0 and step < t_alpha:
239
- alpha_t = min(step * alpha / t_alpha, alpha)
240
234
 
241
235
  if state['factored']:
242
236
  d1, d2 = state['effective_shape']
@@ -272,9 +266,9 @@ class AdamW_adv(torch.optim.Optimizer):
272
266
 
273
267
  mt_slow.mul_(beta3_ema).add_(grad_reshaped, alpha=1.0 - beta3_ema)
274
268
  if beta1 > 0:
275
- update = torch.add(mt, mt_slow, alpha=alpha_t)
269
+ update = torch.add(mt, mt_slow, alpha=alpha)
276
270
  else:
277
- update = torch.add(grad_reshaped, mt_slow, alpha=alpha_t)
271
+ update = torch.add(grad_reshaped, mt_slow, alpha=alpha)
278
272
  else:
279
273
  update = mt.clone() if beta1 > 0 else grad_reshaped.clone()
280
274
  del grad_reshaped
@@ -321,9 +315,9 @@ class AdamW_adv(torch.optim.Optimizer):
321
315
  exp_avg_slow = state['exp_avg_slow']
322
316
  exp_avg_slow.mul_(beta3_ema).add_(grad, alpha=1 - beta3_ema)
323
317
  if beta1 > 0:
324
- update = torch.add(exp_avg, exp_avg_slow, alpha=alpha_t)
318
+ update = torch.add(exp_avg, exp_avg_slow, alpha=alpha)
325
319
  else:
326
- update = torch.add(grad, exp_avg_slow, alpha=alpha_t)
320
+ update = torch.add(grad, exp_avg_slow, alpha=alpha)
327
321
  else:
328
322
  update = exp_avg.clone() if beta1 > 0 else grad.clone()
329
323
 
@@ -343,9 +337,9 @@ class AdamW_adv(torch.optim.Optimizer):
343
337
  # Decoupled weight decay
344
338
  if group["weight_decay"] != 0:
345
339
  if p.dtype == torch.bfloat16 and self.stochastic_rounding:
346
- add_stochastic_(p.data, p.data, alpha=-group["weight_decay"] * group["lr"])
340
+ add_stochastic_(p.data, p.data, alpha=-group["weight_decay"] * lr)
347
341
  else:
348
- p.data.add_(p.data, alpha=-group["weight_decay"] * group["lr"])
342
+ p.data.add_(p.data, alpha=-group["weight_decay"] * lr)
349
343
 
350
344
  if p.dtype == torch.bfloat16 and self.stochastic_rounding:
351
345
  add_stochastic_(p.data, -update)
@@ -353,7 +347,40 @@ class AdamW_adv(torch.optim.Optimizer):
353
347
  p.data.add_(-update)
354
348
  del update
355
349
 
356
- state['step'] += 1
350
+ @torch.no_grad()
351
+ def step_parameter(self, p: torch.Tensor, group: dict, i: int | None = None):
352
+
353
+ state = self.state[p]
354
+
355
+ step = state['step']
356
+
357
+ if group['use_bias_correction']:
358
+ current_step = step + 1
359
+ beta1, beta2 = group['betas']
360
+ bias_correction1 = 1.0 - beta1 ** current_step
361
+ bias_correction2 = 1.0 - beta2 ** current_step
362
+ else:
363
+ bias_correction1 = 1.0
364
+ bias_correction2 = 1.0
365
+
366
+ if group.get('kourkoutas_beta', False):
367
+ # Prepare Kourkoutas-β once per step using the global step counter.
368
+ self.kourkoutas_helper.maybe_prepare_step(step)
369
+
370
+ self.state[p]['step'] += 1
371
+
372
+ if not group.get('compiled_optimizer', False):
373
+ self.__step_parameter(p, group, group['lr'], bias_correction1, bias_correction2)
374
+ else:
375
+ if not hasattr(self, 'lr_tensor') or self.lr_tensor is None:
376
+ # convert to tensors for compiled path once a step
377
+ self.lr_tensor = torch.tensor(group['lr'], device=p.device)
378
+ self.bc1_tensor = torch.tensor(bias_correction1, device=p.device)
379
+ self.bc2_tensor = torch.tensor(bias_correction2, device=p.device)
380
+ self._compiled_step_parameter(p, group, self.lr_tensor, self.bc1_tensor, self.bc2_tensor)
381
+
382
+ def compile(self, *args, **kwargs):
383
+ self._compiled_step_parameter = torch.compile(self.__step_parameter, *args, **kwargs)
357
384
 
358
385
  @torch.no_grad()
359
386
  def step(self, closure=None):
@@ -367,4 +394,7 @@ class AdamW_adv(torch.optim.Optimizer):
367
394
  for i, p in enumerate(group['params']):
368
395
  self.step_parameter(p, group, i)
369
396
 
397
+ if self.param_groups[0].get('compiled_optimizer', False):
398
+ # Reset compile tensors once a step
399
+ self.lr_tensor = None
370
400
  return loss