-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathutils.py
More file actions
3948 lines (3191 loc) · 126 KB
/
utils.py
File metadata and controls
3948 lines (3191 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import contextlib
import enum
import functools
import gc
import inspect
import itertools
import math
import pickle
import re
import string
import warnings
from typing import Any, Callable, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch._dynamo.exc import TorchDynamoException
from torch.backends import cudnn, opt_einsum
from torch.nn import functional as F
from torch.utils._pytree import tree_map
compile_mode = "max-autotune-no-cudagraphs"
dynamic = False
compile_mode_recommended_to_none = None
zeroth_power_mode = "newtonschulz"
precise_zeroth_power_mode = "qr"
tiny_bf16 = torch.finfo(torch.bfloat16).tiny
_cudnn_double_backward_pattern = re.compile(
r"the derivative for .* is not implemented\. Double backwards .* To run double backwards"
)
_torch_compile_double_backward_pattern = re.compile(r"compile.*does not currently support double backward")
_fd_error = (
"You can accelerate startup by globally enabling finite_differences first "
"(via opt.finite_differences=True or by subclassing it)\n"
"Original Error: "
)
default_division_backend = "eps_clamp"
atan2_scale = 16.0
dither_steps = 1
class ZerothPowerMode(enum.Enum):
newtonschulz = "newtonschulz"
legacy_newtonschulz = "legacy_newtonschulz"
qr = "qr"
svd = "svd"
legacy_svd = "legacy_svd"
thinky_polar_express = "thinky_polar_express"
class OrthoScaleMode(enum.Enum):
none = "none"
scale = "scale"
graft = "graft"
class DivisionBackend(enum.Enum):
eps_add = "eps_add"
eps_clamp = "eps_clamp"
atan2 = "atan2"
nan_to_0 = "nan_to_0"
DivisionBackendLike = Union[DivisionBackend, str, None]
def _normalize_division_backend(backend: DivisionBackendLike) -> DivisionBackend:
if backend is None:
return DivisionBackend(default_division_backend)
if isinstance(backend, DivisionBackend):
return backend
try:
return DivisionBackend(backend)
except ValueError as error:
raise ValueError(f"Unknown division backend '{backend}'") from error
def decorator(func):
compiled = None
@functools.wraps(func)
def _fn(*args, **kwargs):
if is_compiling() or compile_mode_recommended_to_none is None:
return func(*args, **kwargs)
nonlocal compiled
if compiled is None:
compiled = torch.compile(fullgraph=True, dynamic=dynamic, mode=compile_mode_recommended_to_none)(func)
return compiled(*args, **kwargs)
return _fn
def decorator_knowngood(func: Callable, fullgraph: bool = True):
compiled = None
@functools.wraps(func)
def _fn(*args, **kwargs):
if is_compiling() or compile_mode is None:
return func(*args, **kwargs)
nonlocal compiled
if compiled is None:
compiled = torch.compile(fullgraph=fullgraph, dynamic=dynamic, mode=compile_mode)(func)
return compiled(*args, **kwargs)
return _fn
def decorator_no_fullgraph(func: Callable):
return decorator_knowngood(func, fullgraph=False)
einsum_base = string.ascii_lowercase
no_compile_qr = torch.compiler.disable(torch.linalg.qr)
no_compile_eigh = torch.compiler.disable(torch.linalg.eigh)
no_compile_solve = torch.compiler.disable(torch.linalg.solve)
no_compile_svd = torch.compiler.disable(torch.linalg.svd)
no_compile_lobpcg = torch.compiler.disable(torch.lobpcg)
no_compile_solve_triangular = torch.compiler.disable(torch.linalg.solve_triangular)
@decorator_knowngood
def compiled_einsum(expr, *args):
"""
this is necessary to avoid the slowdown introduced by uncompiled einsum
uncompiled einsum is twice as slow if we add three 1-sized dimensions
for more, see https://gist.github.com/ClashLuke/a9530f1b9ba4e525369e2dba48528957
"""
return torch.einsum(expr, *args)
@decorator_knowngood
def _compilable_schedule_free_(
p: List[Tensor],
z: List[Tensor],
ckp1: Tensor,
update: List[Tensor],
lr: Tensor,
beta1: Tensor,
decay: float,
grad: List[Tensor],
caution,
):
for op, oz, u_, g_ in zip(p, z, update, grad):
u_ = u_.view_as(op)
p_, z_, u_ = map(promote, (op, oz, u_))
if decay != 0:
u_ = u_ + p_ * decay
if caution:
u_ = _compilable_cautioning(u_, g_)
p_ = p_.lerp(z_, ckp1)
p_ = p_ + u_ * (lr * (beta1 * (1 - ckp1)) - lr)
z_ = z_ + u_ * -lr
copy_stochastic_(op, p_)
copy_stochastic_(oz, z_)
def schedule_free_(
lr: float,
weight_lr_power: float,
weight_sum: float,
beta1: float,
parameters: List[Tensor],
z: List[Tensor],
update: List[Tensor],
grad: List[Tensor],
caution: bool = False,
r: float = 0.0,
step: int = 0,
decay: float = 0.0,
):
weight = abs(lr) ** weight_lr_power * max(step, 1) ** r
weight_sum = weight_sum + weight
try:
ckp1 = weight / weight_sum
except ZeroDivisionError:
ckp1 = 0
update, parameters, z, grad = list_guard(update, parameters, z, grad)
lr, ckp1, beta1 = scalar_guard(lr, ckp1, beta1, grad[0])
_compilable_schedule_free_(parameters, z, ckp1, update, lr, beta1, decay, grad, caution)
return weight_sum
@decorator_knowngood
def _compilable_msam(
lr: Tensor,
beta1: Tensor,
param: List[Tensor],
z: List[Tensor],
update: List[Tensor],
grad: List[Tensor],
exp_avg: List[Tensor],
caution: bool,
decay: Tensor,
sam_step_size: Tensor,
):
exp_avg32 = _lerp(exp_avg, update, beta1)
for u_, g_, z_, p_ in zip(exp_avg32, grad, z, param):
u_ = u_.view_as(z_)
z32_ = promote(z_)
if caution:
u_ = _compilable_cautioning(promote(g_), u_)
z32_ = z32_ * (1 - decay * lr) + u_ * -lr
copy_stochastic_(z_, z32_)
copy_stochastic_(p_, z32_ + u_ / u_.norm().clamp(min=1e-8) * -sam_step_size)
def msam_(
lr: float,
beta1: float,
param: List[Tensor],
z: List[Tensor],
update: List[Tensor],
grad: List[Tensor],
exp_avg: List[Tensor],
caution: bool,
weight_decay: float,
sam_step_size: float,
):
param, z, update, grad, exp_avg = list_guard(param, z, update, grad, exp_avg)
lr, beta1, weight_decay, sam_step_size = scalar_guard(lr, beta1, weight_decay, sam_step_size, exp_avg[0])
_compilable_msam(lr, beta1, param, z, update, grad, exp_avg, caution, weight_decay, sam_step_size)
def append_or_extend(base, new):
if isinstance(new, list):
base.extend(new)
else:
base.append(new)
def dim_merger(grad, max_precond_dim, split: bool = False):
"""
Merges dimensions of the gradient tensor till the product of the dimensions is less than or equal to max_precond_dim.
we don't want to merge fan-in into fan-out,
but we want to merge conv kernels into fan-in or at least merge the kernel
so, [128, 64, 3, 3] should result in [128, 576] or [128, 64, 9] instead of [73728] or [8192, 3, 3] the baseline
would've done
By @francois-rozet (commit: 68cde41eaf7e73b4c46eacb6a944865dcc081f1d), re-commited due to faulty merge
"""
new_shape = []
cum_size = 1
for s in grad.shape[1:][::-1]:
temp_size = cum_size * s
if temp_size > max_precond_dim:
if cum_size > 1:
new_shape.append(cum_size)
cum_size = s
else:
new_shape.append(s)
cum_size = 1
else:
cum_size = temp_size
if cum_size > 1:
new_shape.append(cum_size)
new_shape = [grad.shape[0], *new_shape[::-1]]
new_grad = grad.reshape(new_shape)
if not split:
return new_grad.to(memory_format=torch.contiguous_format).contiguous()
grads = [new_grad]
for i, sh in reversed(list(enumerate(new_shape[:]))):
if sh == 1:
grads = [g.squeeze(dim=i) for g in grads]
continue
if sh <= max_precond_dim:
continue
grads = [a for g in grads for a in g.split(max_precond_dim, dim=i)]
if len(grads) == 1:
return new_grad.to(memory_format=torch.contiguous_format).contiguous()
new_grads = []
for g in grads:
append_or_extend(new_grads, dim_merger(g, max_precond_dim, split))
return new_grads
def linear_warmup_scheduler(
step: int, alpha_end: float, alpha_start: float = 0.0, warmup: Optional[int] = None
) -> float:
if warmup is None or warmup <= 0:
return alpha_end
if step < warmup:
a = step / float(warmup)
return (1.0 - a) * alpha_start + a * alpha_end
return alpha_end
def linear_hl_warmup_scheduler(
step: int, beta_end: float, beta_start: float, warmup: Optional[int] = None, eps: float = 1e-8
) -> float:
if warmup is None or warmup <= 0:
return beta_end
def half_life(beta: float) -> float:
return math.log(0.5) / math.log(beta + eps) - 1
def inv_half_life(t: float) -> float:
return math.pow(0.5, 1.0 / (t + 1.0))
if step < warmup:
a = step / float(warmup)
target = (1.0 - a) * half_life(beta_start) + a * half_life(beta_end)
beta = inv_half_life(target)
return min(max(beta, 0.0), 1.0 - eps)
return beta_end
def _compute_ademamix_hparams(
betas: tuple[float, float, float],
step: int,
alpha: float,
beta3_warmup: Optional[int],
alpha_warmup: Optional[int],
) -> tuple[float, float, float, float]:
if len(betas) != 3:
raise ValueError("AdEMAMix expects betas=(beta1, beta2, beta3).")
beta1, beta2, beta3_final = betas
step = int(step)
alpha_eff = linear_warmup_scheduler(step, alpha_end=alpha, alpha_start=0.0, warmup=alpha_warmup)
beta3_eff = linear_hl_warmup_scheduler(step, beta_end=beta3_final, beta_start=beta1, warmup=beta3_warmup)
return beta1, beta2, beta3_eff, alpha_eff
def beta_debias(beta, step):
return 1 - (1 - beta) / (1 - beta**step)
def _nadam_moments(beta1: Tensor, step: Tensor, momentum_decay: float) -> tuple[Tensor, Tensor]:
md = torch.as_tensor(momentum_decay, dtype=beta1.dtype, device=beta1.device)
base = torch.tensor(0.96, dtype=beta1.dtype, device=beta1.device)
step_f = step.to(beta1.dtype)
mu = beta1 * (1 - 0.5 * torch.pow(base, step_f * md))
mu_next = beta1 * (1 - 0.5 * torch.pow(base, (step_f + 1) * md))
return mu, mu_next
def _nadam_prepare_weight_decay(
update: List[Tensor],
param: List[Tensor],
grad: List[Tensor] | None,
weight_decay: float,
decoupled: bool,
) -> float:
if weight_decay == 0:
return 0.0
if decoupled:
return weight_decay
if grad is not None:
for u_, g_, p_ in zip(update, grad, param):
u_.add_(p_, alpha=weight_decay)
g_.add_(p_, alpha=weight_decay)
else:
for u_, p_ in zip(update, param):
u_.add_(p_, alpha=weight_decay)
return 0.0
def _nadam_finish_weight_decay(
update: List[Tensor],
param: List[Tensor],
weight_decay: float,
decoupled: bool,
) -> List[Tensor]:
if weight_decay != 0 and not decoupled:
update = [u_ - p_ * weight_decay for u_, p_ in zip(update, param)]
return update
def _nadam_compute_update(
exp_avg: List[Tensor],
exp_avg_sq: List[Tensor],
mu_product: List[Tensor],
update: List[Tensor],
beta1: Tensor,
beta2: Tensor,
step: Tensor,
eps: Tensor,
mu: Tensor,
mu_next: Tensor,
) -> List[Tensor]:
exp_avg32 = _lerp(exp_avg, update, beta1)
beta2_corr = beta_debias(beta2, step)
denom = _compilable_exp_avg_sq_(exp_avg_sq, update, beta2_corr, eps, [None])
for mp_ in mu_product:
mp_.mul_(mu)
mu_product32 = promote(mu_product)
mu_t, mu_next_t = scalar_guard(mu, mu_next, mu_product32[0])
one = mu_t.new_ones(())
grad_scale = one - mu_t
out = []
for u_, e_, d_, mp_ in zip(update, exp_avg32, denom, mu_product32):
gw = grad_scale / (one - mp_)
ew = mu_next_t / (one - mp_ * mu_next_t)
out.append(u_ / d_ * gw + e_ / d_ * ew)
return out
def eps_sqrt(item, eps):
return item.sqrt().clamp(min=eps)
@decorator_knowngood
def _compilable_exp_avg_sq_(
state: List[Tensor],
grad: List[Tensor],
beta2: Tensor,
eps: Tensor,
out: None | List[None | Tensor],
):
g32 = promote(grad)
s32 = _lerp(state, [g_ * g_ for g_ in g32], beta2)
denom = [eps_sqrt(d, eps) for d in s32]
if out is None or out[0] is None:
return denom
copy_stochastic_list_(out, denom)
return out
def exp_avg_sq_(state, grad, beta2, eps, out=None):
state, grad, out = list_guard(state, grad, out)
beta2, eps = scalar_guard(beta2, eps, state[0])
return _compilable_exp_avg_sq_(state, grad, beta2, eps, out)
@decorator_knowngood
def _compilable_scale_by_exp_avg_sq_(state: List[Tensor], grad: List[Tensor], beta2: Tensor, eps: Tensor):
g32 = promote(grad)
denom = _compilable_exp_avg_sq_(state, g32, beta2, eps, [None])
copy_stochastic_list_(grad, [g_ / d_ for g_, d_ in zip(g32, denom)])
def scale_by_exp_avg_sq_(exp_avg_sq, grad, beta2, eps):
grad, exp_avg_sq = list_guard(grad, exp_avg_sq)
beta2, eps = scalar_guard(beta2, eps, grad[0])
_compilable_scale_by_exp_avg_sq_(exp_avg_sq, grad, beta2, eps)
return grad
@decorator_knowngood
def _compilable_exp_avg_(state, grad, beta):
lerped = _lerp(state, grad, beta)
copy_stochastic_list_(grad, lerped)
def scale_by_exp_avg_(state, grad, beta):
state, grad = list_guard(state, grad)
beta = scalar_guard(beta, state[0])
_compilable_exp_avg_(state, grad, beta)
return grad
@decorator_knowngood
def _compilable_agc_(parameters: List[Tensor], gradients: List[Tensor], clip_val: float, minimum: float, eps: float):
for param, grad in zip(parameters, gradients):
p32, g32 = promote(param), promote(grad)
scale = min(max(p32.norm(), minimum) / max(g32.norm(), eps) * clip_val, 1)
copy_stochastic_(grad, g32 * scale)
def adaptive_gradient_clipping_(
parameters: List[Tensor], gradients: List[Tensor], clip_val: float, minimum: float = 1e-3, eps: float = 1e-8
):
if clip_val <= 0:
return gradients
parameters, gradients = list_guard(parameters, gradients)
clip_val = scalar_guard(clip_val, parameters[0])
_compilable_agc_(parameters, gradients, clip_val, minimum, eps)
return gradients
def is_compiling():
try:
return torch.compiler.is_compiling()
except (TorchDynamoException, AttributeError):
return False
def set_(dst: Tensor, src: Tensor):
dst.copy_(src)
def capture_param_shapes(params):
"""Capture param shapes before FSDP/sharding. Pass as ``orig_shapes=`` to any optimizer."""
if hasattr(params, "parameters"):
params = params.parameters()
return {id(p): tuple(p.shape) for p in params}
def clean():
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
def _ignore_warning(msg):
warnings.filterwarnings("ignore", f".*{re.escape(msg)}.*")
def set_torch(benchmark_limit: int = 32, einsum_strategy: str = "auto-hq"):
import opt_einsum as _opt_einsum
cudnn.benchmark = True
cudnn.deterministic = False
cudnn.benchmark_limit = benchmark_limit
torch.use_deterministic_algorithms(False)
torch.set_float32_matmul_precision("high") # highest: FP32, high: TF32, medium: bf16
opt_einsum.set_flags(True)
if einsum_strategy == "heavyball":
opt_einsum.strategy = "auto-hq"
choices = _opt_einsum.paths._AUTO_HQ_CHOICES
for max_val, fn in ((20, _opt_einsum.paths.dynamic_programming), (64, 512), (128, 256)):
if isinstance(fn, int):
fn = functools.partial(_opt_einsum.path_random.random_greedy, max_repeats=fn)
for i in range(max(choices.keys()), max_val):
if i not in choices:
choices[i] = fn
else:
opt_einsum.strategy = einsum_strategy
# Torch calls these for 2nd-order optimization in HeavyBall, but they are explicitly handled.
_ignore_warning(
"Using backward() with create_graph=True will create a reference cycle between the parameter and its gradient which can cause a memory leak"
)
_ignore_warning(
"We recommend using autograd.grad when creating the graph to avoid this. If you have to use this function, make sure to reset the .grad fields of your parameters to None after use to break the cycle and avoid the leak"
)
_ignore_warning(
"The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the .grad field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead."
)
@decorator_knowngood
def zeropower_via_newtonschulz5(G, steps=5, eps=1e-7):
assert (
G.ndim >= 2
) # batched Muon implementation by @scottjmaddox, and put into practice in the record by @YouJiacheng
assert steps == 5
G = G.clone()
x = G if G.dtype == torch.float64 else stochastic_round_(G)
if G.size(-2) > G.size(-1):
x = x.mT
# X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
stochastic_divide_with_eps_(x, G.norm(dim=(-2, -1)), eps) # ensure top singular value <= 1
# Perform the NS iterations
for a, b, c in [
(4.0848, -6.8946, 2.9270),
(3.9505, -6.3029, 2.6377),
(3.7418, -5.5913, 2.3037),
(2.8769, -3.1427, 1.2046),
(2.8366, -3.0525, 1.2012),
]:
s = x @ x.mT
y = c * s
y.diagonal(dim1=-2, dim2=-1).add_(b)
y = y @ s
y.diagonal(dim1=-2, dim2=-1).add_(a)
x = y @ x
if G.size(-2) > G.size(-1):
x = x.mT
return x.to(G.dtype)
###### START
# Based on https://arxiv.org/pdf/2505.16932v3
# and https://github.com/NoahAmsel/PolarExpress/blob/5454910920ca8c65afda28820cdf9e49b9436ed0/polar_express.py#L69-L82
# and https://github.com/thinking-machines-lab/manifolds/blob/89dcae50f01af59f1e0570289474da3a2ecaa60b/src/msign.py#L47
#
# under the MIT License
# Coefficients are from https://arxiv.org/pdf/2505.16932v3
ABC_LIST: list[tuple[float, float, float]] = [
(8.28721201814563, -23.595886519098837, 17.300387312530933),
(4.107059111542203, -2.9478499167379106, 0.5448431082926601),
(3.9486908534822946, -2.908902115962949, 0.5518191394370137),
(3.3184196573706015, -2.488488024314874, 0.51004894012372),
(2.300652019954817, -1.6689039845747493, 0.4188073119525673),
(1.891301407787398, -1.2679958271945868, 0.37680408948524835),
(1.8750014808534479, -1.2500016453999487, 0.3750001645474248),
(1.875, -1.25, 0.375),
]
# safety factor for numerical stability (but exclude last polynomial)
ABC_LIST_STABLE: list[tuple[float, float, float]] = [
(a / 1.01, b / 1.01**3, c / 1.01**5) for (a, b, c) in ABC_LIST[:-1]
] + [ABC_LIST[-1]]
def msign(G: torch.Tensor, steps: int = 10, eps: float = 1e-7) -> torch.Tensor:
"""
Polar Express algorithm for the matrix sign function:
https://arxiv.org/abs/2505.16932
"""
assert G.ndim >= 2
should_transpose: bool = G.size(-2) > G.size(-1)
x = G if G.dtype == torch.float64 else stochastic_round_(G)
if should_transpose:
x = x.mT
# x = x / (x.norm(dim=(-2, -1), keepdim=True) * 1.01 + eps)
stochastic_divide_with_eps_(x, x.norm(dim=(-2, -1)) * 1.01, eps)
for step in range(steps):
a, b, c = ABC_LIST_STABLE[step] if step < len(ABC_LIST_STABLE) else ABC_LIST_STABLE[-1]
s = x @ x.mT
# goal is to compute x = a x + b S x + c S^2 x
# we can break this up into: x = (a I + (b I + c S) S) x
y = c * s
y.diagonal(dim1=-2, dim2=-1).add_(b)
y = y @ s
y.diagonal(dim1=-2, dim2=-1).add_(a)
x = y @ x
if should_transpose:
x = x.mT
return x.to(G.dtype)
###### END
@decorator_knowngood
def legacy_zeropower_via_newtonschulz5(G, steps=5, eps=1e-7):
assert len(G.shape) == 2
a, b, c = (3.4445, -4.7750, 2.0315)
G = G.clone()
x = G if G.dtype == torch.float64 else stochastic_round_(G)
# X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
stochastic_divide_with_eps_(x, G.norm(dim=(-2, -1)), eps) # ensure top singular value <= 1
if G.size(0) > G.size(1):
x = x.T
for _ in range(steps):
s = x @ x.mT
y = c * s
y.diagonal(dim1=-2, dim2=-1).add_(b)
y = y @ s
y.diagonal(dim1=-2, dim2=-1).add_(a)
x = y @ x
if G.size(0) > G.size(1):
x = x.T
return x.to(G.dtype)
def _scion_bias_rms_direction(x: Tensor, eps: float = 1e-8) -> Tensor:
if x.ndim == 0:
return x / x.abs().clamp(min=eps)
rms = x.square().mean(dim=0, keepdim=True).sqrt()
stochastic_divide_(x, rms, eps=eps)
return x
def _scion_spectral_direction(x: Tensor) -> Tensor:
flat = x.reshape(x.shape[0], -1)
flat = inplace_orthogonal_(flat)
normalized = flat.reshape_as(x)
in_dim = max(flat.shape[1], 1)
scale = math.sqrt(x.shape[0] / in_dim)
return normalized * scale
def _scion_spectral_conv_direction(x: Tensor) -> Tensor:
flat = x.reshape(x.shape[0], -1)
flat = inplace_orthogonal_(flat)
normalized = flat.reshape_as(x)
out_channels, in_channels = x.shape[:2]
spatial = math.prod(x.shape[2:]) if x.ndim > 2 else 1
scale = math.sqrt(out_channels / max(in_channels, 1)) / max(spatial, 1)
return normalized * scale
@decorator_knowngood
def _compilable_scion_lmo_(update: List[Tensor] | Tensor, scale: Tensor):
for tensor in update:
promoted = promote(tensor)
if promoted.ndim in (3, 4):
direction = _scion_spectral_conv_direction(promoted)
elif promoted.ndim == 2:
direction = _scion_spectral_direction(promoted)
else:
direction = _scion_bias_rms_direction(promoted)
scale_value = scale.to(dtype=direction.dtype, device=direction.device)
direction = direction * scale_value
copy_stochastic_(tensor, direction)
def scion_auto_lmo_(update: List[Tensor] | Tensor, scale: Union[float, Tensor]):
update = list_guard(update)
if not update:
return update
scale_tensor = scalar_guard(scale, update[0])
_compilable_scion_lmo_(update, scale_tensor)
return update
def scion_auto_init_param_(param: Tensor, scale: Union[float, Tensor], seed: int = 0):
scale_tensor = scalar_guard(scale, param)
promoted = promote(param)
gen = torch.Generator(device="cpu")
gen.manual_seed(seed)
if param.ndim >= 2:
init_fp64 = promoted.clone().cpu().double()
for idx in itertools.product(*(range(s) for s in init_fp64.shape[2:])):
torch.nn.init.orthogonal_(init_fp64[(slice(None), slice(None), *idx)], generator=gen)
fan_out, fan_in = init_fp64.shape[:2]
spatial = math.prod(init_fp64.shape[2:])
init_fp64.mul_(math.sqrt(fan_out / max(fan_in, 1)) / max(spatial, 1))
init = init_fp64.to(dtype=promoted.dtype, device=promoted.device)
else:
init = promoted.clone()
torch.nn.init.zeros_(init)
init.mul_(scale_tensor.to(dtype=init.dtype, device=init.device))
copy_stochastic_(param, init.to(dtype=param.dtype, device=param.device))
@decorator_knowngood
def _compilable_heavyball_momentum_(state, grad, beta):
for s_, g_ in zip(state, grad):
v = promote(s_) * beta + promote(g_)
copy_stochastic_(s_, v)
copy_stochastic_(g_, v)
@decorator_knowngood
def _compilable_nesterov_momentum_(state, grad, beta):
for s_, g_ in zip(state, grad):
v = promote(s_) * beta + promote(g_)
copy_stochastic_(s_, v)
copy_stochastic_(g_, promote(g_) + v * beta)
def heavyball_momentum(state, grad, beta):
state, grad = list_guard(state, grad)
beta = scalar_guard(beta, state[0])
_compilable_heavyball_momentum_(state, grad, beta)
return grad
def nesterov_momentum(state, grad, beta):
state, grad = list_guard(state, grad)
beta = scalar_guard(beta, state[0])
_compilable_nesterov_momentum_(state, grad, beta)
return grad
@decorator_knowngood
def _compilable_nesterov_ema_(state, grad, beta):
ema32 = _lerp(state, grad, beta)
stochastic_add_(grad, ema32, 1)
def nesterov_ema(state, grad, beta):
state, grad = list_guard(state, grad)
beta = scalar_guard(beta, state[0])
_compilable_nesterov_ema_(state, grad, beta)
return grad
@decorator_knowngood
def _compilable_grafting(magnitude, direction):
return direction * (magnitude.norm() / direction.norm().clamp(min=1e-6))
@decorator_no_fullgraph
def _compilable_orthogonal_(x: Tensor, mode: str | ZerothPowerMode, out: Tensor | None, scale_mode: str):
if not isinstance(mode, ZerothPowerMode):
mode = ZerothPowerMode(mode)
if not isinstance(scale_mode, OrthoScaleMode):
scale_mode = OrthoScaleMode(scale_mode)
if mode == ZerothPowerMode.newtonschulz or x.shape[0] != x.shape[1]:
y = zeropower_via_newtonschulz5(x, 5)
elif mode == ZerothPowerMode.thinky_polar_express:
y = msign(x, 10)
elif mode == ZerothPowerMode.legacy_newtonschulz:
y = legacy_zeropower_via_newtonschulz5(x, 5)
elif mode == ZerothPowerMode.qr:
y = no_compile_qr(promote(x)).Q
elif mode == ZerothPowerMode.svd:
u, _s, vt = no_compile_svd(promote(x))
y = u @ vt
elif mode == ZerothPowerMode.legacy_svd:
u, _s, vt = no_compile_svd(promote(x))
y = u @ vt.T
else:
raise NotImplementedError(f"Unknown zeroth_power_mode: {mode}")
if scale_mode == OrthoScaleMode.none:
pass
elif scale_mode == OrthoScaleMode.scale:
y *= max(1, x.size(-2) / x.size(-1)) ** 0.5
elif scale_mode == OrthoScaleMode.graft:
y = _compilable_grafting(x, y)
else:
raise NotImplementedError(f"Unknown scale_mode: {scale_mode}")
if out is None:
return y
set_(out, y)
def inplace_orthogonal_(x: Tensor, mode: str | None = None, out: Tensor | None = None, scale_mode: str = "none"):
return _compilable_orthogonal_(x, mode or zeroth_power_mode, out, scale_mode)
@decorator_knowngood
def _compilable_scatter_set(target, source, index):
target[:] = source.contiguous()[index].reshape_as(target)
@decorator_no_fullgraph
def get_orthogonal_matrix_QR(GG: List[Tensor], Q: List[Tensor], *exp_avg: Tensor):
"""
Computes the eigenbases of the preconditioner using one round of power iteration
followed by torch.linalg.qr decomposition, and updates exp_avg in-place from old to new eigenspace.
:param GG: List of accumulated gradient outer products.
:param Q: List of current eigenbases (updated in-place to Q_new).
:param exp_avg: Exponential moving average in the old eigenspace (updated in-place if provided).
"""
if not exp_avg:
return
ref = exp_avg[0]
if ref.dim() == 0: # preconditioning doesn't make sense here
Q.clear()
return
if isinstance(Q, list) and not Q:
return
if ref is not None and ref.dim() != len(Q):
raise ValueError(f"ref dim {ref.dim()} does not match Q length {len(Q)}")
new_qs = []
for m, q in zip(GG, Q):
if m is None:
new_qs.append(None)
continue
m = promote(m.data)
q_old = promote(q.data)
tmp = m @ q_old
est_eig = compiled_einsum("ij,ij->j", q_old, tmp)
sort_idx = torch.argsort(est_eig, descending=True)
tmp[:, sort_idx] = inplace_orthogonal_(tmp[:, sort_idx], precise_zeroth_power_mode)
new_qs.append(tmp)
if ref is None:
for q, q_new in zip(Q, new_qs):
copy_stochastic_(q, q_new)
return
assert ref.ndim < 13, "ref.ndim must be less than 13"
in_str = einsum_base[: ref.dim()]
out_str = einsum_base[ref.dim() : 2 * ref.dim()]
from_shampoo = ",".join([o + i for m, i, o in zip(Q, in_str, in_str.upper()) if m is not None])
if not from_shampoo:
return
to_shampoo = ",".join([i + o for m, i, o in zip(new_qs, in_str.upper(), out_str) if m is not None])
out_str = "".join([o if o in to_shampoo else i for i, o in zip(in_str, out_str)])
subscripts = f"{in_str},{from_shampoo},{to_shampoo}->{out_str}"
for r in exp_avg:
new = compiled_einsum(
subscripts, promote(r), *[promote(q) for q in Q if q is not None], *[q for q in new_qs if q is not None]
)
copy_stochastic_(r, new)
for q, q_new in zip(Q, new_qs):
if q is not None:
copy_stochastic_(q, q_new)
def _transform_projected_state(old_qs: List[Optional[Tensor]], new_qs: List[Optional[Tensor]], *states: Tensor):
if not states:
return
ref = states[0]
if ref is None or ref.dim() == 0:
return
assert ref.ndim < 13, "ref.ndim must be less than 13"
in_str = einsum_base[: ref.dim()]
out_str = einsum_base[ref.dim() : 2 * ref.dim()]
old_basis = ",".join([o + i for q, i, o in zip(old_qs, in_str, in_str.upper()) if q is not None])
if not old_basis:
return
new_basis = ",".join([i + o for q, i, o in zip(new_qs, in_str.upper(), out_str) if q is not None])
out_str = "".join([o if o in new_basis else i for i, o in zip(in_str, out_str)])
subscripts = f"{in_str},{old_basis},{new_basis}->{out_str}"
old_basis = [promote(q) for q in old_qs if q is not None]
new_basis = [promote(q) for q in new_qs if q is not None]
for state in states:
new = compiled_einsum(subscripts, promote(state), *old_basis, *new_basis)
copy_stochastic_(state, new)
@decorator_no_fullgraph
def init_psgd_eigenbasis(Q: List[Tensor]):
out = []
for q in Q:
if q.ndim < 2:
out.append(None)
continue
q32 = promote(q)
out.append(_stable_symmetric_basis(q32.mT @ q32, out_device=q.device, out_dtype=q.dtype))
return out
@decorator_no_fullgraph
def get_psgd_eigenbasis(Q: List[Tensor], prev: List[Optional[Tensor]]):
out = []
for q, old_basis in zip(Q, prev):
if q.ndim < 2:
out.append(None)
continue
if old_basis is None:
raise ValueError(
"get_psgd_eigenbasis requires a previous basis for matrix blocks; use init_psgd_eigenbasis"
)
q32 = promote(q)
old_basis32 = promote(old_basis)
Y = q32.mT @ (q32 @ old_basis32)
basis_raw = no_compile_qr(Y, mode="reduced").Q.to(dtype=q.dtype)
projected = q32 @ promote(basis_raw)
sort_idx = torch.argsort(compiled_einsum("ij,ij->j", projected, projected), descending=True)
basis_raw = basis_raw.index_select(1, sort_idx)
signs = compiled_einsum("ij,ij->j", old_basis32, promote(basis_raw))
signs = torch.where(signs < 0, -torch.ones_like(signs), torch.ones_like(signs)).to(dtype=basis_raw.dtype)
basis = basis_raw * signs.view(1, -1)
out.append(basis)
return out
@decorator_no_fullgraph
def update_psgd_eigenbasis(Q: List[Tensor], Q_basis: List[Tensor], *states: Tensor):
new_basis = get_psgd_eigenbasis(Q, Q_basis)
_transform_projected_state(Q_basis, new_basis, *states)
for i, (old_basis, new_basis_i) in enumerate(zip(Q_basis, new_basis)):
if old_basis is None: # happens only if ndim < 2
continue
copy_stochastic_(old_basis, new_basis_i)
def _stable_symmetric_basis(
m: Tensor,
max_eps: float = 1e-3,
min_eps: float = 1e-30,
*,
out_device=None,
out_dtype=None,
):
out_device = m.device if out_device is None else out_device
out_dtype = m.dtype if out_dtype is None else out_dtype
m = promote(m.data)
eps = min_eps
while True:
try:
eye = torch.eye(m.shape[0], device=m.device, dtype=m.dtype)
_eigval, eigvec = no_compile_eigh(m + eps * eye)
return torch.flip(eigvec, [1]).to(device=out_device, dtype=out_dtype)
except torch.OutOfMemoryError:
if m.device.type == "cpu":
raise
if torch.cuda.is_available():