zhangfz commited on
Commit
f2cf99e
·
1 Parent(s): 0c47ad8
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/avg_loss_log_vs_steps.png +3 -0
  2. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/avg_loss_vs_steps.png +3 -0
  3. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_42/config.json +41 -0
  4. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_42/training_log.txt +0 -0
  5. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_43/config.json +41 -0
  6. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_43/training_log.txt +0 -0
  7. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_44/config.json +41 -0
  8. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_44/training_log.txt +0 -0
  9. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_42/config.json +41 -0
  10. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_42/training_log.txt +1932 -0
  11. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_43/config.json +41 -0
  12. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_43/training_log.txt +0 -0
  13. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_44/config.json +41 -0
  14. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_44/training_log.txt +0 -0
  15. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_42/config.json +41 -0
  16. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_42/training_log.txt +0 -0
  17. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_43/config.json +41 -0
  18. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_43/training_log.txt +0 -0
  19. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_44/config.json +41 -0
  20. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_44/training_log.txt +0 -0
  21. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_42/config.json +41 -0
  22. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_42/training_log.txt +0 -0
  23. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_43/config.json +41 -0
  24. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_43/training_log.txt +0 -0
  25. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_44/config.json +41 -0
  26. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_44/training_log.txt +0 -0
  27. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_42/config.json +41 -0
  28. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_42/training_log.txt +0 -0
  29. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_43/config.json +41 -0
  30. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_43/training_log.txt +0 -0
  31. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_44/config.json +41 -0
  32. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_44/training_log.txt +0 -0
  33. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_42/config.json +41 -0
  34. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_42/training_log.txt +1819 -0
  35. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_43/config.json +41 -0
  36. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_43/training_log.txt +0 -0
  37. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_44/config.json +41 -0
  38. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_44/training_log.txt +0 -0
  39. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_42/config.json +41 -0
  40. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_42/training_log.txt +1819 -0
  41. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_43/config.json +41 -0
  42. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_43/training_log.txt +0 -0
  43. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_44/config.json +41 -0
  44. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_44/training_log.txt +1819 -0
  45. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_42/config.json +41 -0
  46. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_42/training_log.txt +0 -0
  47. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_43/config.json +41 -0
  48. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_43/training_log.txt +0 -0
  49. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_44/config.json +41 -0
  50. logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_44/training_log.txt +0 -0
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/avg_loss_log_vs_steps.png ADDED

Git LFS Details

  • SHA256: 2fd39284ddf247817b63805d0c2269dd053f87c0ae49add580544a66f3298ec1
  • Pointer size: 131 Bytes
  • Size of remote file: 166 kB
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/avg_loss_vs_steps.png ADDED

Git LFS Details

  • SHA256: cd1cdc4eb3a151057c43413d22936469d67d53154f91c504c34d1802b7e7bfa8
  • Pointer size: 131 Bytes
  • Size of remote file: 148 kB
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0001,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "50546d87-1827-453c-b739-8394ec9b4cf5",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_42/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0001,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "5ffd855e-623a-438c-9e89-8ba2b9eb6f4c",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0001,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "159018cc-e918-44bf-b157-117db3870552",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0001_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0002,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "f483da9a-f60a-4caa-8058-ef3f0eccf830",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_42/training_log.txt ADDED
@@ -0,0 +1,1932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reference code for GPT-2 training and inference with Sharpness Analysis.
3
+ Will save the model weights into files, to be read from C as initialization.
4
+
5
+ References:
6
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
7
+ https://github.com/openai/gpt-2/blob/master/src/model.py
8
+ 2) huggingface/transformers PyTorch implementation:
9
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
10
+
11
+ Example launches to only benchmark the speed of bfloat16 compiled GPU training:
12
+ 1 GPU:
13
+ python train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
14
+ you can also turn on flash-attention by appending --flash=1
15
+ 4 GPU:
16
+ torchrun --standalone --nproc_per_node=4 train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
17
+ """
18
+ import sys
19
+ with open(sys.argv[0]) as f:
20
+ code = f.read() # read the code of this file ASAP, for logging
21
+
22
+ import os
23
+ import math
24
+ import glob
25
+ import struct
26
+ import inspect
27
+ from contextlib import nullcontext
28
+ from dataclasses import dataclass
29
+ import random
30
+
31
+ import numpy as np
32
+ import torch
33
+ from torch import Tensor
34
+ import torch.nn as nn
35
+ from torch.nn import functional as F
36
+ import torch._inductor.config as config
37
+ from torch.nn.parallel import DistributedDataParallel as DDP
38
+ from torch.distributed import init_process_group, destroy_process_group
39
+ from torch.distributed.optim import ZeroRedundancyOptimizer
40
+ import torch.distributed as dist
41
+ from torch.amp import autocast
42
+ import copy
43
+ import gc
44
+ import uuid
45
+ import json
46
+ from pathlib import Path
47
+
48
+ # Import Muon optimizer
49
+ import sys
50
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/optimizers")
51
+ from MUON_fix import Muon
52
+
53
+ # Import GPT model
54
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/models")
55
+ import nano_GPT_qkvonorm_pure
56
+ from nano_GPT_qkvonorm_pure import GPT, GPTConfig
57
+
58
+ # Import debug utilities
59
+ # from debug_utils import setup_debugpy
60
+
61
+ # -----------------------------------------------------------------------------
62
+ # Our own simple Distributed Data Loader
63
+
64
+ def _peek_data_shard(filename):
65
+ # only reads the header, returns header data
66
+ with open(filename, "rb") as f:
67
+ # first read the header, which is 256 int32 integers (4 bytes each)
68
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
69
+ if header[0] != 20240520:
70
+ print("ERROR: magic number mismatch in the data .bin file!")
71
+ print("---> HINT: Are you passing in a correct file with --input_bin?")
72
+ print("---> HINT: Dataset encoding changed recently, re-run data prepro or refer again to README")
73
+ print("---> HINT: For example re-run: `python dev/data/tinyshakespeare.py`, then re-try")
74
+ exit(1)
75
+ assert header[1] == 1, "unsupported version"
76
+ ntok = header[2] # number of tokens (claimed)
77
+ return ntok # for now just return the number of tokens
78
+
79
+ def _load_data_shard(filename):
80
+ with open(filename, "rb") as f:
81
+ # first read the header, which is 256 int32 integers (4 bytes each)
82
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
83
+ assert header[0] == 20240520, "magic number mismatch in the data .bin file"
84
+ assert header[1] == 1, "unsupported version"
85
+ ntok = header[2] # number of tokens (claimed)
86
+ # the rest of it are tokens, stored as uint16
87
+ tokens = np.frombuffer(f.read(), dtype=np.uint16)
88
+ assert len(tokens) == ntok, "number of tokens read does not match header?"
89
+ return tokens
90
+
91
+ class DistributedDataLoader:
92
+ def __init__(self, filename_pattern, B, T, process_rank, num_processes,
93
+ shuffle_files=False, random_seed=None):
94
+ self.process_rank = process_rank
95
+ self.num_processes = num_processes
96
+ self.B = B
97
+ self.T = T
98
+ self.shuffle_files = shuffle_files
99
+ self.random_seed = random_seed
100
+ self._rng = random.Random(random_seed) if shuffle_files and random_seed is not None else None
101
+
102
+ # glob files that match the pattern
103
+ self.files = sorted(glob.glob(filename_pattern))
104
+ assert len(self.files) > 0, f"did not find any files that match the pattern {filename_pattern}"
105
+ if self.shuffle_files:
106
+ self._shuffle_files()
107
+
108
+ # load and validate all data shards, count number of tokens in total
109
+ ntok_total = 0
110
+ for fname in self.files:
111
+ shard_ntok = _peek_data_shard(fname)
112
+ assert shard_ntok >= num_processes * B * T + 1
113
+ ntok_total += shard_ntok
114
+ self.ntok_total = ntok_total
115
+ print0(f"DataLoader: total number of tokens: {ntok_total:,} across {len(self.files)} files")
116
+
117
+ # kick things off
118
+ self.current_shard = None
119
+ self.reset()
120
+
121
+ def reset(self):
122
+ # we're being a bit clever here: if we already had shard 0 loaded,
123
+ # then don't do the work to reload it, just reset the pointer
124
+ if self.current_shard != 0:
125
+ self.current_shard = 0
126
+ self.tokens = _load_data_shard(self.files[self.current_shard])
127
+ self.current_position = self.process_rank * self.B * self.T
128
+
129
+ def advance(self): # advance to next data shard
130
+ next_shard = (self.current_shard + 1) % len(self.files)
131
+ if next_shard == 0 and self.shuffle_files:
132
+ self._shuffle_files()
133
+ self.current_shard = next_shard
134
+ self.current_position = self.process_rank * self.B * self.T
135
+ self.tokens = _load_data_shard(self.files[self.current_shard])
136
+
137
+ def next_batch(self):
138
+ B = self.B
139
+ T = self.T
140
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
141
+ buf = torch.tensor(buf.astype(np.int32), dtype=torch.long)
142
+ x = (buf[:-1]).view(B, T) # inputs
143
+ y = (buf[1:]).view(B, T) # targets
144
+ # advance the start pointer in current shard
145
+ self.current_position += B * T * self.num_processes
146
+ # if loading the next batch would be out of bounds advance the shard
147
+ if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
148
+ self.advance()
149
+ return x, y
150
+
151
+ def _shuffle_files(self):
152
+ if self._rng is not None:
153
+ self._rng.shuffle(self.files)
154
+ else:
155
+ random.shuffle(self.files)
156
+
157
+ # -----------------------------------------------------------------------------
158
+ # Python -> C bridge utilities for saving params/grads/activations to .bin files
159
+
160
+ def write_fp32(tensor, file):
161
+ t = tensor.detach().cpu().to(torch.float32)
162
+ b = t.numpy().tobytes()
163
+ file.write(b)
164
+
165
+ def write_bf16(tensor, file):
166
+ t = tensor.detach().cpu().to(torch.bfloat16)
167
+ # numpy doesn't have bf16 datatype so we have to trick it
168
+ t = t.view(torch.int16) # trick: reinterpret as int16
169
+ b = t.numpy().tobytes()
170
+ file.write(b)
171
+
172
+ def write_tensors(model_tensors, L, file, dtype):
173
+ # writes the GPT-2 model's weights to a binary file
174
+ assert dtype in {"float32", "bfloat16"}
175
+ write_fun = write_fp32 if dtype == "float32" else write_bf16
176
+ write_fun(model_tensors["transformer.wte.weight"], file) # (V, C)
177
+ write_fun(model_tensors["transformer.wpe.weight"], file) # (T, C)
178
+ for i in range(L): # (L, C)
179
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.weight"], file)
180
+ for i in range(L): # (L, C)
181
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.bias"], file)
182
+ for i in range(L): # (L, 3C, C)
183
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.weight"], file)
184
+ for i in range(L): # (L, 3C)
185
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.bias"], file)
186
+ for i in range(L): # (L, C, C)
187
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.weight"], file)
188
+ for i in range(L): # (L, C)
189
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.bias"], file)
190
+ for i in range(L): # (L, C)
191
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.weight"], file)
192
+ for i in range(L): # (L, C)
193
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.bias"], file)
194
+ for i in range(L): # (L, 4C, C)
195
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.weight"], file)
196
+ for i in range(L): # (L, 4C)
197
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.bias"], file)
198
+ for i in range(L): # (L, C, 4C)
199
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.weight"], file)
200
+ for i in range(L): # (L, C)
201
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.bias"], file)
202
+ write_fun(model_tensors["transformer.ln_f.weight"], file) # (C, )
203
+ write_fun(model_tensors["transformer.ln_f.bias"], file) # (C, )
204
+
205
+ @torch.no_grad()
206
+ def pad_vocab(tensor, multiple=128, value=0):
207
+ """
208
+ The dimension of the vocab size in GPT-2 is 50,257
209
+ which is unfortunately a very unfriendly number for a lot of
210
+ matrix operations on the GPU. So we pad it to the nearest
211
+ friendlier multiple, e.g. 50,304 if multiple=128 when we
212
+ export the weights into C land. This is a NOOP algorithmically
213
+ and is only done to make the tensor operations more efficient.
214
+ """
215
+ assert tensor.ndim == 2
216
+ V, C = tensor.shape
217
+ assert V == 50257, "just being defensive here"
218
+ # calculate padded vocab size by rounding up to nearest multiple
219
+ Vp = ((V + multiple - 1) // multiple) * multiple
220
+ # pad the tensor
221
+ pad_rows = Vp - V
222
+ padded = tensor if pad_rows == 0 else F.pad(tensor, (0, 0, 0, pad_rows), value=value)
223
+ assert padded.shape == (Vp, C)
224
+ return padded
225
+
226
+ def write_model(model, filename, dtype):
227
+ # everything we need to instantiate the model
228
+ # 1) header is: version int, GPTConfig ints, padding to 1024 bytes
229
+ assert dtype in {"float32", "bfloat16"} # float16 todo maybe later
230
+ version = {
231
+ "float32": 3, # 3: all tensors are fp32, padded vocab
232
+ "bfloat16": 5, # 5: all tensors are bf16, padded vocab
233
+ }[dtype]
234
+ header = torch.zeros(256, dtype=torch.int32)
235
+ header[0] = 20240326 # magic
236
+ header[1] = version # checkpoint version
237
+ header[2] = model.config.block_size
238
+ header[3] = model.config.vocab_size
239
+ header[4] = model.config.n_layer
240
+ header[5] = model.config.n_head
241
+ header[6] = model.config.n_embd
242
+ # 2) the parameters follow the header
243
+ params = {name: param.cpu() for name, param in model.named_parameters()}
244
+ # pad the vocab to a multiple of 128 here at export, for efficiency in C
245
+ wte = params["transformer.wte.weight"] # (V, C)
246
+ wte_padded = pad_vocab(wte) # (Vp, C)
247
+ params["transformer.wte.weight"] = wte_padded # (Vp, C)
248
+ print(f"padded vocab size from {wte.size(0)} to {wte_padded.size(0)}")
249
+ header[7] = wte_padded.size(0) # padded vocab size store in header
250
+ # now write to file
251
+ with open(filename, "wb") as file:
252
+ file.write(header.numpy().tobytes()) # header
253
+ write_tensors(params, model.config.n_layer, file, dtype) # params
254
+ print(f"wrote {filename}")
255
+
256
+ def write_state(model, x, y, logits, loss, filename):
257
+ # the state is used for debugging.
258
+ # it contains information about the input, logits, loss, and the parameter gradients
259
+ # this can be used for checking the computation correctness in C
260
+ header = torch.zeros(256, dtype=torch.int32)
261
+ header[0] = 20240327 # magic
262
+ header[1] = 2 # run state version = 2 (1 -> 2 for padded vocab changes)
263
+ header[2] = x.size(0) # batch size of the batch, B
264
+ header[3] = x.size(1) # temporal extent of the batch, T
265
+ grads = {name: param.grad.cpu() for name, param in model.named_parameters()}
266
+ # pad the vocab grads here as well, to mirror write_model
267
+ wte_grad = grads["transformer.wte.weight"] # (V, C)
268
+ wte_grad_padded = pad_vocab(wte_grad, value=0) # (Vp, C) # TODO later maybe pad with nan?
269
+ grads["transformer.wte.weight"] = wte_grad_padded # (Vp, C)
270
+ print(f"padded vocab size in reference grads from {wte_grad.size(0)} to {wte_grad_padded.size(0)}")
271
+ with open(filename, "wb") as file:
272
+ # header
273
+ file.write(header.numpy().tobytes())
274
+ # input x
275
+ file.write(x.cpu().numpy().astype("int32").tobytes()) # (B, T)
276
+ # targets y
277
+ file.write(y.cpu().numpy().astype("int32").tobytes()) # (B, T)
278
+ # logits (result of the model forward pass)
279
+ write_fp32(logits.cpu(), file)
280
+ # loss (single float, result of the cross entropy loss)
281
+ write_fp32(loss.cpu(), file)
282
+ # gradients
283
+ write_tensors(grads, model.config.n_layer, file, "float32")
284
+ print(f"wrote {filename}")
285
+
286
+ def write_tokenizer(enc, filename):
287
+ n = enc.max_token_value + 1
288
+ header = torch.zeros(256, dtype=torch.int32)
289
+ header[0] = 20240328 # magic
290
+ header[1] = 2 # tokenizer version = 2 (1 -> 2: includes EOT token)
291
+ header[2] = n # number of tokens
292
+ header[3] = enc.eot_token # EOT token
293
+ with open(filename, "wb") as file:
294
+ file.write(header.numpy().tobytes())
295
+ for i in range(n):
296
+ b = enc.decode_bytes([i])
297
+ length = len(b)
298
+ assert length < 256, f"Token length exceeds 255: {length}"
299
+ file.write(struct.pack("<B", length)) # Write the length as a 1-byte unsigned integer
300
+ file.write(b) # Write the actual bytes
301
+ print(f"wrote {filename}")
302
+
303
+ def set_seed(seed):
304
+ random.seed(seed)
305
+ np.random.seed(seed)
306
+ torch.manual_seed(seed)
307
+ if torch.cuda.is_available():
308
+ torch.cuda.manual_seed_all(seed)
309
+ print(f"PRINT: Set seed to {seed}", flush=True) # Print immediately for all ranks
310
+
311
+ # -----------------------------------------------------------------------------
312
+ # Helper functions for norm calculations
313
+
314
+ def calculate_l1_to_linf_norm(matrix):
315
+ if matrix.ndim == 1:
316
+ return torch.sum(torch.abs(matrix))
317
+ elif matrix.ndim == 2:
318
+ # Each row's L1 norm, then take maximum
319
+ row_l1_norms = torch.sum(torch.abs(matrix), dim=1)
320
+ return torch.max(row_l1_norms)
321
+ else:
322
+ # For higher-dimensional tensors, flatten to 2D
323
+ matrix_2d = matrix.view(matrix.shape[0], -1)
324
+ row_l1_norms = torch.sum(torch.abs(matrix_2d), dim=1)
325
+ return torch.max(row_l1_norms)
326
+
327
+ def calculate_spectral_norm(matrix):
328
+ """
329
+ Calculate the spectral norm (largest singular value) of a matrix.
330
+ For vectors, returns the L2 norm.
331
+ """
332
+ # Convert to float32 if needed for linalg operations
333
+ if matrix.dtype in [torch.bfloat16, torch.float16]:
334
+ matrix = matrix.float()
335
+
336
+ if matrix.ndim == 1:
337
+ return torch.norm(matrix, p=2)
338
+ elif matrix.ndim == 2:
339
+ # Use matrix 2-norm (largest singular value)
340
+ return torch.linalg.matrix_norm(matrix, ord=2)
341
+ else:
342
+ # For higher-dimensional tensors, flatten to 2D
343
+ matrix_2d = matrix.view(matrix.shape[0], -1)
344
+ return torch.linalg.matrix_norm(matrix_2d, ord=2)
345
+
346
+ # -----------------------------------------------------------------------------
347
+ # Comprehensive sharpness analysis function
348
+
349
+ def calculate_comprehensive_sharpness(model, model_for_forward, optimizers, step, train_loader, val_loader,
350
+ rank, world_size, device, B, T, ptdtype, grad_accum_steps, last_training_update=None, last_training_gradient=None, last_training_batches=None):
351
+ prev_training_mode = model.training
352
+ model.eval()
353
+
354
+ NUM_LAYERS = model.config.n_layer # Number of transformer blocks
355
+ analysis_results = {}
356
+
357
+ # --- 1. Get the true update direction 'v' ---
358
+ assert last_training_update is not None, \
359
+ f"[Step {step}] BUG: last_training_update is None! Check sharpness timing logic."
360
+
361
+ print0(f"[Enhanced Sharpness @ Step {step}] Using update from previous training step")
362
+ update_direction_v = last_training_update
363
+
364
+
365
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters to θ_t for HVP calculation...")
366
+ with torch.no_grad():
367
+ for p, v in zip(model.parameters(), update_direction_v):
368
+ p.data.sub_(v) # Now parameters are at θ_t
369
+
370
+ # --- 2. Calculate update norms (Frobenius, Max-of-Max, Spectral) ---
371
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating update norms...")
372
+
373
+ total_update_norm_sq = sum(torch.sum(v * v) for v in update_direction_v)
374
+ dist.all_reduce(total_update_norm_sq, op=dist.ReduceOp.AVG)
375
+ analysis_results["total_update_fnorm"] = torch.sqrt(total_update_norm_sq).item()
376
+
377
+ # Calculate TOTAL update Max-of-Max and Spectral norms
378
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating total update Max-of-Max and Spectral norms...")
379
+ try:
380
+ all_updates_flat = torch.cat([v.flatten() for v in update_direction_v if v.numel() > 0])
381
+
382
+ if all_updates_flat.numel() > 0:
383
+ total_l1_linf_norm = torch.sum(torch.abs(all_updates_flat))
384
+ analysis_results["total_l1_linf_norm"] = total_l1_linf_norm.item()
385
+
386
+ total_spectral_norm = torch.norm(all_updates_flat, p=2)
387
+ analysis_results["total_spectral_norm"] = total_spectral_norm.item()
388
+ else:
389
+ analysis_results["total_l1_linf_norm"] = 0.0
390
+ analysis_results["total_spectral_norm"] = 0.0
391
+
392
+ del all_updates_flat
393
+ except Exception as e:
394
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating total norms: {e}")
395
+ analysis_results["total_l1_linf_norm"] = 0.0
396
+ analysis_results["total_spectral_norm"] = 0.0
397
+
398
+ # --- 3. Setup layer parameter groups (adapt to new model structure) ---
399
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up layer parameter groups...")
400
+
401
+ all_param_groups = {}
402
+
403
+
404
+ all_param_groups["embed_lm_head"] = list(model.lm_head.parameters())
405
+
406
+ blocks = model.transformer.h
407
+
408
+ for i, block in enumerate(blocks):
409
+ layer_name = f"layer_{i+1}"
410
+ all_param_groups[layer_name] = list(block.parameters())
411
+
412
+ # Add fine-grained params for selected layers (0, 3, 7, 11)
413
+ selected_layers = [0, 3, 7, 11]
414
+ for layer_idx in selected_layers:
415
+ block = blocks[layer_idx]
416
+ prefix = f"block{layer_idx}"
417
+ # Attention: Q, K, V, O
418
+ all_param_groups[f"{prefix}_q"] = [block.attn.q_w.weight]
419
+ all_param_groups[f"{prefix}_k"] = [block.attn.k_w.weight]
420
+ all_param_groups[f"{prefix}_v"] = [block.attn.v_w.weight]
421
+ all_param_groups[f"{prefix}_o"] = [block.attn.c_proj.weight]
422
+ # MLP: c_fc (win) and c_proj (wout)
423
+ all_param_groups[f"{prefix}_mlp_win"] = [block.mlp.c_fc.weight]
424
+ all_param_groups[f"{prefix}_mlp_wout"] = [block.mlp.c_proj.weight]
425
+
426
+ # --- 4. Calculate layer-wise update norms ---
427
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise update norms...")
428
+
429
+ param_to_idx = {id(p): i for i, p in enumerate(model.parameters())}
430
+
431
+ for group_name, param_group in all_param_groups.items():
432
+ if not param_group:
433
+ continue
434
+
435
+ # Get indices for this group
436
+ indices = [param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx]
437
+ if not indices:
438
+ continue
439
+
440
+ # Calculate Frobenius norm for this group
441
+ group_update_norm_sq = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
442
+ dist.all_reduce(group_update_norm_sq, op=dist.ReduceOp.AVG)
443
+ analysis_results[f"{group_name}_update_fnorm"] = torch.sqrt(group_update_norm_sq).item()
444
+
445
+ # Calculate Max-of-Max and Spectral norms for this group
446
+ group_l1_linf_norms = []
447
+ group_spectral_norms = []
448
+
449
+ for i in indices:
450
+ if i < len(update_direction_v) and update_direction_v[i].numel() > 0:
451
+ try:
452
+ l1_linf_norm = calculate_l1_to_linf_norm(update_direction_v[i])
453
+ group_l1_linf_norms.append(l1_linf_norm.item())
454
+
455
+ spectral_norm = calculate_spectral_norm(update_direction_v[i])
456
+ group_spectral_norms.append(spectral_norm.item())
457
+ except Exception as e:
458
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating norms for group {group_name}, param {i}: {e}")
459
+ group_l1_linf_norms.append(0.0)
460
+ group_spectral_norms.append(0.0)
461
+
462
+ if group_l1_linf_norms:
463
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = max(group_l1_linf_norms)
464
+ else:
465
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = 0.0
466
+
467
+ if group_spectral_norms:
468
+ analysis_results[f"{group_name}_max_spectral_norm"] = max(group_spectral_norms)
469
+ else:
470
+ analysis_results[f"{group_name}_max_spectral_norm"] = 0.0
471
+
472
+ # --- 5. Setup for HVP calculation on TRAIN data ---
473
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up HVP calculation in {ptdtype} on TRAIN data...")
474
+
475
+ original_flash = nano_GPT_qkvonorm_pure.FLASH
476
+ nano_GPT_qkvonorm_pure.FLASH = 0
477
+ print0(f"[Enhanced Sharpness @ Step {step}] Disabled FLASH attention for HVP (was {original_flash})")
478
+
479
+ # Get block parameter indices for cross-layer analysis (need this before loop)
480
+ block_param_indices = set()
481
+ for group_name, param_group in all_param_groups.items():
482
+ if group_name.startswith("layer_"):
483
+ for p in param_group:
484
+ if id(p) in param_to_idx:
485
+ block_param_indices.add(param_to_idx[id(p)])
486
+
487
+ # Initialize accumulators for all quantities we need
488
+ grads_hvp = None
489
+ hvp_v_total = None
490
+ hvp_v_block = None
491
+ hvp_g_accum = None
492
+ layer_hvp_accum = {}
493
+
494
+
495
+ group_names_to_process = [gn for gn, pg in all_param_groups.items()
496
+ if pg and any(id(p) in param_to_idx for p in pg)]
497
+
498
+ if last_training_batches is not None and len(last_training_batches) > 0:
499
+
500
+ batch_iterator = [(x, y) for x, y in last_training_batches]
501
+ n_batches = len(batch_iterator)
502
+ print0(f"[Enhanced Sharpness @ Step {step}] Using {n_batches} microbatches for HVP (out of {grad_accum_steps} training microbatches)")
503
+ restore_loader = False
504
+ else:
505
+ # Fallback: use new batches from train_loader (should rarely happen)
506
+ print0(f"[Enhanced Sharpness @ Step {step}] WARNING: last_training_batches is None/empty, using {grad_accum_steps} new batches (inconsistent)")
507
+ saved_current_shard = train_loader.current_shard
508
+ saved_current_position = train_loader.current_position
509
+ n_batches = grad_accum_steps # Use same number as training for consistency
510
+ batch_iterator = []
511
+ shard_was_changed = False
512
+ for _ in range(n_batches):
513
+ x_hvp, y_hvp = train_loader.next_batch()
514
+ batch_iterator.append((x_hvp, y_hvp))
515
+ shard_was_changed = shard_was_changed or (train_loader.current_shard != saved_current_shard)
516
+ restore_loader = True
517
+
518
+
519
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing HVPs for {n_batches} microbatches")
520
+ for mb_idx, (x_hvp, y_hvp) in enumerate(batch_iterator):
521
+ x_hvp, y_hvp = x_hvp.to(device), y_hvp.to(device)
522
+
523
+
524
+ _, loss_mb = model(x_hvp, y_hvp, return_logits=False)
525
+ grads_mb = torch.autograd.grad(loss_mb, model.parameters(), create_graph=True, allow_unused=True)
526
+
527
+ # Compute H·v (total sharpness)
528
+ v_dot_g_total = sum(torch.sum(g * v) for g, v in zip(grads_mb, update_direction_v) if g is not None)
529
+
530
+ if not isinstance(v_dot_g_total, torch.Tensor):
531
+ v_dot_g_total = torch.tensor(0.0, device=device, requires_grad=True)
532
+ hvp_v_total_mb = torch.autograd.grad(v_dot_g_total, model.parameters(), retain_graph=True, allow_unused=True)
533
+
534
+ # Compute H·v_block (block-only sharpness)
535
+ if block_param_indices:
536
+ v_dot_g_block = sum(torch.sum(grads_mb[i] * update_direction_v[i])
537
+ for i in block_param_indices if grads_mb[i] is not None)
538
+ if not isinstance(v_dot_g_block, torch.Tensor):
539
+ v_dot_g_block = torch.tensor(0.0, device=device, requires_grad=True)
540
+ hvp_v_block_mb = torch.autograd.grad(v_dot_g_block, model.parameters(), retain_graph=True, allow_unused=True)
541
+ else:
542
+
543
+ hvp_v_block_mb = [None] * len(list(model.parameters()))
544
+
545
+
546
+ g_dot_g = sum(torch.sum(g * g) for g in grads_mb if g is not None)
547
+ if not isinstance(g_dot_g, torch.Tensor):
548
+ g_dot_g = torch.tensor(0.0, device=device, requires_grad=True)
549
+
550
+
551
+ hvp_g_mb_raw = torch.autograd.grad(g_dot_g, model.parameters(),
552
+ retain_graph=True, allow_unused=True)
553
+ hvp_g_mb = [h / 2.0 if h is not None else None for h in hvp_g_mb_raw]
554
+
555
+ # Compute per-layer H_kk·v_k (for layer-wise sharpness)
556
+ for group_idx, group_name in enumerate(group_names_to_process):
557
+ param_group = all_param_groups[group_name]
558
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
559
+ if not indices:
560
+ continue
561
+
562
+ is_last_layer = (group_idx == len(group_names_to_process) - 1)
563
+ is_last_microbatch = (mb_idx == n_batches - 1)
564
+ need_retain = not (is_last_layer and is_last_microbatch)
565
+
566
+ try:
567
+ v_dot_g_layer = sum(torch.sum(grads_mb[i] * update_direction_v[i])
568
+ for i in indices if grads_mb[i] is not None)
569
+
570
+ if not isinstance(v_dot_g_layer, torch.Tensor):
571
+ v_dot_g_layer = torch.tensor(0.0, device=device, requires_grad=True)
572
+
573
+ hvp_layer_mb = torch.autograd.grad(v_dot_g_layer, model.parameters(),
574
+ retain_graph=need_retain,
575
+ allow_unused=True)
576
+
577
+ if group_name not in layer_hvp_accum:
578
+ layer_hvp_accum[group_name] = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_layer_mb]
579
+ else:
580
+ layer_hvp_accum[group_name] = [
581
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
582
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
583
+ for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
584
+ ]
585
+
586
+ # Accumulate layer HVP
587
+ # if group_name not in layer_hvp_accum:
588
+ # layer_hvp_accum[group_name] = [h.detach() / n_batches if h is not None else None for h in hvp_layer_mb]
589
+ # else:
590
+ # layer_hvp_accum[group_name] = [
591
+ # (h_acc + h.detach() / n_batches) if (h is not None and h_acc is not None)
592
+ # else (h.detach() / n_batches if h is not None else h_acc)
593
+ # for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
594
+ # ]
595
+ # del hvp_layer_mb, v_dot_g_layer
596
+ # torch.cuda.empty_cache()
597
+ except Exception as e:
598
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing layer HVP for '{group_name}' in microbatch {mb_idx}: {e}")
599
+ if group_name not in layer_hvp_accum:
600
+ layer_hvp_accum[group_name] = None
601
+
602
+ # 6. Accumulate all quantities
603
+ if grads_hvp is None:
604
+ grads_hvp = [(g.detach() / n_batches).cpu() if g is not None else None for g in grads_mb]
605
+ hvp_v_total = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_total_mb]
606
+ hvp_v_block = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_block_mb]
607
+ hvp_g_accum = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_g_mb]
608
+ else:
609
+ grads_hvp = [
610
+ (g_acc + (g.detach() / n_batches).cpu()) if (g is not None and g_acc is not None)
611
+ else ((g.detach() / n_batches).cpu() if g is not None else g_acc)
612
+ for g_acc, g in zip(grads_hvp, grads_mb)
613
+ ]
614
+ hvp_v_total = [
615
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
616
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
617
+ for h_acc, h in zip(hvp_v_total, hvp_v_total_mb)
618
+ ]
619
+ hvp_v_block = [
620
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
621
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
622
+ for h_acc, h in zip(hvp_v_block, hvp_v_block_mb)
623
+ ]
624
+ hvp_g_accum = [
625
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
626
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
627
+ for h_acc, h in zip(hvp_g_accum, hvp_g_mb)
628
+ ]
629
+
630
+
631
+
632
+ if mb_idx % max(1, n_batches // 4) == 0:
633
+ print0(f"[Enhanced Sharpness @ Step {step}] Processed microbatch {mb_idx + 1}/{n_batches}")
634
+
635
+
636
+ if restore_loader:
637
+ train_loader.current_shard = saved_current_shard
638
+ train_loader.current_position = saved_current_position
639
+ if shard_was_changed:
640
+ train_loader.tokens = _load_data_shard(train_loader.files[train_loader.current_shard])
641
+
642
+ print0(f"[Enhanced Sharpness @ Step {step}] Finished computing all HVPs for {n_batches} microbatches")
643
+ grads_hvp = [g.to(device) if g is not None else None for g in grads_hvp]
644
+ hvp_v_total = [h.to(device) if h is not None else None for h in hvp_v_total]
645
+ hvp_v_block = [h.to(device) if h is not None else None for h in hvp_v_block]
646
+ hvp_g_accum = [h.to(device) if h is not None else None for h in hvp_g_accum]
647
+ for group_name in layer_hvp_accum:
648
+ if layer_hvp_accum[group_name] is not None:
649
+ layer_hvp_accum[group_name] = [h.to(device) if h is not None else None for h in layer_hvp_accum[group_name]]
650
+ # --- Calculate TOTAL sharpness ---
651
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating TOTAL sharpness...")
652
+ # hvp_v_total is already computed in the loop above
653
+ vhp_dot_v_total = sum(torch.sum(hvp * v) for hvp, v in zip(hvp_v_total, update_direction_v) if hvp is not None)
654
+ v_norm_sq_total = sum(torch.sum(v * v) for v in update_direction_v)
655
+
656
+ # Ensure they are tensors
657
+ if not isinstance(vhp_dot_v_total, torch.Tensor):
658
+ vhp_dot_v_total = torch.tensor(0.0, device=device)
659
+ if not isinstance(v_norm_sq_total, torch.Tensor):
660
+ v_norm_sq_total = torch.tensor(0.0, device=device)
661
+
662
+ dist.all_reduce(vhp_dot_v_total, op=dist.ReduceOp.AVG)
663
+ dist.all_reduce(v_norm_sq_total, op=dist.ReduceOp.AVG)
664
+
665
+ if v_norm_sq_total.item() > 1e-12:
666
+ analysis_results["total_sharpness"] = (vhp_dot_v_total / v_norm_sq_total).item()
667
+ else:
668
+ analysis_results["total_sharpness"] = 0.0
669
+
670
+
671
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating BLOCK-ONLY total sharpness...")
672
+ # hvp_v_block is already computed in the loop above
673
+ if block_param_indices: # Only compute if there are block parameters
674
+ # Compute v_block^T H v_block (only sum over block indices)
675
+ vhp_dot_v_block = sum(torch.sum(hvp_v_block[i] * update_direction_v[i])
676
+ for i in block_param_indices if hvp_v_block[i] is not None)
677
+
678
+ v_norm_sq_block = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
679
+ for i in block_param_indices)
680
+
681
+ # Ensure they are tensors
682
+ if not isinstance(vhp_dot_v_block, torch.Tensor):
683
+ vhp_dot_v_block = torch.tensor(0.0, device=device)
684
+ if not isinstance(v_norm_sq_block, torch.Tensor):
685
+ v_norm_sq_block = torch.tensor(0.0, device=device)
686
+
687
+ dist.all_reduce(vhp_dot_v_block, op=dist.ReduceOp.AVG)
688
+ dist.all_reduce(v_norm_sq_block, op=dist.ReduceOp.AVG)
689
+
690
+ if v_norm_sq_block.item() > 1e-12:
691
+ analysis_results["block_total_sharpness"] = (vhp_dot_v_block / v_norm_sq_block).item()
692
+ else:
693
+ analysis_results["block_total_sharpness"] = 0.0
694
+
695
+ analysis_results["v_norm_block"] = torch.sqrt(v_norm_sq_block).item()
696
+ analysis_results["v_T_H_v_block"] = vhp_dot_v_block.item()
697
+ else:
698
+ # No block parameters
699
+ analysis_results["block_total_sharpness"] = 0.0
700
+ analysis_results["v_norm_block"] = 0.0
701
+ analysis_results["v_T_H_v_block"] = 0.0
702
+
703
+ torch.cuda.empty_cache()
704
+
705
+ # ---- Alignment metrics between update v and (negative) gradient g ----
706
+ eps = 1e-12
707
+ v_norm = torch.sqrt(v_norm_sq_total + eps)
708
+ analysis_results["v_norm"] = v_norm.item()
709
+
710
+ # --- Version 1: g_hvp ---
711
+ ip_v_neg_g_hvp = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, grads_hvp) if g is not None)
712
+ g_hvp_norm_sq = sum(torch.sum(g * g) for g in grads_hvp if g is not None)
713
+
714
+ if not isinstance(ip_v_neg_g_hvp, torch.Tensor):
715
+ ip_v_neg_g_hvp = torch.tensor(0.0, device=device)
716
+ if not isinstance(g_hvp_norm_sq, torch.Tensor):
717
+ g_hvp_norm_sq = torch.tensor(0.0, device=device)
718
+ dist.all_reduce(ip_v_neg_g_hvp, op=dist.ReduceOp.AVG)
719
+ dist.all_reduce(g_hvp_norm_sq, op=dist.ReduceOp.AVG)
720
+ g_hvp_norm = torch.sqrt(g_hvp_norm_sq + eps)
721
+ analysis_results["ip_v_neg_g_hvp"] = ip_v_neg_g_hvp.item()
722
+ analysis_results["cos_v_neg_g_hvp"] = (ip_v_neg_g_hvp / (v_norm * g_hvp_norm + eps)).item()
723
+ analysis_results["g_hvp_norm"] = g_hvp_norm.item()
724
+
725
+ # --- Version 2: g_t (original gradient that produced v) ---
726
+ # last_training_gradient is the actual gradient from training that led to the update v
727
+ if last_training_gradient is not None:
728
+ ip_v_neg_g_t = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, last_training_gradient) if g is not None)
729
+ g_t_norm_sq = sum(torch.sum(g * g) for g in last_training_gradient if g is not None)
730
+ dist.all_reduce(ip_v_neg_g_t, op=dist.ReduceOp.AVG)
731
+ dist.all_reduce(g_t_norm_sq, op=dist.ReduceOp.AVG)
732
+ g_t_norm = torch.sqrt(g_t_norm_sq + eps)
733
+ analysis_results["ip_v_neg_g_t"] = ip_v_neg_g_t.item()
734
+ analysis_results["cos_v_neg_g_t"] = (ip_v_neg_g_t / (v_norm * g_t_norm + eps)).item()
735
+ analysis_results["g_t_norm"] = g_t_norm.item()
736
+ else:
737
+ print0(f"[Enhanced Sharpness @ Step {step}] Warning: last_training_gradient is None, skipping g_t metrics")
738
+
739
+ # Keep backward compatibility aliases (g_norm uses g_hvp for now)
740
+ g_norm_sq = g_hvp_norm_sq
741
+ g_norm = g_hvp_norm
742
+ analysis_results["g_norm"] = g_norm.item()
743
+
744
+ # ---- Cosine between v and Hv (curvature pull along v) ----
745
+ hv_norm_sq = sum(torch.sum(hvp * hvp) for hvp in hvp_v_total if hvp is not None)
746
+ if not isinstance(hv_norm_sq, torch.Tensor):
747
+ hv_norm_sq = torch.tensor(0.0, device=device)
748
+ dist.all_reduce(hv_norm_sq, op=dist.ReduceOp.AVG)
749
+ hv_norm = torch.sqrt(hv_norm_sq + eps)
750
+ ip_v_hv = vhp_dot_v_total # already reduced AVG
751
+ analysis_results["hv_norm"] = hv_norm.item()
752
+ analysis_results["cos_v_hv"] = (ip_v_hv / (v_norm * hv_norm + eps)).item()
753
+
754
+ # ---- Cosine between g and Hg ----
755
+ # hvp_g_accum is already computed in the loop above
756
+ ip_g_hg = sum(torch.sum(g * hg) for g, hg in zip(grads_hvp, hvp_g_accum) if (g is not None and hg is not None))
757
+ hg_norm_sq = sum(torch.sum(hg * hg) for hg in hvp_g_accum if hg is not None)
758
+ if not isinstance(ip_g_hg, torch.Tensor):
759
+ ip_g_hg = torch.tensor(0.0, device=device)
760
+ if not isinstance(hg_norm_sq, torch.Tensor):
761
+ hg_norm_sq = torch.tensor(0.0, device=device)
762
+ dist.all_reduce(ip_g_hg, op=dist.ReduceOp.AVG)
763
+ dist.all_reduce(hg_norm_sq, op=dist.ReduceOp.AVG)
764
+ hg_norm = torch.sqrt(hg_norm_sq + eps)
765
+ analysis_results["hg_norm"] = hg_norm.item()
766
+ analysis_results["cos_g_hg"] = (ip_g_hg / (g_norm * hg_norm + eps)).item() if g_norm.item() > 0 else 0.0
767
+
768
+ # ---- Decompose v into parallel / perpendicular to -g ----
769
+ if g_norm.item() > 0:
770
+ v_parallel = [(torch.sum(v * (-g)) / (g_norm_sq + eps)) * (-g) if g is not None else torch.zeros_like(v)
771
+ for v, g in zip(update_direction_v, grads_hvp)]
772
+ v_parallel_norm_sq = sum(torch.sum(vp * vp) for vp in v_parallel)
773
+ if not isinstance(v_parallel_norm_sq, torch.Tensor):
774
+ v_parallel_norm_sq = torch.tensor(0.0, device=device)
775
+ dist.all_reduce(v_parallel_norm_sq, op=dist.ReduceOp.AVG)
776
+ v_parallel_norm = torch.sqrt(v_parallel_norm_sq + eps)
777
+ v_perp_norm = torch.sqrt(torch.clamp(v_norm_sq_total - v_parallel_norm_sq, min=0.0) + eps)
778
+ analysis_results["v_parallel_norm"] = v_parallel_norm.item()
779
+ analysis_results["v_perp_norm"] = v_perp_norm.item()
780
+
781
+ # ---- Per-layer additions: cos_v_neg_g_layer, v_norm_layer ----
782
+ for group_name, param_group in all_param_groups.items():
783
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
784
+ if not indices:
785
+ continue
786
+ v_norm_sq_layer = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
787
+ g_norm_sq_layer = sum(torch.sum(grads_hvp[i] * grads_hvp[i]) for i in indices if grads_hvp[i] is not None)
788
+ ip_v_neg_g_layer = sum(torch.sum(update_direction_v[i] * (-grads_hvp[i]))
789
+ for i in indices if grads_hvp[i] is not None)
790
+ # Ensure they are tensors
791
+ if not isinstance(v_norm_sq_layer, torch.Tensor):
792
+ v_norm_sq_layer = torch.tensor(0.0, device=device)
793
+ if not isinstance(g_norm_sq_layer, torch.Tensor):
794
+ g_norm_sq_layer = torch.tensor(0.0, device=device)
795
+ if not isinstance(ip_v_neg_g_layer, torch.Tensor):
796
+ ip_v_neg_g_layer = torch.tensor(0.0, device=device)
797
+ dist.all_reduce(v_norm_sq_layer, op=dist.ReduceOp.AVG)
798
+ dist.all_reduce(g_norm_sq_layer, op=dist.ReduceOp.AVG)
799
+ dist.all_reduce(ip_v_neg_g_layer, op=dist.ReduceOp.AVG)
800
+ v_norm_layer = torch.sqrt(v_norm_sq_layer + eps)
801
+ g_norm_layer = torch.sqrt(g_norm_sq_layer + eps)
802
+ analysis_results[f"{group_name}_v_norm"] = v_norm_layer.item()
803
+ if g_norm_layer.item() > 0:
804
+ analysis_results[f"{group_name}_cos_v_neg_g"] = (ip_v_neg_g_layer / (v_norm_layer * g_norm_layer + eps)).item()
805
+
806
+ # --- 7. Calculate layer-wise sharpness ---
807
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise sharpness...")
808
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing {len(all_param_groups)} layers for sharpness...")
809
+
810
+ for group_name, param_group in all_param_groups.items():
811
+ if not param_group:
812
+ continue
813
+
814
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing '{group_name}'...")
815
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
816
+ if not indices:
817
+ continue
818
+
819
+ try:
820
+ if group_name not in layer_hvp_accum or layer_hvp_accum[group_name] is None:
821
+ print0(f"[Enhanced Sharpness @ Step {step}] No HVP data for '{group_name}', skipping")
822
+ analysis_results[f"{group_name}_sharpness"] = 0.0
823
+ continue
824
+
825
+ hvp_group_result = layer_hvp_accum[group_name]
826
+
827
+ vhp_dot_v_group = sum(torch.sum(hvp_group_result[i] * update_direction_v[i])
828
+ for i in indices if hvp_group_result[i] is not None)
829
+ v_norm_sq_group = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
830
+ for i in indices)
831
+
832
+ # Ensure they are tensors
833
+ if not isinstance(vhp_dot_v_group, torch.Tensor):
834
+ vhp_dot_v_group = torch.tensor(0.0, device=device)
835
+ if not isinstance(v_norm_sq_group, torch.Tensor):
836
+ v_norm_sq_group = torch.tensor(0.0, device=device)
837
+
838
+ dist.all_reduce(vhp_dot_v_group, op=dist.ReduceOp.AVG)
839
+ dist.all_reduce(v_norm_sq_group, op=dist.ReduceOp.AVG)
840
+
841
+ if v_norm_sq_group.item() > 1e-12:
842
+ analysis_results[f"{group_name}_sharpness"] = (vhp_dot_v_group / v_norm_sq_group).item()
843
+ else:
844
+ analysis_results[f"{group_name}_sharpness"] = 0.0
845
+
846
+ except torch.OutOfMemoryError as e:
847
+ print0(f"[Enhanced Sharpness @ Step {step}] OOM error for '{group_name}': {e}")
848
+ analysis_results[f"{group_name}_sharpness"] = 0.0
849
+ torch.cuda.empty_cache()
850
+ except Exception as e:
851
+ print0(f"[Enhanced Sharpness @ Step {step}] Error processing '{group_name}': {e}")
852
+ analysis_results[f"{group_name}_sharpness"] = 0.0
853
+
854
+ # --- Calculate block-diagonal approximation and cross-layer interaction ---
855
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating block-diagonal and cross-layer sharpness...")
856
+
857
+ sum_layer_numerators = 0.0
858
+ for layer in range(1, NUM_LAYERS + 1):
859
+ layer_name = f"layer_{layer}"
860
+ if f"{layer_name}_sharpness" in analysis_results and f"{layer_name}_v_norm" in analysis_results:
861
+ s_k = analysis_results[f"{layer_name}_sharpness"]
862
+ v_k_norm = analysis_results[f"{layer_name}_v_norm"]
863
+ sum_layer_numerators += s_k * (v_k_norm ** 2)
864
+
865
+ analysis_results["sum_layer_numerators"] = sum_layer_numerators
866
+
867
+ # Block-diagonal sharpness (using block ||v||²)
868
+ v_norm_block = analysis_results.get("v_norm_block", 0)
869
+ v_norm_sq_block_val = v_norm_block ** 2 if v_norm_block else 1e-12
870
+
871
+ if v_norm_sq_block_val > 1e-12:
872
+ analysis_results["block_diag_sharpness"] = sum_layer_numerators / v_norm_sq_block_val
873
+ else:
874
+ analysis_results["block_diag_sharpness"] = 0.0
875
+
876
+ # Cross-layer interaction = block_total - block_diag
877
+ block_total = analysis_results.get("block_total_sharpness", 0)
878
+ block_diag = analysis_results.get("block_diag_sharpness", 0)
879
+ analysis_results["cross_layer_sharpness"] = block_total - block_diag
880
+
881
+ print0(f"[Enhanced Sharpness @ Step {step}] block_total={block_total:.6f}, block_diag={block_diag:.6f}, cross_layer={block_total - block_diag:.6f}")
882
+
883
+ # --- Compute true_dec and pred_dec ---
884
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing true_dec (L(t) - L(t+1)) on training batch...")
885
+ try:
886
+ # Restore FLASH for forward pass
887
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
888
+
889
+
890
+ loss_at_theta_t = 0.0
891
+ with torch.no_grad():
892
+ for x_td, y_td in batch_iterator:
893
+ x_td, y_td = x_td.to(device), y_td.to(device)
894
+ _, loss_td = model(x_td, y_td, return_logits=False)
895
+ loss_at_theta_t += loss_td.item()
896
+ loss_at_theta_t /= len(batch_iterator) # average over microbatches
897
+
898
+ with torch.no_grad():
899
+ for p, v in zip(model.parameters(), update_direction_v):
900
+ p.data.add_(v)
901
+
902
+ loss_at_theta_t1 = 0.0
903
+ with torch.no_grad():
904
+ for x_td, y_td in batch_iterator:
905
+ x_td, y_td = x_td.to(device), y_td.to(device)
906
+ _, loss_td = model(x_td, y_td, return_logits=False)
907
+ loss_at_theta_t1 += loss_td.item()
908
+ loss_at_theta_t1 /= len(batch_iterator)
909
+
910
+ with torch.no_grad():
911
+ for p, v in zip(model.parameters(), update_direction_v):
912
+ p.data.sub_(v)
913
+
914
+ loss_t_tensor = torch.tensor(loss_at_theta_t, device=device)
915
+ loss_t1_tensor = torch.tensor(loss_at_theta_t1, device=device)
916
+ dist.all_reduce(loss_t_tensor, op=dist.ReduceOp.AVG)
917
+ dist.all_reduce(loss_t1_tensor, op=dist.ReduceOp.AVG)
918
+ loss_at_theta_t = loss_t_tensor.item()
919
+ loss_at_theta_t1 = loss_t1_tensor.item()
920
+
921
+ true_dec = loss_at_theta_t - loss_at_theta_t1
922
+ analysis_results["loss_at_theta_t"] = loss_at_theta_t
923
+ analysis_results["loss_at_theta_t1"] = loss_at_theta_t1
924
+ analysis_results["true_dec"] = true_dec
925
+
926
+ # pred_dec = (-g)^T v - 0.5 * v^T H v
927
+ first_order = analysis_results.get("ip_v_neg_g_t", analysis_results.get("ip_v_neg_g_hvp", 0.0))
928
+ sharpness_val = analysis_results.get("total_sharpness", 0.0)
929
+ v_norm_val = analysis_results.get("v_norm", 0.0)
930
+ curvature_term = 0.5 * sharpness_val * (v_norm_val ** 2)
931
+ pred_dec = first_order - curvature_term
932
+
933
+ analysis_results["pred_dec"] = pred_dec
934
+ analysis_results["first_order_descent"] = first_order
935
+ analysis_results["curvature_penalty"] = curvature_term
936
+
937
+ print0(f"[Enhanced Sharpness @ Step {step}] L(θ_t)={loss_at_theta_t:.6f}, L(θ_{{t+1}})={loss_at_theta_t1:.6f}, "
938
+ f"true_dec={true_dec:.6f}, pred_dec={pred_dec:.6f}, 1st_order={first_order:.6f}, curvature={curvature_term:.6f}")
939
+ except Exception as e:
940
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing true_dec: {e}")
941
+ analysis_results["true_dec"] = 0.0
942
+ analysis_results["pred_dec"] = 0.0
943
+
944
+ # --- Cleanup ---
945
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
946
+ print0(f"[Enhanced Sharpness @ Step {step}] Restored FLASH attention to {original_flash}")
947
+
948
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters back to θ_{{t+1}}...")
949
+ with torch.no_grad():
950
+ for p, v in zip(model.parameters(), update_direction_v):
951
+ p.data.add_(v)
952
+
953
+ if prev_training_mode:
954
+ model.train()
955
+ else:
956
+ model.eval()
957
+
958
+ # Thorough cleanup of all temporary variables
959
+ del update_direction_v, grads_hvp
960
+ del hvp_v_total, hvp_v_block, hvp_g_accum, layer_hvp_accum
961
+ del vhp_dot_v_total, v_norm_sq_total
962
+ del vhp_dot_v_block, v_norm_sq_block
963
+ if 'all_param_groups' in locals():
964
+ del all_param_groups
965
+ if 'param_to_idx' in locals():
966
+ del param_to_idx
967
+
968
+ # Synchronize CUDA operations before cleanup
969
+ if device == "cuda":
970
+ torch.cuda.synchronize()
971
+
972
+ gc.collect()
973
+ torch.cuda.empty_cache()
974
+
975
+ print0(f"[Enhanced Sharpness @ Step {step}] Analysis complete. Generated {len(analysis_results)} metrics.")
976
+ return analysis_results
977
+
978
+ def format_comprehensive_results(results):
979
+ """
980
+ Format the comprehensive analysis results for logging.
981
+ """
982
+ log_parts = []
983
+
984
+ # Total sharpness
985
+ if 'total_sharpness' in results:
986
+ log_parts.append(f"total_sharp:{results['total_sharpness']:.4e}")
987
+
988
+ # Layer-wise sharpness - dynamically detect number of layers
989
+ layer_sharpness = []
990
+ layer_num = 1
991
+ while True:
992
+ layer_key = f"layer_{layer_num}_sharpness"
993
+ if layer_key in results:
994
+ layer_sharpness.append(f"L{layer_num}_sharp:{results[layer_key]:.4e}")
995
+ layer_num += 1
996
+ else:
997
+ break
998
+
999
+ if layer_sharpness:
1000
+ log_parts.append(" ".join(layer_sharpness))
1001
+
1002
+ # Total update norms
1003
+ total_norms = []
1004
+ if 'total_update_fnorm' in results:
1005
+ total_norms.append(f"total_fnorm:{results['total_update_fnorm']:.4e}")
1006
+ if 'total_l1_linf_norm' in results:
1007
+ total_norms.append(f"total_l1_linf:{results['total_l1_linf_norm']:.4e}")
1008
+ if 'total_spectral_norm' in results:
1009
+ total_norms.append(f"total_spectral:{results['total_spectral_norm']:.4e}")
1010
+
1011
+ if total_norms:
1012
+ log_parts.append(" ".join(total_norms))
1013
+
1014
+ # Layer-wise update norms (Frobenius)
1015
+ layer_fnorms = []
1016
+ layer_num = 1
1017
+ while True:
1018
+ layer_key = f"layer_{layer_num}_update_fnorm"
1019
+ if layer_key in results:
1020
+ layer_fnorms.append(f"L{layer_num}_fnorm:{results[layer_key]:.4e}")
1021
+ layer_num += 1
1022
+ else:
1023
+ break
1024
+
1025
+ if layer_fnorms:
1026
+ log_parts.append(" ".join(layer_fnorms))
1027
+
1028
+ # Layer-wise update norms (Max-of-Max)
1029
+ layer_l1_linf = []
1030
+ layer_num = 1
1031
+ while True:
1032
+ layer_key = f"layer_{layer_num}_max_l1_linf_norm"
1033
+ if layer_key in results:
1034
+ layer_l1_linf.append(f"L{layer_num}_l1linf:{results[layer_key]:.4e}")
1035
+ layer_num += 1
1036
+ else:
1037
+ break
1038
+
1039
+ if layer_l1_linf:
1040
+ log_parts.append(" ".join(layer_l1_linf))
1041
+
1042
+ # Layer-wise update norms (Spectral)
1043
+ layer_spectral = []
1044
+ layer_num = 1
1045
+ while True:
1046
+ layer_key = f"layer_{layer_num}_max_spectral_norm"
1047
+ if layer_key in results:
1048
+ layer_spectral.append(f"L{layer_num}_spectral:{results[layer_key]:.4e}")
1049
+ layer_num += 1
1050
+ else:
1051
+ break
1052
+
1053
+ if layer_spectral:
1054
+ log_parts.append(" ".join(layer_spectral))
1055
+
1056
+ # Alignment and curvature metrics (global)
1057
+ misc_parts = []
1058
+ if 'v_norm' in results:
1059
+ misc_parts.append(f"v_norm:{results['v_norm']:.4e}")
1060
+
1061
+ # Version 1: g_hvp (new batch, computed at θ_t during HVP calculation)
1062
+ if 'cos_v_neg_g_hvp' in results:
1063
+ misc_parts.append(f"cos_v_-g_hvp:{results['cos_v_neg_g_hvp']:.4e}")
1064
+ if 'g_hvp_norm' in results:
1065
+ misc_parts.append(f"g_hvp_norm:{results['g_hvp_norm']:.4e}")
1066
+
1067
+ # Version 2: g_t (original gradient that produced v)
1068
+ if 'cos_v_neg_g_t' in results:
1069
+ misc_parts.append(f"cos_v_-g_t:{results['cos_v_neg_g_t']:.4e}")
1070
+ if 'g_t_norm' in results:
1071
+ misc_parts.append(f"g_t_norm:{results['g_t_norm']:.4e}")
1072
+
1073
+ if 'hv_norm' in results:
1074
+ misc_parts.append(f"hv_norm:{results['hv_norm']:.4e}")
1075
+ if 'cos_v_hv' in results:
1076
+ misc_parts.append(f"cos_v_hv:{results['cos_v_hv']:.4e}")
1077
+ if 'hg_norm' in results:
1078
+ misc_parts.append(f"hg_norm:{results['hg_norm']:.4e}")
1079
+ if 'cos_g_hg' in results:
1080
+ misc_parts.append(f"cos_g_hg:{results['cos_g_hg']:.4e}")
1081
+ if 'v_parallel_norm' in results:
1082
+ misc_parts.append(f"v_par:{results['v_parallel_norm']:.4e}")
1083
+ if 'v_perp_norm' in results:
1084
+ misc_parts.append(f"v_perp:{results['v_perp_norm']:.4e}")
1085
+ if misc_parts:
1086
+ log_parts.append(" ".join(misc_parts))
1087
+
1088
+ # Per-layer alignment metrics (cos_v_neg_g and v_norm per layer)
1089
+ layer_cos = []
1090
+ layer_num = 1
1091
+ while True:
1092
+ layer_key = f"layer_{layer_num}_cos_v_neg_g"
1093
+ layer_vn_key = f"layer_{layer_num}_v_norm"
1094
+ if layer_key in results:
1095
+ layer_cos.append(f"L{layer_num}_cos_v_neg_g:{results[layer_key]:.4e}")
1096
+ if layer_vn_key in results:
1097
+ layer_cos.append(f"L{layer_num}_v_norm:{results[layer_vn_key]:.4e}")
1098
+ if layer_key not in results and layer_vn_key not in results:
1099
+ break
1100
+ layer_num += 1
1101
+ if layer_cos:
1102
+ log_parts.append(" ".join(layer_cos))
1103
+
1104
+ return " ".join(log_parts)
1105
+
1106
+ # -----------------------------------------------------------------------------
1107
+ # int main
1108
+
1109
+ def print0(*args, **kwargs):
1110
+ # modified print that only prints from the master process
1111
+ # if this is not a distributed run, it's just a print
1112
+ if int(os.environ.get("RANK", 0)) == 0:
1113
+ print(*args, **kwargs)
1114
+
1115
+ if __name__ == "__main__":
1116
+ import time
1117
+ import argparse
1118
+ import tiktoken
1119
+ print0(f"Running pytorch {torch.version.__version__}")
1120
+
1121
+ # default settings will overfit a tiny batch of data
1122
+ # and save model weights and debug state to disk on the first iteration
1123
+ parser = argparse.ArgumentParser()
1124
+ # file system input / output
1125
+ parser.add_argument("--input_bin", type=str, default="dev/data/tinyshakespeare/tiny_shakespeare_val.bin", help="input .bin to train on")
1126
+ parser.add_argument("--input_val_bin", type=str, default="", help="input .bin to eval validation loss on")
1127
+ parser.add_argument("--output_dir", type=str, default="", help="output directory to which to write logs and checkpoints")
1128
+ parser.add_argument("--model", type=str, default="gpt2", help="gpt2|gpt2-medium|gpt2-large|gpt2-xl|d8|d12|d24|d36|d48")
1129
+ # token layout for each step of the optimization
1130
+ parser.add_argument("--batch_size", type=int, default=4, help="batch size, in units of #batch dimensions")
1131
+ parser.add_argument("--sequence_length", type=int, default=64, help="sequence length")
1132
+ parser.add_argument("--total_batch_size", type=int, default=256, help="total desired batch size, in units of #tokens")
1133
+ # workload (number of steps)
1134
+ parser.add_argument("--num_iterations", type=int, default=10, help="number of iterations to run")
1135
+ parser.add_argument("--inference_only", type=int, default=0, help="only run inference")
1136
+ # optimization
1137
+ parser.add_argument("--adam_lr", type=float, default=1e-4, help="learning rate warmup iterations")
1138
+ parser.add_argument("--warmup_iters", type=int, default=0, help="learning rate warmup iterations")
1139
+ parser.add_argument("--lr_decay_frac", type=float, default=1.0, help="learning rate warmup iterations")
1140
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="weight decay")
1141
+ parser.add_argument("--grad_clip", type=float, default=1.0, help="maximum gradient magnitude")
1142
+ # evaluation
1143
+ parser.add_argument("--val_loss_every", type=int, default=0, help="every how mant steps to evaluate val loss?")
1144
+ parser.add_argument("--val_max_steps", type=int, default=20, help="how many batches of val to average?")
1145
+ parser.add_argument("--sample_every", type=int, default=0, help="how often to sample from the model?")
1146
+ # debugging
1147
+ parser.add_argument("--overfit_single_batch", type=int, default=0, help="overfit just one batch of data")
1148
+ parser.add_argument("--shuffle_files", action="store_true")
1149
+ # numerics
1150
+ parser.add_argument("--tensorcores", type=int, default=0, help="use tensorcores")
1151
+ # memory management
1152
+ parser.add_argument("--device", type=str, default="", help="by default we autodetect, or set it here")
1153
+ parser.add_argument("--compile", type=int, default=0, help="torch.compile the model")
1154
+ parser.add_argument("--flash", type=int, default=0, help="use flash attention")
1155
+ parser.add_argument("--dtype", type=str, default="float32", help="float32|float16|bfloat16")
1156
+ parser.add_argument("--zero_stage", type=int, default=0, help="zero redundancy optimizer stage (0/1/2/3)")
1157
+ # Muon optimizer specific arguments
1158
+ parser.add_argument("--optimizer", type=str, default="adam", help="optimizer to use: adam|muon")
1159
+ parser.add_argument("--muon_lr", type=float, default=0.02, help="learning rate for Muon optimizer")
1160
+ parser.add_argument("--muon_momentum", type=float, default=0.95, help="momentum for Muon optimizer")
1161
+ parser.add_argument("--muon_weight_decay", type=float, default=0.00, help="weight decay for Muon optimizer")
1162
+ parser.add_argument("--muon_ns_steps", type=int, default=5, help="number of Newton-Schulz steps for Muon")
1163
+ parser.add_argument("--muon_nesterov", type=bool, default=False, help="use Nesterov momentum for Muon (0/1)")
1164
+ # python -> C bridge
1165
+ parser.add_argument("--write_tensors", type=int, default=1, help="write tensors to disk")
1166
+ parser.add_argument("--seed", type=int, default=42, help="random seed")
1167
+ # Sharpness analysis arguments
1168
+ parser.add_argument("--analyze_sharpness", action="store_true", help="Enable comprehensive sharpness analysis")
1169
+ parser.add_argument("--sharpness_analysis_interval", type=int, default=500, help="Interval for sharpness analysis")
1170
+ args = parser.parse_args()
1171
+
1172
+ # args error checking and convenience variables
1173
+ B, T = args.batch_size, args.sequence_length
1174
+ assert 1 <= T <= 1024
1175
+ assert args.dtype in {"float32", "float16", "bfloat16"}
1176
+ assert args.model in {"gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl", "d8", "d12", "d24", "d36", "d48"}
1177
+ assert args.optimizer in {"adam", "muon"}
1178
+
1179
+ set_seed(args.seed)
1180
+
1181
+ # set up DDP (distributed data parallel). torchrun sets this env variable
1182
+ ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
1183
+ if ddp:
1184
+ # use of DDP atm demands CUDA, we set the device appropriately according to rank
1185
+ assert torch.cuda.is_available(), "for now i think we need CUDA for DDP"
1186
+ init_process_group(backend='nccl')
1187
+ ddp_rank = int(os.environ['RANK'])
1188
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
1189
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
1190
+ device = f'cuda:{ddp_local_rank}'
1191
+ torch.cuda.set_device(device)
1192
+ master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
1193
+ seed_offset = 0 # each process gets the exact same seed
1194
+ zero_stage = args.zero_stage
1195
+ else:
1196
+ ddp_rank = 0
1197
+ ddp_local_rank = 0
1198
+ zero_stage = 0
1199
+ ddp_world_size = 1
1200
+ master_process = True
1201
+ seed_offset = 0
1202
+ # select the device
1203
+ if args.device:
1204
+ # provided explicitly by the user
1205
+ device = args.device
1206
+ else:
1207
+ # attempt to autodetect the device
1208
+ device = "cpu"
1209
+ if torch.cuda.is_available():
1210
+ device = "cuda"
1211
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
1212
+ device = "mps"
1213
+ print(f"using device: {device}")
1214
+ device_type = 'cuda' if 'cuda' in device else 'cpu'
1215
+
1216
+ # Setup debugpy for remote debugging (only activates if DEBUGPY env var is set)
1217
+ # setup_debugpy(rank=ddp_rank, force=True)
1218
+
1219
+ # calculate gradient accumulation from the desired total batch size and the current run configuration
1220
+ tokens_per_fwdbwd = B * T * ddp_world_size
1221
+ assert args.total_batch_size % tokens_per_fwdbwd == 0
1222
+ grad_accum_steps = args.total_batch_size // tokens_per_fwdbwd
1223
+ print0(f"total desired batch size: {args.total_batch_size}")
1224
+ print0(f"=> calculated gradient accumulation steps: {grad_accum_steps}")
1225
+
1226
+ # set up a context manager following the desired dtype and device
1227
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[args.dtype]
1228
+ ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype) if device_type == "cuda" else nullcontext()
1229
+
1230
+ # rng / reproducibility
1231
+ torch.manual_seed(42)
1232
+ if torch.cuda.is_available():
1233
+ torch.cuda.manual_seed(42)
1234
+
1235
+ # set the torch precision mode to use TensorFloat32 (TF32) for matmuls
1236
+ # docs https://pytorch.org/docs/stable/generated/torch.set_float32_matmul_precision.html
1237
+ if args.tensorcores:
1238
+ torch.set_float32_matmul_precision('high')
1239
+
1240
+ # turn on/off flash attention
1241
+ assert args.flash in {0, 1}
1242
+ nano_GPT_qkvonorm_pure.FLASH = args.flash # Set module-level FLASH for training
1243
+
1244
+ # init (and write) the tokenizer
1245
+ enc = tiktoken.get_encoding("gpt2")
1246
+ if master_process and args.write_tensors: # tokenizer is technically not tensors but ok
1247
+ write_tokenizer(enc, "gpt2_tokenizer.bin")
1248
+
1249
+ # init the model, either from scratch or from OpenAI pretrained checkpoint
1250
+ if args.model[0] == "d":
1251
+ # from scratch (random weights)
1252
+ model_config = {
1253
+ "d8": GPTConfig(block_size=1024, vocab_size=50257, n_layer=8, n_head=8, n_embd=512),
1254
+ "d12": GPTConfig(block_size=1024, vocab_size=50257, n_layer=12, n_head=12, n_embd=768),
1255
+ "d24": GPTConfig(block_size=1024, vocab_size=50257, n_layer=24, n_head=16, n_embd=1024),
1256
+ "d36": GPTConfig(block_size=1024, vocab_size=50257, n_layer=36, n_head=20, n_embd=1280),
1257
+ "d48": GPTConfig(block_size=1024, vocab_size=50257, n_layer=48, n_head=25, n_embd=1600),
1258
+ }[args.model]
1259
+ model = GPT(model_config)
1260
+ else:
1261
+ # load the GPT-2 model weights
1262
+ model = GPT.from_pretrained(args.model)
1263
+ model.train()
1264
+ model.to(device)
1265
+
1266
+ # Save uncompiled model reference for sharpness analysis (needs double backward)
1267
+ raw_model_uncompiled = model
1268
+
1269
+ if args.compile:
1270
+ if hasattr(config, "coordinate_descent_tuning"):
1271
+ config.coordinate_descent_tuning = True # suggested by @Chillee
1272
+ print0("compiling the model...")
1273
+ model = torch.compile(model)
1274
+
1275
+ # -------------------------------------------------------------------------
1276
+ # Our own version of a simple DistributedDataLoader
1277
+
1278
+ # load tokens
1279
+ train_loader = DistributedDataLoader(
1280
+ args.input_bin, B, T, ddp_rank, ddp_world_size,
1281
+ shuffle_files=args.shuffle_files, random_seed=args.seed
1282
+ )
1283
+ val_loader = None
1284
+ if args.input_val_bin:
1285
+ val_loader = DistributedDataLoader(args.input_val_bin, B, T, ddp_rank, ddp_world_size)
1286
+
1287
+ # -------------------------------------------------------------------------
1288
+ # PyTorch -> C bridge: save some weights and state for C to load later as reference
1289
+
1290
+ # do one forward pass to generate ground truth for our C tests
1291
+ if master_process and args.write_tensors and (not args.inference_only):
1292
+ x, y = train_loader.next_batch()
1293
+ x, y = x.to(device), y.to(device)
1294
+ logits, loss = model(x, y, return_logits=True) # Need logits for write_state
1295
+ loss.backward()
1296
+ # save model params, in both float32 and bfloat16
1297
+ model_to_size = {"gpt2": "124M", "gpt2-medium": "355M", "gpt2-large": "774M", "gpt2-xl": "1558M"}
1298
+ model_to_size.update({f"d{d}": f"d{d}" for d in [12, 24, 36, 48]})
1299
+ model_size_str = model_to_size[args.model] # e.g. "124M", or "d12"
1300
+ write_model(model, f"gpt2_{model_size_str}.bin", dtype="float32")
1301
+ write_model(model, f"gpt2_{model_size_str}_bf16.bin", dtype="bfloat16")
1302
+ # save x, y, logits, loss, and parameter gradients, for debugging C
1303
+ # always store these in fp32 to have an accurate reference (?)
1304
+ write_state(model, x, y, logits, loss, f"gpt2_{model_size_str}_debug_state.bin")
1305
+ # reset the train_loader for the optimization below
1306
+ train_loader.reset()
1307
+
1308
+ # -------------------------------------------------------------------------
1309
+ # main training loop
1310
+
1311
+ # here we wrap model into DDP container
1312
+ if ddp:
1313
+ model = DDP(model, device_ids=[ddp_local_rank])
1314
+ raw_model = model.module if ddp else model # always contains the "raw" unwrapped model
1315
+
1316
+ base_module = model.module if ddp else model
1317
+ # If compiled, unwrap to get the original module
1318
+ if hasattr(base_module, "_orig_mod"):
1319
+ base_module = base_module._orig_mod
1320
+
1321
+ raw_params = list(raw_model_uncompiled.parameters())
1322
+ train_params = list(base_module.parameters())
1323
+
1324
+ assert len(raw_params) == len(train_params), \
1325
+ f"Parameter count mismatch: raw_model_uncompiled has {len(raw_params)}, training model has {len(train_params)}"
1326
+ for i, (rp, tp) in enumerate(zip(raw_params, train_params)):
1327
+ assert rp.data_ptr() == tp.data_ptr(), \
1328
+ f"Parameter {i} has different data_ptr: raw_model_uncompiled and training model do not share parameters!"
1329
+ print0(f"[Verified] raw_model_uncompiled and training model share the same {len(raw_params)} Parameter objects")
1330
+
1331
+ last_training_update = None
1332
+ last_training_gradient = None # Store the original gradient that produced the update
1333
+ last_training_batches = None # Store ALL microbatches (x, y) for consistent HVP calculation
1334
+
1335
+
1336
+ def configure_adam(model, weight_decay, learning_rate, betas, device_type, zero_stage):
1337
+ # start with all of the candidate parameters
1338
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1339
+ # filter out those that do not require grad
1340
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1341
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
1342
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
1343
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
1344
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
1345
+ optim_groups = [
1346
+ {'params': decay_params, 'weight_decay': weight_decay},
1347
+ {'params': nodecay_params, 'weight_decay': 0.0}
1348
+ ]
1349
+ num_decay_params = sum(p.numel() for p in decay_params)
1350
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
1351
+ print0(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
1352
+ print0(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
1353
+ # Create AdamW optimizer and use the fused version if it is available
1354
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1355
+ use_fused = fused_available and device_type == 'cuda'
1356
+ print0(f"using fused AdamW: {use_fused}")
1357
+ if zero_stage == 1:
1358
+ print0("using ZeroRedundancyOptimizer")
1359
+ optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1360
+ lr=learning_rate, betas=betas, fused=use_fused)
1361
+ optimizer.add_param_group(optim_groups[1])
1362
+ else:
1363
+ print0("using regular AdamW")
1364
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=use_fused)
1365
+ return [optimizer]
1366
+
1367
+ def configure_muon(model, weight_decay, adam_lr, muon_lr, momentum, nesterov, ns_steps, device_type, zero_stage, ddp_rank, ddp_world_size):
1368
+ # start with all of the candidate parameters
1369
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1370
+ # filter out those that do not require grad
1371
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1372
+
1373
+ # For Muon, we need to separate 2D parameters (which can be orthogonalized)
1374
+ # from other parameters (which should use standard optimization)
1375
+ muon_params = [] # 2D parameters for Muon
1376
+ other_params = [] # other parameters for AdamW
1377
+
1378
+ muon_name = []
1379
+ other_name = []
1380
+ for n, p in param_dict.items():
1381
+ if "wte.weight" in n :
1382
+ other_params.append(p)
1383
+ other_name.append(n)
1384
+ continue
1385
+
1386
+ if p.dim() >= 2: # 2D parameters (weight matrices)
1387
+ muon_params.append(p)
1388
+ muon_name.append(n)
1389
+ else: # 1D parameters (biases, embeddings, etc.)
1390
+ other_params.append(p)
1391
+ other_name.append(n)
1392
+
1393
+ # print("================================================\n")
1394
+ # print(f"Muon parameters: {muon_name}\n")
1395
+ # print(f"Other parameters: {other_name}\n")
1396
+ # print("================================================\n")
1397
+
1398
+ print0(f"Muon parameters (2D): {len(muon_params)} tensors")
1399
+ print0(f"Other parameters (non-2D): {len(other_params)} tensors")
1400
+
1401
+ # Create Muon optimizer for 2D parameters
1402
+ muon_optimizer = None
1403
+ if muon_params:
1404
+ muon_optimizer = Muon(
1405
+ params=muon_params,
1406
+ lr=muon_lr,
1407
+ weight_decay=weight_decay,
1408
+ momentum=momentum,
1409
+ nesterov=nesterov,
1410
+ ns_steps=ns_steps,
1411
+ rank=ddp_rank,
1412
+ world_size=ddp_world_size
1413
+ )
1414
+
1415
+ # Create AdamW optimizer for non-2D parameters
1416
+ adam_optimizer = None
1417
+ if other_params:
1418
+ # create optim groups for AdamW
1419
+ # decay_params = [p for p in other_params if p.dim() >= 2]
1420
+ # nodecay_params = [p for p in other_params if p.dim() < 2]
1421
+ optim_groups = [
1422
+ {'params': other_params, 'weight_decay': weight_decay},
1423
+ # {'params': nodecay_params, 'weight_decay': 0.0}
1424
+ ]
1425
+
1426
+ # Create AdamW optimizer
1427
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1428
+ use_fused = fused_available and device_type == 'cuda'
1429
+ print0(f"using fused AdamW for non-Muon params: {use_fused}")
1430
+
1431
+ if zero_stage == 1:
1432
+ print0("using ZeroRedundancyOptimizer for non-Muon params")
1433
+ adam_optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1434
+ lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1435
+ # adam_optimizer.add_param_group(optim_groups[1])
1436
+ else:
1437
+ print0("using regular AdamW for non-Muon params")
1438
+ adam_optimizer = torch.optim.AdamW(optim_groups, lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1439
+
1440
+ return [muon_optimizer, adam_optimizer]
1441
+
1442
+ # init the optimizer
1443
+ if args.optimizer == "adam":
1444
+ optimizers = configure_adam(model=raw_model_uncompiled, weight_decay=args.weight_decay,
1445
+ learning_rate=args.adam_lr, betas=(0.9, 0.95),
1446
+ device_type=device, zero_stage=zero_stage)
1447
+ elif args.optimizer == "muon":
1448
+ optimizers = configure_muon(
1449
+ model=raw_model_uncompiled,
1450
+ weight_decay=args.muon_weight_decay,
1451
+ muon_lr=args.muon_lr,
1452
+ adam_lr=args.adam_lr,
1453
+ momentum=args.muon_momentum,
1454
+ nesterov=bool(args.muon_nesterov),
1455
+ ns_steps=args.muon_ns_steps,
1456
+ device_type=device,
1457
+ zero_stage=zero_stage,
1458
+ ddp_rank=ddp_rank,
1459
+ ddp_world_size=ddp_world_size
1460
+ )
1461
+ # We'll use muon_optimizer and adam_optimizer separately
1462
+
1463
+ # learning rate decay scheduler (cosine with warmup)
1464
+ def get_lr(it,base_lr):
1465
+ # if args.optimizer == "adam":
1466
+ # base_lr = args.adam_lr
1467
+ # else: # muon
1468
+ # base_lr = args.muon_lr
1469
+ min_lr = base_lr * args.lr_decay_frac
1470
+ # 1) linear warmup for warmup_iters steps
1471
+ if it < args.warmup_iters:
1472
+ return base_lr * (it+1) / args.warmup_iters
1473
+ # 2) if it > lr_decay_iters, return min learning rate
1474
+ if it > args.num_iterations:
1475
+ return min_lr
1476
+ # 3) in between, use cosine decay down to min learning rate
1477
+ decay_ratio = (it - args.warmup_iters) / (args.num_iterations - args.warmup_iters)
1478
+ assert 0 <= decay_ratio <= 1
1479
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff starts at 1 and goes to 0
1480
+ return min_lr + coeff * (base_lr - min_lr)
1481
+
1482
+ def get_wsd_lr(it, base_lr):
1483
+ min_lr = base_lr * args.lr_decay_frac
1484
+ # cooldown_iters = int(args.num_iterations * 0.2)
1485
+ cooldown_iters = int(0)
1486
+ # 1) Warmup: linear warmup for warmup_iters steps
1487
+ if it < args.warmup_iters:
1488
+ return base_lr * (it + 1) / args.warmup_iters
1489
+ # 3) Decay: linear decay from base_lr to min_lr in the last cooldown_iters steps
1490
+ cooldown_start = args.num_iterations - cooldown_iters
1491
+ if it >= cooldown_start:
1492
+ decay_ratio = (it - cooldown_start) / cooldown_iters
1493
+ return base_lr - decay_ratio * (base_lr - min_lr)
1494
+ # 2) Stable: constant learning rate at base_lr
1495
+ return base_lr
1496
+
1497
+ # create the logging directory if it does not exist
1498
+ logfile = None
1499
+ run_dir_path = None
1500
+
1501
+ file_name = f"mode_{args.optimizer}_adam_lr_{args.adam_lr}_muon_lr_{args.muon_lr}_seed_{args.seed}.log"
1502
+ if args.output_dir:
1503
+ base_log_dir = Path(args.output_dir)
1504
+ base_log_dir.mkdir(parents=True, exist_ok=True)
1505
+
1506
+ # Create run-specific directory
1507
+ # Generate UUID on master process and broadcast to all ranks
1508
+ if master_process:
1509
+ run_uuid = uuid.uuid4()
1510
+ uuid_str = str(run_uuid)
1511
+ else:
1512
+ uuid_str = None
1513
+
1514
+ # Broadcast UUID from rank 0 to all other ranks
1515
+ if ddp:
1516
+ # Create a tensor to hold the UUID string length and content
1517
+ if master_process:
1518
+ uuid_bytes = uuid_str.encode('utf-8')
1519
+ uuid_len = len(uuid_bytes)
1520
+ else:
1521
+ uuid_len = 0
1522
+
1523
+ # Broadcast length
1524
+ uuid_len_tensor = torch.tensor(uuid_len, dtype=torch.long, device=device)
1525
+ dist.broadcast(uuid_len_tensor, src=0)
1526
+
1527
+ # Broadcast UUID string
1528
+ if master_process:
1529
+ uuid_tensor = torch.ByteTensor(list(uuid_bytes)).to(device)
1530
+ else:
1531
+ uuid_tensor = torch.ByteTensor([0] * uuid_len_tensor.item()).to(device)
1532
+ dist.broadcast(uuid_tensor, src=0)
1533
+
1534
+ # Decode on non-master processes
1535
+ if not master_process:
1536
+ uuid_str = bytes(uuid_tensor.cpu().numpy()).decode('utf-8')
1537
+ run_uuid = uuid.UUID(uuid_str)
1538
+ else:
1539
+ run_uuid = uuid.UUID(uuid_str)
1540
+ else:
1541
+ run_uuid = uuid.uuid4()
1542
+
1543
+ # run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}_{run_uuid}"
1544
+ run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}"
1545
+ run_dir_path = base_log_dir / run_folder_name
1546
+ if run_dir_path.exists():
1547
+ run_flag = False
1548
+ else:
1549
+ run_flag = True
1550
+ torch.cuda.synchronize()
1551
+
1552
+
1553
+ # Only master process creates the directory
1554
+ if master_process:
1555
+ run_dir_path.mkdir(parents=True, exist_ok=True)
1556
+
1557
+ logfile = str(run_dir_path / "training_log.txt")
1558
+
1559
+ # Save configuration
1560
+
1561
+ if run_flag:
1562
+ if master_process:
1563
+ config_to_save = {
1564
+ "cli_args": vars(args),
1565
+ "run_uuid": str(run_uuid),
1566
+ "script_code_logged_at_start": True
1567
+ }
1568
+ config_file_path = run_dir_path / "config.json"
1569
+ with open(config_file_path, "w") as f:
1570
+ json.dump(config_to_save, f, indent=4)
1571
+ print0(f"Saved configuration to: {config_file_path}")
1572
+
1573
+ if master_process and logfile:
1574
+ with open(logfile, "w") as f:
1575
+ pass # Create/clear the file
1576
+ with open(logfile, "a") as f:
1577
+ f.write(code)
1578
+
1579
+ if device == "cuda":
1580
+ torch.cuda.reset_peak_memory_stats()
1581
+ timings = []
1582
+ norm = -1.0 # dummy value to print in inference-only mode
1583
+ for step in range(args.num_iterations + 1):
1584
+ t0 = time.time()
1585
+ last_step = (step == args.num_iterations)
1586
+
1587
+ # once in a while evaluate the validation dataset
1588
+ if (args.val_loss_every > 0 \
1589
+ and (step % args.val_loss_every == 0 or last_step)) \
1590
+ and (val_loader is not None):
1591
+ model.eval()
1592
+ val_loader.reset()
1593
+ with torch.no_grad():
1594
+ val_loss = 0.0
1595
+ for _ in range(args.val_max_steps):
1596
+ x, y = val_loader.next_batch()
1597
+ x, y = x.to(device), y.to(device)
1598
+ _, loss = model(x, y, return_logits=False)
1599
+ val_loss += loss.item()
1600
+ val_loss /= args.val_max_steps
1601
+
1602
+ # --- Comprehensive Sharpness Analysis ---
1603
+ sharpness_log_str = ""
1604
+ # Skip step 0 since we don't have a previous training update yet
1605
+ if args.analyze_sharpness and step > 0 and (step % args.sharpness_analysis_interval == 0 or last_step):
1606
+ print0(f"[Sharpness @ Step {step}] Starting comprehensive sharpness analysis...")
1607
+ for optimizer in optimizers:
1608
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1609
+ optimizer.zero_grad(set_to_none=True)
1610
+ elif isinstance(optimizer, Muon):
1611
+ optimizer.zero_grad()
1612
+ comprehensive_results = calculate_comprehensive_sharpness(
1613
+ model=raw_model_uncompiled, # Use uncompiled model for HVP (double backward)
1614
+ model_for_forward=model, # Use compiled+DDP model for forward pass
1615
+ optimizers=optimizers,
1616
+ step=step,
1617
+ train_loader=train_loader,
1618
+ val_loader=val_loader,
1619
+ rank=ddp_rank,
1620
+ world_size=ddp_world_size,
1621
+ device=device,
1622
+ B=B,
1623
+ T=T,
1624
+ ptdtype=ptdtype,
1625
+ grad_accum_steps=grad_accum_steps, # Pass grad accumulation steps to scale loss correctly
1626
+ last_training_update=last_training_update, # Pass the real update captured from training
1627
+ last_training_gradient=last_training_gradient, # Pass the original gradient g_t
1628
+ last_training_batches=last_training_batches # Pass ALL microbatches for consistent HVP
1629
+ )
1630
+ sharpness_log_str = format_comprehensive_results(comprehensive_results)
1631
+
1632
+ # Save sharpness results to file
1633
+ if master_process and run_dir_path:
1634
+ sharpness_file = run_dir_path / f"sharpness_step_{step}.json"
1635
+ with open(sharpness_file, "w") as f:
1636
+ json.dump(comprehensive_results, f, indent=4)
1637
+ print0(f"[Sharpness @ Step {step}] Results saved to {sharpness_file}")
1638
+
1639
+ # Clean up memory after sharpness analysis
1640
+ del comprehensive_results
1641
+ # Ensure all CUDA operations are complete before cleaning up
1642
+ if device == "cuda":
1643
+ torch.cuda.synchronize()
1644
+ torch.cuda.empty_cache()
1645
+ gc.collect()
1646
+ if ddp:
1647
+ dist.barrier() # Sync all ranks after cleanup
1648
+ print0(f"[Step {step}] Memory cleaned up after sharpness analysis")
1649
+
1650
+ # log to console and to file
1651
+ if sharpness_log_str:
1652
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f} | {sharpness_log_str}")
1653
+ else:
1654
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f}")
1655
+
1656
+ if master_process and logfile is not None:
1657
+ with open(logfile, "a") as f:
1658
+ f.write("step:%d validation loss:%f" % (step, val_loss))
1659
+ if sharpness_log_str:
1660
+ f.write(" %s" % sharpness_log_str)
1661
+ f.write("\n")
1662
+
1663
+ # once in a while perform model inference on the master process
1664
+ if (args.sample_every > 0 \
1665
+ and (step % args.sample_every == 0 or last_step)) \
1666
+ and master_process:
1667
+ model.eval()
1668
+ # before we end, let's also do one round of inference
1669
+ # we'll kick off the generation with "<|endoftext|>", which designates the start of a new sequence
1670
+ start_ids = [enc.eot_token]
1671
+ xg = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
1672
+ max_new_tokens = 32
1673
+ temperature = 1.0
1674
+ top_k = 40
1675
+ yg = raw_model.generate(xg, max_new_tokens, temperature=temperature, top_k=top_k)
1676
+ print0('---------------')
1677
+ print0(enc.decode(yg[0].tolist()))
1678
+ print0('---------------')
1679
+
1680
+ # bit confusing: we want to make sure to eval and sample on 0th iteration
1681
+ # but also after the very last iteration. so we loop for step <= num_iterations
1682
+ # instead of just < num_iterations (one extra due to <=), only to do
1683
+ # the validation/sampling one last time, and then we break right here as we're done.
1684
+ if last_step:
1685
+ break
1686
+
1687
+ # --------------- TRAINING SECTION BEGIN -----------------
1688
+ model.train()
1689
+ # Zero gradients for the appropriate optimizer(s)
1690
+
1691
+ for optimizer in optimizers:
1692
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1693
+ optimizer.zero_grad(set_to_none=True)
1694
+ elif isinstance(optimizer, Muon):
1695
+ optimizer.zero_grad()
1696
+ # if args.optimizer == "adam":
1697
+ # optimizer.zero_grad(set_to_none=True)
1698
+ # else: # muon
1699
+ # if muon_optimizer is not None:
1700
+ # muon_optimizer.zero_grad()
1701
+ # if adam_optimizer is not None:
1702
+ # adam_optimizer.zero_grad(set_to_none=True)
1703
+ # if we are trying to overfit a single batch, we reset the loader here
1704
+ if args.overfit_single_batch:
1705
+ train_loader.reset()
1706
+ # micro-batch loop where we do gradient accumulation to reach desired total batch size
1707
+ lossf = 0.0 # for getting the mean loss (as simple float) over the accumulation steps
1708
+
1709
+ # Pre-check if we need to collect microbatches for sharpness analysis
1710
+ next_step = step + 1
1711
+ will_analyze_sharpness_next = args.analyze_sharpness and next_step > 0 and (
1712
+ (next_step % args.sharpness_analysis_interval == 0) or
1713
+ (next_step == args.num_iterations)
1714
+ )
1715
+
1716
+
1717
+ microbatches_this_step = [] if will_analyze_sharpness_next else None
1718
+
1719
+ for micro_step in range(grad_accum_steps):
1720
+ # fetch a batch
1721
+ x, y = train_loader.next_batch()
1722
+ x, y = x.to(device), y.to(device)
1723
+
1724
+ # Store ALL microbatches for memory-efficient HVP calculation
1725
+ if will_analyze_sharpness_next:
1726
+ microbatches_this_step.append((x.detach().clone(), y.detach().clone()))
1727
+
1728
+ if ddp:
1729
+ model.require_backward_grad_sync = (micro_step == grad_accum_steps - 1)
1730
+ # forward pass
1731
+ with ctx:
1732
+ _, loss = model(x, y, return_logits=False)
1733
+ loss = loss / grad_accum_steps
1734
+ lossf += loss.detach() # keep track of the mean loss
1735
+ # backward pass
1736
+ if not args.inference_only:
1737
+ loss.backward()
1738
+ if ddp:
1739
+ dist.all_reduce(lossf, op=dist.ReduceOp.AVG)
1740
+ lossf = lossf.item()
1741
+
1742
+ #no clipping
1743
+ norm = torch.nn.utils.clip_grad_norm_(raw_model_uncompiled.parameters(), args.grad_clip)
1744
+
1745
+
1746
+ if will_analyze_sharpness_next:
1747
+ # Use raw_model_uncompiled's parameter order so it matches sharpness analysis codepaths.
1748
+ # (DDP/torch.compile wrappers can be a footgun if parameter iteration order ever diverges.)
1749
+ print(raw_model_uncompiled.transformer.h[0].attn.q_w.weight[:5,:5])
1750
+ params_before_optimizer_step = [p.detach().clone() for p in raw_model_uncompiled.parameters()]
1751
+ # Save the original gradient g_t that will produce the update v
1752
+ last_training_gradient = [
1753
+ p.grad.detach().clone() if p.grad is not None else torch.zeros_like(p)
1754
+ for p in raw_model_uncompiled.parameters()
1755
+ ]
1756
+ # Capture ALL microbatches for consistent HVP calculation
1757
+ # This ensures H is computed on the exact same objective as g_t and v
1758
+ last_training_batches = microbatches_this_step # Already cloned above
1759
+ else:
1760
+ params_before_optimizer_step = None
1761
+ last_training_batches = None
1762
+
1763
+ # Update learning rate and step optimizers
1764
+ for optimizer in optimizers:
1765
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1766
+ adam_lr = get_wsd_lr(step,args.adam_lr)
1767
+ for param_group in optimizer.param_groups:
1768
+ param_group['lr'] = adam_lr
1769
+ optimizer.step()
1770
+ elif isinstance(optimizer, Muon):
1771
+ muon_lr = get_wsd_lr(step,args.muon_lr)
1772
+ for param_group in optimizer.param_groups:
1773
+ param_group['lr'] = muon_lr
1774
+ optimizer.step()
1775
+ else:
1776
+ raise ValueError(f"Unsupported optimizer: {type(optimizer)}")
1777
+
1778
+
1779
+ if params_before_optimizer_step is not None:
1780
+ # Clean up old update to save memory
1781
+ if last_training_update is not None:
1782
+ del last_training_update
1783
+
1784
+ last_training_update = [
1785
+ p.detach() - p_before
1786
+ for p_before, p in zip(params_before_optimizer_step, raw_model_uncompiled.parameters())
1787
+ ]
1788
+ del params_before_optimizer_step
1789
+
1790
+ # --------------- TRAINING SECTION END -------------------
1791
+
1792
+ # wait on the CPU for all device work to end so we get accurate per-iteration timings below
1793
+ if device == "mps":
1794
+ torch.mps.synchronize()
1795
+ elif device == "cuda":
1796
+ torch.cuda.synchronize()
1797
+ # time and print
1798
+ t1 = time.time()
1799
+ # the 0th iteration is often an outlier (much slower) => skip logging it
1800
+ tokens_per_second = grad_accum_steps * ddp_world_size * B * T / (t1-t0)
1801
+ print0(f"step {step+1:4d}/{args.num_iterations} | train loss {lossf:.6f} | norm {norm:.4f} | ({(t1-t0)*1000:.2f} ms | {tokens_per_second:.0f} tok/s)")
1802
+ # log to logile
1803
+ if master_process and logfile is not None:
1804
+ with open(logfile, "a") as f:
1805
+ f.write("step:%d train loss:%f\n" % (step, lossf))
1806
+
1807
+ # keep track of smooth timings, last 20 iterations
1808
+ if step > 0 and step > args.num_iterations - 20:
1809
+ timings.append(t1-t0)
1810
+
1811
+ # print the average of the last 20 timings, to get something smooth-ish
1812
+ timings = timings[-20:]
1813
+ print0(f"final {len(timings)} iters avg: {np.mean(timings)*1000:.3f}ms")
1814
+ print0(f"peak memory consumption: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB")
1815
+
1816
+ # -------------------------------------------------------------------------
1817
+ # clean up nice
1818
+ if ddp:
1819
+ destroy_process_group()step:0 validation loss:11.020914
1820
+ step:0 train loss:11.018947
1821
+ step:1 train loss:11.015901
1822
+ step:2 train loss:11.001139
1823
+ step:3 train loss:10.974218
1824
+ step:4 train loss:10.947017
1825
+ step:5 train loss:10.921179
1826
+ step:6 train loss:10.861053
1827
+ step:7 train loss:10.812024
1828
+ step:8 train loss:10.757435
1829
+ step:9 train loss:10.703061
1830
+ step:10 train loss:10.627495
1831
+ step:11 train loss:10.570812
1832
+ step:12 train loss:10.518988
1833
+ step:13 train loss:10.450851
1834
+ step:14 train loss:10.389409
1835
+ step:15 train loss:10.324161
1836
+ step:16 train loss:10.293379
1837
+ step:17 train loss:10.256920
1838
+ step:18 train loss:10.199411
1839
+ step:19 train loss:10.153182
1840
+ step:20 train loss:10.085126
1841
+ step:21 train loss:10.072214
1842
+ step:22 train loss:10.032795
1843
+ step:23 train loss:9.983107
1844
+ step:24 train loss:9.939043
1845
+ step:25 train loss:9.952696
1846
+ step:26 train loss:9.890882
1847
+ step:27 train loss:9.873850
1848
+ step:28 train loss:9.837166
1849
+ step:29 train loss:9.804578
1850
+ step:30 train loss:9.789116
1851
+ step:31 train loss:9.762375
1852
+ step:32 train loss:9.722699
1853
+ step:33 train loss:9.734813
1854
+ step:34 train loss:9.722623
1855
+ step:35 train loss:9.703139
1856
+ step:36 train loss:9.685809
1857
+ step:37 train loss:9.658072
1858
+ step:38 train loss:9.661681
1859
+ step:39 train loss:9.631407
1860
+ step:40 train loss:9.609830
1861
+ step:41 train loss:9.626093
1862
+ step:42 train loss:9.632925
1863
+ step:43 train loss:9.592793
1864
+ step:44 train loss:9.580933
1865
+ step:45 train loss:9.595030
1866
+ step:46 train loss:9.563819
1867
+ step:47 train loss:9.542810
1868
+ step:48 train loss:9.543258
1869
+ step:49 train loss:9.526043
1870
+ step:50 train loss:9.511073
1871
+ step:51 train loss:9.493608
1872
+ step:52 train loss:9.483408
1873
+ step:53 train loss:9.484899
1874
+ step:54 train loss:9.470613
1875
+ step:55 train loss:9.465339
1876
+ step:56 train loss:9.434980
1877
+ step:57 train loss:9.422531
1878
+ step:58 train loss:9.431874
1879
+ step:59 train loss:9.385880
1880
+ step:60 train loss:9.388974
1881
+ step:61 train loss:9.419999
1882
+ step:62 train loss:9.358437
1883
+ step:63 train loss:9.337664
1884
+ step:64 train loss:9.336971
1885
+ step:65 train loss:9.322704
1886
+ step:66 train loss:9.252651
1887
+ step:67 train loss:9.313890
1888
+ step:68 train loss:9.279621
1889
+ step:69 train loss:9.212382
1890
+ step:70 train loss:9.240768
1891
+ step:71 train loss:9.234261
1892
+ step:72 train loss:9.163614
1893
+ step:73 train loss:9.146738
1894
+ step:74 train loss:9.177152
1895
+ step:75 train loss:9.150363
1896
+ step:76 train loss:9.106675
1897
+ step:77 train loss:9.146784
1898
+ step:78 train loss:9.107823
1899
+ step:79 train loss:9.082148
1900
+ step:80 train loss:9.059367
1901
+ step:81 train loss:9.079405
1902
+ step:82 train loss:9.099257
1903
+ step:83 train loss:9.031517
1904
+ step:84 train loss:9.043550
1905
+ step:85 train loss:9.016241
1906
+ step:86 train loss:8.968640
1907
+ step:87 train loss:8.988386
1908
+ step:88 train loss:8.979951
1909
+ step:89 train loss:8.933968
1910
+ step:90 train loss:8.959427
1911
+ step:91 train loss:8.941217
1912
+ step:92 train loss:8.921014
1913
+ step:93 train loss:8.867045
1914
+ step:94 train loss:8.873112
1915
+ step:95 train loss:8.868813
1916
+ step:96 train loss:8.847641
1917
+ step:97 train loss:8.841789
1918
+ step:98 train loss:8.850140
1919
+ step:99 train loss:8.791707
1920
+ step:100 train loss:8.756621
1921
+ step:101 train loss:8.784798
1922
+ step:102 train loss:8.775515
1923
+ step:103 train loss:8.782326
1924
+ step:104 train loss:8.687901
1925
+ step:105 train loss:8.757630
1926
+ step:106 train loss:8.700429
1927
+ step:107 train loss:8.685413
1928
+ step:108 train loss:8.628991
1929
+ step:109 train loss:8.796276
1930
+ step:110 train loss:8.646223
1931
+ step:111 train loss:8.637555
1932
+ step:112 train loss:8.621561
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0002,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "8b654986-1317-48b5-9e08-c1064a25bd30",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0002,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "844818d1-11a7-4b2f-9276-af4502cf3ab0",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0002_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0005,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "35307a01-6527-4f49-8de1-26bf220d63a5",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_42/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0005,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "0ebf0760-8c51-44f3-8325-aed663a64a9c",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.0005,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "95c102cc-02c4-4501-8021-b8881b637d8c",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.0005_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.001,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "243865af-2ce2-43f3-8609-4742cef9ebe0",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_42/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.001,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "6347f5e5-e9d1-445c-aeb1-8231b5c874aa",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.001,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "1aa19b22-d653-4300-a823-9aed4bcc29d2",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.001_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.002,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "158aab84-4c15-43a1-b32b-e91df5d7b08c",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_42/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.002,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "90d01ca9-df46-40ad-a3e5-b6f274313dd1",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.002,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "8b031d99-ab22-4c6c-ba27-d51289e64de3",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.002_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.005,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "dc7eaf93-71ea-4340-b7cb-7436b55e754d",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_42/training_log.txt ADDED
@@ -0,0 +1,1819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reference code for GPT-2 training and inference with Sharpness Analysis.
3
+ Will save the model weights into files, to be read from C as initialization.
4
+
5
+ References:
6
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
7
+ https://github.com/openai/gpt-2/blob/master/src/model.py
8
+ 2) huggingface/transformers PyTorch implementation:
9
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
10
+
11
+ Example launches to only benchmark the speed of bfloat16 compiled GPU training:
12
+ 1 GPU:
13
+ python train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
14
+ you can also turn on flash-attention by appending --flash=1
15
+ 4 GPU:
16
+ torchrun --standalone --nproc_per_node=4 train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
17
+ """
18
+ import sys
19
+ with open(sys.argv[0]) as f:
20
+ code = f.read() # read the code of this file ASAP, for logging
21
+
22
+ import os
23
+ import math
24
+ import glob
25
+ import struct
26
+ import inspect
27
+ from contextlib import nullcontext
28
+ from dataclasses import dataclass
29
+ import random
30
+
31
+ import numpy as np
32
+ import torch
33
+ from torch import Tensor
34
+ import torch.nn as nn
35
+ from torch.nn import functional as F
36
+ import torch._inductor.config as config
37
+ from torch.nn.parallel import DistributedDataParallel as DDP
38
+ from torch.distributed import init_process_group, destroy_process_group
39
+ from torch.distributed.optim import ZeroRedundancyOptimizer
40
+ import torch.distributed as dist
41
+ from torch.amp import autocast
42
+ import copy
43
+ import gc
44
+ import uuid
45
+ import json
46
+ from pathlib import Path
47
+
48
+ # Import Muon optimizer
49
+ import sys
50
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/optimizers")
51
+ from MUON_fix import Muon
52
+
53
+ # Import GPT model
54
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/models")
55
+ import nano_GPT_qkvonorm_pure
56
+ from nano_GPT_qkvonorm_pure import GPT, GPTConfig
57
+
58
+ # Import debug utilities
59
+ # from debug_utils import setup_debugpy
60
+
61
+ # -----------------------------------------------------------------------------
62
+ # Our own simple Distributed Data Loader
63
+
64
+ def _peek_data_shard(filename):
65
+ # only reads the header, returns header data
66
+ with open(filename, "rb") as f:
67
+ # first read the header, which is 256 int32 integers (4 bytes each)
68
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
69
+ if header[0] != 20240520:
70
+ print("ERROR: magic number mismatch in the data .bin file!")
71
+ print("---> HINT: Are you passing in a correct file with --input_bin?")
72
+ print("---> HINT: Dataset encoding changed recently, re-run data prepro or refer again to README")
73
+ print("---> HINT: For example re-run: `python dev/data/tinyshakespeare.py`, then re-try")
74
+ exit(1)
75
+ assert header[1] == 1, "unsupported version"
76
+ ntok = header[2] # number of tokens (claimed)
77
+ return ntok # for now just return the number of tokens
78
+
79
+ def _load_data_shard(filename):
80
+ with open(filename, "rb") as f:
81
+ # first read the header, which is 256 int32 integers (4 bytes each)
82
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
83
+ assert header[0] == 20240520, "magic number mismatch in the data .bin file"
84
+ assert header[1] == 1, "unsupported version"
85
+ ntok = header[2] # number of tokens (claimed)
86
+ # the rest of it are tokens, stored as uint16
87
+ tokens = np.frombuffer(f.read(), dtype=np.uint16)
88
+ assert len(tokens) == ntok, "number of tokens read does not match header?"
89
+ return tokens
90
+
91
+ class DistributedDataLoader:
92
+ def __init__(self, filename_pattern, B, T, process_rank, num_processes,
93
+ shuffle_files=False, random_seed=None):
94
+ self.process_rank = process_rank
95
+ self.num_processes = num_processes
96
+ self.B = B
97
+ self.T = T
98
+ self.shuffle_files = shuffle_files
99
+ self.random_seed = random_seed
100
+ self._rng = random.Random(random_seed) if shuffle_files and random_seed is not None else None
101
+
102
+ # glob files that match the pattern
103
+ self.files = sorted(glob.glob(filename_pattern))
104
+ assert len(self.files) > 0, f"did not find any files that match the pattern {filename_pattern}"
105
+ if self.shuffle_files:
106
+ self._shuffle_files()
107
+
108
+ # load and validate all data shards, count number of tokens in total
109
+ ntok_total = 0
110
+ for fname in self.files:
111
+ shard_ntok = _peek_data_shard(fname)
112
+ assert shard_ntok >= num_processes * B * T + 1
113
+ ntok_total += shard_ntok
114
+ self.ntok_total = ntok_total
115
+ print0(f"DataLoader: total number of tokens: {ntok_total:,} across {len(self.files)} files")
116
+
117
+ # kick things off
118
+ self.current_shard = None
119
+ self.reset()
120
+
121
+ def reset(self):
122
+ # we're being a bit clever here: if we already had shard 0 loaded,
123
+ # then don't do the work to reload it, just reset the pointer
124
+ if self.current_shard != 0:
125
+ self.current_shard = 0
126
+ self.tokens = _load_data_shard(self.files[self.current_shard])
127
+ self.current_position = self.process_rank * self.B * self.T
128
+
129
+ def advance(self): # advance to next data shard
130
+ next_shard = (self.current_shard + 1) % len(self.files)
131
+ if next_shard == 0 and self.shuffle_files:
132
+ self._shuffle_files()
133
+ self.current_shard = next_shard
134
+ self.current_position = self.process_rank * self.B * self.T
135
+ self.tokens = _load_data_shard(self.files[self.current_shard])
136
+
137
+ def next_batch(self):
138
+ B = self.B
139
+ T = self.T
140
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
141
+ buf = torch.tensor(buf.astype(np.int32), dtype=torch.long)
142
+ x = (buf[:-1]).view(B, T) # inputs
143
+ y = (buf[1:]).view(B, T) # targets
144
+ # advance the start pointer in current shard
145
+ self.current_position += B * T * self.num_processes
146
+ # if loading the next batch would be out of bounds advance the shard
147
+ if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
148
+ self.advance()
149
+ return x, y
150
+
151
+ def _shuffle_files(self):
152
+ if self._rng is not None:
153
+ self._rng.shuffle(self.files)
154
+ else:
155
+ random.shuffle(self.files)
156
+
157
+ # -----------------------------------------------------------------------------
158
+ # Python -> C bridge utilities for saving params/grads/activations to .bin files
159
+
160
+ def write_fp32(tensor, file):
161
+ t = tensor.detach().cpu().to(torch.float32)
162
+ b = t.numpy().tobytes()
163
+ file.write(b)
164
+
165
+ def write_bf16(tensor, file):
166
+ t = tensor.detach().cpu().to(torch.bfloat16)
167
+ # numpy doesn't have bf16 datatype so we have to trick it
168
+ t = t.view(torch.int16) # trick: reinterpret as int16
169
+ b = t.numpy().tobytes()
170
+ file.write(b)
171
+
172
+ def write_tensors(model_tensors, L, file, dtype):
173
+ # writes the GPT-2 model's weights to a binary file
174
+ assert dtype in {"float32", "bfloat16"}
175
+ write_fun = write_fp32 if dtype == "float32" else write_bf16
176
+ write_fun(model_tensors["transformer.wte.weight"], file) # (V, C)
177
+ write_fun(model_tensors["transformer.wpe.weight"], file) # (T, C)
178
+ for i in range(L): # (L, C)
179
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.weight"], file)
180
+ for i in range(L): # (L, C)
181
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.bias"], file)
182
+ for i in range(L): # (L, 3C, C)
183
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.weight"], file)
184
+ for i in range(L): # (L, 3C)
185
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.bias"], file)
186
+ for i in range(L): # (L, C, C)
187
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.weight"], file)
188
+ for i in range(L): # (L, C)
189
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.bias"], file)
190
+ for i in range(L): # (L, C)
191
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.weight"], file)
192
+ for i in range(L): # (L, C)
193
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.bias"], file)
194
+ for i in range(L): # (L, 4C, C)
195
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.weight"], file)
196
+ for i in range(L): # (L, 4C)
197
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.bias"], file)
198
+ for i in range(L): # (L, C, 4C)
199
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.weight"], file)
200
+ for i in range(L): # (L, C)
201
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.bias"], file)
202
+ write_fun(model_tensors["transformer.ln_f.weight"], file) # (C, )
203
+ write_fun(model_tensors["transformer.ln_f.bias"], file) # (C, )
204
+
205
+ @torch.no_grad()
206
+ def pad_vocab(tensor, multiple=128, value=0):
207
+ """
208
+ The dimension of the vocab size in GPT-2 is 50,257
209
+ which is unfortunately a very unfriendly number for a lot of
210
+ matrix operations on the GPU. So we pad it to the nearest
211
+ friendlier multiple, e.g. 50,304 if multiple=128 when we
212
+ export the weights into C land. This is a NOOP algorithmically
213
+ and is only done to make the tensor operations more efficient.
214
+ """
215
+ assert tensor.ndim == 2
216
+ V, C = tensor.shape
217
+ assert V == 50257, "just being defensive here"
218
+ # calculate padded vocab size by rounding up to nearest multiple
219
+ Vp = ((V + multiple - 1) // multiple) * multiple
220
+ # pad the tensor
221
+ pad_rows = Vp - V
222
+ padded = tensor if pad_rows == 0 else F.pad(tensor, (0, 0, 0, pad_rows), value=value)
223
+ assert padded.shape == (Vp, C)
224
+ return padded
225
+
226
+ def write_model(model, filename, dtype):
227
+ # everything we need to instantiate the model
228
+ # 1) header is: version int, GPTConfig ints, padding to 1024 bytes
229
+ assert dtype in {"float32", "bfloat16"} # float16 todo maybe later
230
+ version = {
231
+ "float32": 3, # 3: all tensors are fp32, padded vocab
232
+ "bfloat16": 5, # 5: all tensors are bf16, padded vocab
233
+ }[dtype]
234
+ header = torch.zeros(256, dtype=torch.int32)
235
+ header[0] = 20240326 # magic
236
+ header[1] = version # checkpoint version
237
+ header[2] = model.config.block_size
238
+ header[3] = model.config.vocab_size
239
+ header[4] = model.config.n_layer
240
+ header[5] = model.config.n_head
241
+ header[6] = model.config.n_embd
242
+ # 2) the parameters follow the header
243
+ params = {name: param.cpu() for name, param in model.named_parameters()}
244
+ # pad the vocab to a multiple of 128 here at export, for efficiency in C
245
+ wte = params["transformer.wte.weight"] # (V, C)
246
+ wte_padded = pad_vocab(wte) # (Vp, C)
247
+ params["transformer.wte.weight"] = wte_padded # (Vp, C)
248
+ print(f"padded vocab size from {wte.size(0)} to {wte_padded.size(0)}")
249
+ header[7] = wte_padded.size(0) # padded vocab size store in header
250
+ # now write to file
251
+ with open(filename, "wb") as file:
252
+ file.write(header.numpy().tobytes()) # header
253
+ write_tensors(params, model.config.n_layer, file, dtype) # params
254
+ print(f"wrote {filename}")
255
+
256
+ def write_state(model, x, y, logits, loss, filename):
257
+ # the state is used for debugging.
258
+ # it contains information about the input, logits, loss, and the parameter gradients
259
+ # this can be used for checking the computation correctness in C
260
+ header = torch.zeros(256, dtype=torch.int32)
261
+ header[0] = 20240327 # magic
262
+ header[1] = 2 # run state version = 2 (1 -> 2 for padded vocab changes)
263
+ header[2] = x.size(0) # batch size of the batch, B
264
+ header[3] = x.size(1) # temporal extent of the batch, T
265
+ grads = {name: param.grad.cpu() for name, param in model.named_parameters()}
266
+ # pad the vocab grads here as well, to mirror write_model
267
+ wte_grad = grads["transformer.wte.weight"] # (V, C)
268
+ wte_grad_padded = pad_vocab(wte_grad, value=0) # (Vp, C) # TODO later maybe pad with nan?
269
+ grads["transformer.wte.weight"] = wte_grad_padded # (Vp, C)
270
+ print(f"padded vocab size in reference grads from {wte_grad.size(0)} to {wte_grad_padded.size(0)}")
271
+ with open(filename, "wb") as file:
272
+ # header
273
+ file.write(header.numpy().tobytes())
274
+ # input x
275
+ file.write(x.cpu().numpy().astype("int32").tobytes()) # (B, T)
276
+ # targets y
277
+ file.write(y.cpu().numpy().astype("int32").tobytes()) # (B, T)
278
+ # logits (result of the model forward pass)
279
+ write_fp32(logits.cpu(), file)
280
+ # loss (single float, result of the cross entropy loss)
281
+ write_fp32(loss.cpu(), file)
282
+ # gradients
283
+ write_tensors(grads, model.config.n_layer, file, "float32")
284
+ print(f"wrote {filename}")
285
+
286
+ def write_tokenizer(enc, filename):
287
+ n = enc.max_token_value + 1
288
+ header = torch.zeros(256, dtype=torch.int32)
289
+ header[0] = 20240328 # magic
290
+ header[1] = 2 # tokenizer version = 2 (1 -> 2: includes EOT token)
291
+ header[2] = n # number of tokens
292
+ header[3] = enc.eot_token # EOT token
293
+ with open(filename, "wb") as file:
294
+ file.write(header.numpy().tobytes())
295
+ for i in range(n):
296
+ b = enc.decode_bytes([i])
297
+ length = len(b)
298
+ assert length < 256, f"Token length exceeds 255: {length}"
299
+ file.write(struct.pack("<B", length)) # Write the length as a 1-byte unsigned integer
300
+ file.write(b) # Write the actual bytes
301
+ print(f"wrote {filename}")
302
+
303
+ def set_seed(seed):
304
+ random.seed(seed)
305
+ np.random.seed(seed)
306
+ torch.manual_seed(seed)
307
+ if torch.cuda.is_available():
308
+ torch.cuda.manual_seed_all(seed)
309
+ print(f"PRINT: Set seed to {seed}", flush=True) # Print immediately for all ranks
310
+
311
+ # -----------------------------------------------------------------------------
312
+ # Helper functions for norm calculations
313
+
314
+ def calculate_l1_to_linf_norm(matrix):
315
+ if matrix.ndim == 1:
316
+ return torch.sum(torch.abs(matrix))
317
+ elif matrix.ndim == 2:
318
+ # Each row's L1 norm, then take maximum
319
+ row_l1_norms = torch.sum(torch.abs(matrix), dim=1)
320
+ return torch.max(row_l1_norms)
321
+ else:
322
+ # For higher-dimensional tensors, flatten to 2D
323
+ matrix_2d = matrix.view(matrix.shape[0], -1)
324
+ row_l1_norms = torch.sum(torch.abs(matrix_2d), dim=1)
325
+ return torch.max(row_l1_norms)
326
+
327
+ def calculate_spectral_norm(matrix):
328
+ """
329
+ Calculate the spectral norm (largest singular value) of a matrix.
330
+ For vectors, returns the L2 norm.
331
+ """
332
+ # Convert to float32 if needed for linalg operations
333
+ if matrix.dtype in [torch.bfloat16, torch.float16]:
334
+ matrix = matrix.float()
335
+
336
+ if matrix.ndim == 1:
337
+ return torch.norm(matrix, p=2)
338
+ elif matrix.ndim == 2:
339
+ # Use matrix 2-norm (largest singular value)
340
+ return torch.linalg.matrix_norm(matrix, ord=2)
341
+ else:
342
+ # For higher-dimensional tensors, flatten to 2D
343
+ matrix_2d = matrix.view(matrix.shape[0], -1)
344
+ return torch.linalg.matrix_norm(matrix_2d, ord=2)
345
+
346
+ # -----------------------------------------------------------------------------
347
+ # Comprehensive sharpness analysis function
348
+
349
+ def calculate_comprehensive_sharpness(model, model_for_forward, optimizers, step, train_loader, val_loader,
350
+ rank, world_size, device, B, T, ptdtype, grad_accum_steps, last_training_update=None, last_training_gradient=None, last_training_batches=None):
351
+ prev_training_mode = model.training
352
+ model.eval()
353
+
354
+ NUM_LAYERS = model.config.n_layer # Number of transformer blocks
355
+ analysis_results = {}
356
+
357
+ # --- 1. Get the true update direction 'v' ---
358
+ assert last_training_update is not None, \
359
+ f"[Step {step}] BUG: last_training_update is None! Check sharpness timing logic."
360
+
361
+ print0(f"[Enhanced Sharpness @ Step {step}] Using update from previous training step")
362
+ update_direction_v = last_training_update
363
+
364
+
365
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters to θ_t for HVP calculation...")
366
+ with torch.no_grad():
367
+ for p, v in zip(model.parameters(), update_direction_v):
368
+ p.data.sub_(v) # Now parameters are at θ_t
369
+
370
+ # --- 2. Calculate update norms (Frobenius, Max-of-Max, Spectral) ---
371
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating update norms...")
372
+
373
+ total_update_norm_sq = sum(torch.sum(v * v) for v in update_direction_v)
374
+ dist.all_reduce(total_update_norm_sq, op=dist.ReduceOp.AVG)
375
+ analysis_results["total_update_fnorm"] = torch.sqrt(total_update_norm_sq).item()
376
+
377
+ # Calculate TOTAL update Max-of-Max and Spectral norms
378
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating total update Max-of-Max and Spectral norms...")
379
+ try:
380
+ all_updates_flat = torch.cat([v.flatten() for v in update_direction_v if v.numel() > 0])
381
+
382
+ if all_updates_flat.numel() > 0:
383
+ total_l1_linf_norm = torch.sum(torch.abs(all_updates_flat))
384
+ analysis_results["total_l1_linf_norm"] = total_l1_linf_norm.item()
385
+
386
+ total_spectral_norm = torch.norm(all_updates_flat, p=2)
387
+ analysis_results["total_spectral_norm"] = total_spectral_norm.item()
388
+ else:
389
+ analysis_results["total_l1_linf_norm"] = 0.0
390
+ analysis_results["total_spectral_norm"] = 0.0
391
+
392
+ del all_updates_flat
393
+ except Exception as e:
394
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating total norms: {e}")
395
+ analysis_results["total_l1_linf_norm"] = 0.0
396
+ analysis_results["total_spectral_norm"] = 0.0
397
+
398
+ # --- 3. Setup layer parameter groups (adapt to new model structure) ---
399
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up layer parameter groups...")
400
+
401
+ all_param_groups = {}
402
+
403
+
404
+ all_param_groups["embed_lm_head"] = list(model.lm_head.parameters())
405
+
406
+ blocks = model.transformer.h
407
+
408
+ for i, block in enumerate(blocks):
409
+ layer_name = f"layer_{i+1}"
410
+ all_param_groups[layer_name] = list(block.parameters())
411
+
412
+ # Add fine-grained params for selected layers (0, 3, 7, 11)
413
+ selected_layers = [0, 3, 7, 11]
414
+ for layer_idx in selected_layers:
415
+ block = blocks[layer_idx]
416
+ prefix = f"block{layer_idx}"
417
+ # Attention: Q, K, V, O
418
+ all_param_groups[f"{prefix}_q"] = [block.attn.q_w.weight]
419
+ all_param_groups[f"{prefix}_k"] = [block.attn.k_w.weight]
420
+ all_param_groups[f"{prefix}_v"] = [block.attn.v_w.weight]
421
+ all_param_groups[f"{prefix}_o"] = [block.attn.c_proj.weight]
422
+ # MLP: c_fc (win) and c_proj (wout)
423
+ all_param_groups[f"{prefix}_mlp_win"] = [block.mlp.c_fc.weight]
424
+ all_param_groups[f"{prefix}_mlp_wout"] = [block.mlp.c_proj.weight]
425
+
426
+ # --- 4. Calculate layer-wise update norms ---
427
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise update norms...")
428
+
429
+ param_to_idx = {id(p): i for i, p in enumerate(model.parameters())}
430
+
431
+ for group_name, param_group in all_param_groups.items():
432
+ if not param_group:
433
+ continue
434
+
435
+ # Get indices for this group
436
+ indices = [param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx]
437
+ if not indices:
438
+ continue
439
+
440
+ # Calculate Frobenius norm for this group
441
+ group_update_norm_sq = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
442
+ dist.all_reduce(group_update_norm_sq, op=dist.ReduceOp.AVG)
443
+ analysis_results[f"{group_name}_update_fnorm"] = torch.sqrt(group_update_norm_sq).item()
444
+
445
+ # Calculate Max-of-Max and Spectral norms for this group
446
+ group_l1_linf_norms = []
447
+ group_spectral_norms = []
448
+
449
+ for i in indices:
450
+ if i < len(update_direction_v) and update_direction_v[i].numel() > 0:
451
+ try:
452
+ l1_linf_norm = calculate_l1_to_linf_norm(update_direction_v[i])
453
+ group_l1_linf_norms.append(l1_linf_norm.item())
454
+
455
+ spectral_norm = calculate_spectral_norm(update_direction_v[i])
456
+ group_spectral_norms.append(spectral_norm.item())
457
+ except Exception as e:
458
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating norms for group {group_name}, param {i}: {e}")
459
+ group_l1_linf_norms.append(0.0)
460
+ group_spectral_norms.append(0.0)
461
+
462
+ if group_l1_linf_norms:
463
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = max(group_l1_linf_norms)
464
+ else:
465
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = 0.0
466
+
467
+ if group_spectral_norms:
468
+ analysis_results[f"{group_name}_max_spectral_norm"] = max(group_spectral_norms)
469
+ else:
470
+ analysis_results[f"{group_name}_max_spectral_norm"] = 0.0
471
+
472
+ # --- 5. Setup for HVP calculation on TRAIN data ---
473
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up HVP calculation in {ptdtype} on TRAIN data...")
474
+
475
+ original_flash = nano_GPT_qkvonorm_pure.FLASH
476
+ nano_GPT_qkvonorm_pure.FLASH = 0
477
+ print0(f"[Enhanced Sharpness @ Step {step}] Disabled FLASH attention for HVP (was {original_flash})")
478
+
479
+ # Get block parameter indices for cross-layer analysis (need this before loop)
480
+ block_param_indices = set()
481
+ for group_name, param_group in all_param_groups.items():
482
+ if group_name.startswith("layer_"):
483
+ for p in param_group:
484
+ if id(p) in param_to_idx:
485
+ block_param_indices.add(param_to_idx[id(p)])
486
+
487
+ # Initialize accumulators for all quantities we need
488
+ grads_hvp = None
489
+ hvp_v_total = None
490
+ hvp_v_block = None
491
+ hvp_g_accum = None
492
+ layer_hvp_accum = {}
493
+
494
+
495
+ group_names_to_process = [gn for gn, pg in all_param_groups.items()
496
+ if pg and any(id(p) in param_to_idx for p in pg)]
497
+
498
+ if last_training_batches is not None and len(last_training_batches) > 0:
499
+
500
+ batch_iterator = [(x, y) for x, y in last_training_batches]
501
+ n_batches = len(batch_iterator)
502
+ print0(f"[Enhanced Sharpness @ Step {step}] Using {n_batches} microbatches for HVP (out of {grad_accum_steps} training microbatches)")
503
+ restore_loader = False
504
+ else:
505
+ # Fallback: use new batches from train_loader (should rarely happen)
506
+ print0(f"[Enhanced Sharpness @ Step {step}] WARNING: last_training_batches is None/empty, using {grad_accum_steps} new batches (inconsistent)")
507
+ saved_current_shard = train_loader.current_shard
508
+ saved_current_position = train_loader.current_position
509
+ n_batches = grad_accum_steps # Use same number as training for consistency
510
+ batch_iterator = []
511
+ shard_was_changed = False
512
+ for _ in range(n_batches):
513
+ x_hvp, y_hvp = train_loader.next_batch()
514
+ batch_iterator.append((x_hvp, y_hvp))
515
+ shard_was_changed = shard_was_changed or (train_loader.current_shard != saved_current_shard)
516
+ restore_loader = True
517
+
518
+
519
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing HVPs for {n_batches} microbatches")
520
+ for mb_idx, (x_hvp, y_hvp) in enumerate(batch_iterator):
521
+ x_hvp, y_hvp = x_hvp.to(device), y_hvp.to(device)
522
+
523
+
524
+ _, loss_mb = model(x_hvp, y_hvp, return_logits=False)
525
+ grads_mb = torch.autograd.grad(loss_mb, model.parameters(), create_graph=True, allow_unused=True)
526
+
527
+ # Compute H·v (total sharpness)
528
+ v_dot_g_total = sum(torch.sum(g * v) for g, v in zip(grads_mb, update_direction_v) if g is not None)
529
+
530
+ if not isinstance(v_dot_g_total, torch.Tensor):
531
+ v_dot_g_total = torch.tensor(0.0, device=device, requires_grad=True)
532
+ hvp_v_total_mb = torch.autograd.grad(v_dot_g_total, model.parameters(), retain_graph=True, allow_unused=True)
533
+
534
+ # Compute H·v_block (block-only sharpness)
535
+ if block_param_indices:
536
+ v_dot_g_block = sum(torch.sum(grads_mb[i] * update_direction_v[i])
537
+ for i in block_param_indices if grads_mb[i] is not None)
538
+ if not isinstance(v_dot_g_block, torch.Tensor):
539
+ v_dot_g_block = torch.tensor(0.0, device=device, requires_grad=True)
540
+ hvp_v_block_mb = torch.autograd.grad(v_dot_g_block, model.parameters(), retain_graph=True, allow_unused=True)
541
+ else:
542
+
543
+ hvp_v_block_mb = [None] * len(list(model.parameters()))
544
+
545
+
546
+ g_dot_g = sum(torch.sum(g * g) for g in grads_mb if g is not None)
547
+ if not isinstance(g_dot_g, torch.Tensor):
548
+ g_dot_g = torch.tensor(0.0, device=device, requires_grad=True)
549
+
550
+
551
+ hvp_g_mb_raw = torch.autograd.grad(g_dot_g, model.parameters(),
552
+ retain_graph=True, allow_unused=True)
553
+ hvp_g_mb = [h / 2.0 if h is not None else None for h in hvp_g_mb_raw]
554
+
555
+ # Compute per-layer H_kk·v_k (for layer-wise sharpness)
556
+ for group_idx, group_name in enumerate(group_names_to_process):
557
+ param_group = all_param_groups[group_name]
558
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
559
+ if not indices:
560
+ continue
561
+
562
+ is_last_layer = (group_idx == len(group_names_to_process) - 1)
563
+ is_last_microbatch = (mb_idx == n_batches - 1)
564
+ need_retain = not (is_last_layer and is_last_microbatch)
565
+
566
+ try:
567
+ v_dot_g_layer = sum(torch.sum(grads_mb[i] * update_direction_v[i])
568
+ for i in indices if grads_mb[i] is not None)
569
+
570
+ if not isinstance(v_dot_g_layer, torch.Tensor):
571
+ v_dot_g_layer = torch.tensor(0.0, device=device, requires_grad=True)
572
+
573
+ hvp_layer_mb = torch.autograd.grad(v_dot_g_layer, model.parameters(),
574
+ retain_graph=need_retain,
575
+ allow_unused=True)
576
+
577
+ if group_name not in layer_hvp_accum:
578
+ layer_hvp_accum[group_name] = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_layer_mb]
579
+ else:
580
+ layer_hvp_accum[group_name] = [
581
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
582
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
583
+ for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
584
+ ]
585
+
586
+ # Accumulate layer HVP
587
+ # if group_name not in layer_hvp_accum:
588
+ # layer_hvp_accum[group_name] = [h.detach() / n_batches if h is not None else None for h in hvp_layer_mb]
589
+ # else:
590
+ # layer_hvp_accum[group_name] = [
591
+ # (h_acc + h.detach() / n_batches) if (h is not None and h_acc is not None)
592
+ # else (h.detach() / n_batches if h is not None else h_acc)
593
+ # for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
594
+ # ]
595
+ # del hvp_layer_mb, v_dot_g_layer
596
+ # torch.cuda.empty_cache()
597
+ except Exception as e:
598
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing layer HVP for '{group_name}' in microbatch {mb_idx}: {e}")
599
+ if group_name not in layer_hvp_accum:
600
+ layer_hvp_accum[group_name] = None
601
+
602
+ # 6. Accumulate all quantities
603
+ if grads_hvp is None:
604
+ grads_hvp = [(g.detach() / n_batches).cpu() if g is not None else None for g in grads_mb]
605
+ hvp_v_total = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_total_mb]
606
+ hvp_v_block = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_block_mb]
607
+ hvp_g_accum = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_g_mb]
608
+ else:
609
+ grads_hvp = [
610
+ (g_acc + (g.detach() / n_batches).cpu()) if (g is not None and g_acc is not None)
611
+ else ((g.detach() / n_batches).cpu() if g is not None else g_acc)
612
+ for g_acc, g in zip(grads_hvp, grads_mb)
613
+ ]
614
+ hvp_v_total = [
615
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
616
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
617
+ for h_acc, h in zip(hvp_v_total, hvp_v_total_mb)
618
+ ]
619
+ hvp_v_block = [
620
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
621
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
622
+ for h_acc, h in zip(hvp_v_block, hvp_v_block_mb)
623
+ ]
624
+ hvp_g_accum = [
625
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
626
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
627
+ for h_acc, h in zip(hvp_g_accum, hvp_g_mb)
628
+ ]
629
+
630
+
631
+
632
+ if mb_idx % max(1, n_batches // 4) == 0:
633
+ print0(f"[Enhanced Sharpness @ Step {step}] Processed microbatch {mb_idx + 1}/{n_batches}")
634
+
635
+
636
+ if restore_loader:
637
+ train_loader.current_shard = saved_current_shard
638
+ train_loader.current_position = saved_current_position
639
+ if shard_was_changed:
640
+ train_loader.tokens = _load_data_shard(train_loader.files[train_loader.current_shard])
641
+
642
+ print0(f"[Enhanced Sharpness @ Step {step}] Finished computing all HVPs for {n_batches} microbatches")
643
+ grads_hvp = [g.to(device) if g is not None else None for g in grads_hvp]
644
+ hvp_v_total = [h.to(device) if h is not None else None for h in hvp_v_total]
645
+ hvp_v_block = [h.to(device) if h is not None else None for h in hvp_v_block]
646
+ hvp_g_accum = [h.to(device) if h is not None else None for h in hvp_g_accum]
647
+ for group_name in layer_hvp_accum:
648
+ if layer_hvp_accum[group_name] is not None:
649
+ layer_hvp_accum[group_name] = [h.to(device) if h is not None else None for h in layer_hvp_accum[group_name]]
650
+ # --- Calculate TOTAL sharpness ---
651
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating TOTAL sharpness...")
652
+ # hvp_v_total is already computed in the loop above
653
+ vhp_dot_v_total = sum(torch.sum(hvp * v) for hvp, v in zip(hvp_v_total, update_direction_v) if hvp is not None)
654
+ v_norm_sq_total = sum(torch.sum(v * v) for v in update_direction_v)
655
+
656
+ # Ensure they are tensors
657
+ if not isinstance(vhp_dot_v_total, torch.Tensor):
658
+ vhp_dot_v_total = torch.tensor(0.0, device=device)
659
+ if not isinstance(v_norm_sq_total, torch.Tensor):
660
+ v_norm_sq_total = torch.tensor(0.0, device=device)
661
+
662
+ dist.all_reduce(vhp_dot_v_total, op=dist.ReduceOp.AVG)
663
+ dist.all_reduce(v_norm_sq_total, op=dist.ReduceOp.AVG)
664
+
665
+ if v_norm_sq_total.item() > 1e-12:
666
+ analysis_results["total_sharpness"] = (vhp_dot_v_total / v_norm_sq_total).item()
667
+ else:
668
+ analysis_results["total_sharpness"] = 0.0
669
+
670
+
671
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating BLOCK-ONLY total sharpness...")
672
+ # hvp_v_block is already computed in the loop above
673
+ if block_param_indices: # Only compute if there are block parameters
674
+ # Compute v_block^T H v_block (only sum over block indices)
675
+ vhp_dot_v_block = sum(torch.sum(hvp_v_block[i] * update_direction_v[i])
676
+ for i in block_param_indices if hvp_v_block[i] is not None)
677
+
678
+ v_norm_sq_block = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
679
+ for i in block_param_indices)
680
+
681
+ # Ensure they are tensors
682
+ if not isinstance(vhp_dot_v_block, torch.Tensor):
683
+ vhp_dot_v_block = torch.tensor(0.0, device=device)
684
+ if not isinstance(v_norm_sq_block, torch.Tensor):
685
+ v_norm_sq_block = torch.tensor(0.0, device=device)
686
+
687
+ dist.all_reduce(vhp_dot_v_block, op=dist.ReduceOp.AVG)
688
+ dist.all_reduce(v_norm_sq_block, op=dist.ReduceOp.AVG)
689
+
690
+ if v_norm_sq_block.item() > 1e-12:
691
+ analysis_results["block_total_sharpness"] = (vhp_dot_v_block / v_norm_sq_block).item()
692
+ else:
693
+ analysis_results["block_total_sharpness"] = 0.0
694
+
695
+ analysis_results["v_norm_block"] = torch.sqrt(v_norm_sq_block).item()
696
+ analysis_results["v_T_H_v_block"] = vhp_dot_v_block.item()
697
+ else:
698
+ # No block parameters
699
+ analysis_results["block_total_sharpness"] = 0.0
700
+ analysis_results["v_norm_block"] = 0.0
701
+ analysis_results["v_T_H_v_block"] = 0.0
702
+
703
+ torch.cuda.empty_cache()
704
+
705
+ # ---- Alignment metrics between update v and (negative) gradient g ----
706
+ eps = 1e-12
707
+ v_norm = torch.sqrt(v_norm_sq_total + eps)
708
+ analysis_results["v_norm"] = v_norm.item()
709
+
710
+ # --- Version 1: g_hvp ---
711
+ ip_v_neg_g_hvp = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, grads_hvp) if g is not None)
712
+ g_hvp_norm_sq = sum(torch.sum(g * g) for g in grads_hvp if g is not None)
713
+
714
+ if not isinstance(ip_v_neg_g_hvp, torch.Tensor):
715
+ ip_v_neg_g_hvp = torch.tensor(0.0, device=device)
716
+ if not isinstance(g_hvp_norm_sq, torch.Tensor):
717
+ g_hvp_norm_sq = torch.tensor(0.0, device=device)
718
+ dist.all_reduce(ip_v_neg_g_hvp, op=dist.ReduceOp.AVG)
719
+ dist.all_reduce(g_hvp_norm_sq, op=dist.ReduceOp.AVG)
720
+ g_hvp_norm = torch.sqrt(g_hvp_norm_sq + eps)
721
+ analysis_results["ip_v_neg_g_hvp"] = ip_v_neg_g_hvp.item()
722
+ analysis_results["cos_v_neg_g_hvp"] = (ip_v_neg_g_hvp / (v_norm * g_hvp_norm + eps)).item()
723
+ analysis_results["g_hvp_norm"] = g_hvp_norm.item()
724
+
725
+ # --- Version 2: g_t (original gradient that produced v) ---
726
+ # last_training_gradient is the actual gradient from training that led to the update v
727
+ if last_training_gradient is not None:
728
+ ip_v_neg_g_t = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, last_training_gradient) if g is not None)
729
+ g_t_norm_sq = sum(torch.sum(g * g) for g in last_training_gradient if g is not None)
730
+ dist.all_reduce(ip_v_neg_g_t, op=dist.ReduceOp.AVG)
731
+ dist.all_reduce(g_t_norm_sq, op=dist.ReduceOp.AVG)
732
+ g_t_norm = torch.sqrt(g_t_norm_sq + eps)
733
+ analysis_results["ip_v_neg_g_t"] = ip_v_neg_g_t.item()
734
+ analysis_results["cos_v_neg_g_t"] = (ip_v_neg_g_t / (v_norm * g_t_norm + eps)).item()
735
+ analysis_results["g_t_norm"] = g_t_norm.item()
736
+ else:
737
+ print0(f"[Enhanced Sharpness @ Step {step}] Warning: last_training_gradient is None, skipping g_t metrics")
738
+
739
+ # Keep backward compatibility aliases (g_norm uses g_hvp for now)
740
+ g_norm_sq = g_hvp_norm_sq
741
+ g_norm = g_hvp_norm
742
+ analysis_results["g_norm"] = g_norm.item()
743
+
744
+ # ---- Cosine between v and Hv (curvature pull along v) ----
745
+ hv_norm_sq = sum(torch.sum(hvp * hvp) for hvp in hvp_v_total if hvp is not None)
746
+ if not isinstance(hv_norm_sq, torch.Tensor):
747
+ hv_norm_sq = torch.tensor(0.0, device=device)
748
+ dist.all_reduce(hv_norm_sq, op=dist.ReduceOp.AVG)
749
+ hv_norm = torch.sqrt(hv_norm_sq + eps)
750
+ ip_v_hv = vhp_dot_v_total # already reduced AVG
751
+ analysis_results["hv_norm"] = hv_norm.item()
752
+ analysis_results["cos_v_hv"] = (ip_v_hv / (v_norm * hv_norm + eps)).item()
753
+
754
+ # ---- Cosine between g and Hg ----
755
+ # hvp_g_accum is already computed in the loop above
756
+ ip_g_hg = sum(torch.sum(g * hg) for g, hg in zip(grads_hvp, hvp_g_accum) if (g is not None and hg is not None))
757
+ hg_norm_sq = sum(torch.sum(hg * hg) for hg in hvp_g_accum if hg is not None)
758
+ if not isinstance(ip_g_hg, torch.Tensor):
759
+ ip_g_hg = torch.tensor(0.0, device=device)
760
+ if not isinstance(hg_norm_sq, torch.Tensor):
761
+ hg_norm_sq = torch.tensor(0.0, device=device)
762
+ dist.all_reduce(ip_g_hg, op=dist.ReduceOp.AVG)
763
+ dist.all_reduce(hg_norm_sq, op=dist.ReduceOp.AVG)
764
+ hg_norm = torch.sqrt(hg_norm_sq + eps)
765
+ analysis_results["hg_norm"] = hg_norm.item()
766
+ analysis_results["cos_g_hg"] = (ip_g_hg / (g_norm * hg_norm + eps)).item() if g_norm.item() > 0 else 0.0
767
+
768
+ # ---- Decompose v into parallel / perpendicular to -g ----
769
+ if g_norm.item() > 0:
770
+ v_parallel = [(torch.sum(v * (-g)) / (g_norm_sq + eps)) * (-g) if g is not None else torch.zeros_like(v)
771
+ for v, g in zip(update_direction_v, grads_hvp)]
772
+ v_parallel_norm_sq = sum(torch.sum(vp * vp) for vp in v_parallel)
773
+ if not isinstance(v_parallel_norm_sq, torch.Tensor):
774
+ v_parallel_norm_sq = torch.tensor(0.0, device=device)
775
+ dist.all_reduce(v_parallel_norm_sq, op=dist.ReduceOp.AVG)
776
+ v_parallel_norm = torch.sqrt(v_parallel_norm_sq + eps)
777
+ v_perp_norm = torch.sqrt(torch.clamp(v_norm_sq_total - v_parallel_norm_sq, min=0.0) + eps)
778
+ analysis_results["v_parallel_norm"] = v_parallel_norm.item()
779
+ analysis_results["v_perp_norm"] = v_perp_norm.item()
780
+
781
+ # ---- Per-layer additions: cos_v_neg_g_layer, v_norm_layer ----
782
+ for group_name, param_group in all_param_groups.items():
783
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
784
+ if not indices:
785
+ continue
786
+ v_norm_sq_layer = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
787
+ g_norm_sq_layer = sum(torch.sum(grads_hvp[i] * grads_hvp[i]) for i in indices if grads_hvp[i] is not None)
788
+ ip_v_neg_g_layer = sum(torch.sum(update_direction_v[i] * (-grads_hvp[i]))
789
+ for i in indices if grads_hvp[i] is not None)
790
+ # Ensure they are tensors
791
+ if not isinstance(v_norm_sq_layer, torch.Tensor):
792
+ v_norm_sq_layer = torch.tensor(0.0, device=device)
793
+ if not isinstance(g_norm_sq_layer, torch.Tensor):
794
+ g_norm_sq_layer = torch.tensor(0.0, device=device)
795
+ if not isinstance(ip_v_neg_g_layer, torch.Tensor):
796
+ ip_v_neg_g_layer = torch.tensor(0.0, device=device)
797
+ dist.all_reduce(v_norm_sq_layer, op=dist.ReduceOp.AVG)
798
+ dist.all_reduce(g_norm_sq_layer, op=dist.ReduceOp.AVG)
799
+ dist.all_reduce(ip_v_neg_g_layer, op=dist.ReduceOp.AVG)
800
+ v_norm_layer = torch.sqrt(v_norm_sq_layer + eps)
801
+ g_norm_layer = torch.sqrt(g_norm_sq_layer + eps)
802
+ analysis_results[f"{group_name}_v_norm"] = v_norm_layer.item()
803
+ if g_norm_layer.item() > 0:
804
+ analysis_results[f"{group_name}_cos_v_neg_g"] = (ip_v_neg_g_layer / (v_norm_layer * g_norm_layer + eps)).item()
805
+
806
+ # --- 7. Calculate layer-wise sharpness ---
807
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise sharpness...")
808
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing {len(all_param_groups)} layers for sharpness...")
809
+
810
+ for group_name, param_group in all_param_groups.items():
811
+ if not param_group:
812
+ continue
813
+
814
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing '{group_name}'...")
815
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
816
+ if not indices:
817
+ continue
818
+
819
+ try:
820
+ if group_name not in layer_hvp_accum or layer_hvp_accum[group_name] is None:
821
+ print0(f"[Enhanced Sharpness @ Step {step}] No HVP data for '{group_name}', skipping")
822
+ analysis_results[f"{group_name}_sharpness"] = 0.0
823
+ continue
824
+
825
+ hvp_group_result = layer_hvp_accum[group_name]
826
+
827
+ vhp_dot_v_group = sum(torch.sum(hvp_group_result[i] * update_direction_v[i])
828
+ for i in indices if hvp_group_result[i] is not None)
829
+ v_norm_sq_group = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
830
+ for i in indices)
831
+
832
+ # Ensure they are tensors
833
+ if not isinstance(vhp_dot_v_group, torch.Tensor):
834
+ vhp_dot_v_group = torch.tensor(0.0, device=device)
835
+ if not isinstance(v_norm_sq_group, torch.Tensor):
836
+ v_norm_sq_group = torch.tensor(0.0, device=device)
837
+
838
+ dist.all_reduce(vhp_dot_v_group, op=dist.ReduceOp.AVG)
839
+ dist.all_reduce(v_norm_sq_group, op=dist.ReduceOp.AVG)
840
+
841
+ if v_norm_sq_group.item() > 1e-12:
842
+ analysis_results[f"{group_name}_sharpness"] = (vhp_dot_v_group / v_norm_sq_group).item()
843
+ else:
844
+ analysis_results[f"{group_name}_sharpness"] = 0.0
845
+
846
+ except torch.OutOfMemoryError as e:
847
+ print0(f"[Enhanced Sharpness @ Step {step}] OOM error for '{group_name}': {e}")
848
+ analysis_results[f"{group_name}_sharpness"] = 0.0
849
+ torch.cuda.empty_cache()
850
+ except Exception as e:
851
+ print0(f"[Enhanced Sharpness @ Step {step}] Error processing '{group_name}': {e}")
852
+ analysis_results[f"{group_name}_sharpness"] = 0.0
853
+
854
+ # --- Calculate block-diagonal approximation and cross-layer interaction ---
855
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating block-diagonal and cross-layer sharpness...")
856
+
857
+ sum_layer_numerators = 0.0
858
+ for layer in range(1, NUM_LAYERS + 1):
859
+ layer_name = f"layer_{layer}"
860
+ if f"{layer_name}_sharpness" in analysis_results and f"{layer_name}_v_norm" in analysis_results:
861
+ s_k = analysis_results[f"{layer_name}_sharpness"]
862
+ v_k_norm = analysis_results[f"{layer_name}_v_norm"]
863
+ sum_layer_numerators += s_k * (v_k_norm ** 2)
864
+
865
+ analysis_results["sum_layer_numerators"] = sum_layer_numerators
866
+
867
+ # Block-diagonal sharpness (using block ||v||²)
868
+ v_norm_block = analysis_results.get("v_norm_block", 0)
869
+ v_norm_sq_block_val = v_norm_block ** 2 if v_norm_block else 1e-12
870
+
871
+ if v_norm_sq_block_val > 1e-12:
872
+ analysis_results["block_diag_sharpness"] = sum_layer_numerators / v_norm_sq_block_val
873
+ else:
874
+ analysis_results["block_diag_sharpness"] = 0.0
875
+
876
+ # Cross-layer interaction = block_total - block_diag
877
+ block_total = analysis_results.get("block_total_sharpness", 0)
878
+ block_diag = analysis_results.get("block_diag_sharpness", 0)
879
+ analysis_results["cross_layer_sharpness"] = block_total - block_diag
880
+
881
+ print0(f"[Enhanced Sharpness @ Step {step}] block_total={block_total:.6f}, block_diag={block_diag:.6f}, cross_layer={block_total - block_diag:.6f}")
882
+
883
+ # --- Compute true_dec and pred_dec ---
884
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing true_dec (L(t) - L(t+1)) on training batch...")
885
+ try:
886
+ # Restore FLASH for forward pass
887
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
888
+
889
+
890
+ loss_at_theta_t = 0.0
891
+ with torch.no_grad():
892
+ for x_td, y_td in batch_iterator:
893
+ x_td, y_td = x_td.to(device), y_td.to(device)
894
+ _, loss_td = model(x_td, y_td, return_logits=False)
895
+ loss_at_theta_t += loss_td.item()
896
+ loss_at_theta_t /= len(batch_iterator) # average over microbatches
897
+
898
+ with torch.no_grad():
899
+ for p, v in zip(model.parameters(), update_direction_v):
900
+ p.data.add_(v)
901
+
902
+ loss_at_theta_t1 = 0.0
903
+ with torch.no_grad():
904
+ for x_td, y_td in batch_iterator:
905
+ x_td, y_td = x_td.to(device), y_td.to(device)
906
+ _, loss_td = model(x_td, y_td, return_logits=False)
907
+ loss_at_theta_t1 += loss_td.item()
908
+ loss_at_theta_t1 /= len(batch_iterator)
909
+
910
+ with torch.no_grad():
911
+ for p, v in zip(model.parameters(), update_direction_v):
912
+ p.data.sub_(v)
913
+
914
+ loss_t_tensor = torch.tensor(loss_at_theta_t, device=device)
915
+ loss_t1_tensor = torch.tensor(loss_at_theta_t1, device=device)
916
+ dist.all_reduce(loss_t_tensor, op=dist.ReduceOp.AVG)
917
+ dist.all_reduce(loss_t1_tensor, op=dist.ReduceOp.AVG)
918
+ loss_at_theta_t = loss_t_tensor.item()
919
+ loss_at_theta_t1 = loss_t1_tensor.item()
920
+
921
+ true_dec = loss_at_theta_t - loss_at_theta_t1
922
+ analysis_results["loss_at_theta_t"] = loss_at_theta_t
923
+ analysis_results["loss_at_theta_t1"] = loss_at_theta_t1
924
+ analysis_results["true_dec"] = true_dec
925
+
926
+ # pred_dec = (-g)^T v - 0.5 * v^T H v
927
+ first_order = analysis_results.get("ip_v_neg_g_t", analysis_results.get("ip_v_neg_g_hvp", 0.0))
928
+ sharpness_val = analysis_results.get("total_sharpness", 0.0)
929
+ v_norm_val = analysis_results.get("v_norm", 0.0)
930
+ curvature_term = 0.5 * sharpness_val * (v_norm_val ** 2)
931
+ pred_dec = first_order - curvature_term
932
+
933
+ analysis_results["pred_dec"] = pred_dec
934
+ analysis_results["first_order_descent"] = first_order
935
+ analysis_results["curvature_penalty"] = curvature_term
936
+
937
+ print0(f"[Enhanced Sharpness @ Step {step}] L(θ_t)={loss_at_theta_t:.6f}, L(θ_{{t+1}})={loss_at_theta_t1:.6f}, "
938
+ f"true_dec={true_dec:.6f}, pred_dec={pred_dec:.6f}, 1st_order={first_order:.6f}, curvature={curvature_term:.6f}")
939
+ except Exception as e:
940
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing true_dec: {e}")
941
+ analysis_results["true_dec"] = 0.0
942
+ analysis_results["pred_dec"] = 0.0
943
+
944
+ # --- Cleanup ---
945
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
946
+ print0(f"[Enhanced Sharpness @ Step {step}] Restored FLASH attention to {original_flash}")
947
+
948
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters back to θ_{{t+1}}...")
949
+ with torch.no_grad():
950
+ for p, v in zip(model.parameters(), update_direction_v):
951
+ p.data.add_(v)
952
+
953
+ if prev_training_mode:
954
+ model.train()
955
+ else:
956
+ model.eval()
957
+
958
+ # Thorough cleanup of all temporary variables
959
+ del update_direction_v, grads_hvp
960
+ del hvp_v_total, hvp_v_block, hvp_g_accum, layer_hvp_accum
961
+ del vhp_dot_v_total, v_norm_sq_total
962
+ del vhp_dot_v_block, v_norm_sq_block
963
+ if 'all_param_groups' in locals():
964
+ del all_param_groups
965
+ if 'param_to_idx' in locals():
966
+ del param_to_idx
967
+
968
+ # Synchronize CUDA operations before cleanup
969
+ if device == "cuda":
970
+ torch.cuda.synchronize()
971
+
972
+ gc.collect()
973
+ torch.cuda.empty_cache()
974
+
975
+ print0(f"[Enhanced Sharpness @ Step {step}] Analysis complete. Generated {len(analysis_results)} metrics.")
976
+ return analysis_results
977
+
978
+ def format_comprehensive_results(results):
979
+ """
980
+ Format the comprehensive analysis results for logging.
981
+ """
982
+ log_parts = []
983
+
984
+ # Total sharpness
985
+ if 'total_sharpness' in results:
986
+ log_parts.append(f"total_sharp:{results['total_sharpness']:.4e}")
987
+
988
+ # Layer-wise sharpness - dynamically detect number of layers
989
+ layer_sharpness = []
990
+ layer_num = 1
991
+ while True:
992
+ layer_key = f"layer_{layer_num}_sharpness"
993
+ if layer_key in results:
994
+ layer_sharpness.append(f"L{layer_num}_sharp:{results[layer_key]:.4e}")
995
+ layer_num += 1
996
+ else:
997
+ break
998
+
999
+ if layer_sharpness:
1000
+ log_parts.append(" ".join(layer_sharpness))
1001
+
1002
+ # Total update norms
1003
+ total_norms = []
1004
+ if 'total_update_fnorm' in results:
1005
+ total_norms.append(f"total_fnorm:{results['total_update_fnorm']:.4e}")
1006
+ if 'total_l1_linf_norm' in results:
1007
+ total_norms.append(f"total_l1_linf:{results['total_l1_linf_norm']:.4e}")
1008
+ if 'total_spectral_norm' in results:
1009
+ total_norms.append(f"total_spectral:{results['total_spectral_norm']:.4e}")
1010
+
1011
+ if total_norms:
1012
+ log_parts.append(" ".join(total_norms))
1013
+
1014
+ # Layer-wise update norms (Frobenius)
1015
+ layer_fnorms = []
1016
+ layer_num = 1
1017
+ while True:
1018
+ layer_key = f"layer_{layer_num}_update_fnorm"
1019
+ if layer_key in results:
1020
+ layer_fnorms.append(f"L{layer_num}_fnorm:{results[layer_key]:.4e}")
1021
+ layer_num += 1
1022
+ else:
1023
+ break
1024
+
1025
+ if layer_fnorms:
1026
+ log_parts.append(" ".join(layer_fnorms))
1027
+
1028
+ # Layer-wise update norms (Max-of-Max)
1029
+ layer_l1_linf = []
1030
+ layer_num = 1
1031
+ while True:
1032
+ layer_key = f"layer_{layer_num}_max_l1_linf_norm"
1033
+ if layer_key in results:
1034
+ layer_l1_linf.append(f"L{layer_num}_l1linf:{results[layer_key]:.4e}")
1035
+ layer_num += 1
1036
+ else:
1037
+ break
1038
+
1039
+ if layer_l1_linf:
1040
+ log_parts.append(" ".join(layer_l1_linf))
1041
+
1042
+ # Layer-wise update norms (Spectral)
1043
+ layer_spectral = []
1044
+ layer_num = 1
1045
+ while True:
1046
+ layer_key = f"layer_{layer_num}_max_spectral_norm"
1047
+ if layer_key in results:
1048
+ layer_spectral.append(f"L{layer_num}_spectral:{results[layer_key]:.4e}")
1049
+ layer_num += 1
1050
+ else:
1051
+ break
1052
+
1053
+ if layer_spectral:
1054
+ log_parts.append(" ".join(layer_spectral))
1055
+
1056
+ # Alignment and curvature metrics (global)
1057
+ misc_parts = []
1058
+ if 'v_norm' in results:
1059
+ misc_parts.append(f"v_norm:{results['v_norm']:.4e}")
1060
+
1061
+ # Version 1: g_hvp (new batch, computed at θ_t during HVP calculation)
1062
+ if 'cos_v_neg_g_hvp' in results:
1063
+ misc_parts.append(f"cos_v_-g_hvp:{results['cos_v_neg_g_hvp']:.4e}")
1064
+ if 'g_hvp_norm' in results:
1065
+ misc_parts.append(f"g_hvp_norm:{results['g_hvp_norm']:.4e}")
1066
+
1067
+ # Version 2: g_t (original gradient that produced v)
1068
+ if 'cos_v_neg_g_t' in results:
1069
+ misc_parts.append(f"cos_v_-g_t:{results['cos_v_neg_g_t']:.4e}")
1070
+ if 'g_t_norm' in results:
1071
+ misc_parts.append(f"g_t_norm:{results['g_t_norm']:.4e}")
1072
+
1073
+ if 'hv_norm' in results:
1074
+ misc_parts.append(f"hv_norm:{results['hv_norm']:.4e}")
1075
+ if 'cos_v_hv' in results:
1076
+ misc_parts.append(f"cos_v_hv:{results['cos_v_hv']:.4e}")
1077
+ if 'hg_norm' in results:
1078
+ misc_parts.append(f"hg_norm:{results['hg_norm']:.4e}")
1079
+ if 'cos_g_hg' in results:
1080
+ misc_parts.append(f"cos_g_hg:{results['cos_g_hg']:.4e}")
1081
+ if 'v_parallel_norm' in results:
1082
+ misc_parts.append(f"v_par:{results['v_parallel_norm']:.4e}")
1083
+ if 'v_perp_norm' in results:
1084
+ misc_parts.append(f"v_perp:{results['v_perp_norm']:.4e}")
1085
+ if misc_parts:
1086
+ log_parts.append(" ".join(misc_parts))
1087
+
1088
+ # Per-layer alignment metrics (cos_v_neg_g and v_norm per layer)
1089
+ layer_cos = []
1090
+ layer_num = 1
1091
+ while True:
1092
+ layer_key = f"layer_{layer_num}_cos_v_neg_g"
1093
+ layer_vn_key = f"layer_{layer_num}_v_norm"
1094
+ if layer_key in results:
1095
+ layer_cos.append(f"L{layer_num}_cos_v_neg_g:{results[layer_key]:.4e}")
1096
+ if layer_vn_key in results:
1097
+ layer_cos.append(f"L{layer_num}_v_norm:{results[layer_vn_key]:.4e}")
1098
+ if layer_key not in results and layer_vn_key not in results:
1099
+ break
1100
+ layer_num += 1
1101
+ if layer_cos:
1102
+ log_parts.append(" ".join(layer_cos))
1103
+
1104
+ return " ".join(log_parts)
1105
+
1106
+ # -----------------------------------------------------------------------------
1107
+ # int main
1108
+
1109
+ def print0(*args, **kwargs):
1110
+ # modified print that only prints from the master process
1111
+ # if this is not a distributed run, it's just a print
1112
+ if int(os.environ.get("RANK", 0)) == 0:
1113
+ print(*args, **kwargs)
1114
+
1115
+ if __name__ == "__main__":
1116
+ import time
1117
+ import argparse
1118
+ import tiktoken
1119
+ print0(f"Running pytorch {torch.version.__version__}")
1120
+
1121
+ # default settings will overfit a tiny batch of data
1122
+ # and save model weights and debug state to disk on the first iteration
1123
+ parser = argparse.ArgumentParser()
1124
+ # file system input / output
1125
+ parser.add_argument("--input_bin", type=str, default="dev/data/tinyshakespeare/tiny_shakespeare_val.bin", help="input .bin to train on")
1126
+ parser.add_argument("--input_val_bin", type=str, default="", help="input .bin to eval validation loss on")
1127
+ parser.add_argument("--output_dir", type=str, default="", help="output directory to which to write logs and checkpoints")
1128
+ parser.add_argument("--model", type=str, default="gpt2", help="gpt2|gpt2-medium|gpt2-large|gpt2-xl|d8|d12|d24|d36|d48")
1129
+ # token layout for each step of the optimization
1130
+ parser.add_argument("--batch_size", type=int, default=4, help="batch size, in units of #batch dimensions")
1131
+ parser.add_argument("--sequence_length", type=int, default=64, help="sequence length")
1132
+ parser.add_argument("--total_batch_size", type=int, default=256, help="total desired batch size, in units of #tokens")
1133
+ # workload (number of steps)
1134
+ parser.add_argument("--num_iterations", type=int, default=10, help="number of iterations to run")
1135
+ parser.add_argument("--inference_only", type=int, default=0, help="only run inference")
1136
+ # optimization
1137
+ parser.add_argument("--adam_lr", type=float, default=1e-4, help="learning rate warmup iterations")
1138
+ parser.add_argument("--warmup_iters", type=int, default=0, help="learning rate warmup iterations")
1139
+ parser.add_argument("--lr_decay_frac", type=float, default=1.0, help="learning rate warmup iterations")
1140
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="weight decay")
1141
+ parser.add_argument("--grad_clip", type=float, default=1.0, help="maximum gradient magnitude")
1142
+ # evaluation
1143
+ parser.add_argument("--val_loss_every", type=int, default=0, help="every how mant steps to evaluate val loss?")
1144
+ parser.add_argument("--val_max_steps", type=int, default=20, help="how many batches of val to average?")
1145
+ parser.add_argument("--sample_every", type=int, default=0, help="how often to sample from the model?")
1146
+ # debugging
1147
+ parser.add_argument("--overfit_single_batch", type=int, default=0, help="overfit just one batch of data")
1148
+ parser.add_argument("--shuffle_files", action="store_true")
1149
+ # numerics
1150
+ parser.add_argument("--tensorcores", type=int, default=0, help="use tensorcores")
1151
+ # memory management
1152
+ parser.add_argument("--device", type=str, default="", help="by default we autodetect, or set it here")
1153
+ parser.add_argument("--compile", type=int, default=0, help="torch.compile the model")
1154
+ parser.add_argument("--flash", type=int, default=0, help="use flash attention")
1155
+ parser.add_argument("--dtype", type=str, default="float32", help="float32|float16|bfloat16")
1156
+ parser.add_argument("--zero_stage", type=int, default=0, help="zero redundancy optimizer stage (0/1/2/3)")
1157
+ # Muon optimizer specific arguments
1158
+ parser.add_argument("--optimizer", type=str, default="adam", help="optimizer to use: adam|muon")
1159
+ parser.add_argument("--muon_lr", type=float, default=0.02, help="learning rate for Muon optimizer")
1160
+ parser.add_argument("--muon_momentum", type=float, default=0.95, help="momentum for Muon optimizer")
1161
+ parser.add_argument("--muon_weight_decay", type=float, default=0.00, help="weight decay for Muon optimizer")
1162
+ parser.add_argument("--muon_ns_steps", type=int, default=5, help="number of Newton-Schulz steps for Muon")
1163
+ parser.add_argument("--muon_nesterov", type=bool, default=False, help="use Nesterov momentum for Muon (0/1)")
1164
+ # python -> C bridge
1165
+ parser.add_argument("--write_tensors", type=int, default=1, help="write tensors to disk")
1166
+ parser.add_argument("--seed", type=int, default=42, help="random seed")
1167
+ # Sharpness analysis arguments
1168
+ parser.add_argument("--analyze_sharpness", action="store_true", help="Enable comprehensive sharpness analysis")
1169
+ parser.add_argument("--sharpness_analysis_interval", type=int, default=500, help="Interval for sharpness analysis")
1170
+ args = parser.parse_args()
1171
+
1172
+ # args error checking and convenience variables
1173
+ B, T = args.batch_size, args.sequence_length
1174
+ assert 1 <= T <= 1024
1175
+ assert args.dtype in {"float32", "float16", "bfloat16"}
1176
+ assert args.model in {"gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl", "d8", "d12", "d24", "d36", "d48"}
1177
+ assert args.optimizer in {"adam", "muon"}
1178
+
1179
+ set_seed(args.seed)
1180
+
1181
+ # set up DDP (distributed data parallel). torchrun sets this env variable
1182
+ ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
1183
+ if ddp:
1184
+ # use of DDP atm demands CUDA, we set the device appropriately according to rank
1185
+ assert torch.cuda.is_available(), "for now i think we need CUDA for DDP"
1186
+ init_process_group(backend='nccl')
1187
+ ddp_rank = int(os.environ['RANK'])
1188
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
1189
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
1190
+ device = f'cuda:{ddp_local_rank}'
1191
+ torch.cuda.set_device(device)
1192
+ master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
1193
+ seed_offset = 0 # each process gets the exact same seed
1194
+ zero_stage = args.zero_stage
1195
+ else:
1196
+ ddp_rank = 0
1197
+ ddp_local_rank = 0
1198
+ zero_stage = 0
1199
+ ddp_world_size = 1
1200
+ master_process = True
1201
+ seed_offset = 0
1202
+ # select the device
1203
+ if args.device:
1204
+ # provided explicitly by the user
1205
+ device = args.device
1206
+ else:
1207
+ # attempt to autodetect the device
1208
+ device = "cpu"
1209
+ if torch.cuda.is_available():
1210
+ device = "cuda"
1211
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
1212
+ device = "mps"
1213
+ print(f"using device: {device}")
1214
+ device_type = 'cuda' if 'cuda' in device else 'cpu'
1215
+
1216
+ # Setup debugpy for remote debugging (only activates if DEBUGPY env var is set)
1217
+ # setup_debugpy(rank=ddp_rank, force=True)
1218
+
1219
+ # calculate gradient accumulation from the desired total batch size and the current run configuration
1220
+ tokens_per_fwdbwd = B * T * ddp_world_size
1221
+ assert args.total_batch_size % tokens_per_fwdbwd == 0
1222
+ grad_accum_steps = args.total_batch_size // tokens_per_fwdbwd
1223
+ print0(f"total desired batch size: {args.total_batch_size}")
1224
+ print0(f"=> calculated gradient accumulation steps: {grad_accum_steps}")
1225
+
1226
+ # set up a context manager following the desired dtype and device
1227
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[args.dtype]
1228
+ ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype) if device_type == "cuda" else nullcontext()
1229
+
1230
+ # rng / reproducibility
1231
+ torch.manual_seed(42)
1232
+ if torch.cuda.is_available():
1233
+ torch.cuda.manual_seed(42)
1234
+
1235
+ # set the torch precision mode to use TensorFloat32 (TF32) for matmuls
1236
+ # docs https://pytorch.org/docs/stable/generated/torch.set_float32_matmul_precision.html
1237
+ if args.tensorcores:
1238
+ torch.set_float32_matmul_precision('high')
1239
+
1240
+ # turn on/off flash attention
1241
+ assert args.flash in {0, 1}
1242
+ nano_GPT_qkvonorm_pure.FLASH = args.flash # Set module-level FLASH for training
1243
+
1244
+ # init (and write) the tokenizer
1245
+ enc = tiktoken.get_encoding("gpt2")
1246
+ if master_process and args.write_tensors: # tokenizer is technically not tensors but ok
1247
+ write_tokenizer(enc, "gpt2_tokenizer.bin")
1248
+
1249
+ # init the model, either from scratch or from OpenAI pretrained checkpoint
1250
+ if args.model[0] == "d":
1251
+ # from scratch (random weights)
1252
+ model_config = {
1253
+ "d8": GPTConfig(block_size=1024, vocab_size=50257, n_layer=8, n_head=8, n_embd=512),
1254
+ "d12": GPTConfig(block_size=1024, vocab_size=50257, n_layer=12, n_head=12, n_embd=768),
1255
+ "d24": GPTConfig(block_size=1024, vocab_size=50257, n_layer=24, n_head=16, n_embd=1024),
1256
+ "d36": GPTConfig(block_size=1024, vocab_size=50257, n_layer=36, n_head=20, n_embd=1280),
1257
+ "d48": GPTConfig(block_size=1024, vocab_size=50257, n_layer=48, n_head=25, n_embd=1600),
1258
+ }[args.model]
1259
+ model = GPT(model_config)
1260
+ else:
1261
+ # load the GPT-2 model weights
1262
+ model = GPT.from_pretrained(args.model)
1263
+ model.train()
1264
+ model.to(device)
1265
+
1266
+ # Save uncompiled model reference for sharpness analysis (needs double backward)
1267
+ raw_model_uncompiled = model
1268
+
1269
+ if args.compile:
1270
+ if hasattr(config, "coordinate_descent_tuning"):
1271
+ config.coordinate_descent_tuning = True # suggested by @Chillee
1272
+ print0("compiling the model...")
1273
+ model = torch.compile(model)
1274
+
1275
+ # -------------------------------------------------------------------------
1276
+ # Our own version of a simple DistributedDataLoader
1277
+
1278
+ # load tokens
1279
+ train_loader = DistributedDataLoader(
1280
+ args.input_bin, B, T, ddp_rank, ddp_world_size,
1281
+ shuffle_files=args.shuffle_files, random_seed=args.seed
1282
+ )
1283
+ val_loader = None
1284
+ if args.input_val_bin:
1285
+ val_loader = DistributedDataLoader(args.input_val_bin, B, T, ddp_rank, ddp_world_size)
1286
+
1287
+ # -------------------------------------------------------------------------
1288
+ # PyTorch -> C bridge: save some weights and state for C to load later as reference
1289
+
1290
+ # do one forward pass to generate ground truth for our C tests
1291
+ if master_process and args.write_tensors and (not args.inference_only):
1292
+ x, y = train_loader.next_batch()
1293
+ x, y = x.to(device), y.to(device)
1294
+ logits, loss = model(x, y, return_logits=True) # Need logits for write_state
1295
+ loss.backward()
1296
+ # save model params, in both float32 and bfloat16
1297
+ model_to_size = {"gpt2": "124M", "gpt2-medium": "355M", "gpt2-large": "774M", "gpt2-xl": "1558M"}
1298
+ model_to_size.update({f"d{d}": f"d{d}" for d in [12, 24, 36, 48]})
1299
+ model_size_str = model_to_size[args.model] # e.g. "124M", or "d12"
1300
+ write_model(model, f"gpt2_{model_size_str}.bin", dtype="float32")
1301
+ write_model(model, f"gpt2_{model_size_str}_bf16.bin", dtype="bfloat16")
1302
+ # save x, y, logits, loss, and parameter gradients, for debugging C
1303
+ # always store these in fp32 to have an accurate reference (?)
1304
+ write_state(model, x, y, logits, loss, f"gpt2_{model_size_str}_debug_state.bin")
1305
+ # reset the train_loader for the optimization below
1306
+ train_loader.reset()
1307
+
1308
+ # -------------------------------------------------------------------------
1309
+ # main training loop
1310
+
1311
+ # here we wrap model into DDP container
1312
+ if ddp:
1313
+ model = DDP(model, device_ids=[ddp_local_rank])
1314
+ raw_model = model.module if ddp else model # always contains the "raw" unwrapped model
1315
+
1316
+ base_module = model.module if ddp else model
1317
+ # If compiled, unwrap to get the original module
1318
+ if hasattr(base_module, "_orig_mod"):
1319
+ base_module = base_module._orig_mod
1320
+
1321
+ raw_params = list(raw_model_uncompiled.parameters())
1322
+ train_params = list(base_module.parameters())
1323
+
1324
+ assert len(raw_params) == len(train_params), \
1325
+ f"Parameter count mismatch: raw_model_uncompiled has {len(raw_params)}, training model has {len(train_params)}"
1326
+ for i, (rp, tp) in enumerate(zip(raw_params, train_params)):
1327
+ assert rp.data_ptr() == tp.data_ptr(), \
1328
+ f"Parameter {i} has different data_ptr: raw_model_uncompiled and training model do not share parameters!"
1329
+ print0(f"[Verified] raw_model_uncompiled and training model share the same {len(raw_params)} Parameter objects")
1330
+
1331
+ last_training_update = None
1332
+ last_training_gradient = None # Store the original gradient that produced the update
1333
+ last_training_batches = None # Store ALL microbatches (x, y) for consistent HVP calculation
1334
+
1335
+
1336
+ def configure_adam(model, weight_decay, learning_rate, betas, device_type, zero_stage):
1337
+ # start with all of the candidate parameters
1338
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1339
+ # filter out those that do not require grad
1340
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1341
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
1342
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
1343
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
1344
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
1345
+ optim_groups = [
1346
+ {'params': decay_params, 'weight_decay': weight_decay},
1347
+ {'params': nodecay_params, 'weight_decay': 0.0}
1348
+ ]
1349
+ num_decay_params = sum(p.numel() for p in decay_params)
1350
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
1351
+ print0(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
1352
+ print0(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
1353
+ # Create AdamW optimizer and use the fused version if it is available
1354
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1355
+ use_fused = fused_available and device_type == 'cuda'
1356
+ print0(f"using fused AdamW: {use_fused}")
1357
+ if zero_stage == 1:
1358
+ print0("using ZeroRedundancyOptimizer")
1359
+ optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1360
+ lr=learning_rate, betas=betas, fused=use_fused)
1361
+ optimizer.add_param_group(optim_groups[1])
1362
+ else:
1363
+ print0("using regular AdamW")
1364
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=use_fused)
1365
+ return [optimizer]
1366
+
1367
+ def configure_muon(model, weight_decay, adam_lr, muon_lr, momentum, nesterov, ns_steps, device_type, zero_stage, ddp_rank, ddp_world_size):
1368
+ # start with all of the candidate parameters
1369
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1370
+ # filter out those that do not require grad
1371
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1372
+
1373
+ # For Muon, we need to separate 2D parameters (which can be orthogonalized)
1374
+ # from other parameters (which should use standard optimization)
1375
+ muon_params = [] # 2D parameters for Muon
1376
+ other_params = [] # other parameters for AdamW
1377
+
1378
+ muon_name = []
1379
+ other_name = []
1380
+ for n, p in param_dict.items():
1381
+ if "wte.weight" in n :
1382
+ other_params.append(p)
1383
+ other_name.append(n)
1384
+ continue
1385
+
1386
+ if p.dim() >= 2: # 2D parameters (weight matrices)
1387
+ muon_params.append(p)
1388
+ muon_name.append(n)
1389
+ else: # 1D parameters (biases, embeddings, etc.)
1390
+ other_params.append(p)
1391
+ other_name.append(n)
1392
+
1393
+ # print("================================================\n")
1394
+ # print(f"Muon parameters: {muon_name}\n")
1395
+ # print(f"Other parameters: {other_name}\n")
1396
+ # print("================================================\n")
1397
+
1398
+ print0(f"Muon parameters (2D): {len(muon_params)} tensors")
1399
+ print0(f"Other parameters (non-2D): {len(other_params)} tensors")
1400
+
1401
+ # Create Muon optimizer for 2D parameters
1402
+ muon_optimizer = None
1403
+ if muon_params:
1404
+ muon_optimizer = Muon(
1405
+ params=muon_params,
1406
+ lr=muon_lr,
1407
+ weight_decay=weight_decay,
1408
+ momentum=momentum,
1409
+ nesterov=nesterov,
1410
+ ns_steps=ns_steps,
1411
+ rank=ddp_rank,
1412
+ world_size=ddp_world_size
1413
+ )
1414
+
1415
+ # Create AdamW optimizer for non-2D parameters
1416
+ adam_optimizer = None
1417
+ if other_params:
1418
+ # create optim groups for AdamW
1419
+ # decay_params = [p for p in other_params if p.dim() >= 2]
1420
+ # nodecay_params = [p for p in other_params if p.dim() < 2]
1421
+ optim_groups = [
1422
+ {'params': other_params, 'weight_decay': weight_decay},
1423
+ # {'params': nodecay_params, 'weight_decay': 0.0}
1424
+ ]
1425
+
1426
+ # Create AdamW optimizer
1427
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1428
+ use_fused = fused_available and device_type == 'cuda'
1429
+ print0(f"using fused AdamW for non-Muon params: {use_fused}")
1430
+
1431
+ if zero_stage == 1:
1432
+ print0("using ZeroRedundancyOptimizer for non-Muon params")
1433
+ adam_optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1434
+ lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1435
+ # adam_optimizer.add_param_group(optim_groups[1])
1436
+ else:
1437
+ print0("using regular AdamW for non-Muon params")
1438
+ adam_optimizer = torch.optim.AdamW(optim_groups, lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1439
+
1440
+ return [muon_optimizer, adam_optimizer]
1441
+
1442
+ # init the optimizer
1443
+ if args.optimizer == "adam":
1444
+ optimizers = configure_adam(model=raw_model_uncompiled, weight_decay=args.weight_decay,
1445
+ learning_rate=args.adam_lr, betas=(0.9, 0.95),
1446
+ device_type=device, zero_stage=zero_stage)
1447
+ elif args.optimizer == "muon":
1448
+ optimizers = configure_muon(
1449
+ model=raw_model_uncompiled,
1450
+ weight_decay=args.muon_weight_decay,
1451
+ muon_lr=args.muon_lr,
1452
+ adam_lr=args.adam_lr,
1453
+ momentum=args.muon_momentum,
1454
+ nesterov=bool(args.muon_nesterov),
1455
+ ns_steps=args.muon_ns_steps,
1456
+ device_type=device,
1457
+ zero_stage=zero_stage,
1458
+ ddp_rank=ddp_rank,
1459
+ ddp_world_size=ddp_world_size
1460
+ )
1461
+ # We'll use muon_optimizer and adam_optimizer separately
1462
+
1463
+ # learning rate decay scheduler (cosine with warmup)
1464
+ def get_lr(it,base_lr):
1465
+ # if args.optimizer == "adam":
1466
+ # base_lr = args.adam_lr
1467
+ # else: # muon
1468
+ # base_lr = args.muon_lr
1469
+ min_lr = base_lr * args.lr_decay_frac
1470
+ # 1) linear warmup for warmup_iters steps
1471
+ if it < args.warmup_iters:
1472
+ return base_lr * (it+1) / args.warmup_iters
1473
+ # 2) if it > lr_decay_iters, return min learning rate
1474
+ if it > args.num_iterations:
1475
+ return min_lr
1476
+ # 3) in between, use cosine decay down to min learning rate
1477
+ decay_ratio = (it - args.warmup_iters) / (args.num_iterations - args.warmup_iters)
1478
+ assert 0 <= decay_ratio <= 1
1479
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff starts at 1 and goes to 0
1480
+ return min_lr + coeff * (base_lr - min_lr)
1481
+
1482
+ def get_wsd_lr(it, base_lr):
1483
+ min_lr = base_lr * args.lr_decay_frac
1484
+ # cooldown_iters = int(args.num_iterations * 0.2)
1485
+ cooldown_iters = int(0)
1486
+ # 1) Warmup: linear warmup for warmup_iters steps
1487
+ if it < args.warmup_iters:
1488
+ return base_lr * (it + 1) / args.warmup_iters
1489
+ # 3) Decay: linear decay from base_lr to min_lr in the last cooldown_iters steps
1490
+ cooldown_start = args.num_iterations - cooldown_iters
1491
+ if it >= cooldown_start:
1492
+ decay_ratio = (it - cooldown_start) / cooldown_iters
1493
+ return base_lr - decay_ratio * (base_lr - min_lr)
1494
+ # 2) Stable: constant learning rate at base_lr
1495
+ return base_lr
1496
+
1497
+ # create the logging directory if it does not exist
1498
+ logfile = None
1499
+ run_dir_path = None
1500
+
1501
+ file_name = f"mode_{args.optimizer}_adam_lr_{args.adam_lr}_muon_lr_{args.muon_lr}_seed_{args.seed}.log"
1502
+ if args.output_dir:
1503
+ base_log_dir = Path(args.output_dir)
1504
+ base_log_dir.mkdir(parents=True, exist_ok=True)
1505
+
1506
+ # Create run-specific directory
1507
+ # Generate UUID on master process and broadcast to all ranks
1508
+ if master_process:
1509
+ run_uuid = uuid.uuid4()
1510
+ uuid_str = str(run_uuid)
1511
+ else:
1512
+ uuid_str = None
1513
+
1514
+ # Broadcast UUID from rank 0 to all other ranks
1515
+ if ddp:
1516
+ # Create a tensor to hold the UUID string length and content
1517
+ if master_process:
1518
+ uuid_bytes = uuid_str.encode('utf-8')
1519
+ uuid_len = len(uuid_bytes)
1520
+ else:
1521
+ uuid_len = 0
1522
+
1523
+ # Broadcast length
1524
+ uuid_len_tensor = torch.tensor(uuid_len, dtype=torch.long, device=device)
1525
+ dist.broadcast(uuid_len_tensor, src=0)
1526
+
1527
+ # Broadcast UUID string
1528
+ if master_process:
1529
+ uuid_tensor = torch.ByteTensor(list(uuid_bytes)).to(device)
1530
+ else:
1531
+ uuid_tensor = torch.ByteTensor([0] * uuid_len_tensor.item()).to(device)
1532
+ dist.broadcast(uuid_tensor, src=0)
1533
+
1534
+ # Decode on non-master processes
1535
+ if not master_process:
1536
+ uuid_str = bytes(uuid_tensor.cpu().numpy()).decode('utf-8')
1537
+ run_uuid = uuid.UUID(uuid_str)
1538
+ else:
1539
+ run_uuid = uuid.UUID(uuid_str)
1540
+ else:
1541
+ run_uuid = uuid.uuid4()
1542
+
1543
+ # run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}_{run_uuid}"
1544
+ run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}"
1545
+ run_dir_path = base_log_dir / run_folder_name
1546
+ if run_dir_path.exists():
1547
+ run_flag = False
1548
+ else:
1549
+ run_flag = True
1550
+ torch.cuda.synchronize()
1551
+
1552
+
1553
+ # Only master process creates the directory
1554
+ if master_process:
1555
+ run_dir_path.mkdir(parents=True, exist_ok=True)
1556
+
1557
+ logfile = str(run_dir_path / "training_log.txt")
1558
+
1559
+ # Save configuration
1560
+
1561
+ if run_flag:
1562
+ if master_process:
1563
+ config_to_save = {
1564
+ "cli_args": vars(args),
1565
+ "run_uuid": str(run_uuid),
1566
+ "script_code_logged_at_start": True
1567
+ }
1568
+ config_file_path = run_dir_path / "config.json"
1569
+ with open(config_file_path, "w") as f:
1570
+ json.dump(config_to_save, f, indent=4)
1571
+ print0(f"Saved configuration to: {config_file_path}")
1572
+
1573
+ if master_process and logfile:
1574
+ with open(logfile, "w") as f:
1575
+ pass # Create/clear the file
1576
+ with open(logfile, "a") as f:
1577
+ f.write(code)
1578
+
1579
+ if device == "cuda":
1580
+ torch.cuda.reset_peak_memory_stats()
1581
+ timings = []
1582
+ norm = -1.0 # dummy value to print in inference-only mode
1583
+ for step in range(args.num_iterations + 1):
1584
+ t0 = time.time()
1585
+ last_step = (step == args.num_iterations)
1586
+
1587
+ # once in a while evaluate the validation dataset
1588
+ if (args.val_loss_every > 0 \
1589
+ and (step % args.val_loss_every == 0 or last_step)) \
1590
+ and (val_loader is not None):
1591
+ model.eval()
1592
+ val_loader.reset()
1593
+ with torch.no_grad():
1594
+ val_loss = 0.0
1595
+ for _ in range(args.val_max_steps):
1596
+ x, y = val_loader.next_batch()
1597
+ x, y = x.to(device), y.to(device)
1598
+ _, loss = model(x, y, return_logits=False)
1599
+ val_loss += loss.item()
1600
+ val_loss /= args.val_max_steps
1601
+
1602
+ # --- Comprehensive Sharpness Analysis ---
1603
+ sharpness_log_str = ""
1604
+ # Skip step 0 since we don't have a previous training update yet
1605
+ if args.analyze_sharpness and step > 0 and (step % args.sharpness_analysis_interval == 0 or last_step):
1606
+ print0(f"[Sharpness @ Step {step}] Starting comprehensive sharpness analysis...")
1607
+ for optimizer in optimizers:
1608
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1609
+ optimizer.zero_grad(set_to_none=True)
1610
+ elif isinstance(optimizer, Muon):
1611
+ optimizer.zero_grad()
1612
+ comprehensive_results = calculate_comprehensive_sharpness(
1613
+ model=raw_model_uncompiled, # Use uncompiled model for HVP (double backward)
1614
+ model_for_forward=model, # Use compiled+DDP model for forward pass
1615
+ optimizers=optimizers,
1616
+ step=step,
1617
+ train_loader=train_loader,
1618
+ val_loader=val_loader,
1619
+ rank=ddp_rank,
1620
+ world_size=ddp_world_size,
1621
+ device=device,
1622
+ B=B,
1623
+ T=T,
1624
+ ptdtype=ptdtype,
1625
+ grad_accum_steps=grad_accum_steps, # Pass grad accumulation steps to scale loss correctly
1626
+ last_training_update=last_training_update, # Pass the real update captured from training
1627
+ last_training_gradient=last_training_gradient, # Pass the original gradient g_t
1628
+ last_training_batches=last_training_batches # Pass ALL microbatches for consistent HVP
1629
+ )
1630
+ sharpness_log_str = format_comprehensive_results(comprehensive_results)
1631
+
1632
+ # Save sharpness results to file
1633
+ if master_process and run_dir_path:
1634
+ sharpness_file = run_dir_path / f"sharpness_step_{step}.json"
1635
+ with open(sharpness_file, "w") as f:
1636
+ json.dump(comprehensive_results, f, indent=4)
1637
+ print0(f"[Sharpness @ Step {step}] Results saved to {sharpness_file}")
1638
+
1639
+ # Clean up memory after sharpness analysis
1640
+ del comprehensive_results
1641
+ # Ensure all CUDA operations are complete before cleaning up
1642
+ if device == "cuda":
1643
+ torch.cuda.synchronize()
1644
+ torch.cuda.empty_cache()
1645
+ gc.collect()
1646
+ if ddp:
1647
+ dist.barrier() # Sync all ranks after cleanup
1648
+ print0(f"[Step {step}] Memory cleaned up after sharpness analysis")
1649
+
1650
+ # log to console and to file
1651
+ if sharpness_log_str:
1652
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f} | {sharpness_log_str}")
1653
+ else:
1654
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f}")
1655
+
1656
+ if master_process and logfile is not None:
1657
+ with open(logfile, "a") as f:
1658
+ f.write("step:%d validation loss:%f" % (step, val_loss))
1659
+ if sharpness_log_str:
1660
+ f.write(" %s" % sharpness_log_str)
1661
+ f.write("\n")
1662
+
1663
+ # once in a while perform model inference on the master process
1664
+ if (args.sample_every > 0 \
1665
+ and (step % args.sample_every == 0 or last_step)) \
1666
+ and master_process:
1667
+ model.eval()
1668
+ # before we end, let's also do one round of inference
1669
+ # we'll kick off the generation with "<|endoftext|>", which designates the start of a new sequence
1670
+ start_ids = [enc.eot_token]
1671
+ xg = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
1672
+ max_new_tokens = 32
1673
+ temperature = 1.0
1674
+ top_k = 40
1675
+ yg = raw_model.generate(xg, max_new_tokens, temperature=temperature, top_k=top_k)
1676
+ print0('---------------')
1677
+ print0(enc.decode(yg[0].tolist()))
1678
+ print0('---------------')
1679
+
1680
+ # bit confusing: we want to make sure to eval and sample on 0th iteration
1681
+ # but also after the very last iteration. so we loop for step <= num_iterations
1682
+ # instead of just < num_iterations (one extra due to <=), only to do
1683
+ # the validation/sampling one last time, and then we break right here as we're done.
1684
+ if last_step:
1685
+ break
1686
+
1687
+ # --------------- TRAINING SECTION BEGIN -----------------
1688
+ model.train()
1689
+ # Zero gradients for the appropriate optimizer(s)
1690
+
1691
+ for optimizer in optimizers:
1692
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1693
+ optimizer.zero_grad(set_to_none=True)
1694
+ elif isinstance(optimizer, Muon):
1695
+ optimizer.zero_grad()
1696
+ # if args.optimizer == "adam":
1697
+ # optimizer.zero_grad(set_to_none=True)
1698
+ # else: # muon
1699
+ # if muon_optimizer is not None:
1700
+ # muon_optimizer.zero_grad()
1701
+ # if adam_optimizer is not None:
1702
+ # adam_optimizer.zero_grad(set_to_none=True)
1703
+ # if we are trying to overfit a single batch, we reset the loader here
1704
+ if args.overfit_single_batch:
1705
+ train_loader.reset()
1706
+ # micro-batch loop where we do gradient accumulation to reach desired total batch size
1707
+ lossf = 0.0 # for getting the mean loss (as simple float) over the accumulation steps
1708
+
1709
+ # Pre-check if we need to collect microbatches for sharpness analysis
1710
+ next_step = step + 1
1711
+ will_analyze_sharpness_next = args.analyze_sharpness and next_step > 0 and (
1712
+ (next_step % args.sharpness_analysis_interval == 0) or
1713
+ (next_step == args.num_iterations)
1714
+ )
1715
+
1716
+
1717
+ microbatches_this_step = [] if will_analyze_sharpness_next else None
1718
+
1719
+ for micro_step in range(grad_accum_steps):
1720
+ # fetch a batch
1721
+ x, y = train_loader.next_batch()
1722
+ x, y = x.to(device), y.to(device)
1723
+
1724
+ # Store ALL microbatches for memory-efficient HVP calculation
1725
+ if will_analyze_sharpness_next:
1726
+ microbatches_this_step.append((x.detach().clone(), y.detach().clone()))
1727
+
1728
+ if ddp:
1729
+ model.require_backward_grad_sync = (micro_step == grad_accum_steps - 1)
1730
+ # forward pass
1731
+ with ctx:
1732
+ _, loss = model(x, y, return_logits=False)
1733
+ loss = loss / grad_accum_steps
1734
+ lossf += loss.detach() # keep track of the mean loss
1735
+ # backward pass
1736
+ if not args.inference_only:
1737
+ loss.backward()
1738
+ if ddp:
1739
+ dist.all_reduce(lossf, op=dist.ReduceOp.AVG)
1740
+ lossf = lossf.item()
1741
+
1742
+ #no clipping
1743
+ norm = torch.nn.utils.clip_grad_norm_(raw_model_uncompiled.parameters(), args.grad_clip)
1744
+
1745
+
1746
+ if will_analyze_sharpness_next:
1747
+ # Use raw_model_uncompiled's parameter order so it matches sharpness analysis codepaths.
1748
+ # (DDP/torch.compile wrappers can be a footgun if parameter iteration order ever diverges.)
1749
+ print(raw_model_uncompiled.transformer.h[0].attn.q_w.weight[:5,:5])
1750
+ params_before_optimizer_step = [p.detach().clone() for p in raw_model_uncompiled.parameters()]
1751
+ # Save the original gradient g_t that will produce the update v
1752
+ last_training_gradient = [
1753
+ p.grad.detach().clone() if p.grad is not None else torch.zeros_like(p)
1754
+ for p in raw_model_uncompiled.parameters()
1755
+ ]
1756
+ # Capture ALL microbatches for consistent HVP calculation
1757
+ # This ensures H is computed on the exact same objective as g_t and v
1758
+ last_training_batches = microbatches_this_step # Already cloned above
1759
+ else:
1760
+ params_before_optimizer_step = None
1761
+ last_training_batches = None
1762
+
1763
+ # Update learning rate and step optimizers
1764
+ for optimizer in optimizers:
1765
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1766
+ adam_lr = get_wsd_lr(step,args.adam_lr)
1767
+ for param_group in optimizer.param_groups:
1768
+ param_group['lr'] = adam_lr
1769
+ optimizer.step()
1770
+ elif isinstance(optimizer, Muon):
1771
+ muon_lr = get_wsd_lr(step,args.muon_lr)
1772
+ for param_group in optimizer.param_groups:
1773
+ param_group['lr'] = muon_lr
1774
+ optimizer.step()
1775
+ else:
1776
+ raise ValueError(f"Unsupported optimizer: {type(optimizer)}")
1777
+
1778
+
1779
+ if params_before_optimizer_step is not None:
1780
+ # Clean up old update to save memory
1781
+ if last_training_update is not None:
1782
+ del last_training_update
1783
+
1784
+ last_training_update = [
1785
+ p.detach() - p_before
1786
+ for p_before, p in zip(params_before_optimizer_step, raw_model_uncompiled.parameters())
1787
+ ]
1788
+ del params_before_optimizer_step
1789
+
1790
+ # --------------- TRAINING SECTION END -------------------
1791
+
1792
+ # wait on the CPU for all device work to end so we get accurate per-iteration timings below
1793
+ if device == "mps":
1794
+ torch.mps.synchronize()
1795
+ elif device == "cuda":
1796
+ torch.cuda.synchronize()
1797
+ # time and print
1798
+ t1 = time.time()
1799
+ # the 0th iteration is often an outlier (much slower) => skip logging it
1800
+ tokens_per_second = grad_accum_steps * ddp_world_size * B * T / (t1-t0)
1801
+ print0(f"step {step+1:4d}/{args.num_iterations} | train loss {lossf:.6f} | norm {norm:.4f} | ({(t1-t0)*1000:.2f} ms | {tokens_per_second:.0f} tok/s)")
1802
+ # log to logile
1803
+ if master_process and logfile is not None:
1804
+ with open(logfile, "a") as f:
1805
+ f.write("step:%d train loss:%f\n" % (step, lossf))
1806
+
1807
+ # keep track of smooth timings, last 20 iterations
1808
+ if step > 0 and step > args.num_iterations - 20:
1809
+ timings.append(t1-t0)
1810
+
1811
+ # print the average of the last 20 timings, to get something smooth-ish
1812
+ timings = timings[-20:]
1813
+ print0(f"final {len(timings)} iters avg: {np.mean(timings)*1000:.3f}ms")
1814
+ print0(f"peak memory consumption: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB")
1815
+
1816
+ # -------------------------------------------------------------------------
1817
+ # clean up nice
1818
+ if ddp:
1819
+ destroy_process_group()step:0 validation loss:11.020913
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.005,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "c99b1b66-7532-4deb-823d-bdfbb8c6549a",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.005,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "5a199f32-8e9a-4ef5-b431-c80a5fd4dcd9",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.005_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.01,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "fa3316af-70cf-44df-ad5e-5695fe819bde",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_42/training_log.txt ADDED
@@ -0,0 +1,1819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reference code for GPT-2 training and inference with Sharpness Analysis.
3
+ Will save the model weights into files, to be read from C as initialization.
4
+
5
+ References:
6
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
7
+ https://github.com/openai/gpt-2/blob/master/src/model.py
8
+ 2) huggingface/transformers PyTorch implementation:
9
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
10
+
11
+ Example launches to only benchmark the speed of bfloat16 compiled GPU training:
12
+ 1 GPU:
13
+ python train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
14
+ you can also turn on flash-attention by appending --flash=1
15
+ 4 GPU:
16
+ torchrun --standalone --nproc_per_node=4 train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
17
+ """
18
+ import sys
19
+ with open(sys.argv[0]) as f:
20
+ code = f.read() # read the code of this file ASAP, for logging
21
+
22
+ import os
23
+ import math
24
+ import glob
25
+ import struct
26
+ import inspect
27
+ from contextlib import nullcontext
28
+ from dataclasses import dataclass
29
+ import random
30
+
31
+ import numpy as np
32
+ import torch
33
+ from torch import Tensor
34
+ import torch.nn as nn
35
+ from torch.nn import functional as F
36
+ import torch._inductor.config as config
37
+ from torch.nn.parallel import DistributedDataParallel as DDP
38
+ from torch.distributed import init_process_group, destroy_process_group
39
+ from torch.distributed.optim import ZeroRedundancyOptimizer
40
+ import torch.distributed as dist
41
+ from torch.amp import autocast
42
+ import copy
43
+ import gc
44
+ import uuid
45
+ import json
46
+ from pathlib import Path
47
+
48
+ # Import Muon optimizer
49
+ import sys
50
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/optimizers")
51
+ from MUON_fix import Muon
52
+
53
+ # Import GPT model
54
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/models")
55
+ import nano_GPT_qkvonorm_pure
56
+ from nano_GPT_qkvonorm_pure import GPT, GPTConfig
57
+
58
+ # Import debug utilities
59
+ # from debug_utils import setup_debugpy
60
+
61
+ # -----------------------------------------------------------------------------
62
+ # Our own simple Distributed Data Loader
63
+
64
+ def _peek_data_shard(filename):
65
+ # only reads the header, returns header data
66
+ with open(filename, "rb") as f:
67
+ # first read the header, which is 256 int32 integers (4 bytes each)
68
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
69
+ if header[0] != 20240520:
70
+ print("ERROR: magic number mismatch in the data .bin file!")
71
+ print("---> HINT: Are you passing in a correct file with --input_bin?")
72
+ print("---> HINT: Dataset encoding changed recently, re-run data prepro or refer again to README")
73
+ print("---> HINT: For example re-run: `python dev/data/tinyshakespeare.py`, then re-try")
74
+ exit(1)
75
+ assert header[1] == 1, "unsupported version"
76
+ ntok = header[2] # number of tokens (claimed)
77
+ return ntok # for now just return the number of tokens
78
+
79
+ def _load_data_shard(filename):
80
+ with open(filename, "rb") as f:
81
+ # first read the header, which is 256 int32 integers (4 bytes each)
82
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
83
+ assert header[0] == 20240520, "magic number mismatch in the data .bin file"
84
+ assert header[1] == 1, "unsupported version"
85
+ ntok = header[2] # number of tokens (claimed)
86
+ # the rest of it are tokens, stored as uint16
87
+ tokens = np.frombuffer(f.read(), dtype=np.uint16)
88
+ assert len(tokens) == ntok, "number of tokens read does not match header?"
89
+ return tokens
90
+
91
+ class DistributedDataLoader:
92
+ def __init__(self, filename_pattern, B, T, process_rank, num_processes,
93
+ shuffle_files=False, random_seed=None):
94
+ self.process_rank = process_rank
95
+ self.num_processes = num_processes
96
+ self.B = B
97
+ self.T = T
98
+ self.shuffle_files = shuffle_files
99
+ self.random_seed = random_seed
100
+ self._rng = random.Random(random_seed) if shuffle_files and random_seed is not None else None
101
+
102
+ # glob files that match the pattern
103
+ self.files = sorted(glob.glob(filename_pattern))
104
+ assert len(self.files) > 0, f"did not find any files that match the pattern {filename_pattern}"
105
+ if self.shuffle_files:
106
+ self._shuffle_files()
107
+
108
+ # load and validate all data shards, count number of tokens in total
109
+ ntok_total = 0
110
+ for fname in self.files:
111
+ shard_ntok = _peek_data_shard(fname)
112
+ assert shard_ntok >= num_processes * B * T + 1
113
+ ntok_total += shard_ntok
114
+ self.ntok_total = ntok_total
115
+ print0(f"DataLoader: total number of tokens: {ntok_total:,} across {len(self.files)} files")
116
+
117
+ # kick things off
118
+ self.current_shard = None
119
+ self.reset()
120
+
121
+ def reset(self):
122
+ # we're being a bit clever here: if we already had shard 0 loaded,
123
+ # then don't do the work to reload it, just reset the pointer
124
+ if self.current_shard != 0:
125
+ self.current_shard = 0
126
+ self.tokens = _load_data_shard(self.files[self.current_shard])
127
+ self.current_position = self.process_rank * self.B * self.T
128
+
129
+ def advance(self): # advance to next data shard
130
+ next_shard = (self.current_shard + 1) % len(self.files)
131
+ if next_shard == 0 and self.shuffle_files:
132
+ self._shuffle_files()
133
+ self.current_shard = next_shard
134
+ self.current_position = self.process_rank * self.B * self.T
135
+ self.tokens = _load_data_shard(self.files[self.current_shard])
136
+
137
+ def next_batch(self):
138
+ B = self.B
139
+ T = self.T
140
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
141
+ buf = torch.tensor(buf.astype(np.int32), dtype=torch.long)
142
+ x = (buf[:-1]).view(B, T) # inputs
143
+ y = (buf[1:]).view(B, T) # targets
144
+ # advance the start pointer in current shard
145
+ self.current_position += B * T * self.num_processes
146
+ # if loading the next batch would be out of bounds advance the shard
147
+ if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
148
+ self.advance()
149
+ return x, y
150
+
151
+ def _shuffle_files(self):
152
+ if self._rng is not None:
153
+ self._rng.shuffle(self.files)
154
+ else:
155
+ random.shuffle(self.files)
156
+
157
+ # -----------------------------------------------------------------------------
158
+ # Python -> C bridge utilities for saving params/grads/activations to .bin files
159
+
160
+ def write_fp32(tensor, file):
161
+ t = tensor.detach().cpu().to(torch.float32)
162
+ b = t.numpy().tobytes()
163
+ file.write(b)
164
+
165
+ def write_bf16(tensor, file):
166
+ t = tensor.detach().cpu().to(torch.bfloat16)
167
+ # numpy doesn't have bf16 datatype so we have to trick it
168
+ t = t.view(torch.int16) # trick: reinterpret as int16
169
+ b = t.numpy().tobytes()
170
+ file.write(b)
171
+
172
+ def write_tensors(model_tensors, L, file, dtype):
173
+ # writes the GPT-2 model's weights to a binary file
174
+ assert dtype in {"float32", "bfloat16"}
175
+ write_fun = write_fp32 if dtype == "float32" else write_bf16
176
+ write_fun(model_tensors["transformer.wte.weight"], file) # (V, C)
177
+ write_fun(model_tensors["transformer.wpe.weight"], file) # (T, C)
178
+ for i in range(L): # (L, C)
179
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.weight"], file)
180
+ for i in range(L): # (L, C)
181
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.bias"], file)
182
+ for i in range(L): # (L, 3C, C)
183
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.weight"], file)
184
+ for i in range(L): # (L, 3C)
185
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.bias"], file)
186
+ for i in range(L): # (L, C, C)
187
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.weight"], file)
188
+ for i in range(L): # (L, C)
189
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.bias"], file)
190
+ for i in range(L): # (L, C)
191
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.weight"], file)
192
+ for i in range(L): # (L, C)
193
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.bias"], file)
194
+ for i in range(L): # (L, 4C, C)
195
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.weight"], file)
196
+ for i in range(L): # (L, 4C)
197
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.bias"], file)
198
+ for i in range(L): # (L, C, 4C)
199
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.weight"], file)
200
+ for i in range(L): # (L, C)
201
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.bias"], file)
202
+ write_fun(model_tensors["transformer.ln_f.weight"], file) # (C, )
203
+ write_fun(model_tensors["transformer.ln_f.bias"], file) # (C, )
204
+
205
+ @torch.no_grad()
206
+ def pad_vocab(tensor, multiple=128, value=0):
207
+ """
208
+ The dimension of the vocab size in GPT-2 is 50,257
209
+ which is unfortunately a very unfriendly number for a lot of
210
+ matrix operations on the GPU. So we pad it to the nearest
211
+ friendlier multiple, e.g. 50,304 if multiple=128 when we
212
+ export the weights into C land. This is a NOOP algorithmically
213
+ and is only done to make the tensor operations more efficient.
214
+ """
215
+ assert tensor.ndim == 2
216
+ V, C = tensor.shape
217
+ assert V == 50257, "just being defensive here"
218
+ # calculate padded vocab size by rounding up to nearest multiple
219
+ Vp = ((V + multiple - 1) // multiple) * multiple
220
+ # pad the tensor
221
+ pad_rows = Vp - V
222
+ padded = tensor if pad_rows == 0 else F.pad(tensor, (0, 0, 0, pad_rows), value=value)
223
+ assert padded.shape == (Vp, C)
224
+ return padded
225
+
226
+ def write_model(model, filename, dtype):
227
+ # everything we need to instantiate the model
228
+ # 1) header is: version int, GPTConfig ints, padding to 1024 bytes
229
+ assert dtype in {"float32", "bfloat16"} # float16 todo maybe later
230
+ version = {
231
+ "float32": 3, # 3: all tensors are fp32, padded vocab
232
+ "bfloat16": 5, # 5: all tensors are bf16, padded vocab
233
+ }[dtype]
234
+ header = torch.zeros(256, dtype=torch.int32)
235
+ header[0] = 20240326 # magic
236
+ header[1] = version # checkpoint version
237
+ header[2] = model.config.block_size
238
+ header[3] = model.config.vocab_size
239
+ header[4] = model.config.n_layer
240
+ header[5] = model.config.n_head
241
+ header[6] = model.config.n_embd
242
+ # 2) the parameters follow the header
243
+ params = {name: param.cpu() for name, param in model.named_parameters()}
244
+ # pad the vocab to a multiple of 128 here at export, for efficiency in C
245
+ wte = params["transformer.wte.weight"] # (V, C)
246
+ wte_padded = pad_vocab(wte) # (Vp, C)
247
+ params["transformer.wte.weight"] = wte_padded # (Vp, C)
248
+ print(f"padded vocab size from {wte.size(0)} to {wte_padded.size(0)}")
249
+ header[7] = wte_padded.size(0) # padded vocab size store in header
250
+ # now write to file
251
+ with open(filename, "wb") as file:
252
+ file.write(header.numpy().tobytes()) # header
253
+ write_tensors(params, model.config.n_layer, file, dtype) # params
254
+ print(f"wrote {filename}")
255
+
256
+ def write_state(model, x, y, logits, loss, filename):
257
+ # the state is used for debugging.
258
+ # it contains information about the input, logits, loss, and the parameter gradients
259
+ # this can be used for checking the computation correctness in C
260
+ header = torch.zeros(256, dtype=torch.int32)
261
+ header[0] = 20240327 # magic
262
+ header[1] = 2 # run state version = 2 (1 -> 2 for padded vocab changes)
263
+ header[2] = x.size(0) # batch size of the batch, B
264
+ header[3] = x.size(1) # temporal extent of the batch, T
265
+ grads = {name: param.grad.cpu() for name, param in model.named_parameters()}
266
+ # pad the vocab grads here as well, to mirror write_model
267
+ wte_grad = grads["transformer.wte.weight"] # (V, C)
268
+ wte_grad_padded = pad_vocab(wte_grad, value=0) # (Vp, C) # TODO later maybe pad with nan?
269
+ grads["transformer.wte.weight"] = wte_grad_padded # (Vp, C)
270
+ print(f"padded vocab size in reference grads from {wte_grad.size(0)} to {wte_grad_padded.size(0)}")
271
+ with open(filename, "wb") as file:
272
+ # header
273
+ file.write(header.numpy().tobytes())
274
+ # input x
275
+ file.write(x.cpu().numpy().astype("int32").tobytes()) # (B, T)
276
+ # targets y
277
+ file.write(y.cpu().numpy().astype("int32").tobytes()) # (B, T)
278
+ # logits (result of the model forward pass)
279
+ write_fp32(logits.cpu(), file)
280
+ # loss (single float, result of the cross entropy loss)
281
+ write_fp32(loss.cpu(), file)
282
+ # gradients
283
+ write_tensors(grads, model.config.n_layer, file, "float32")
284
+ print(f"wrote {filename}")
285
+
286
+ def write_tokenizer(enc, filename):
287
+ n = enc.max_token_value + 1
288
+ header = torch.zeros(256, dtype=torch.int32)
289
+ header[0] = 20240328 # magic
290
+ header[1] = 2 # tokenizer version = 2 (1 -> 2: includes EOT token)
291
+ header[2] = n # number of tokens
292
+ header[3] = enc.eot_token # EOT token
293
+ with open(filename, "wb") as file:
294
+ file.write(header.numpy().tobytes())
295
+ for i in range(n):
296
+ b = enc.decode_bytes([i])
297
+ length = len(b)
298
+ assert length < 256, f"Token length exceeds 255: {length}"
299
+ file.write(struct.pack("<B", length)) # Write the length as a 1-byte unsigned integer
300
+ file.write(b) # Write the actual bytes
301
+ print(f"wrote {filename}")
302
+
303
+ def set_seed(seed):
304
+ random.seed(seed)
305
+ np.random.seed(seed)
306
+ torch.manual_seed(seed)
307
+ if torch.cuda.is_available():
308
+ torch.cuda.manual_seed_all(seed)
309
+ print(f"PRINT: Set seed to {seed}", flush=True) # Print immediately for all ranks
310
+
311
+ # -----------------------------------------------------------------------------
312
+ # Helper functions for norm calculations
313
+
314
+ def calculate_l1_to_linf_norm(matrix):
315
+ if matrix.ndim == 1:
316
+ return torch.sum(torch.abs(matrix))
317
+ elif matrix.ndim == 2:
318
+ # Each row's L1 norm, then take maximum
319
+ row_l1_norms = torch.sum(torch.abs(matrix), dim=1)
320
+ return torch.max(row_l1_norms)
321
+ else:
322
+ # For higher-dimensional tensors, flatten to 2D
323
+ matrix_2d = matrix.view(matrix.shape[0], -1)
324
+ row_l1_norms = torch.sum(torch.abs(matrix_2d), dim=1)
325
+ return torch.max(row_l1_norms)
326
+
327
+ def calculate_spectral_norm(matrix):
328
+ """
329
+ Calculate the spectral norm (largest singular value) of a matrix.
330
+ For vectors, returns the L2 norm.
331
+ """
332
+ # Convert to float32 if needed for linalg operations
333
+ if matrix.dtype in [torch.bfloat16, torch.float16]:
334
+ matrix = matrix.float()
335
+
336
+ if matrix.ndim == 1:
337
+ return torch.norm(matrix, p=2)
338
+ elif matrix.ndim == 2:
339
+ # Use matrix 2-norm (largest singular value)
340
+ return torch.linalg.matrix_norm(matrix, ord=2)
341
+ else:
342
+ # For higher-dimensional tensors, flatten to 2D
343
+ matrix_2d = matrix.view(matrix.shape[0], -1)
344
+ return torch.linalg.matrix_norm(matrix_2d, ord=2)
345
+
346
+ # -----------------------------------------------------------------------------
347
+ # Comprehensive sharpness analysis function
348
+
349
+ def calculate_comprehensive_sharpness(model, model_for_forward, optimizers, step, train_loader, val_loader,
350
+ rank, world_size, device, B, T, ptdtype, grad_accum_steps, last_training_update=None, last_training_gradient=None, last_training_batches=None):
351
+ prev_training_mode = model.training
352
+ model.eval()
353
+
354
+ NUM_LAYERS = model.config.n_layer # Number of transformer blocks
355
+ analysis_results = {}
356
+
357
+ # --- 1. Get the true update direction 'v' ---
358
+ assert last_training_update is not None, \
359
+ f"[Step {step}] BUG: last_training_update is None! Check sharpness timing logic."
360
+
361
+ print0(f"[Enhanced Sharpness @ Step {step}] Using update from previous training step")
362
+ update_direction_v = last_training_update
363
+
364
+
365
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters to θ_t for HVP calculation...")
366
+ with torch.no_grad():
367
+ for p, v in zip(model.parameters(), update_direction_v):
368
+ p.data.sub_(v) # Now parameters are at θ_t
369
+
370
+ # --- 2. Calculate update norms (Frobenius, Max-of-Max, Spectral) ---
371
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating update norms...")
372
+
373
+ total_update_norm_sq = sum(torch.sum(v * v) for v in update_direction_v)
374
+ dist.all_reduce(total_update_norm_sq, op=dist.ReduceOp.AVG)
375
+ analysis_results["total_update_fnorm"] = torch.sqrt(total_update_norm_sq).item()
376
+
377
+ # Calculate TOTAL update Max-of-Max and Spectral norms
378
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating total update Max-of-Max and Spectral norms...")
379
+ try:
380
+ all_updates_flat = torch.cat([v.flatten() for v in update_direction_v if v.numel() > 0])
381
+
382
+ if all_updates_flat.numel() > 0:
383
+ total_l1_linf_norm = torch.sum(torch.abs(all_updates_flat))
384
+ analysis_results["total_l1_linf_norm"] = total_l1_linf_norm.item()
385
+
386
+ total_spectral_norm = torch.norm(all_updates_flat, p=2)
387
+ analysis_results["total_spectral_norm"] = total_spectral_norm.item()
388
+ else:
389
+ analysis_results["total_l1_linf_norm"] = 0.0
390
+ analysis_results["total_spectral_norm"] = 0.0
391
+
392
+ del all_updates_flat
393
+ except Exception as e:
394
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating total norms: {e}")
395
+ analysis_results["total_l1_linf_norm"] = 0.0
396
+ analysis_results["total_spectral_norm"] = 0.0
397
+
398
+ # --- 3. Setup layer parameter groups (adapt to new model structure) ---
399
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up layer parameter groups...")
400
+
401
+ all_param_groups = {}
402
+
403
+
404
+ all_param_groups["embed_lm_head"] = list(model.lm_head.parameters())
405
+
406
+ blocks = model.transformer.h
407
+
408
+ for i, block in enumerate(blocks):
409
+ layer_name = f"layer_{i+1}"
410
+ all_param_groups[layer_name] = list(block.parameters())
411
+
412
+ # Add fine-grained params for selected layers (0, 3, 7, 11)
413
+ selected_layers = [0, 3, 7, 11]
414
+ for layer_idx in selected_layers:
415
+ block = blocks[layer_idx]
416
+ prefix = f"block{layer_idx}"
417
+ # Attention: Q, K, V, O
418
+ all_param_groups[f"{prefix}_q"] = [block.attn.q_w.weight]
419
+ all_param_groups[f"{prefix}_k"] = [block.attn.k_w.weight]
420
+ all_param_groups[f"{prefix}_v"] = [block.attn.v_w.weight]
421
+ all_param_groups[f"{prefix}_o"] = [block.attn.c_proj.weight]
422
+ # MLP: c_fc (win) and c_proj (wout)
423
+ all_param_groups[f"{prefix}_mlp_win"] = [block.mlp.c_fc.weight]
424
+ all_param_groups[f"{prefix}_mlp_wout"] = [block.mlp.c_proj.weight]
425
+
426
+ # --- 4. Calculate layer-wise update norms ---
427
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise update norms...")
428
+
429
+ param_to_idx = {id(p): i for i, p in enumerate(model.parameters())}
430
+
431
+ for group_name, param_group in all_param_groups.items():
432
+ if not param_group:
433
+ continue
434
+
435
+ # Get indices for this group
436
+ indices = [param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx]
437
+ if not indices:
438
+ continue
439
+
440
+ # Calculate Frobenius norm for this group
441
+ group_update_norm_sq = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
442
+ dist.all_reduce(group_update_norm_sq, op=dist.ReduceOp.AVG)
443
+ analysis_results[f"{group_name}_update_fnorm"] = torch.sqrt(group_update_norm_sq).item()
444
+
445
+ # Calculate Max-of-Max and Spectral norms for this group
446
+ group_l1_linf_norms = []
447
+ group_spectral_norms = []
448
+
449
+ for i in indices:
450
+ if i < len(update_direction_v) and update_direction_v[i].numel() > 0:
451
+ try:
452
+ l1_linf_norm = calculate_l1_to_linf_norm(update_direction_v[i])
453
+ group_l1_linf_norms.append(l1_linf_norm.item())
454
+
455
+ spectral_norm = calculate_spectral_norm(update_direction_v[i])
456
+ group_spectral_norms.append(spectral_norm.item())
457
+ except Exception as e:
458
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating norms for group {group_name}, param {i}: {e}")
459
+ group_l1_linf_norms.append(0.0)
460
+ group_spectral_norms.append(0.0)
461
+
462
+ if group_l1_linf_norms:
463
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = max(group_l1_linf_norms)
464
+ else:
465
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = 0.0
466
+
467
+ if group_spectral_norms:
468
+ analysis_results[f"{group_name}_max_spectral_norm"] = max(group_spectral_norms)
469
+ else:
470
+ analysis_results[f"{group_name}_max_spectral_norm"] = 0.0
471
+
472
+ # --- 5. Setup for HVP calculation on TRAIN data ---
473
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up HVP calculation in {ptdtype} on TRAIN data...")
474
+
475
+ original_flash = nano_GPT_qkvonorm_pure.FLASH
476
+ nano_GPT_qkvonorm_pure.FLASH = 0
477
+ print0(f"[Enhanced Sharpness @ Step {step}] Disabled FLASH attention for HVP (was {original_flash})")
478
+
479
+ # Get block parameter indices for cross-layer analysis (need this before loop)
480
+ block_param_indices = set()
481
+ for group_name, param_group in all_param_groups.items():
482
+ if group_name.startswith("layer_"):
483
+ for p in param_group:
484
+ if id(p) in param_to_idx:
485
+ block_param_indices.add(param_to_idx[id(p)])
486
+
487
+ # Initialize accumulators for all quantities we need
488
+ grads_hvp = None
489
+ hvp_v_total = None
490
+ hvp_v_block = None
491
+ hvp_g_accum = None
492
+ layer_hvp_accum = {}
493
+
494
+
495
+ group_names_to_process = [gn for gn, pg in all_param_groups.items()
496
+ if pg and any(id(p) in param_to_idx for p in pg)]
497
+
498
+ if last_training_batches is not None and len(last_training_batches) > 0:
499
+
500
+ batch_iterator = [(x, y) for x, y in last_training_batches]
501
+ n_batches = len(batch_iterator)
502
+ print0(f"[Enhanced Sharpness @ Step {step}] Using {n_batches} microbatches for HVP (out of {grad_accum_steps} training microbatches)")
503
+ restore_loader = False
504
+ else:
505
+ # Fallback: use new batches from train_loader (should rarely happen)
506
+ print0(f"[Enhanced Sharpness @ Step {step}] WARNING: last_training_batches is None/empty, using {grad_accum_steps} new batches (inconsistent)")
507
+ saved_current_shard = train_loader.current_shard
508
+ saved_current_position = train_loader.current_position
509
+ n_batches = grad_accum_steps # Use same number as training for consistency
510
+ batch_iterator = []
511
+ shard_was_changed = False
512
+ for _ in range(n_batches):
513
+ x_hvp, y_hvp = train_loader.next_batch()
514
+ batch_iterator.append((x_hvp, y_hvp))
515
+ shard_was_changed = shard_was_changed or (train_loader.current_shard != saved_current_shard)
516
+ restore_loader = True
517
+
518
+
519
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing HVPs for {n_batches} microbatches")
520
+ for mb_idx, (x_hvp, y_hvp) in enumerate(batch_iterator):
521
+ x_hvp, y_hvp = x_hvp.to(device), y_hvp.to(device)
522
+
523
+
524
+ _, loss_mb = model(x_hvp, y_hvp, return_logits=False)
525
+ grads_mb = torch.autograd.grad(loss_mb, model.parameters(), create_graph=True, allow_unused=True)
526
+
527
+ # Compute H·v (total sharpness)
528
+ v_dot_g_total = sum(torch.sum(g * v) for g, v in zip(grads_mb, update_direction_v) if g is not None)
529
+
530
+ if not isinstance(v_dot_g_total, torch.Tensor):
531
+ v_dot_g_total = torch.tensor(0.0, device=device, requires_grad=True)
532
+ hvp_v_total_mb = torch.autograd.grad(v_dot_g_total, model.parameters(), retain_graph=True, allow_unused=True)
533
+
534
+ # Compute H·v_block (block-only sharpness)
535
+ if block_param_indices:
536
+ v_dot_g_block = sum(torch.sum(grads_mb[i] * update_direction_v[i])
537
+ for i in block_param_indices if grads_mb[i] is not None)
538
+ if not isinstance(v_dot_g_block, torch.Tensor):
539
+ v_dot_g_block = torch.tensor(0.0, device=device, requires_grad=True)
540
+ hvp_v_block_mb = torch.autograd.grad(v_dot_g_block, model.parameters(), retain_graph=True, allow_unused=True)
541
+ else:
542
+
543
+ hvp_v_block_mb = [None] * len(list(model.parameters()))
544
+
545
+
546
+ g_dot_g = sum(torch.sum(g * g) for g in grads_mb if g is not None)
547
+ if not isinstance(g_dot_g, torch.Tensor):
548
+ g_dot_g = torch.tensor(0.0, device=device, requires_grad=True)
549
+
550
+
551
+ hvp_g_mb_raw = torch.autograd.grad(g_dot_g, model.parameters(),
552
+ retain_graph=True, allow_unused=True)
553
+ hvp_g_mb = [h / 2.0 if h is not None else None for h in hvp_g_mb_raw]
554
+
555
+ # Compute per-layer H_kk·v_k (for layer-wise sharpness)
556
+ for group_idx, group_name in enumerate(group_names_to_process):
557
+ param_group = all_param_groups[group_name]
558
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
559
+ if not indices:
560
+ continue
561
+
562
+ is_last_layer = (group_idx == len(group_names_to_process) - 1)
563
+ is_last_microbatch = (mb_idx == n_batches - 1)
564
+ need_retain = not (is_last_layer and is_last_microbatch)
565
+
566
+ try:
567
+ v_dot_g_layer = sum(torch.sum(grads_mb[i] * update_direction_v[i])
568
+ for i in indices if grads_mb[i] is not None)
569
+
570
+ if not isinstance(v_dot_g_layer, torch.Tensor):
571
+ v_dot_g_layer = torch.tensor(0.0, device=device, requires_grad=True)
572
+
573
+ hvp_layer_mb = torch.autograd.grad(v_dot_g_layer, model.parameters(),
574
+ retain_graph=need_retain,
575
+ allow_unused=True)
576
+
577
+ if group_name not in layer_hvp_accum:
578
+ layer_hvp_accum[group_name] = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_layer_mb]
579
+ else:
580
+ layer_hvp_accum[group_name] = [
581
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
582
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
583
+ for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
584
+ ]
585
+
586
+ # Accumulate layer HVP
587
+ # if group_name not in layer_hvp_accum:
588
+ # layer_hvp_accum[group_name] = [h.detach() / n_batches if h is not None else None for h in hvp_layer_mb]
589
+ # else:
590
+ # layer_hvp_accum[group_name] = [
591
+ # (h_acc + h.detach() / n_batches) if (h is not None and h_acc is not None)
592
+ # else (h.detach() / n_batches if h is not None else h_acc)
593
+ # for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
594
+ # ]
595
+ # del hvp_layer_mb, v_dot_g_layer
596
+ # torch.cuda.empty_cache()
597
+ except Exception as e:
598
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing layer HVP for '{group_name}' in microbatch {mb_idx}: {e}")
599
+ if group_name not in layer_hvp_accum:
600
+ layer_hvp_accum[group_name] = None
601
+
602
+ # 6. Accumulate all quantities
603
+ if grads_hvp is None:
604
+ grads_hvp = [(g.detach() / n_batches).cpu() if g is not None else None for g in grads_mb]
605
+ hvp_v_total = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_total_mb]
606
+ hvp_v_block = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_block_mb]
607
+ hvp_g_accum = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_g_mb]
608
+ else:
609
+ grads_hvp = [
610
+ (g_acc + (g.detach() / n_batches).cpu()) if (g is not None and g_acc is not None)
611
+ else ((g.detach() / n_batches).cpu() if g is not None else g_acc)
612
+ for g_acc, g in zip(grads_hvp, grads_mb)
613
+ ]
614
+ hvp_v_total = [
615
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
616
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
617
+ for h_acc, h in zip(hvp_v_total, hvp_v_total_mb)
618
+ ]
619
+ hvp_v_block = [
620
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
621
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
622
+ for h_acc, h in zip(hvp_v_block, hvp_v_block_mb)
623
+ ]
624
+ hvp_g_accum = [
625
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
626
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
627
+ for h_acc, h in zip(hvp_g_accum, hvp_g_mb)
628
+ ]
629
+
630
+
631
+
632
+ if mb_idx % max(1, n_batches // 4) == 0:
633
+ print0(f"[Enhanced Sharpness @ Step {step}] Processed microbatch {mb_idx + 1}/{n_batches}")
634
+
635
+
636
+ if restore_loader:
637
+ train_loader.current_shard = saved_current_shard
638
+ train_loader.current_position = saved_current_position
639
+ if shard_was_changed:
640
+ train_loader.tokens = _load_data_shard(train_loader.files[train_loader.current_shard])
641
+
642
+ print0(f"[Enhanced Sharpness @ Step {step}] Finished computing all HVPs for {n_batches} microbatches")
643
+ grads_hvp = [g.to(device) if g is not None else None for g in grads_hvp]
644
+ hvp_v_total = [h.to(device) if h is not None else None for h in hvp_v_total]
645
+ hvp_v_block = [h.to(device) if h is not None else None for h in hvp_v_block]
646
+ hvp_g_accum = [h.to(device) if h is not None else None for h in hvp_g_accum]
647
+ for group_name in layer_hvp_accum:
648
+ if layer_hvp_accum[group_name] is not None:
649
+ layer_hvp_accum[group_name] = [h.to(device) if h is not None else None for h in layer_hvp_accum[group_name]]
650
+ # --- Calculate TOTAL sharpness ---
651
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating TOTAL sharpness...")
652
+ # hvp_v_total is already computed in the loop above
653
+ vhp_dot_v_total = sum(torch.sum(hvp * v) for hvp, v in zip(hvp_v_total, update_direction_v) if hvp is not None)
654
+ v_norm_sq_total = sum(torch.sum(v * v) for v in update_direction_v)
655
+
656
+ # Ensure they are tensors
657
+ if not isinstance(vhp_dot_v_total, torch.Tensor):
658
+ vhp_dot_v_total = torch.tensor(0.0, device=device)
659
+ if not isinstance(v_norm_sq_total, torch.Tensor):
660
+ v_norm_sq_total = torch.tensor(0.0, device=device)
661
+
662
+ dist.all_reduce(vhp_dot_v_total, op=dist.ReduceOp.AVG)
663
+ dist.all_reduce(v_norm_sq_total, op=dist.ReduceOp.AVG)
664
+
665
+ if v_norm_sq_total.item() > 1e-12:
666
+ analysis_results["total_sharpness"] = (vhp_dot_v_total / v_norm_sq_total).item()
667
+ else:
668
+ analysis_results["total_sharpness"] = 0.0
669
+
670
+
671
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating BLOCK-ONLY total sharpness...")
672
+ # hvp_v_block is already computed in the loop above
673
+ if block_param_indices: # Only compute if there are block parameters
674
+ # Compute v_block^T H v_block (only sum over block indices)
675
+ vhp_dot_v_block = sum(torch.sum(hvp_v_block[i] * update_direction_v[i])
676
+ for i in block_param_indices if hvp_v_block[i] is not None)
677
+
678
+ v_norm_sq_block = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
679
+ for i in block_param_indices)
680
+
681
+ # Ensure they are tensors
682
+ if not isinstance(vhp_dot_v_block, torch.Tensor):
683
+ vhp_dot_v_block = torch.tensor(0.0, device=device)
684
+ if not isinstance(v_norm_sq_block, torch.Tensor):
685
+ v_norm_sq_block = torch.tensor(0.0, device=device)
686
+
687
+ dist.all_reduce(vhp_dot_v_block, op=dist.ReduceOp.AVG)
688
+ dist.all_reduce(v_norm_sq_block, op=dist.ReduceOp.AVG)
689
+
690
+ if v_norm_sq_block.item() > 1e-12:
691
+ analysis_results["block_total_sharpness"] = (vhp_dot_v_block / v_norm_sq_block).item()
692
+ else:
693
+ analysis_results["block_total_sharpness"] = 0.0
694
+
695
+ analysis_results["v_norm_block"] = torch.sqrt(v_norm_sq_block).item()
696
+ analysis_results["v_T_H_v_block"] = vhp_dot_v_block.item()
697
+ else:
698
+ # No block parameters
699
+ analysis_results["block_total_sharpness"] = 0.0
700
+ analysis_results["v_norm_block"] = 0.0
701
+ analysis_results["v_T_H_v_block"] = 0.0
702
+
703
+ torch.cuda.empty_cache()
704
+
705
+ # ---- Alignment metrics between update v and (negative) gradient g ----
706
+ eps = 1e-12
707
+ v_norm = torch.sqrt(v_norm_sq_total + eps)
708
+ analysis_results["v_norm"] = v_norm.item()
709
+
710
+ # --- Version 1: g_hvp ---
711
+ ip_v_neg_g_hvp = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, grads_hvp) if g is not None)
712
+ g_hvp_norm_sq = sum(torch.sum(g * g) for g in grads_hvp if g is not None)
713
+
714
+ if not isinstance(ip_v_neg_g_hvp, torch.Tensor):
715
+ ip_v_neg_g_hvp = torch.tensor(0.0, device=device)
716
+ if not isinstance(g_hvp_norm_sq, torch.Tensor):
717
+ g_hvp_norm_sq = torch.tensor(0.0, device=device)
718
+ dist.all_reduce(ip_v_neg_g_hvp, op=dist.ReduceOp.AVG)
719
+ dist.all_reduce(g_hvp_norm_sq, op=dist.ReduceOp.AVG)
720
+ g_hvp_norm = torch.sqrt(g_hvp_norm_sq + eps)
721
+ analysis_results["ip_v_neg_g_hvp"] = ip_v_neg_g_hvp.item()
722
+ analysis_results["cos_v_neg_g_hvp"] = (ip_v_neg_g_hvp / (v_norm * g_hvp_norm + eps)).item()
723
+ analysis_results["g_hvp_norm"] = g_hvp_norm.item()
724
+
725
+ # --- Version 2: g_t (original gradient that produced v) ---
726
+ # last_training_gradient is the actual gradient from training that led to the update v
727
+ if last_training_gradient is not None:
728
+ ip_v_neg_g_t = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, last_training_gradient) if g is not None)
729
+ g_t_norm_sq = sum(torch.sum(g * g) for g in last_training_gradient if g is not None)
730
+ dist.all_reduce(ip_v_neg_g_t, op=dist.ReduceOp.AVG)
731
+ dist.all_reduce(g_t_norm_sq, op=dist.ReduceOp.AVG)
732
+ g_t_norm = torch.sqrt(g_t_norm_sq + eps)
733
+ analysis_results["ip_v_neg_g_t"] = ip_v_neg_g_t.item()
734
+ analysis_results["cos_v_neg_g_t"] = (ip_v_neg_g_t / (v_norm * g_t_norm + eps)).item()
735
+ analysis_results["g_t_norm"] = g_t_norm.item()
736
+ else:
737
+ print0(f"[Enhanced Sharpness @ Step {step}] Warning: last_training_gradient is None, skipping g_t metrics")
738
+
739
+ # Keep backward compatibility aliases (g_norm uses g_hvp for now)
740
+ g_norm_sq = g_hvp_norm_sq
741
+ g_norm = g_hvp_norm
742
+ analysis_results["g_norm"] = g_norm.item()
743
+
744
+ # ---- Cosine between v and Hv (curvature pull along v) ----
745
+ hv_norm_sq = sum(torch.sum(hvp * hvp) for hvp in hvp_v_total if hvp is not None)
746
+ if not isinstance(hv_norm_sq, torch.Tensor):
747
+ hv_norm_sq = torch.tensor(0.0, device=device)
748
+ dist.all_reduce(hv_norm_sq, op=dist.ReduceOp.AVG)
749
+ hv_norm = torch.sqrt(hv_norm_sq + eps)
750
+ ip_v_hv = vhp_dot_v_total # already reduced AVG
751
+ analysis_results["hv_norm"] = hv_norm.item()
752
+ analysis_results["cos_v_hv"] = (ip_v_hv / (v_norm * hv_norm + eps)).item()
753
+
754
+ # ---- Cosine between g and Hg ----
755
+ # hvp_g_accum is already computed in the loop above
756
+ ip_g_hg = sum(torch.sum(g * hg) for g, hg in zip(grads_hvp, hvp_g_accum) if (g is not None and hg is not None))
757
+ hg_norm_sq = sum(torch.sum(hg * hg) for hg in hvp_g_accum if hg is not None)
758
+ if not isinstance(ip_g_hg, torch.Tensor):
759
+ ip_g_hg = torch.tensor(0.0, device=device)
760
+ if not isinstance(hg_norm_sq, torch.Tensor):
761
+ hg_norm_sq = torch.tensor(0.0, device=device)
762
+ dist.all_reduce(ip_g_hg, op=dist.ReduceOp.AVG)
763
+ dist.all_reduce(hg_norm_sq, op=dist.ReduceOp.AVG)
764
+ hg_norm = torch.sqrt(hg_norm_sq + eps)
765
+ analysis_results["hg_norm"] = hg_norm.item()
766
+ analysis_results["cos_g_hg"] = (ip_g_hg / (g_norm * hg_norm + eps)).item() if g_norm.item() > 0 else 0.0
767
+
768
+ # ---- Decompose v into parallel / perpendicular to -g ----
769
+ if g_norm.item() > 0:
770
+ v_parallel = [(torch.sum(v * (-g)) / (g_norm_sq + eps)) * (-g) if g is not None else torch.zeros_like(v)
771
+ for v, g in zip(update_direction_v, grads_hvp)]
772
+ v_parallel_norm_sq = sum(torch.sum(vp * vp) for vp in v_parallel)
773
+ if not isinstance(v_parallel_norm_sq, torch.Tensor):
774
+ v_parallel_norm_sq = torch.tensor(0.0, device=device)
775
+ dist.all_reduce(v_parallel_norm_sq, op=dist.ReduceOp.AVG)
776
+ v_parallel_norm = torch.sqrt(v_parallel_norm_sq + eps)
777
+ v_perp_norm = torch.sqrt(torch.clamp(v_norm_sq_total - v_parallel_norm_sq, min=0.0) + eps)
778
+ analysis_results["v_parallel_norm"] = v_parallel_norm.item()
779
+ analysis_results["v_perp_norm"] = v_perp_norm.item()
780
+
781
+ # ---- Per-layer additions: cos_v_neg_g_layer, v_norm_layer ----
782
+ for group_name, param_group in all_param_groups.items():
783
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
784
+ if not indices:
785
+ continue
786
+ v_norm_sq_layer = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
787
+ g_norm_sq_layer = sum(torch.sum(grads_hvp[i] * grads_hvp[i]) for i in indices if grads_hvp[i] is not None)
788
+ ip_v_neg_g_layer = sum(torch.sum(update_direction_v[i] * (-grads_hvp[i]))
789
+ for i in indices if grads_hvp[i] is not None)
790
+ # Ensure they are tensors
791
+ if not isinstance(v_norm_sq_layer, torch.Tensor):
792
+ v_norm_sq_layer = torch.tensor(0.0, device=device)
793
+ if not isinstance(g_norm_sq_layer, torch.Tensor):
794
+ g_norm_sq_layer = torch.tensor(0.0, device=device)
795
+ if not isinstance(ip_v_neg_g_layer, torch.Tensor):
796
+ ip_v_neg_g_layer = torch.tensor(0.0, device=device)
797
+ dist.all_reduce(v_norm_sq_layer, op=dist.ReduceOp.AVG)
798
+ dist.all_reduce(g_norm_sq_layer, op=dist.ReduceOp.AVG)
799
+ dist.all_reduce(ip_v_neg_g_layer, op=dist.ReduceOp.AVG)
800
+ v_norm_layer = torch.sqrt(v_norm_sq_layer + eps)
801
+ g_norm_layer = torch.sqrt(g_norm_sq_layer + eps)
802
+ analysis_results[f"{group_name}_v_norm"] = v_norm_layer.item()
803
+ if g_norm_layer.item() > 0:
804
+ analysis_results[f"{group_name}_cos_v_neg_g"] = (ip_v_neg_g_layer / (v_norm_layer * g_norm_layer + eps)).item()
805
+
806
+ # --- 7. Calculate layer-wise sharpness ---
807
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise sharpness...")
808
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing {len(all_param_groups)} layers for sharpness...")
809
+
810
+ for group_name, param_group in all_param_groups.items():
811
+ if not param_group:
812
+ continue
813
+
814
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing '{group_name}'...")
815
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
816
+ if not indices:
817
+ continue
818
+
819
+ try:
820
+ if group_name not in layer_hvp_accum or layer_hvp_accum[group_name] is None:
821
+ print0(f"[Enhanced Sharpness @ Step {step}] No HVP data for '{group_name}', skipping")
822
+ analysis_results[f"{group_name}_sharpness"] = 0.0
823
+ continue
824
+
825
+ hvp_group_result = layer_hvp_accum[group_name]
826
+
827
+ vhp_dot_v_group = sum(torch.sum(hvp_group_result[i] * update_direction_v[i])
828
+ for i in indices if hvp_group_result[i] is not None)
829
+ v_norm_sq_group = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
830
+ for i in indices)
831
+
832
+ # Ensure they are tensors
833
+ if not isinstance(vhp_dot_v_group, torch.Tensor):
834
+ vhp_dot_v_group = torch.tensor(0.0, device=device)
835
+ if not isinstance(v_norm_sq_group, torch.Tensor):
836
+ v_norm_sq_group = torch.tensor(0.0, device=device)
837
+
838
+ dist.all_reduce(vhp_dot_v_group, op=dist.ReduceOp.AVG)
839
+ dist.all_reduce(v_norm_sq_group, op=dist.ReduceOp.AVG)
840
+
841
+ if v_norm_sq_group.item() > 1e-12:
842
+ analysis_results[f"{group_name}_sharpness"] = (vhp_dot_v_group / v_norm_sq_group).item()
843
+ else:
844
+ analysis_results[f"{group_name}_sharpness"] = 0.0
845
+
846
+ except torch.OutOfMemoryError as e:
847
+ print0(f"[Enhanced Sharpness @ Step {step}] OOM error for '{group_name}': {e}")
848
+ analysis_results[f"{group_name}_sharpness"] = 0.0
849
+ torch.cuda.empty_cache()
850
+ except Exception as e:
851
+ print0(f"[Enhanced Sharpness @ Step {step}] Error processing '{group_name}': {e}")
852
+ analysis_results[f"{group_name}_sharpness"] = 0.0
853
+
854
+ # --- Calculate block-diagonal approximation and cross-layer interaction ---
855
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating block-diagonal and cross-layer sharpness...")
856
+
857
+ sum_layer_numerators = 0.0
858
+ for layer in range(1, NUM_LAYERS + 1):
859
+ layer_name = f"layer_{layer}"
860
+ if f"{layer_name}_sharpness" in analysis_results and f"{layer_name}_v_norm" in analysis_results:
861
+ s_k = analysis_results[f"{layer_name}_sharpness"]
862
+ v_k_norm = analysis_results[f"{layer_name}_v_norm"]
863
+ sum_layer_numerators += s_k * (v_k_norm ** 2)
864
+
865
+ analysis_results["sum_layer_numerators"] = sum_layer_numerators
866
+
867
+ # Block-diagonal sharpness (using block ||v||²)
868
+ v_norm_block = analysis_results.get("v_norm_block", 0)
869
+ v_norm_sq_block_val = v_norm_block ** 2 if v_norm_block else 1e-12
870
+
871
+ if v_norm_sq_block_val > 1e-12:
872
+ analysis_results["block_diag_sharpness"] = sum_layer_numerators / v_norm_sq_block_val
873
+ else:
874
+ analysis_results["block_diag_sharpness"] = 0.0
875
+
876
+ # Cross-layer interaction = block_total - block_diag
877
+ block_total = analysis_results.get("block_total_sharpness", 0)
878
+ block_diag = analysis_results.get("block_diag_sharpness", 0)
879
+ analysis_results["cross_layer_sharpness"] = block_total - block_diag
880
+
881
+ print0(f"[Enhanced Sharpness @ Step {step}] block_total={block_total:.6f}, block_diag={block_diag:.6f}, cross_layer={block_total - block_diag:.6f}")
882
+
883
+ # --- Compute true_dec and pred_dec ---
884
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing true_dec (L(t) - L(t+1)) on training batch...")
885
+ try:
886
+ # Restore FLASH for forward pass
887
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
888
+
889
+
890
+ loss_at_theta_t = 0.0
891
+ with torch.no_grad():
892
+ for x_td, y_td in batch_iterator:
893
+ x_td, y_td = x_td.to(device), y_td.to(device)
894
+ _, loss_td = model(x_td, y_td, return_logits=False)
895
+ loss_at_theta_t += loss_td.item()
896
+ loss_at_theta_t /= len(batch_iterator) # average over microbatches
897
+
898
+ with torch.no_grad():
899
+ for p, v in zip(model.parameters(), update_direction_v):
900
+ p.data.add_(v)
901
+
902
+ loss_at_theta_t1 = 0.0
903
+ with torch.no_grad():
904
+ for x_td, y_td in batch_iterator:
905
+ x_td, y_td = x_td.to(device), y_td.to(device)
906
+ _, loss_td = model(x_td, y_td, return_logits=False)
907
+ loss_at_theta_t1 += loss_td.item()
908
+ loss_at_theta_t1 /= len(batch_iterator)
909
+
910
+ with torch.no_grad():
911
+ for p, v in zip(model.parameters(), update_direction_v):
912
+ p.data.sub_(v)
913
+
914
+ loss_t_tensor = torch.tensor(loss_at_theta_t, device=device)
915
+ loss_t1_tensor = torch.tensor(loss_at_theta_t1, device=device)
916
+ dist.all_reduce(loss_t_tensor, op=dist.ReduceOp.AVG)
917
+ dist.all_reduce(loss_t1_tensor, op=dist.ReduceOp.AVG)
918
+ loss_at_theta_t = loss_t_tensor.item()
919
+ loss_at_theta_t1 = loss_t1_tensor.item()
920
+
921
+ true_dec = loss_at_theta_t - loss_at_theta_t1
922
+ analysis_results["loss_at_theta_t"] = loss_at_theta_t
923
+ analysis_results["loss_at_theta_t1"] = loss_at_theta_t1
924
+ analysis_results["true_dec"] = true_dec
925
+
926
+ # pred_dec = (-g)^T v - 0.5 * v^T H v
927
+ first_order = analysis_results.get("ip_v_neg_g_t", analysis_results.get("ip_v_neg_g_hvp", 0.0))
928
+ sharpness_val = analysis_results.get("total_sharpness", 0.0)
929
+ v_norm_val = analysis_results.get("v_norm", 0.0)
930
+ curvature_term = 0.5 * sharpness_val * (v_norm_val ** 2)
931
+ pred_dec = first_order - curvature_term
932
+
933
+ analysis_results["pred_dec"] = pred_dec
934
+ analysis_results["first_order_descent"] = first_order
935
+ analysis_results["curvature_penalty"] = curvature_term
936
+
937
+ print0(f"[Enhanced Sharpness @ Step {step}] L(θ_t)={loss_at_theta_t:.6f}, L(θ_{{t+1}})={loss_at_theta_t1:.6f}, "
938
+ f"true_dec={true_dec:.6f}, pred_dec={pred_dec:.6f}, 1st_order={first_order:.6f}, curvature={curvature_term:.6f}")
939
+ except Exception as e:
940
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing true_dec: {e}")
941
+ analysis_results["true_dec"] = 0.0
942
+ analysis_results["pred_dec"] = 0.0
943
+
944
+ # --- Cleanup ---
945
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
946
+ print0(f"[Enhanced Sharpness @ Step {step}] Restored FLASH attention to {original_flash}")
947
+
948
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters back to θ_{{t+1}}...")
949
+ with torch.no_grad():
950
+ for p, v in zip(model.parameters(), update_direction_v):
951
+ p.data.add_(v)
952
+
953
+ if prev_training_mode:
954
+ model.train()
955
+ else:
956
+ model.eval()
957
+
958
+ # Thorough cleanup of all temporary variables
959
+ del update_direction_v, grads_hvp
960
+ del hvp_v_total, hvp_v_block, hvp_g_accum, layer_hvp_accum
961
+ del vhp_dot_v_total, v_norm_sq_total
962
+ del vhp_dot_v_block, v_norm_sq_block
963
+ if 'all_param_groups' in locals():
964
+ del all_param_groups
965
+ if 'param_to_idx' in locals():
966
+ del param_to_idx
967
+
968
+ # Synchronize CUDA operations before cleanup
969
+ if device == "cuda":
970
+ torch.cuda.synchronize()
971
+
972
+ gc.collect()
973
+ torch.cuda.empty_cache()
974
+
975
+ print0(f"[Enhanced Sharpness @ Step {step}] Analysis complete. Generated {len(analysis_results)} metrics.")
976
+ return analysis_results
977
+
978
+ def format_comprehensive_results(results):
979
+ """
980
+ Format the comprehensive analysis results for logging.
981
+ """
982
+ log_parts = []
983
+
984
+ # Total sharpness
985
+ if 'total_sharpness' in results:
986
+ log_parts.append(f"total_sharp:{results['total_sharpness']:.4e}")
987
+
988
+ # Layer-wise sharpness - dynamically detect number of layers
989
+ layer_sharpness = []
990
+ layer_num = 1
991
+ while True:
992
+ layer_key = f"layer_{layer_num}_sharpness"
993
+ if layer_key in results:
994
+ layer_sharpness.append(f"L{layer_num}_sharp:{results[layer_key]:.4e}")
995
+ layer_num += 1
996
+ else:
997
+ break
998
+
999
+ if layer_sharpness:
1000
+ log_parts.append(" ".join(layer_sharpness))
1001
+
1002
+ # Total update norms
1003
+ total_norms = []
1004
+ if 'total_update_fnorm' in results:
1005
+ total_norms.append(f"total_fnorm:{results['total_update_fnorm']:.4e}")
1006
+ if 'total_l1_linf_norm' in results:
1007
+ total_norms.append(f"total_l1_linf:{results['total_l1_linf_norm']:.4e}")
1008
+ if 'total_spectral_norm' in results:
1009
+ total_norms.append(f"total_spectral:{results['total_spectral_norm']:.4e}")
1010
+
1011
+ if total_norms:
1012
+ log_parts.append(" ".join(total_norms))
1013
+
1014
+ # Layer-wise update norms (Frobenius)
1015
+ layer_fnorms = []
1016
+ layer_num = 1
1017
+ while True:
1018
+ layer_key = f"layer_{layer_num}_update_fnorm"
1019
+ if layer_key in results:
1020
+ layer_fnorms.append(f"L{layer_num}_fnorm:{results[layer_key]:.4e}")
1021
+ layer_num += 1
1022
+ else:
1023
+ break
1024
+
1025
+ if layer_fnorms:
1026
+ log_parts.append(" ".join(layer_fnorms))
1027
+
1028
+ # Layer-wise update norms (Max-of-Max)
1029
+ layer_l1_linf = []
1030
+ layer_num = 1
1031
+ while True:
1032
+ layer_key = f"layer_{layer_num}_max_l1_linf_norm"
1033
+ if layer_key in results:
1034
+ layer_l1_linf.append(f"L{layer_num}_l1linf:{results[layer_key]:.4e}")
1035
+ layer_num += 1
1036
+ else:
1037
+ break
1038
+
1039
+ if layer_l1_linf:
1040
+ log_parts.append(" ".join(layer_l1_linf))
1041
+
1042
+ # Layer-wise update norms (Spectral)
1043
+ layer_spectral = []
1044
+ layer_num = 1
1045
+ while True:
1046
+ layer_key = f"layer_{layer_num}_max_spectral_norm"
1047
+ if layer_key in results:
1048
+ layer_spectral.append(f"L{layer_num}_spectral:{results[layer_key]:.4e}")
1049
+ layer_num += 1
1050
+ else:
1051
+ break
1052
+
1053
+ if layer_spectral:
1054
+ log_parts.append(" ".join(layer_spectral))
1055
+
1056
+ # Alignment and curvature metrics (global)
1057
+ misc_parts = []
1058
+ if 'v_norm' in results:
1059
+ misc_parts.append(f"v_norm:{results['v_norm']:.4e}")
1060
+
1061
+ # Version 1: g_hvp (new batch, computed at θ_t during HVP calculation)
1062
+ if 'cos_v_neg_g_hvp' in results:
1063
+ misc_parts.append(f"cos_v_-g_hvp:{results['cos_v_neg_g_hvp']:.4e}")
1064
+ if 'g_hvp_norm' in results:
1065
+ misc_parts.append(f"g_hvp_norm:{results['g_hvp_norm']:.4e}")
1066
+
1067
+ # Version 2: g_t (original gradient that produced v)
1068
+ if 'cos_v_neg_g_t' in results:
1069
+ misc_parts.append(f"cos_v_-g_t:{results['cos_v_neg_g_t']:.4e}")
1070
+ if 'g_t_norm' in results:
1071
+ misc_parts.append(f"g_t_norm:{results['g_t_norm']:.4e}")
1072
+
1073
+ if 'hv_norm' in results:
1074
+ misc_parts.append(f"hv_norm:{results['hv_norm']:.4e}")
1075
+ if 'cos_v_hv' in results:
1076
+ misc_parts.append(f"cos_v_hv:{results['cos_v_hv']:.4e}")
1077
+ if 'hg_norm' in results:
1078
+ misc_parts.append(f"hg_norm:{results['hg_norm']:.4e}")
1079
+ if 'cos_g_hg' in results:
1080
+ misc_parts.append(f"cos_g_hg:{results['cos_g_hg']:.4e}")
1081
+ if 'v_parallel_norm' in results:
1082
+ misc_parts.append(f"v_par:{results['v_parallel_norm']:.4e}")
1083
+ if 'v_perp_norm' in results:
1084
+ misc_parts.append(f"v_perp:{results['v_perp_norm']:.4e}")
1085
+ if misc_parts:
1086
+ log_parts.append(" ".join(misc_parts))
1087
+
1088
+ # Per-layer alignment metrics (cos_v_neg_g and v_norm per layer)
1089
+ layer_cos = []
1090
+ layer_num = 1
1091
+ while True:
1092
+ layer_key = f"layer_{layer_num}_cos_v_neg_g"
1093
+ layer_vn_key = f"layer_{layer_num}_v_norm"
1094
+ if layer_key in results:
1095
+ layer_cos.append(f"L{layer_num}_cos_v_neg_g:{results[layer_key]:.4e}")
1096
+ if layer_vn_key in results:
1097
+ layer_cos.append(f"L{layer_num}_v_norm:{results[layer_vn_key]:.4e}")
1098
+ if layer_key not in results and layer_vn_key not in results:
1099
+ break
1100
+ layer_num += 1
1101
+ if layer_cos:
1102
+ log_parts.append(" ".join(layer_cos))
1103
+
1104
+ return " ".join(log_parts)
1105
+
1106
+ # -----------------------------------------------------------------------------
1107
+ # int main
1108
+
1109
+ def print0(*args, **kwargs):
1110
+ # modified print that only prints from the master process
1111
+ # if this is not a distributed run, it's just a print
1112
+ if int(os.environ.get("RANK", 0)) == 0:
1113
+ print(*args, **kwargs)
1114
+
1115
+ if __name__ == "__main__":
1116
+ import time
1117
+ import argparse
1118
+ import tiktoken
1119
+ print0(f"Running pytorch {torch.version.__version__}")
1120
+
1121
+ # default settings will overfit a tiny batch of data
1122
+ # and save model weights and debug state to disk on the first iteration
1123
+ parser = argparse.ArgumentParser()
1124
+ # file system input / output
1125
+ parser.add_argument("--input_bin", type=str, default="dev/data/tinyshakespeare/tiny_shakespeare_val.bin", help="input .bin to train on")
1126
+ parser.add_argument("--input_val_bin", type=str, default="", help="input .bin to eval validation loss on")
1127
+ parser.add_argument("--output_dir", type=str, default="", help="output directory to which to write logs and checkpoints")
1128
+ parser.add_argument("--model", type=str, default="gpt2", help="gpt2|gpt2-medium|gpt2-large|gpt2-xl|d8|d12|d24|d36|d48")
1129
+ # token layout for each step of the optimization
1130
+ parser.add_argument("--batch_size", type=int, default=4, help="batch size, in units of #batch dimensions")
1131
+ parser.add_argument("--sequence_length", type=int, default=64, help="sequence length")
1132
+ parser.add_argument("--total_batch_size", type=int, default=256, help="total desired batch size, in units of #tokens")
1133
+ # workload (number of steps)
1134
+ parser.add_argument("--num_iterations", type=int, default=10, help="number of iterations to run")
1135
+ parser.add_argument("--inference_only", type=int, default=0, help="only run inference")
1136
+ # optimization
1137
+ parser.add_argument("--adam_lr", type=float, default=1e-4, help="learning rate warmup iterations")
1138
+ parser.add_argument("--warmup_iters", type=int, default=0, help="learning rate warmup iterations")
1139
+ parser.add_argument("--lr_decay_frac", type=float, default=1.0, help="learning rate warmup iterations")
1140
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="weight decay")
1141
+ parser.add_argument("--grad_clip", type=float, default=1.0, help="maximum gradient magnitude")
1142
+ # evaluation
1143
+ parser.add_argument("--val_loss_every", type=int, default=0, help="every how mant steps to evaluate val loss?")
1144
+ parser.add_argument("--val_max_steps", type=int, default=20, help="how many batches of val to average?")
1145
+ parser.add_argument("--sample_every", type=int, default=0, help="how often to sample from the model?")
1146
+ # debugging
1147
+ parser.add_argument("--overfit_single_batch", type=int, default=0, help="overfit just one batch of data")
1148
+ parser.add_argument("--shuffle_files", action="store_true")
1149
+ # numerics
1150
+ parser.add_argument("--tensorcores", type=int, default=0, help="use tensorcores")
1151
+ # memory management
1152
+ parser.add_argument("--device", type=str, default="", help="by default we autodetect, or set it here")
1153
+ parser.add_argument("--compile", type=int, default=0, help="torch.compile the model")
1154
+ parser.add_argument("--flash", type=int, default=0, help="use flash attention")
1155
+ parser.add_argument("--dtype", type=str, default="float32", help="float32|float16|bfloat16")
1156
+ parser.add_argument("--zero_stage", type=int, default=0, help="zero redundancy optimizer stage (0/1/2/3)")
1157
+ # Muon optimizer specific arguments
1158
+ parser.add_argument("--optimizer", type=str, default="adam", help="optimizer to use: adam|muon")
1159
+ parser.add_argument("--muon_lr", type=float, default=0.02, help="learning rate for Muon optimizer")
1160
+ parser.add_argument("--muon_momentum", type=float, default=0.95, help="momentum for Muon optimizer")
1161
+ parser.add_argument("--muon_weight_decay", type=float, default=0.00, help="weight decay for Muon optimizer")
1162
+ parser.add_argument("--muon_ns_steps", type=int, default=5, help="number of Newton-Schulz steps for Muon")
1163
+ parser.add_argument("--muon_nesterov", type=bool, default=False, help="use Nesterov momentum for Muon (0/1)")
1164
+ # python -> C bridge
1165
+ parser.add_argument("--write_tensors", type=int, default=1, help="write tensors to disk")
1166
+ parser.add_argument("--seed", type=int, default=42, help="random seed")
1167
+ # Sharpness analysis arguments
1168
+ parser.add_argument("--analyze_sharpness", action="store_true", help="Enable comprehensive sharpness analysis")
1169
+ parser.add_argument("--sharpness_analysis_interval", type=int, default=500, help="Interval for sharpness analysis")
1170
+ args = parser.parse_args()
1171
+
1172
+ # args error checking and convenience variables
1173
+ B, T = args.batch_size, args.sequence_length
1174
+ assert 1 <= T <= 1024
1175
+ assert args.dtype in {"float32", "float16", "bfloat16"}
1176
+ assert args.model in {"gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl", "d8", "d12", "d24", "d36", "d48"}
1177
+ assert args.optimizer in {"adam", "muon"}
1178
+
1179
+ set_seed(args.seed)
1180
+
1181
+ # set up DDP (distributed data parallel). torchrun sets this env variable
1182
+ ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
1183
+ if ddp:
1184
+ # use of DDP atm demands CUDA, we set the device appropriately according to rank
1185
+ assert torch.cuda.is_available(), "for now i think we need CUDA for DDP"
1186
+ init_process_group(backend='nccl')
1187
+ ddp_rank = int(os.environ['RANK'])
1188
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
1189
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
1190
+ device = f'cuda:{ddp_local_rank}'
1191
+ torch.cuda.set_device(device)
1192
+ master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
1193
+ seed_offset = 0 # each process gets the exact same seed
1194
+ zero_stage = args.zero_stage
1195
+ else:
1196
+ ddp_rank = 0
1197
+ ddp_local_rank = 0
1198
+ zero_stage = 0
1199
+ ddp_world_size = 1
1200
+ master_process = True
1201
+ seed_offset = 0
1202
+ # select the device
1203
+ if args.device:
1204
+ # provided explicitly by the user
1205
+ device = args.device
1206
+ else:
1207
+ # attempt to autodetect the device
1208
+ device = "cpu"
1209
+ if torch.cuda.is_available():
1210
+ device = "cuda"
1211
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
1212
+ device = "mps"
1213
+ print(f"using device: {device}")
1214
+ device_type = 'cuda' if 'cuda' in device else 'cpu'
1215
+
1216
+ # Setup debugpy for remote debugging (only activates if DEBUGPY env var is set)
1217
+ # setup_debugpy(rank=ddp_rank, force=True)
1218
+
1219
+ # calculate gradient accumulation from the desired total batch size and the current run configuration
1220
+ tokens_per_fwdbwd = B * T * ddp_world_size
1221
+ assert args.total_batch_size % tokens_per_fwdbwd == 0
1222
+ grad_accum_steps = args.total_batch_size // tokens_per_fwdbwd
1223
+ print0(f"total desired batch size: {args.total_batch_size}")
1224
+ print0(f"=> calculated gradient accumulation steps: {grad_accum_steps}")
1225
+
1226
+ # set up a context manager following the desired dtype and device
1227
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[args.dtype]
1228
+ ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype) if device_type == "cuda" else nullcontext()
1229
+
1230
+ # rng / reproducibility
1231
+ torch.manual_seed(42)
1232
+ if torch.cuda.is_available():
1233
+ torch.cuda.manual_seed(42)
1234
+
1235
+ # set the torch precision mode to use TensorFloat32 (TF32) for matmuls
1236
+ # docs https://pytorch.org/docs/stable/generated/torch.set_float32_matmul_precision.html
1237
+ if args.tensorcores:
1238
+ torch.set_float32_matmul_precision('high')
1239
+
1240
+ # turn on/off flash attention
1241
+ assert args.flash in {0, 1}
1242
+ nano_GPT_qkvonorm_pure.FLASH = args.flash # Set module-level FLASH for training
1243
+
1244
+ # init (and write) the tokenizer
1245
+ enc = tiktoken.get_encoding("gpt2")
1246
+ if master_process and args.write_tensors: # tokenizer is technically not tensors but ok
1247
+ write_tokenizer(enc, "gpt2_tokenizer.bin")
1248
+
1249
+ # init the model, either from scratch or from OpenAI pretrained checkpoint
1250
+ if args.model[0] == "d":
1251
+ # from scratch (random weights)
1252
+ model_config = {
1253
+ "d8": GPTConfig(block_size=1024, vocab_size=50257, n_layer=8, n_head=8, n_embd=512),
1254
+ "d12": GPTConfig(block_size=1024, vocab_size=50257, n_layer=12, n_head=12, n_embd=768),
1255
+ "d24": GPTConfig(block_size=1024, vocab_size=50257, n_layer=24, n_head=16, n_embd=1024),
1256
+ "d36": GPTConfig(block_size=1024, vocab_size=50257, n_layer=36, n_head=20, n_embd=1280),
1257
+ "d48": GPTConfig(block_size=1024, vocab_size=50257, n_layer=48, n_head=25, n_embd=1600),
1258
+ }[args.model]
1259
+ model = GPT(model_config)
1260
+ else:
1261
+ # load the GPT-2 model weights
1262
+ model = GPT.from_pretrained(args.model)
1263
+ model.train()
1264
+ model.to(device)
1265
+
1266
+ # Save uncompiled model reference for sharpness analysis (needs double backward)
1267
+ raw_model_uncompiled = model
1268
+
1269
+ if args.compile:
1270
+ if hasattr(config, "coordinate_descent_tuning"):
1271
+ config.coordinate_descent_tuning = True # suggested by @Chillee
1272
+ print0("compiling the model...")
1273
+ model = torch.compile(model)
1274
+
1275
+ # -------------------------------------------------------------------------
1276
+ # Our own version of a simple DistributedDataLoader
1277
+
1278
+ # load tokens
1279
+ train_loader = DistributedDataLoader(
1280
+ args.input_bin, B, T, ddp_rank, ddp_world_size,
1281
+ shuffle_files=args.shuffle_files, random_seed=args.seed
1282
+ )
1283
+ val_loader = None
1284
+ if args.input_val_bin:
1285
+ val_loader = DistributedDataLoader(args.input_val_bin, B, T, ddp_rank, ddp_world_size)
1286
+
1287
+ # -------------------------------------------------------------------------
1288
+ # PyTorch -> C bridge: save some weights and state for C to load later as reference
1289
+
1290
+ # do one forward pass to generate ground truth for our C tests
1291
+ if master_process and args.write_tensors and (not args.inference_only):
1292
+ x, y = train_loader.next_batch()
1293
+ x, y = x.to(device), y.to(device)
1294
+ logits, loss = model(x, y, return_logits=True) # Need logits for write_state
1295
+ loss.backward()
1296
+ # save model params, in both float32 and bfloat16
1297
+ model_to_size = {"gpt2": "124M", "gpt2-medium": "355M", "gpt2-large": "774M", "gpt2-xl": "1558M"}
1298
+ model_to_size.update({f"d{d}": f"d{d}" for d in [12, 24, 36, 48]})
1299
+ model_size_str = model_to_size[args.model] # e.g. "124M", or "d12"
1300
+ write_model(model, f"gpt2_{model_size_str}.bin", dtype="float32")
1301
+ write_model(model, f"gpt2_{model_size_str}_bf16.bin", dtype="bfloat16")
1302
+ # save x, y, logits, loss, and parameter gradients, for debugging C
1303
+ # always store these in fp32 to have an accurate reference (?)
1304
+ write_state(model, x, y, logits, loss, f"gpt2_{model_size_str}_debug_state.bin")
1305
+ # reset the train_loader for the optimization below
1306
+ train_loader.reset()
1307
+
1308
+ # -------------------------------------------------------------------------
1309
+ # main training loop
1310
+
1311
+ # here we wrap model into DDP container
1312
+ if ddp:
1313
+ model = DDP(model, device_ids=[ddp_local_rank])
1314
+ raw_model = model.module if ddp else model # always contains the "raw" unwrapped model
1315
+
1316
+ base_module = model.module if ddp else model
1317
+ # If compiled, unwrap to get the original module
1318
+ if hasattr(base_module, "_orig_mod"):
1319
+ base_module = base_module._orig_mod
1320
+
1321
+ raw_params = list(raw_model_uncompiled.parameters())
1322
+ train_params = list(base_module.parameters())
1323
+
1324
+ assert len(raw_params) == len(train_params), \
1325
+ f"Parameter count mismatch: raw_model_uncompiled has {len(raw_params)}, training model has {len(train_params)}"
1326
+ for i, (rp, tp) in enumerate(zip(raw_params, train_params)):
1327
+ assert rp.data_ptr() == tp.data_ptr(), \
1328
+ f"Parameter {i} has different data_ptr: raw_model_uncompiled and training model do not share parameters!"
1329
+ print0(f"[Verified] raw_model_uncompiled and training model share the same {len(raw_params)} Parameter objects")
1330
+
1331
+ last_training_update = None
1332
+ last_training_gradient = None # Store the original gradient that produced the update
1333
+ last_training_batches = None # Store ALL microbatches (x, y) for consistent HVP calculation
1334
+
1335
+
1336
+ def configure_adam(model, weight_decay, learning_rate, betas, device_type, zero_stage):
1337
+ # start with all of the candidate parameters
1338
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1339
+ # filter out those that do not require grad
1340
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1341
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
1342
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
1343
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
1344
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
1345
+ optim_groups = [
1346
+ {'params': decay_params, 'weight_decay': weight_decay},
1347
+ {'params': nodecay_params, 'weight_decay': 0.0}
1348
+ ]
1349
+ num_decay_params = sum(p.numel() for p in decay_params)
1350
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
1351
+ print0(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
1352
+ print0(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
1353
+ # Create AdamW optimizer and use the fused version if it is available
1354
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1355
+ use_fused = fused_available and device_type == 'cuda'
1356
+ print0(f"using fused AdamW: {use_fused}")
1357
+ if zero_stage == 1:
1358
+ print0("using ZeroRedundancyOptimizer")
1359
+ optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1360
+ lr=learning_rate, betas=betas, fused=use_fused)
1361
+ optimizer.add_param_group(optim_groups[1])
1362
+ else:
1363
+ print0("using regular AdamW")
1364
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=use_fused)
1365
+ return [optimizer]
1366
+
1367
+ def configure_muon(model, weight_decay, adam_lr, muon_lr, momentum, nesterov, ns_steps, device_type, zero_stage, ddp_rank, ddp_world_size):
1368
+ # start with all of the candidate parameters
1369
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1370
+ # filter out those that do not require grad
1371
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1372
+
1373
+ # For Muon, we need to separate 2D parameters (which can be orthogonalized)
1374
+ # from other parameters (which should use standard optimization)
1375
+ muon_params = [] # 2D parameters for Muon
1376
+ other_params = [] # other parameters for AdamW
1377
+
1378
+ muon_name = []
1379
+ other_name = []
1380
+ for n, p in param_dict.items():
1381
+ if "wte.weight" in n :
1382
+ other_params.append(p)
1383
+ other_name.append(n)
1384
+ continue
1385
+
1386
+ if p.dim() >= 2: # 2D parameters (weight matrices)
1387
+ muon_params.append(p)
1388
+ muon_name.append(n)
1389
+ else: # 1D parameters (biases, embeddings, etc.)
1390
+ other_params.append(p)
1391
+ other_name.append(n)
1392
+
1393
+ # print("================================================\n")
1394
+ # print(f"Muon parameters: {muon_name}\n")
1395
+ # print(f"Other parameters: {other_name}\n")
1396
+ # print("================================================\n")
1397
+
1398
+ print0(f"Muon parameters (2D): {len(muon_params)} tensors")
1399
+ print0(f"Other parameters (non-2D): {len(other_params)} tensors")
1400
+
1401
+ # Create Muon optimizer for 2D parameters
1402
+ muon_optimizer = None
1403
+ if muon_params:
1404
+ muon_optimizer = Muon(
1405
+ params=muon_params,
1406
+ lr=muon_lr,
1407
+ weight_decay=weight_decay,
1408
+ momentum=momentum,
1409
+ nesterov=nesterov,
1410
+ ns_steps=ns_steps,
1411
+ rank=ddp_rank,
1412
+ world_size=ddp_world_size
1413
+ )
1414
+
1415
+ # Create AdamW optimizer for non-2D parameters
1416
+ adam_optimizer = None
1417
+ if other_params:
1418
+ # create optim groups for AdamW
1419
+ # decay_params = [p for p in other_params if p.dim() >= 2]
1420
+ # nodecay_params = [p for p in other_params if p.dim() < 2]
1421
+ optim_groups = [
1422
+ {'params': other_params, 'weight_decay': weight_decay},
1423
+ # {'params': nodecay_params, 'weight_decay': 0.0}
1424
+ ]
1425
+
1426
+ # Create AdamW optimizer
1427
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1428
+ use_fused = fused_available and device_type == 'cuda'
1429
+ print0(f"using fused AdamW for non-Muon params: {use_fused}")
1430
+
1431
+ if zero_stage == 1:
1432
+ print0("using ZeroRedundancyOptimizer for non-Muon params")
1433
+ adam_optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1434
+ lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1435
+ # adam_optimizer.add_param_group(optim_groups[1])
1436
+ else:
1437
+ print0("using regular AdamW for non-Muon params")
1438
+ adam_optimizer = torch.optim.AdamW(optim_groups, lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1439
+
1440
+ return [muon_optimizer, adam_optimizer]
1441
+
1442
+ # init the optimizer
1443
+ if args.optimizer == "adam":
1444
+ optimizers = configure_adam(model=raw_model_uncompiled, weight_decay=args.weight_decay,
1445
+ learning_rate=args.adam_lr, betas=(0.9, 0.95),
1446
+ device_type=device, zero_stage=zero_stage)
1447
+ elif args.optimizer == "muon":
1448
+ optimizers = configure_muon(
1449
+ model=raw_model_uncompiled,
1450
+ weight_decay=args.muon_weight_decay,
1451
+ muon_lr=args.muon_lr,
1452
+ adam_lr=args.adam_lr,
1453
+ momentum=args.muon_momentum,
1454
+ nesterov=bool(args.muon_nesterov),
1455
+ ns_steps=args.muon_ns_steps,
1456
+ device_type=device,
1457
+ zero_stage=zero_stage,
1458
+ ddp_rank=ddp_rank,
1459
+ ddp_world_size=ddp_world_size
1460
+ )
1461
+ # We'll use muon_optimizer and adam_optimizer separately
1462
+
1463
+ # learning rate decay scheduler (cosine with warmup)
1464
+ def get_lr(it,base_lr):
1465
+ # if args.optimizer == "adam":
1466
+ # base_lr = args.adam_lr
1467
+ # else: # muon
1468
+ # base_lr = args.muon_lr
1469
+ min_lr = base_lr * args.lr_decay_frac
1470
+ # 1) linear warmup for warmup_iters steps
1471
+ if it < args.warmup_iters:
1472
+ return base_lr * (it+1) / args.warmup_iters
1473
+ # 2) if it > lr_decay_iters, return min learning rate
1474
+ if it > args.num_iterations:
1475
+ return min_lr
1476
+ # 3) in between, use cosine decay down to min learning rate
1477
+ decay_ratio = (it - args.warmup_iters) / (args.num_iterations - args.warmup_iters)
1478
+ assert 0 <= decay_ratio <= 1
1479
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff starts at 1 and goes to 0
1480
+ return min_lr + coeff * (base_lr - min_lr)
1481
+
1482
+ def get_wsd_lr(it, base_lr):
1483
+ min_lr = base_lr * args.lr_decay_frac
1484
+ # cooldown_iters = int(args.num_iterations * 0.2)
1485
+ cooldown_iters = int(0)
1486
+ # 1) Warmup: linear warmup for warmup_iters steps
1487
+ if it < args.warmup_iters:
1488
+ return base_lr * (it + 1) / args.warmup_iters
1489
+ # 3) Decay: linear decay from base_lr to min_lr in the last cooldown_iters steps
1490
+ cooldown_start = args.num_iterations - cooldown_iters
1491
+ if it >= cooldown_start:
1492
+ decay_ratio = (it - cooldown_start) / cooldown_iters
1493
+ return base_lr - decay_ratio * (base_lr - min_lr)
1494
+ # 2) Stable: constant learning rate at base_lr
1495
+ return base_lr
1496
+
1497
+ # create the logging directory if it does not exist
1498
+ logfile = None
1499
+ run_dir_path = None
1500
+
1501
+ file_name = f"mode_{args.optimizer}_adam_lr_{args.adam_lr}_muon_lr_{args.muon_lr}_seed_{args.seed}.log"
1502
+ if args.output_dir:
1503
+ base_log_dir = Path(args.output_dir)
1504
+ base_log_dir.mkdir(parents=True, exist_ok=True)
1505
+
1506
+ # Create run-specific directory
1507
+ # Generate UUID on master process and broadcast to all ranks
1508
+ if master_process:
1509
+ run_uuid = uuid.uuid4()
1510
+ uuid_str = str(run_uuid)
1511
+ else:
1512
+ uuid_str = None
1513
+
1514
+ # Broadcast UUID from rank 0 to all other ranks
1515
+ if ddp:
1516
+ # Create a tensor to hold the UUID string length and content
1517
+ if master_process:
1518
+ uuid_bytes = uuid_str.encode('utf-8')
1519
+ uuid_len = len(uuid_bytes)
1520
+ else:
1521
+ uuid_len = 0
1522
+
1523
+ # Broadcast length
1524
+ uuid_len_tensor = torch.tensor(uuid_len, dtype=torch.long, device=device)
1525
+ dist.broadcast(uuid_len_tensor, src=0)
1526
+
1527
+ # Broadcast UUID string
1528
+ if master_process:
1529
+ uuid_tensor = torch.ByteTensor(list(uuid_bytes)).to(device)
1530
+ else:
1531
+ uuid_tensor = torch.ByteTensor([0] * uuid_len_tensor.item()).to(device)
1532
+ dist.broadcast(uuid_tensor, src=0)
1533
+
1534
+ # Decode on non-master processes
1535
+ if not master_process:
1536
+ uuid_str = bytes(uuid_tensor.cpu().numpy()).decode('utf-8')
1537
+ run_uuid = uuid.UUID(uuid_str)
1538
+ else:
1539
+ run_uuid = uuid.UUID(uuid_str)
1540
+ else:
1541
+ run_uuid = uuid.uuid4()
1542
+
1543
+ # run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}_{run_uuid}"
1544
+ run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}"
1545
+ run_dir_path = base_log_dir / run_folder_name
1546
+ if run_dir_path.exists():
1547
+ run_flag = False
1548
+ else:
1549
+ run_flag = True
1550
+ torch.cuda.synchronize()
1551
+
1552
+
1553
+ # Only master process creates the directory
1554
+ if master_process:
1555
+ run_dir_path.mkdir(parents=True, exist_ok=True)
1556
+
1557
+ logfile = str(run_dir_path / "training_log.txt")
1558
+
1559
+ # Save configuration
1560
+
1561
+ if run_flag:
1562
+ if master_process:
1563
+ config_to_save = {
1564
+ "cli_args": vars(args),
1565
+ "run_uuid": str(run_uuid),
1566
+ "script_code_logged_at_start": True
1567
+ }
1568
+ config_file_path = run_dir_path / "config.json"
1569
+ with open(config_file_path, "w") as f:
1570
+ json.dump(config_to_save, f, indent=4)
1571
+ print0(f"Saved configuration to: {config_file_path}")
1572
+
1573
+ if master_process and logfile:
1574
+ with open(logfile, "w") as f:
1575
+ pass # Create/clear the file
1576
+ with open(logfile, "a") as f:
1577
+ f.write(code)
1578
+
1579
+ if device == "cuda":
1580
+ torch.cuda.reset_peak_memory_stats()
1581
+ timings = []
1582
+ norm = -1.0 # dummy value to print in inference-only mode
1583
+ for step in range(args.num_iterations + 1):
1584
+ t0 = time.time()
1585
+ last_step = (step == args.num_iterations)
1586
+
1587
+ # once in a while evaluate the validation dataset
1588
+ if (args.val_loss_every > 0 \
1589
+ and (step % args.val_loss_every == 0 or last_step)) \
1590
+ and (val_loader is not None):
1591
+ model.eval()
1592
+ val_loader.reset()
1593
+ with torch.no_grad():
1594
+ val_loss = 0.0
1595
+ for _ in range(args.val_max_steps):
1596
+ x, y = val_loader.next_batch()
1597
+ x, y = x.to(device), y.to(device)
1598
+ _, loss = model(x, y, return_logits=False)
1599
+ val_loss += loss.item()
1600
+ val_loss /= args.val_max_steps
1601
+
1602
+ # --- Comprehensive Sharpness Analysis ---
1603
+ sharpness_log_str = ""
1604
+ # Skip step 0 since we don't have a previous training update yet
1605
+ if args.analyze_sharpness and step > 0 and (step % args.sharpness_analysis_interval == 0 or last_step):
1606
+ print0(f"[Sharpness @ Step {step}] Starting comprehensive sharpness analysis...")
1607
+ for optimizer in optimizers:
1608
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1609
+ optimizer.zero_grad(set_to_none=True)
1610
+ elif isinstance(optimizer, Muon):
1611
+ optimizer.zero_grad()
1612
+ comprehensive_results = calculate_comprehensive_sharpness(
1613
+ model=raw_model_uncompiled, # Use uncompiled model for HVP (double backward)
1614
+ model_for_forward=model, # Use compiled+DDP model for forward pass
1615
+ optimizers=optimizers,
1616
+ step=step,
1617
+ train_loader=train_loader,
1618
+ val_loader=val_loader,
1619
+ rank=ddp_rank,
1620
+ world_size=ddp_world_size,
1621
+ device=device,
1622
+ B=B,
1623
+ T=T,
1624
+ ptdtype=ptdtype,
1625
+ grad_accum_steps=grad_accum_steps, # Pass grad accumulation steps to scale loss correctly
1626
+ last_training_update=last_training_update, # Pass the real update captured from training
1627
+ last_training_gradient=last_training_gradient, # Pass the original gradient g_t
1628
+ last_training_batches=last_training_batches # Pass ALL microbatches for consistent HVP
1629
+ )
1630
+ sharpness_log_str = format_comprehensive_results(comprehensive_results)
1631
+
1632
+ # Save sharpness results to file
1633
+ if master_process and run_dir_path:
1634
+ sharpness_file = run_dir_path / f"sharpness_step_{step}.json"
1635
+ with open(sharpness_file, "w") as f:
1636
+ json.dump(comprehensive_results, f, indent=4)
1637
+ print0(f"[Sharpness @ Step {step}] Results saved to {sharpness_file}")
1638
+
1639
+ # Clean up memory after sharpness analysis
1640
+ del comprehensive_results
1641
+ # Ensure all CUDA operations are complete before cleaning up
1642
+ if device == "cuda":
1643
+ torch.cuda.synchronize()
1644
+ torch.cuda.empty_cache()
1645
+ gc.collect()
1646
+ if ddp:
1647
+ dist.barrier() # Sync all ranks after cleanup
1648
+ print0(f"[Step {step}] Memory cleaned up after sharpness analysis")
1649
+
1650
+ # log to console and to file
1651
+ if sharpness_log_str:
1652
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f} | {sharpness_log_str}")
1653
+ else:
1654
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f}")
1655
+
1656
+ if master_process and logfile is not None:
1657
+ with open(logfile, "a") as f:
1658
+ f.write("step:%d validation loss:%f" % (step, val_loss))
1659
+ if sharpness_log_str:
1660
+ f.write(" %s" % sharpness_log_str)
1661
+ f.write("\n")
1662
+
1663
+ # once in a while perform model inference on the master process
1664
+ if (args.sample_every > 0 \
1665
+ and (step % args.sample_every == 0 or last_step)) \
1666
+ and master_process:
1667
+ model.eval()
1668
+ # before we end, let's also do one round of inference
1669
+ # we'll kick off the generation with "<|endoftext|>", which designates the start of a new sequence
1670
+ start_ids = [enc.eot_token]
1671
+ xg = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
1672
+ max_new_tokens = 32
1673
+ temperature = 1.0
1674
+ top_k = 40
1675
+ yg = raw_model.generate(xg, max_new_tokens, temperature=temperature, top_k=top_k)
1676
+ print0('---------------')
1677
+ print0(enc.decode(yg[0].tolist()))
1678
+ print0('---------------')
1679
+
1680
+ # bit confusing: we want to make sure to eval and sample on 0th iteration
1681
+ # but also after the very last iteration. so we loop for step <= num_iterations
1682
+ # instead of just < num_iterations (one extra due to <=), only to do
1683
+ # the validation/sampling one last time, and then we break right here as we're done.
1684
+ if last_step:
1685
+ break
1686
+
1687
+ # --------------- TRAINING SECTION BEGIN -----------------
1688
+ model.train()
1689
+ # Zero gradients for the appropriate optimizer(s)
1690
+
1691
+ for optimizer in optimizers:
1692
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1693
+ optimizer.zero_grad(set_to_none=True)
1694
+ elif isinstance(optimizer, Muon):
1695
+ optimizer.zero_grad()
1696
+ # if args.optimizer == "adam":
1697
+ # optimizer.zero_grad(set_to_none=True)
1698
+ # else: # muon
1699
+ # if muon_optimizer is not None:
1700
+ # muon_optimizer.zero_grad()
1701
+ # if adam_optimizer is not None:
1702
+ # adam_optimizer.zero_grad(set_to_none=True)
1703
+ # if we are trying to overfit a single batch, we reset the loader here
1704
+ if args.overfit_single_batch:
1705
+ train_loader.reset()
1706
+ # micro-batch loop where we do gradient accumulation to reach desired total batch size
1707
+ lossf = 0.0 # for getting the mean loss (as simple float) over the accumulation steps
1708
+
1709
+ # Pre-check if we need to collect microbatches for sharpness analysis
1710
+ next_step = step + 1
1711
+ will_analyze_sharpness_next = args.analyze_sharpness and next_step > 0 and (
1712
+ (next_step % args.sharpness_analysis_interval == 0) or
1713
+ (next_step == args.num_iterations)
1714
+ )
1715
+
1716
+
1717
+ microbatches_this_step = [] if will_analyze_sharpness_next else None
1718
+
1719
+ for micro_step in range(grad_accum_steps):
1720
+ # fetch a batch
1721
+ x, y = train_loader.next_batch()
1722
+ x, y = x.to(device), y.to(device)
1723
+
1724
+ # Store ALL microbatches for memory-efficient HVP calculation
1725
+ if will_analyze_sharpness_next:
1726
+ microbatches_this_step.append((x.detach().clone(), y.detach().clone()))
1727
+
1728
+ if ddp:
1729
+ model.require_backward_grad_sync = (micro_step == grad_accum_steps - 1)
1730
+ # forward pass
1731
+ with ctx:
1732
+ _, loss = model(x, y, return_logits=False)
1733
+ loss = loss / grad_accum_steps
1734
+ lossf += loss.detach() # keep track of the mean loss
1735
+ # backward pass
1736
+ if not args.inference_only:
1737
+ loss.backward()
1738
+ if ddp:
1739
+ dist.all_reduce(lossf, op=dist.ReduceOp.AVG)
1740
+ lossf = lossf.item()
1741
+
1742
+ #no clipping
1743
+ norm = torch.nn.utils.clip_grad_norm_(raw_model_uncompiled.parameters(), args.grad_clip)
1744
+
1745
+
1746
+ if will_analyze_sharpness_next:
1747
+ # Use raw_model_uncompiled's parameter order so it matches sharpness analysis codepaths.
1748
+ # (DDP/torch.compile wrappers can be a footgun if parameter iteration order ever diverges.)
1749
+ print(raw_model_uncompiled.transformer.h[0].attn.q_w.weight[:5,:5])
1750
+ params_before_optimizer_step = [p.detach().clone() for p in raw_model_uncompiled.parameters()]
1751
+ # Save the original gradient g_t that will produce the update v
1752
+ last_training_gradient = [
1753
+ p.grad.detach().clone() if p.grad is not None else torch.zeros_like(p)
1754
+ for p in raw_model_uncompiled.parameters()
1755
+ ]
1756
+ # Capture ALL microbatches for consistent HVP calculation
1757
+ # This ensures H is computed on the exact same objective as g_t and v
1758
+ last_training_batches = microbatches_this_step # Already cloned above
1759
+ else:
1760
+ params_before_optimizer_step = None
1761
+ last_training_batches = None
1762
+
1763
+ # Update learning rate and step optimizers
1764
+ for optimizer in optimizers:
1765
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1766
+ adam_lr = get_wsd_lr(step,args.adam_lr)
1767
+ for param_group in optimizer.param_groups:
1768
+ param_group['lr'] = adam_lr
1769
+ optimizer.step()
1770
+ elif isinstance(optimizer, Muon):
1771
+ muon_lr = get_wsd_lr(step,args.muon_lr)
1772
+ for param_group in optimizer.param_groups:
1773
+ param_group['lr'] = muon_lr
1774
+ optimizer.step()
1775
+ else:
1776
+ raise ValueError(f"Unsupported optimizer: {type(optimizer)}")
1777
+
1778
+
1779
+ if params_before_optimizer_step is not None:
1780
+ # Clean up old update to save memory
1781
+ if last_training_update is not None:
1782
+ del last_training_update
1783
+
1784
+ last_training_update = [
1785
+ p.detach() - p_before
1786
+ for p_before, p in zip(params_before_optimizer_step, raw_model_uncompiled.parameters())
1787
+ ]
1788
+ del params_before_optimizer_step
1789
+
1790
+ # --------------- TRAINING SECTION END -------------------
1791
+
1792
+ # wait on the CPU for all device work to end so we get accurate per-iteration timings below
1793
+ if device == "mps":
1794
+ torch.mps.synchronize()
1795
+ elif device == "cuda":
1796
+ torch.cuda.synchronize()
1797
+ # time and print
1798
+ t1 = time.time()
1799
+ # the 0th iteration is often an outlier (much slower) => skip logging it
1800
+ tokens_per_second = grad_accum_steps * ddp_world_size * B * T / (t1-t0)
1801
+ print0(f"step {step+1:4d}/{args.num_iterations} | train loss {lossf:.6f} | norm {norm:.4f} | ({(t1-t0)*1000:.2f} ms | {tokens_per_second:.0f} tok/s)")
1802
+ # log to logile
1803
+ if master_process and logfile is not None:
1804
+ with open(logfile, "a") as f:
1805
+ f.write("step:%d train loss:%f\n" % (step, lossf))
1806
+
1807
+ # keep track of smooth timings, last 20 iterations
1808
+ if step > 0 and step > args.num_iterations - 20:
1809
+ timings.append(t1-t0)
1810
+
1811
+ # print the average of the last 20 timings, to get something smooth-ish
1812
+ timings = timings[-20:]
1813
+ print0(f"final {len(timings)} iters avg: {np.mean(timings)*1000:.3f}ms")
1814
+ print0(f"peak memory consumption: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB")
1815
+
1816
+ # -------------------------------------------------------------------------
1817
+ # clean up nice
1818
+ if ddp:
1819
+ destroy_process_group()step:0 validation loss:11.020913
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.01,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "47f63560-10bc-4d75-b4e5-15f00f3f71f4",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.01,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "95e21787-edbd-4ea3-bf86-ba9b7bcad9f1",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.01_mlr_0.01_seed_44/training_log.txt ADDED
@@ -0,0 +1,1819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reference code for GPT-2 training and inference with Sharpness Analysis.
3
+ Will save the model weights into files, to be read from C as initialization.
4
+
5
+ References:
6
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
7
+ https://github.com/openai/gpt-2/blob/master/src/model.py
8
+ 2) huggingface/transformers PyTorch implementation:
9
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
10
+
11
+ Example launches to only benchmark the speed of bfloat16 compiled GPU training:
12
+ 1 GPU:
13
+ python train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
14
+ you can also turn on flash-attention by appending --flash=1
15
+ 4 GPU:
16
+ torchrun --standalone --nproc_per_node=4 train_gpt2.py --write_tensors=0 --num_iterations=50 --sequence_length=1024 --compile=1 --tensorcores=1 --dtype=bfloat16
17
+ """
18
+ import sys
19
+ with open(sys.argv[0]) as f:
20
+ code = f.read() # read the code of this file ASAP, for logging
21
+
22
+ import os
23
+ import math
24
+ import glob
25
+ import struct
26
+ import inspect
27
+ from contextlib import nullcontext
28
+ from dataclasses import dataclass
29
+ import random
30
+
31
+ import numpy as np
32
+ import torch
33
+ from torch import Tensor
34
+ import torch.nn as nn
35
+ from torch.nn import functional as F
36
+ import torch._inductor.config as config
37
+ from torch.nn.parallel import DistributedDataParallel as DDP
38
+ from torch.distributed import init_process_group, destroy_process_group
39
+ from torch.distributed.optim import ZeroRedundancyOptimizer
40
+ import torch.distributed as dist
41
+ from torch.amp import autocast
42
+ import copy
43
+ import gc
44
+ import uuid
45
+ import json
46
+ from pathlib import Path
47
+
48
+ # Import Muon optimizer
49
+ import sys
50
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/optimizers")
51
+ from MUON_fix import Muon
52
+
53
+ # Import GPT model
54
+ sys.path.append("/home/aiops/zhangfz/MUON_sharpness/modded-nanogpt/models")
55
+ import nano_GPT_qkvonorm_pure
56
+ from nano_GPT_qkvonorm_pure import GPT, GPTConfig
57
+
58
+ # Import debug utilities
59
+ # from debug_utils import setup_debugpy
60
+
61
+ # -----------------------------------------------------------------------------
62
+ # Our own simple Distributed Data Loader
63
+
64
+ def _peek_data_shard(filename):
65
+ # only reads the header, returns header data
66
+ with open(filename, "rb") as f:
67
+ # first read the header, which is 256 int32 integers (4 bytes each)
68
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
69
+ if header[0] != 20240520:
70
+ print("ERROR: magic number mismatch in the data .bin file!")
71
+ print("---> HINT: Are you passing in a correct file with --input_bin?")
72
+ print("---> HINT: Dataset encoding changed recently, re-run data prepro or refer again to README")
73
+ print("---> HINT: For example re-run: `python dev/data/tinyshakespeare.py`, then re-try")
74
+ exit(1)
75
+ assert header[1] == 1, "unsupported version"
76
+ ntok = header[2] # number of tokens (claimed)
77
+ return ntok # for now just return the number of tokens
78
+
79
+ def _load_data_shard(filename):
80
+ with open(filename, "rb") as f:
81
+ # first read the header, which is 256 int32 integers (4 bytes each)
82
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
83
+ assert header[0] == 20240520, "magic number mismatch in the data .bin file"
84
+ assert header[1] == 1, "unsupported version"
85
+ ntok = header[2] # number of tokens (claimed)
86
+ # the rest of it are tokens, stored as uint16
87
+ tokens = np.frombuffer(f.read(), dtype=np.uint16)
88
+ assert len(tokens) == ntok, "number of tokens read does not match header?"
89
+ return tokens
90
+
91
+ class DistributedDataLoader:
92
+ def __init__(self, filename_pattern, B, T, process_rank, num_processes,
93
+ shuffle_files=False, random_seed=None):
94
+ self.process_rank = process_rank
95
+ self.num_processes = num_processes
96
+ self.B = B
97
+ self.T = T
98
+ self.shuffle_files = shuffle_files
99
+ self.random_seed = random_seed
100
+ self._rng = random.Random(random_seed) if shuffle_files and random_seed is not None else None
101
+
102
+ # glob files that match the pattern
103
+ self.files = sorted(glob.glob(filename_pattern))
104
+ assert len(self.files) > 0, f"did not find any files that match the pattern {filename_pattern}"
105
+ if self.shuffle_files:
106
+ self._shuffle_files()
107
+
108
+ # load and validate all data shards, count number of tokens in total
109
+ ntok_total = 0
110
+ for fname in self.files:
111
+ shard_ntok = _peek_data_shard(fname)
112
+ assert shard_ntok >= num_processes * B * T + 1
113
+ ntok_total += shard_ntok
114
+ self.ntok_total = ntok_total
115
+ print0(f"DataLoader: total number of tokens: {ntok_total:,} across {len(self.files)} files")
116
+
117
+ # kick things off
118
+ self.current_shard = None
119
+ self.reset()
120
+
121
+ def reset(self):
122
+ # we're being a bit clever here: if we already had shard 0 loaded,
123
+ # then don't do the work to reload it, just reset the pointer
124
+ if self.current_shard != 0:
125
+ self.current_shard = 0
126
+ self.tokens = _load_data_shard(self.files[self.current_shard])
127
+ self.current_position = self.process_rank * self.B * self.T
128
+
129
+ def advance(self): # advance to next data shard
130
+ next_shard = (self.current_shard + 1) % len(self.files)
131
+ if next_shard == 0 and self.shuffle_files:
132
+ self._shuffle_files()
133
+ self.current_shard = next_shard
134
+ self.current_position = self.process_rank * self.B * self.T
135
+ self.tokens = _load_data_shard(self.files[self.current_shard])
136
+
137
+ def next_batch(self):
138
+ B = self.B
139
+ T = self.T
140
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
141
+ buf = torch.tensor(buf.astype(np.int32), dtype=torch.long)
142
+ x = (buf[:-1]).view(B, T) # inputs
143
+ y = (buf[1:]).view(B, T) # targets
144
+ # advance the start pointer in current shard
145
+ self.current_position += B * T * self.num_processes
146
+ # if loading the next batch would be out of bounds advance the shard
147
+ if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
148
+ self.advance()
149
+ return x, y
150
+
151
+ def _shuffle_files(self):
152
+ if self._rng is not None:
153
+ self._rng.shuffle(self.files)
154
+ else:
155
+ random.shuffle(self.files)
156
+
157
+ # -----------------------------------------------------------------------------
158
+ # Python -> C bridge utilities for saving params/grads/activations to .bin files
159
+
160
+ def write_fp32(tensor, file):
161
+ t = tensor.detach().cpu().to(torch.float32)
162
+ b = t.numpy().tobytes()
163
+ file.write(b)
164
+
165
+ def write_bf16(tensor, file):
166
+ t = tensor.detach().cpu().to(torch.bfloat16)
167
+ # numpy doesn't have bf16 datatype so we have to trick it
168
+ t = t.view(torch.int16) # trick: reinterpret as int16
169
+ b = t.numpy().tobytes()
170
+ file.write(b)
171
+
172
+ def write_tensors(model_tensors, L, file, dtype):
173
+ # writes the GPT-2 model's weights to a binary file
174
+ assert dtype in {"float32", "bfloat16"}
175
+ write_fun = write_fp32 if dtype == "float32" else write_bf16
176
+ write_fun(model_tensors["transformer.wte.weight"], file) # (V, C)
177
+ write_fun(model_tensors["transformer.wpe.weight"], file) # (T, C)
178
+ for i in range(L): # (L, C)
179
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.weight"], file)
180
+ for i in range(L): # (L, C)
181
+ write_fun(model_tensors[f"transformer.h.{i}.ln_1.bias"], file)
182
+ for i in range(L): # (L, 3C, C)
183
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.weight"], file)
184
+ for i in range(L): # (L, 3C)
185
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_attn.bias"], file)
186
+ for i in range(L): # (L, C, C)
187
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.weight"], file)
188
+ for i in range(L): # (L, C)
189
+ write_fun(model_tensors[f"transformer.h.{i}.attn.c_proj.bias"], file)
190
+ for i in range(L): # (L, C)
191
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.weight"], file)
192
+ for i in range(L): # (L, C)
193
+ write_fun(model_tensors[f"transformer.h.{i}.ln_2.bias"], file)
194
+ for i in range(L): # (L, 4C, C)
195
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.weight"], file)
196
+ for i in range(L): # (L, 4C)
197
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_fc.bias"], file)
198
+ for i in range(L): # (L, C, 4C)
199
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.weight"], file)
200
+ for i in range(L): # (L, C)
201
+ write_fun(model_tensors[f"transformer.h.{i}.mlp.c_proj.bias"], file)
202
+ write_fun(model_tensors["transformer.ln_f.weight"], file) # (C, )
203
+ write_fun(model_tensors["transformer.ln_f.bias"], file) # (C, )
204
+
205
+ @torch.no_grad()
206
+ def pad_vocab(tensor, multiple=128, value=0):
207
+ """
208
+ The dimension of the vocab size in GPT-2 is 50,257
209
+ which is unfortunately a very unfriendly number for a lot of
210
+ matrix operations on the GPU. So we pad it to the nearest
211
+ friendlier multiple, e.g. 50,304 if multiple=128 when we
212
+ export the weights into C land. This is a NOOP algorithmically
213
+ and is only done to make the tensor operations more efficient.
214
+ """
215
+ assert tensor.ndim == 2
216
+ V, C = tensor.shape
217
+ assert V == 50257, "just being defensive here"
218
+ # calculate padded vocab size by rounding up to nearest multiple
219
+ Vp = ((V + multiple - 1) // multiple) * multiple
220
+ # pad the tensor
221
+ pad_rows = Vp - V
222
+ padded = tensor if pad_rows == 0 else F.pad(tensor, (0, 0, 0, pad_rows), value=value)
223
+ assert padded.shape == (Vp, C)
224
+ return padded
225
+
226
+ def write_model(model, filename, dtype):
227
+ # everything we need to instantiate the model
228
+ # 1) header is: version int, GPTConfig ints, padding to 1024 bytes
229
+ assert dtype in {"float32", "bfloat16"} # float16 todo maybe later
230
+ version = {
231
+ "float32": 3, # 3: all tensors are fp32, padded vocab
232
+ "bfloat16": 5, # 5: all tensors are bf16, padded vocab
233
+ }[dtype]
234
+ header = torch.zeros(256, dtype=torch.int32)
235
+ header[0] = 20240326 # magic
236
+ header[1] = version # checkpoint version
237
+ header[2] = model.config.block_size
238
+ header[3] = model.config.vocab_size
239
+ header[4] = model.config.n_layer
240
+ header[5] = model.config.n_head
241
+ header[6] = model.config.n_embd
242
+ # 2) the parameters follow the header
243
+ params = {name: param.cpu() for name, param in model.named_parameters()}
244
+ # pad the vocab to a multiple of 128 here at export, for efficiency in C
245
+ wte = params["transformer.wte.weight"] # (V, C)
246
+ wte_padded = pad_vocab(wte) # (Vp, C)
247
+ params["transformer.wte.weight"] = wte_padded # (Vp, C)
248
+ print(f"padded vocab size from {wte.size(0)} to {wte_padded.size(0)}")
249
+ header[7] = wte_padded.size(0) # padded vocab size store in header
250
+ # now write to file
251
+ with open(filename, "wb") as file:
252
+ file.write(header.numpy().tobytes()) # header
253
+ write_tensors(params, model.config.n_layer, file, dtype) # params
254
+ print(f"wrote {filename}")
255
+
256
+ def write_state(model, x, y, logits, loss, filename):
257
+ # the state is used for debugging.
258
+ # it contains information about the input, logits, loss, and the parameter gradients
259
+ # this can be used for checking the computation correctness in C
260
+ header = torch.zeros(256, dtype=torch.int32)
261
+ header[0] = 20240327 # magic
262
+ header[1] = 2 # run state version = 2 (1 -> 2 for padded vocab changes)
263
+ header[2] = x.size(0) # batch size of the batch, B
264
+ header[3] = x.size(1) # temporal extent of the batch, T
265
+ grads = {name: param.grad.cpu() for name, param in model.named_parameters()}
266
+ # pad the vocab grads here as well, to mirror write_model
267
+ wte_grad = grads["transformer.wte.weight"] # (V, C)
268
+ wte_grad_padded = pad_vocab(wte_grad, value=0) # (Vp, C) # TODO later maybe pad with nan?
269
+ grads["transformer.wte.weight"] = wte_grad_padded # (Vp, C)
270
+ print(f"padded vocab size in reference grads from {wte_grad.size(0)} to {wte_grad_padded.size(0)}")
271
+ with open(filename, "wb") as file:
272
+ # header
273
+ file.write(header.numpy().tobytes())
274
+ # input x
275
+ file.write(x.cpu().numpy().astype("int32").tobytes()) # (B, T)
276
+ # targets y
277
+ file.write(y.cpu().numpy().astype("int32").tobytes()) # (B, T)
278
+ # logits (result of the model forward pass)
279
+ write_fp32(logits.cpu(), file)
280
+ # loss (single float, result of the cross entropy loss)
281
+ write_fp32(loss.cpu(), file)
282
+ # gradients
283
+ write_tensors(grads, model.config.n_layer, file, "float32")
284
+ print(f"wrote {filename}")
285
+
286
+ def write_tokenizer(enc, filename):
287
+ n = enc.max_token_value + 1
288
+ header = torch.zeros(256, dtype=torch.int32)
289
+ header[0] = 20240328 # magic
290
+ header[1] = 2 # tokenizer version = 2 (1 -> 2: includes EOT token)
291
+ header[2] = n # number of tokens
292
+ header[3] = enc.eot_token # EOT token
293
+ with open(filename, "wb") as file:
294
+ file.write(header.numpy().tobytes())
295
+ for i in range(n):
296
+ b = enc.decode_bytes([i])
297
+ length = len(b)
298
+ assert length < 256, f"Token length exceeds 255: {length}"
299
+ file.write(struct.pack("<B", length)) # Write the length as a 1-byte unsigned integer
300
+ file.write(b) # Write the actual bytes
301
+ print(f"wrote {filename}")
302
+
303
+ def set_seed(seed):
304
+ random.seed(seed)
305
+ np.random.seed(seed)
306
+ torch.manual_seed(seed)
307
+ if torch.cuda.is_available():
308
+ torch.cuda.manual_seed_all(seed)
309
+ print(f"PRINT: Set seed to {seed}", flush=True) # Print immediately for all ranks
310
+
311
+ # -----------------------------------------------------------------------------
312
+ # Helper functions for norm calculations
313
+
314
+ def calculate_l1_to_linf_norm(matrix):
315
+ if matrix.ndim == 1:
316
+ return torch.sum(torch.abs(matrix))
317
+ elif matrix.ndim == 2:
318
+ # Each row's L1 norm, then take maximum
319
+ row_l1_norms = torch.sum(torch.abs(matrix), dim=1)
320
+ return torch.max(row_l1_norms)
321
+ else:
322
+ # For higher-dimensional tensors, flatten to 2D
323
+ matrix_2d = matrix.view(matrix.shape[0], -1)
324
+ row_l1_norms = torch.sum(torch.abs(matrix_2d), dim=1)
325
+ return torch.max(row_l1_norms)
326
+
327
+ def calculate_spectral_norm(matrix):
328
+ """
329
+ Calculate the spectral norm (largest singular value) of a matrix.
330
+ For vectors, returns the L2 norm.
331
+ """
332
+ # Convert to float32 if needed for linalg operations
333
+ if matrix.dtype in [torch.bfloat16, torch.float16]:
334
+ matrix = matrix.float()
335
+
336
+ if matrix.ndim == 1:
337
+ return torch.norm(matrix, p=2)
338
+ elif matrix.ndim == 2:
339
+ # Use matrix 2-norm (largest singular value)
340
+ return torch.linalg.matrix_norm(matrix, ord=2)
341
+ else:
342
+ # For higher-dimensional tensors, flatten to 2D
343
+ matrix_2d = matrix.view(matrix.shape[0], -1)
344
+ return torch.linalg.matrix_norm(matrix_2d, ord=2)
345
+
346
+ # -----------------------------------------------------------------------------
347
+ # Comprehensive sharpness analysis function
348
+
349
+ def calculate_comprehensive_sharpness(model, model_for_forward, optimizers, step, train_loader, val_loader,
350
+ rank, world_size, device, B, T, ptdtype, grad_accum_steps, last_training_update=None, last_training_gradient=None, last_training_batches=None):
351
+ prev_training_mode = model.training
352
+ model.eval()
353
+
354
+ NUM_LAYERS = model.config.n_layer # Number of transformer blocks
355
+ analysis_results = {}
356
+
357
+ # --- 1. Get the true update direction 'v' ---
358
+ assert last_training_update is not None, \
359
+ f"[Step {step}] BUG: last_training_update is None! Check sharpness timing logic."
360
+
361
+ print0(f"[Enhanced Sharpness @ Step {step}] Using update from previous training step")
362
+ update_direction_v = last_training_update
363
+
364
+
365
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters to θ_t for HVP calculation...")
366
+ with torch.no_grad():
367
+ for p, v in zip(model.parameters(), update_direction_v):
368
+ p.data.sub_(v) # Now parameters are at θ_t
369
+
370
+ # --- 2. Calculate update norms (Frobenius, Max-of-Max, Spectral) ---
371
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating update norms...")
372
+
373
+ total_update_norm_sq = sum(torch.sum(v * v) for v in update_direction_v)
374
+ dist.all_reduce(total_update_norm_sq, op=dist.ReduceOp.AVG)
375
+ analysis_results["total_update_fnorm"] = torch.sqrt(total_update_norm_sq).item()
376
+
377
+ # Calculate TOTAL update Max-of-Max and Spectral norms
378
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating total update Max-of-Max and Spectral norms...")
379
+ try:
380
+ all_updates_flat = torch.cat([v.flatten() for v in update_direction_v if v.numel() > 0])
381
+
382
+ if all_updates_flat.numel() > 0:
383
+ total_l1_linf_norm = torch.sum(torch.abs(all_updates_flat))
384
+ analysis_results["total_l1_linf_norm"] = total_l1_linf_norm.item()
385
+
386
+ total_spectral_norm = torch.norm(all_updates_flat, p=2)
387
+ analysis_results["total_spectral_norm"] = total_spectral_norm.item()
388
+ else:
389
+ analysis_results["total_l1_linf_norm"] = 0.0
390
+ analysis_results["total_spectral_norm"] = 0.0
391
+
392
+ del all_updates_flat
393
+ except Exception as e:
394
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating total norms: {e}")
395
+ analysis_results["total_l1_linf_norm"] = 0.0
396
+ analysis_results["total_spectral_norm"] = 0.0
397
+
398
+ # --- 3. Setup layer parameter groups (adapt to new model structure) ---
399
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up layer parameter groups...")
400
+
401
+ all_param_groups = {}
402
+
403
+
404
+ all_param_groups["embed_lm_head"] = list(model.lm_head.parameters())
405
+
406
+ blocks = model.transformer.h
407
+
408
+ for i, block in enumerate(blocks):
409
+ layer_name = f"layer_{i+1}"
410
+ all_param_groups[layer_name] = list(block.parameters())
411
+
412
+ # Add fine-grained params for selected layers (0, 3, 7, 11)
413
+ selected_layers = [0, 3, 7, 11]
414
+ for layer_idx in selected_layers:
415
+ block = blocks[layer_idx]
416
+ prefix = f"block{layer_idx}"
417
+ # Attention: Q, K, V, O
418
+ all_param_groups[f"{prefix}_q"] = [block.attn.q_w.weight]
419
+ all_param_groups[f"{prefix}_k"] = [block.attn.k_w.weight]
420
+ all_param_groups[f"{prefix}_v"] = [block.attn.v_w.weight]
421
+ all_param_groups[f"{prefix}_o"] = [block.attn.c_proj.weight]
422
+ # MLP: c_fc (win) and c_proj (wout)
423
+ all_param_groups[f"{prefix}_mlp_win"] = [block.mlp.c_fc.weight]
424
+ all_param_groups[f"{prefix}_mlp_wout"] = [block.mlp.c_proj.weight]
425
+
426
+ # --- 4. Calculate layer-wise update norms ---
427
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise update norms...")
428
+
429
+ param_to_idx = {id(p): i for i, p in enumerate(model.parameters())}
430
+
431
+ for group_name, param_group in all_param_groups.items():
432
+ if not param_group:
433
+ continue
434
+
435
+ # Get indices for this group
436
+ indices = [param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx]
437
+ if not indices:
438
+ continue
439
+
440
+ # Calculate Frobenius norm for this group
441
+ group_update_norm_sq = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
442
+ dist.all_reduce(group_update_norm_sq, op=dist.ReduceOp.AVG)
443
+ analysis_results[f"{group_name}_update_fnorm"] = torch.sqrt(group_update_norm_sq).item()
444
+
445
+ # Calculate Max-of-Max and Spectral norms for this group
446
+ group_l1_linf_norms = []
447
+ group_spectral_norms = []
448
+
449
+ for i in indices:
450
+ if i < len(update_direction_v) and update_direction_v[i].numel() > 0:
451
+ try:
452
+ l1_linf_norm = calculate_l1_to_linf_norm(update_direction_v[i])
453
+ group_l1_linf_norms.append(l1_linf_norm.item())
454
+
455
+ spectral_norm = calculate_spectral_norm(update_direction_v[i])
456
+ group_spectral_norms.append(spectral_norm.item())
457
+ except Exception as e:
458
+ print0(f"[Enhanced Sharpness @ Step {step}] Error calculating norms for group {group_name}, param {i}: {e}")
459
+ group_l1_linf_norms.append(0.0)
460
+ group_spectral_norms.append(0.0)
461
+
462
+ if group_l1_linf_norms:
463
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = max(group_l1_linf_norms)
464
+ else:
465
+ analysis_results[f"{group_name}_max_l1_linf_norm"] = 0.0
466
+
467
+ if group_spectral_norms:
468
+ analysis_results[f"{group_name}_max_spectral_norm"] = max(group_spectral_norms)
469
+ else:
470
+ analysis_results[f"{group_name}_max_spectral_norm"] = 0.0
471
+
472
+ # --- 5. Setup for HVP calculation on TRAIN data ---
473
+ print0(f"[Enhanced Sharpness @ Step {step}] Setting up HVP calculation in {ptdtype} on TRAIN data...")
474
+
475
+ original_flash = nano_GPT_qkvonorm_pure.FLASH
476
+ nano_GPT_qkvonorm_pure.FLASH = 0
477
+ print0(f"[Enhanced Sharpness @ Step {step}] Disabled FLASH attention for HVP (was {original_flash})")
478
+
479
+ # Get block parameter indices for cross-layer analysis (need this before loop)
480
+ block_param_indices = set()
481
+ for group_name, param_group in all_param_groups.items():
482
+ if group_name.startswith("layer_"):
483
+ for p in param_group:
484
+ if id(p) in param_to_idx:
485
+ block_param_indices.add(param_to_idx[id(p)])
486
+
487
+ # Initialize accumulators for all quantities we need
488
+ grads_hvp = None
489
+ hvp_v_total = None
490
+ hvp_v_block = None
491
+ hvp_g_accum = None
492
+ layer_hvp_accum = {}
493
+
494
+
495
+ group_names_to_process = [gn for gn, pg in all_param_groups.items()
496
+ if pg and any(id(p) in param_to_idx for p in pg)]
497
+
498
+ if last_training_batches is not None and len(last_training_batches) > 0:
499
+
500
+ batch_iterator = [(x, y) for x, y in last_training_batches]
501
+ n_batches = len(batch_iterator)
502
+ print0(f"[Enhanced Sharpness @ Step {step}] Using {n_batches} microbatches for HVP (out of {grad_accum_steps} training microbatches)")
503
+ restore_loader = False
504
+ else:
505
+ # Fallback: use new batches from train_loader (should rarely happen)
506
+ print0(f"[Enhanced Sharpness @ Step {step}] WARNING: last_training_batches is None/empty, using {grad_accum_steps} new batches (inconsistent)")
507
+ saved_current_shard = train_loader.current_shard
508
+ saved_current_position = train_loader.current_position
509
+ n_batches = grad_accum_steps # Use same number as training for consistency
510
+ batch_iterator = []
511
+ shard_was_changed = False
512
+ for _ in range(n_batches):
513
+ x_hvp, y_hvp = train_loader.next_batch()
514
+ batch_iterator.append((x_hvp, y_hvp))
515
+ shard_was_changed = shard_was_changed or (train_loader.current_shard != saved_current_shard)
516
+ restore_loader = True
517
+
518
+
519
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing HVPs for {n_batches} microbatches")
520
+ for mb_idx, (x_hvp, y_hvp) in enumerate(batch_iterator):
521
+ x_hvp, y_hvp = x_hvp.to(device), y_hvp.to(device)
522
+
523
+
524
+ _, loss_mb = model(x_hvp, y_hvp, return_logits=False)
525
+ grads_mb = torch.autograd.grad(loss_mb, model.parameters(), create_graph=True, allow_unused=True)
526
+
527
+ # Compute H·v (total sharpness)
528
+ v_dot_g_total = sum(torch.sum(g * v) for g, v in zip(grads_mb, update_direction_v) if g is not None)
529
+
530
+ if not isinstance(v_dot_g_total, torch.Tensor):
531
+ v_dot_g_total = torch.tensor(0.0, device=device, requires_grad=True)
532
+ hvp_v_total_mb = torch.autograd.grad(v_dot_g_total, model.parameters(), retain_graph=True, allow_unused=True)
533
+
534
+ # Compute H·v_block (block-only sharpness)
535
+ if block_param_indices:
536
+ v_dot_g_block = sum(torch.sum(grads_mb[i] * update_direction_v[i])
537
+ for i in block_param_indices if grads_mb[i] is not None)
538
+ if not isinstance(v_dot_g_block, torch.Tensor):
539
+ v_dot_g_block = torch.tensor(0.0, device=device, requires_grad=True)
540
+ hvp_v_block_mb = torch.autograd.grad(v_dot_g_block, model.parameters(), retain_graph=True, allow_unused=True)
541
+ else:
542
+
543
+ hvp_v_block_mb = [None] * len(list(model.parameters()))
544
+
545
+
546
+ g_dot_g = sum(torch.sum(g * g) for g in grads_mb if g is not None)
547
+ if not isinstance(g_dot_g, torch.Tensor):
548
+ g_dot_g = torch.tensor(0.0, device=device, requires_grad=True)
549
+
550
+
551
+ hvp_g_mb_raw = torch.autograd.grad(g_dot_g, model.parameters(),
552
+ retain_graph=True, allow_unused=True)
553
+ hvp_g_mb = [h / 2.0 if h is not None else None for h in hvp_g_mb_raw]
554
+
555
+ # Compute per-layer H_kk·v_k (for layer-wise sharpness)
556
+ for group_idx, group_name in enumerate(group_names_to_process):
557
+ param_group = all_param_groups[group_name]
558
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
559
+ if not indices:
560
+ continue
561
+
562
+ is_last_layer = (group_idx == len(group_names_to_process) - 1)
563
+ is_last_microbatch = (mb_idx == n_batches - 1)
564
+ need_retain = not (is_last_layer and is_last_microbatch)
565
+
566
+ try:
567
+ v_dot_g_layer = sum(torch.sum(grads_mb[i] * update_direction_v[i])
568
+ for i in indices if grads_mb[i] is not None)
569
+
570
+ if not isinstance(v_dot_g_layer, torch.Tensor):
571
+ v_dot_g_layer = torch.tensor(0.0, device=device, requires_grad=True)
572
+
573
+ hvp_layer_mb = torch.autograd.grad(v_dot_g_layer, model.parameters(),
574
+ retain_graph=need_retain,
575
+ allow_unused=True)
576
+
577
+ if group_name not in layer_hvp_accum:
578
+ layer_hvp_accum[group_name] = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_layer_mb]
579
+ else:
580
+ layer_hvp_accum[group_name] = [
581
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
582
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
583
+ for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
584
+ ]
585
+
586
+ # Accumulate layer HVP
587
+ # if group_name not in layer_hvp_accum:
588
+ # layer_hvp_accum[group_name] = [h.detach() / n_batches if h is not None else None for h in hvp_layer_mb]
589
+ # else:
590
+ # layer_hvp_accum[group_name] = [
591
+ # (h_acc + h.detach() / n_batches) if (h is not None and h_acc is not None)
592
+ # else (h.detach() / n_batches if h is not None else h_acc)
593
+ # for h_acc, h in zip(layer_hvp_accum[group_name], hvp_layer_mb)
594
+ # ]
595
+ # del hvp_layer_mb, v_dot_g_layer
596
+ # torch.cuda.empty_cache()
597
+ except Exception as e:
598
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing layer HVP for '{group_name}' in microbatch {mb_idx}: {e}")
599
+ if group_name not in layer_hvp_accum:
600
+ layer_hvp_accum[group_name] = None
601
+
602
+ # 6. Accumulate all quantities
603
+ if grads_hvp is None:
604
+ grads_hvp = [(g.detach() / n_batches).cpu() if g is not None else None for g in grads_mb]
605
+ hvp_v_total = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_total_mb]
606
+ hvp_v_block = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_v_block_mb]
607
+ hvp_g_accum = [(h.detach() / n_batches).cpu() if h is not None else None for h in hvp_g_mb]
608
+ else:
609
+ grads_hvp = [
610
+ (g_acc + (g.detach() / n_batches).cpu()) if (g is not None and g_acc is not None)
611
+ else ((g.detach() / n_batches).cpu() if g is not None else g_acc)
612
+ for g_acc, g in zip(grads_hvp, grads_mb)
613
+ ]
614
+ hvp_v_total = [
615
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
616
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
617
+ for h_acc, h in zip(hvp_v_total, hvp_v_total_mb)
618
+ ]
619
+ hvp_v_block = [
620
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
621
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
622
+ for h_acc, h in zip(hvp_v_block, hvp_v_block_mb)
623
+ ]
624
+ hvp_g_accum = [
625
+ (h_acc + (h.detach() / n_batches).cpu()) if (h is not None and h_acc is not None)
626
+ else ((h.detach() / n_batches).cpu() if h is not None else h_acc)
627
+ for h_acc, h in zip(hvp_g_accum, hvp_g_mb)
628
+ ]
629
+
630
+
631
+
632
+ if mb_idx % max(1, n_batches // 4) == 0:
633
+ print0(f"[Enhanced Sharpness @ Step {step}] Processed microbatch {mb_idx + 1}/{n_batches}")
634
+
635
+
636
+ if restore_loader:
637
+ train_loader.current_shard = saved_current_shard
638
+ train_loader.current_position = saved_current_position
639
+ if shard_was_changed:
640
+ train_loader.tokens = _load_data_shard(train_loader.files[train_loader.current_shard])
641
+
642
+ print0(f"[Enhanced Sharpness @ Step {step}] Finished computing all HVPs for {n_batches} microbatches")
643
+ grads_hvp = [g.to(device) if g is not None else None for g in grads_hvp]
644
+ hvp_v_total = [h.to(device) if h is not None else None for h in hvp_v_total]
645
+ hvp_v_block = [h.to(device) if h is not None else None for h in hvp_v_block]
646
+ hvp_g_accum = [h.to(device) if h is not None else None for h in hvp_g_accum]
647
+ for group_name in layer_hvp_accum:
648
+ if layer_hvp_accum[group_name] is not None:
649
+ layer_hvp_accum[group_name] = [h.to(device) if h is not None else None for h in layer_hvp_accum[group_name]]
650
+ # --- Calculate TOTAL sharpness ---
651
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating TOTAL sharpness...")
652
+ # hvp_v_total is already computed in the loop above
653
+ vhp_dot_v_total = sum(torch.sum(hvp * v) for hvp, v in zip(hvp_v_total, update_direction_v) if hvp is not None)
654
+ v_norm_sq_total = sum(torch.sum(v * v) for v in update_direction_v)
655
+
656
+ # Ensure they are tensors
657
+ if not isinstance(vhp_dot_v_total, torch.Tensor):
658
+ vhp_dot_v_total = torch.tensor(0.0, device=device)
659
+ if not isinstance(v_norm_sq_total, torch.Tensor):
660
+ v_norm_sq_total = torch.tensor(0.0, device=device)
661
+
662
+ dist.all_reduce(vhp_dot_v_total, op=dist.ReduceOp.AVG)
663
+ dist.all_reduce(v_norm_sq_total, op=dist.ReduceOp.AVG)
664
+
665
+ if v_norm_sq_total.item() > 1e-12:
666
+ analysis_results["total_sharpness"] = (vhp_dot_v_total / v_norm_sq_total).item()
667
+ else:
668
+ analysis_results["total_sharpness"] = 0.0
669
+
670
+
671
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating BLOCK-ONLY total sharpness...")
672
+ # hvp_v_block is already computed in the loop above
673
+ if block_param_indices: # Only compute if there are block parameters
674
+ # Compute v_block^T H v_block (only sum over block indices)
675
+ vhp_dot_v_block = sum(torch.sum(hvp_v_block[i] * update_direction_v[i])
676
+ for i in block_param_indices if hvp_v_block[i] is not None)
677
+
678
+ v_norm_sq_block = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
679
+ for i in block_param_indices)
680
+
681
+ # Ensure they are tensors
682
+ if not isinstance(vhp_dot_v_block, torch.Tensor):
683
+ vhp_dot_v_block = torch.tensor(0.0, device=device)
684
+ if not isinstance(v_norm_sq_block, torch.Tensor):
685
+ v_norm_sq_block = torch.tensor(0.0, device=device)
686
+
687
+ dist.all_reduce(vhp_dot_v_block, op=dist.ReduceOp.AVG)
688
+ dist.all_reduce(v_norm_sq_block, op=dist.ReduceOp.AVG)
689
+
690
+ if v_norm_sq_block.item() > 1e-12:
691
+ analysis_results["block_total_sharpness"] = (vhp_dot_v_block / v_norm_sq_block).item()
692
+ else:
693
+ analysis_results["block_total_sharpness"] = 0.0
694
+
695
+ analysis_results["v_norm_block"] = torch.sqrt(v_norm_sq_block).item()
696
+ analysis_results["v_T_H_v_block"] = vhp_dot_v_block.item()
697
+ else:
698
+ # No block parameters
699
+ analysis_results["block_total_sharpness"] = 0.0
700
+ analysis_results["v_norm_block"] = 0.0
701
+ analysis_results["v_T_H_v_block"] = 0.0
702
+
703
+ torch.cuda.empty_cache()
704
+
705
+ # ---- Alignment metrics between update v and (negative) gradient g ----
706
+ eps = 1e-12
707
+ v_norm = torch.sqrt(v_norm_sq_total + eps)
708
+ analysis_results["v_norm"] = v_norm.item()
709
+
710
+ # --- Version 1: g_hvp ---
711
+ ip_v_neg_g_hvp = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, grads_hvp) if g is not None)
712
+ g_hvp_norm_sq = sum(torch.sum(g * g) for g in grads_hvp if g is not None)
713
+
714
+ if not isinstance(ip_v_neg_g_hvp, torch.Tensor):
715
+ ip_v_neg_g_hvp = torch.tensor(0.0, device=device)
716
+ if not isinstance(g_hvp_norm_sq, torch.Tensor):
717
+ g_hvp_norm_sq = torch.tensor(0.0, device=device)
718
+ dist.all_reduce(ip_v_neg_g_hvp, op=dist.ReduceOp.AVG)
719
+ dist.all_reduce(g_hvp_norm_sq, op=dist.ReduceOp.AVG)
720
+ g_hvp_norm = torch.sqrt(g_hvp_norm_sq + eps)
721
+ analysis_results["ip_v_neg_g_hvp"] = ip_v_neg_g_hvp.item()
722
+ analysis_results["cos_v_neg_g_hvp"] = (ip_v_neg_g_hvp / (v_norm * g_hvp_norm + eps)).item()
723
+ analysis_results["g_hvp_norm"] = g_hvp_norm.item()
724
+
725
+ # --- Version 2: g_t (original gradient that produced v) ---
726
+ # last_training_gradient is the actual gradient from training that led to the update v
727
+ if last_training_gradient is not None:
728
+ ip_v_neg_g_t = sum(torch.sum(v * (-g)) for v, g in zip(update_direction_v, last_training_gradient) if g is not None)
729
+ g_t_norm_sq = sum(torch.sum(g * g) for g in last_training_gradient if g is not None)
730
+ dist.all_reduce(ip_v_neg_g_t, op=dist.ReduceOp.AVG)
731
+ dist.all_reduce(g_t_norm_sq, op=dist.ReduceOp.AVG)
732
+ g_t_norm = torch.sqrt(g_t_norm_sq + eps)
733
+ analysis_results["ip_v_neg_g_t"] = ip_v_neg_g_t.item()
734
+ analysis_results["cos_v_neg_g_t"] = (ip_v_neg_g_t / (v_norm * g_t_norm + eps)).item()
735
+ analysis_results["g_t_norm"] = g_t_norm.item()
736
+ else:
737
+ print0(f"[Enhanced Sharpness @ Step {step}] Warning: last_training_gradient is None, skipping g_t metrics")
738
+
739
+ # Keep backward compatibility aliases (g_norm uses g_hvp for now)
740
+ g_norm_sq = g_hvp_norm_sq
741
+ g_norm = g_hvp_norm
742
+ analysis_results["g_norm"] = g_norm.item()
743
+
744
+ # ---- Cosine between v and Hv (curvature pull along v) ----
745
+ hv_norm_sq = sum(torch.sum(hvp * hvp) for hvp in hvp_v_total if hvp is not None)
746
+ if not isinstance(hv_norm_sq, torch.Tensor):
747
+ hv_norm_sq = torch.tensor(0.0, device=device)
748
+ dist.all_reduce(hv_norm_sq, op=dist.ReduceOp.AVG)
749
+ hv_norm = torch.sqrt(hv_norm_sq + eps)
750
+ ip_v_hv = vhp_dot_v_total # already reduced AVG
751
+ analysis_results["hv_norm"] = hv_norm.item()
752
+ analysis_results["cos_v_hv"] = (ip_v_hv / (v_norm * hv_norm + eps)).item()
753
+
754
+ # ---- Cosine between g and Hg ----
755
+ # hvp_g_accum is already computed in the loop above
756
+ ip_g_hg = sum(torch.sum(g * hg) for g, hg in zip(grads_hvp, hvp_g_accum) if (g is not None and hg is not None))
757
+ hg_norm_sq = sum(torch.sum(hg * hg) for hg in hvp_g_accum if hg is not None)
758
+ if not isinstance(ip_g_hg, torch.Tensor):
759
+ ip_g_hg = torch.tensor(0.0, device=device)
760
+ if not isinstance(hg_norm_sq, torch.Tensor):
761
+ hg_norm_sq = torch.tensor(0.0, device=device)
762
+ dist.all_reduce(ip_g_hg, op=dist.ReduceOp.AVG)
763
+ dist.all_reduce(hg_norm_sq, op=dist.ReduceOp.AVG)
764
+ hg_norm = torch.sqrt(hg_norm_sq + eps)
765
+ analysis_results["hg_norm"] = hg_norm.item()
766
+ analysis_results["cos_g_hg"] = (ip_g_hg / (g_norm * hg_norm + eps)).item() if g_norm.item() > 0 else 0.0
767
+
768
+ # ---- Decompose v into parallel / perpendicular to -g ----
769
+ if g_norm.item() > 0:
770
+ v_parallel = [(torch.sum(v * (-g)) / (g_norm_sq + eps)) * (-g) if g is not None else torch.zeros_like(v)
771
+ for v, g in zip(update_direction_v, grads_hvp)]
772
+ v_parallel_norm_sq = sum(torch.sum(vp * vp) for vp in v_parallel)
773
+ if not isinstance(v_parallel_norm_sq, torch.Tensor):
774
+ v_parallel_norm_sq = torch.tensor(0.0, device=device)
775
+ dist.all_reduce(v_parallel_norm_sq, op=dist.ReduceOp.AVG)
776
+ v_parallel_norm = torch.sqrt(v_parallel_norm_sq + eps)
777
+ v_perp_norm = torch.sqrt(torch.clamp(v_norm_sq_total - v_parallel_norm_sq, min=0.0) + eps)
778
+ analysis_results["v_parallel_norm"] = v_parallel_norm.item()
779
+ analysis_results["v_perp_norm"] = v_perp_norm.item()
780
+
781
+ # ---- Per-layer additions: cos_v_neg_g_layer, v_norm_layer ----
782
+ for group_name, param_group in all_param_groups.items():
783
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
784
+ if not indices:
785
+ continue
786
+ v_norm_sq_layer = sum(torch.sum(update_direction_v[i] * update_direction_v[i]) for i in indices)
787
+ g_norm_sq_layer = sum(torch.sum(grads_hvp[i] * grads_hvp[i]) for i in indices if grads_hvp[i] is not None)
788
+ ip_v_neg_g_layer = sum(torch.sum(update_direction_v[i] * (-grads_hvp[i]))
789
+ for i in indices if grads_hvp[i] is not None)
790
+ # Ensure they are tensors
791
+ if not isinstance(v_norm_sq_layer, torch.Tensor):
792
+ v_norm_sq_layer = torch.tensor(0.0, device=device)
793
+ if not isinstance(g_norm_sq_layer, torch.Tensor):
794
+ g_norm_sq_layer = torch.tensor(0.0, device=device)
795
+ if not isinstance(ip_v_neg_g_layer, torch.Tensor):
796
+ ip_v_neg_g_layer = torch.tensor(0.0, device=device)
797
+ dist.all_reduce(v_norm_sq_layer, op=dist.ReduceOp.AVG)
798
+ dist.all_reduce(g_norm_sq_layer, op=dist.ReduceOp.AVG)
799
+ dist.all_reduce(ip_v_neg_g_layer, op=dist.ReduceOp.AVG)
800
+ v_norm_layer = torch.sqrt(v_norm_sq_layer + eps)
801
+ g_norm_layer = torch.sqrt(g_norm_sq_layer + eps)
802
+ analysis_results[f"{group_name}_v_norm"] = v_norm_layer.item()
803
+ if g_norm_layer.item() > 0:
804
+ analysis_results[f"{group_name}_cos_v_neg_g"] = (ip_v_neg_g_layer / (v_norm_layer * g_norm_layer + eps)).item()
805
+
806
+ # --- 7. Calculate layer-wise sharpness ---
807
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating layer-wise sharpness...")
808
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing {len(all_param_groups)} layers for sharpness...")
809
+
810
+ for group_name, param_group in all_param_groups.items():
811
+ if not param_group:
812
+ continue
813
+
814
+ print0(f"[Enhanced Sharpness @ Step {step}] Processing '{group_name}'...")
815
+ indices = {param_to_idx[id(p)] for p in param_group if id(p) in param_to_idx}
816
+ if not indices:
817
+ continue
818
+
819
+ try:
820
+ if group_name not in layer_hvp_accum or layer_hvp_accum[group_name] is None:
821
+ print0(f"[Enhanced Sharpness @ Step {step}] No HVP data for '{group_name}', skipping")
822
+ analysis_results[f"{group_name}_sharpness"] = 0.0
823
+ continue
824
+
825
+ hvp_group_result = layer_hvp_accum[group_name]
826
+
827
+ vhp_dot_v_group = sum(torch.sum(hvp_group_result[i] * update_direction_v[i])
828
+ for i in indices if hvp_group_result[i] is not None)
829
+ v_norm_sq_group = sum(torch.sum(update_direction_v[i] * update_direction_v[i])
830
+ for i in indices)
831
+
832
+ # Ensure they are tensors
833
+ if not isinstance(vhp_dot_v_group, torch.Tensor):
834
+ vhp_dot_v_group = torch.tensor(0.0, device=device)
835
+ if not isinstance(v_norm_sq_group, torch.Tensor):
836
+ v_norm_sq_group = torch.tensor(0.0, device=device)
837
+
838
+ dist.all_reduce(vhp_dot_v_group, op=dist.ReduceOp.AVG)
839
+ dist.all_reduce(v_norm_sq_group, op=dist.ReduceOp.AVG)
840
+
841
+ if v_norm_sq_group.item() > 1e-12:
842
+ analysis_results[f"{group_name}_sharpness"] = (vhp_dot_v_group / v_norm_sq_group).item()
843
+ else:
844
+ analysis_results[f"{group_name}_sharpness"] = 0.0
845
+
846
+ except torch.OutOfMemoryError as e:
847
+ print0(f"[Enhanced Sharpness @ Step {step}] OOM error for '{group_name}': {e}")
848
+ analysis_results[f"{group_name}_sharpness"] = 0.0
849
+ torch.cuda.empty_cache()
850
+ except Exception as e:
851
+ print0(f"[Enhanced Sharpness @ Step {step}] Error processing '{group_name}': {e}")
852
+ analysis_results[f"{group_name}_sharpness"] = 0.0
853
+
854
+ # --- Calculate block-diagonal approximation and cross-layer interaction ---
855
+ print0(f"[Enhanced Sharpness @ Step {step}] Calculating block-diagonal and cross-layer sharpness...")
856
+
857
+ sum_layer_numerators = 0.0
858
+ for layer in range(1, NUM_LAYERS + 1):
859
+ layer_name = f"layer_{layer}"
860
+ if f"{layer_name}_sharpness" in analysis_results and f"{layer_name}_v_norm" in analysis_results:
861
+ s_k = analysis_results[f"{layer_name}_sharpness"]
862
+ v_k_norm = analysis_results[f"{layer_name}_v_norm"]
863
+ sum_layer_numerators += s_k * (v_k_norm ** 2)
864
+
865
+ analysis_results["sum_layer_numerators"] = sum_layer_numerators
866
+
867
+ # Block-diagonal sharpness (using block ||v||²)
868
+ v_norm_block = analysis_results.get("v_norm_block", 0)
869
+ v_norm_sq_block_val = v_norm_block ** 2 if v_norm_block else 1e-12
870
+
871
+ if v_norm_sq_block_val > 1e-12:
872
+ analysis_results["block_diag_sharpness"] = sum_layer_numerators / v_norm_sq_block_val
873
+ else:
874
+ analysis_results["block_diag_sharpness"] = 0.0
875
+
876
+ # Cross-layer interaction = block_total - block_diag
877
+ block_total = analysis_results.get("block_total_sharpness", 0)
878
+ block_diag = analysis_results.get("block_diag_sharpness", 0)
879
+ analysis_results["cross_layer_sharpness"] = block_total - block_diag
880
+
881
+ print0(f"[Enhanced Sharpness @ Step {step}] block_total={block_total:.6f}, block_diag={block_diag:.6f}, cross_layer={block_total - block_diag:.6f}")
882
+
883
+ # --- Compute true_dec and pred_dec ---
884
+ print0(f"[Enhanced Sharpness @ Step {step}] Computing true_dec (L(t) - L(t+1)) on training batch...")
885
+ try:
886
+ # Restore FLASH for forward pass
887
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
888
+
889
+
890
+ loss_at_theta_t = 0.0
891
+ with torch.no_grad():
892
+ for x_td, y_td in batch_iterator:
893
+ x_td, y_td = x_td.to(device), y_td.to(device)
894
+ _, loss_td = model(x_td, y_td, return_logits=False)
895
+ loss_at_theta_t += loss_td.item()
896
+ loss_at_theta_t /= len(batch_iterator) # average over microbatches
897
+
898
+ with torch.no_grad():
899
+ for p, v in zip(model.parameters(), update_direction_v):
900
+ p.data.add_(v)
901
+
902
+ loss_at_theta_t1 = 0.0
903
+ with torch.no_grad():
904
+ for x_td, y_td in batch_iterator:
905
+ x_td, y_td = x_td.to(device), y_td.to(device)
906
+ _, loss_td = model(x_td, y_td, return_logits=False)
907
+ loss_at_theta_t1 += loss_td.item()
908
+ loss_at_theta_t1 /= len(batch_iterator)
909
+
910
+ with torch.no_grad():
911
+ for p, v in zip(model.parameters(), update_direction_v):
912
+ p.data.sub_(v)
913
+
914
+ loss_t_tensor = torch.tensor(loss_at_theta_t, device=device)
915
+ loss_t1_tensor = torch.tensor(loss_at_theta_t1, device=device)
916
+ dist.all_reduce(loss_t_tensor, op=dist.ReduceOp.AVG)
917
+ dist.all_reduce(loss_t1_tensor, op=dist.ReduceOp.AVG)
918
+ loss_at_theta_t = loss_t_tensor.item()
919
+ loss_at_theta_t1 = loss_t1_tensor.item()
920
+
921
+ true_dec = loss_at_theta_t - loss_at_theta_t1
922
+ analysis_results["loss_at_theta_t"] = loss_at_theta_t
923
+ analysis_results["loss_at_theta_t1"] = loss_at_theta_t1
924
+ analysis_results["true_dec"] = true_dec
925
+
926
+ # pred_dec = (-g)^T v - 0.5 * v^T H v
927
+ first_order = analysis_results.get("ip_v_neg_g_t", analysis_results.get("ip_v_neg_g_hvp", 0.0))
928
+ sharpness_val = analysis_results.get("total_sharpness", 0.0)
929
+ v_norm_val = analysis_results.get("v_norm", 0.0)
930
+ curvature_term = 0.5 * sharpness_val * (v_norm_val ** 2)
931
+ pred_dec = first_order - curvature_term
932
+
933
+ analysis_results["pred_dec"] = pred_dec
934
+ analysis_results["first_order_descent"] = first_order
935
+ analysis_results["curvature_penalty"] = curvature_term
936
+
937
+ print0(f"[Enhanced Sharpness @ Step {step}] L(θ_t)={loss_at_theta_t:.6f}, L(θ_{{t+1}})={loss_at_theta_t1:.6f}, "
938
+ f"true_dec={true_dec:.6f}, pred_dec={pred_dec:.6f}, 1st_order={first_order:.6f}, curvature={curvature_term:.6f}")
939
+ except Exception as e:
940
+ print0(f"[Enhanced Sharpness @ Step {step}] Error computing true_dec: {e}")
941
+ analysis_results["true_dec"] = 0.0
942
+ analysis_results["pred_dec"] = 0.0
943
+
944
+ # --- Cleanup ---
945
+ nano_GPT_qkvonorm_pure.FLASH = original_flash
946
+ print0(f"[Enhanced Sharpness @ Step {step}] Restored FLASH attention to {original_flash}")
947
+
948
+ print0(f"[Enhanced Sharpness @ Step {step}] Restoring parameters back to θ_{{t+1}}...")
949
+ with torch.no_grad():
950
+ for p, v in zip(model.parameters(), update_direction_v):
951
+ p.data.add_(v)
952
+
953
+ if prev_training_mode:
954
+ model.train()
955
+ else:
956
+ model.eval()
957
+
958
+ # Thorough cleanup of all temporary variables
959
+ del update_direction_v, grads_hvp
960
+ del hvp_v_total, hvp_v_block, hvp_g_accum, layer_hvp_accum
961
+ del vhp_dot_v_total, v_norm_sq_total
962
+ del vhp_dot_v_block, v_norm_sq_block
963
+ if 'all_param_groups' in locals():
964
+ del all_param_groups
965
+ if 'param_to_idx' in locals():
966
+ del param_to_idx
967
+
968
+ # Synchronize CUDA operations before cleanup
969
+ if device == "cuda":
970
+ torch.cuda.synchronize()
971
+
972
+ gc.collect()
973
+ torch.cuda.empty_cache()
974
+
975
+ print0(f"[Enhanced Sharpness @ Step {step}] Analysis complete. Generated {len(analysis_results)} metrics.")
976
+ return analysis_results
977
+
978
+ def format_comprehensive_results(results):
979
+ """
980
+ Format the comprehensive analysis results for logging.
981
+ """
982
+ log_parts = []
983
+
984
+ # Total sharpness
985
+ if 'total_sharpness' in results:
986
+ log_parts.append(f"total_sharp:{results['total_sharpness']:.4e}")
987
+
988
+ # Layer-wise sharpness - dynamically detect number of layers
989
+ layer_sharpness = []
990
+ layer_num = 1
991
+ while True:
992
+ layer_key = f"layer_{layer_num}_sharpness"
993
+ if layer_key in results:
994
+ layer_sharpness.append(f"L{layer_num}_sharp:{results[layer_key]:.4e}")
995
+ layer_num += 1
996
+ else:
997
+ break
998
+
999
+ if layer_sharpness:
1000
+ log_parts.append(" ".join(layer_sharpness))
1001
+
1002
+ # Total update norms
1003
+ total_norms = []
1004
+ if 'total_update_fnorm' in results:
1005
+ total_norms.append(f"total_fnorm:{results['total_update_fnorm']:.4e}")
1006
+ if 'total_l1_linf_norm' in results:
1007
+ total_norms.append(f"total_l1_linf:{results['total_l1_linf_norm']:.4e}")
1008
+ if 'total_spectral_norm' in results:
1009
+ total_norms.append(f"total_spectral:{results['total_spectral_norm']:.4e}")
1010
+
1011
+ if total_norms:
1012
+ log_parts.append(" ".join(total_norms))
1013
+
1014
+ # Layer-wise update norms (Frobenius)
1015
+ layer_fnorms = []
1016
+ layer_num = 1
1017
+ while True:
1018
+ layer_key = f"layer_{layer_num}_update_fnorm"
1019
+ if layer_key in results:
1020
+ layer_fnorms.append(f"L{layer_num}_fnorm:{results[layer_key]:.4e}")
1021
+ layer_num += 1
1022
+ else:
1023
+ break
1024
+
1025
+ if layer_fnorms:
1026
+ log_parts.append(" ".join(layer_fnorms))
1027
+
1028
+ # Layer-wise update norms (Max-of-Max)
1029
+ layer_l1_linf = []
1030
+ layer_num = 1
1031
+ while True:
1032
+ layer_key = f"layer_{layer_num}_max_l1_linf_norm"
1033
+ if layer_key in results:
1034
+ layer_l1_linf.append(f"L{layer_num}_l1linf:{results[layer_key]:.4e}")
1035
+ layer_num += 1
1036
+ else:
1037
+ break
1038
+
1039
+ if layer_l1_linf:
1040
+ log_parts.append(" ".join(layer_l1_linf))
1041
+
1042
+ # Layer-wise update norms (Spectral)
1043
+ layer_spectral = []
1044
+ layer_num = 1
1045
+ while True:
1046
+ layer_key = f"layer_{layer_num}_max_spectral_norm"
1047
+ if layer_key in results:
1048
+ layer_spectral.append(f"L{layer_num}_spectral:{results[layer_key]:.4e}")
1049
+ layer_num += 1
1050
+ else:
1051
+ break
1052
+
1053
+ if layer_spectral:
1054
+ log_parts.append(" ".join(layer_spectral))
1055
+
1056
+ # Alignment and curvature metrics (global)
1057
+ misc_parts = []
1058
+ if 'v_norm' in results:
1059
+ misc_parts.append(f"v_norm:{results['v_norm']:.4e}")
1060
+
1061
+ # Version 1: g_hvp (new batch, computed at θ_t during HVP calculation)
1062
+ if 'cos_v_neg_g_hvp' in results:
1063
+ misc_parts.append(f"cos_v_-g_hvp:{results['cos_v_neg_g_hvp']:.4e}")
1064
+ if 'g_hvp_norm' in results:
1065
+ misc_parts.append(f"g_hvp_norm:{results['g_hvp_norm']:.4e}")
1066
+
1067
+ # Version 2: g_t (original gradient that produced v)
1068
+ if 'cos_v_neg_g_t' in results:
1069
+ misc_parts.append(f"cos_v_-g_t:{results['cos_v_neg_g_t']:.4e}")
1070
+ if 'g_t_norm' in results:
1071
+ misc_parts.append(f"g_t_norm:{results['g_t_norm']:.4e}")
1072
+
1073
+ if 'hv_norm' in results:
1074
+ misc_parts.append(f"hv_norm:{results['hv_norm']:.4e}")
1075
+ if 'cos_v_hv' in results:
1076
+ misc_parts.append(f"cos_v_hv:{results['cos_v_hv']:.4e}")
1077
+ if 'hg_norm' in results:
1078
+ misc_parts.append(f"hg_norm:{results['hg_norm']:.4e}")
1079
+ if 'cos_g_hg' in results:
1080
+ misc_parts.append(f"cos_g_hg:{results['cos_g_hg']:.4e}")
1081
+ if 'v_parallel_norm' in results:
1082
+ misc_parts.append(f"v_par:{results['v_parallel_norm']:.4e}")
1083
+ if 'v_perp_norm' in results:
1084
+ misc_parts.append(f"v_perp:{results['v_perp_norm']:.4e}")
1085
+ if misc_parts:
1086
+ log_parts.append(" ".join(misc_parts))
1087
+
1088
+ # Per-layer alignment metrics (cos_v_neg_g and v_norm per layer)
1089
+ layer_cos = []
1090
+ layer_num = 1
1091
+ while True:
1092
+ layer_key = f"layer_{layer_num}_cos_v_neg_g"
1093
+ layer_vn_key = f"layer_{layer_num}_v_norm"
1094
+ if layer_key in results:
1095
+ layer_cos.append(f"L{layer_num}_cos_v_neg_g:{results[layer_key]:.4e}")
1096
+ if layer_vn_key in results:
1097
+ layer_cos.append(f"L{layer_num}_v_norm:{results[layer_vn_key]:.4e}")
1098
+ if layer_key not in results and layer_vn_key not in results:
1099
+ break
1100
+ layer_num += 1
1101
+ if layer_cos:
1102
+ log_parts.append(" ".join(layer_cos))
1103
+
1104
+ return " ".join(log_parts)
1105
+
1106
+ # -----------------------------------------------------------------------------
1107
+ # int main
1108
+
1109
+ def print0(*args, **kwargs):
1110
+ # modified print that only prints from the master process
1111
+ # if this is not a distributed run, it's just a print
1112
+ if int(os.environ.get("RANK", 0)) == 0:
1113
+ print(*args, **kwargs)
1114
+
1115
+ if __name__ == "__main__":
1116
+ import time
1117
+ import argparse
1118
+ import tiktoken
1119
+ print0(f"Running pytorch {torch.version.__version__}")
1120
+
1121
+ # default settings will overfit a tiny batch of data
1122
+ # and save model weights and debug state to disk on the first iteration
1123
+ parser = argparse.ArgumentParser()
1124
+ # file system input / output
1125
+ parser.add_argument("--input_bin", type=str, default="dev/data/tinyshakespeare/tiny_shakespeare_val.bin", help="input .bin to train on")
1126
+ parser.add_argument("--input_val_bin", type=str, default="", help="input .bin to eval validation loss on")
1127
+ parser.add_argument("--output_dir", type=str, default="", help="output directory to which to write logs and checkpoints")
1128
+ parser.add_argument("--model", type=str, default="gpt2", help="gpt2|gpt2-medium|gpt2-large|gpt2-xl|d8|d12|d24|d36|d48")
1129
+ # token layout for each step of the optimization
1130
+ parser.add_argument("--batch_size", type=int, default=4, help="batch size, in units of #batch dimensions")
1131
+ parser.add_argument("--sequence_length", type=int, default=64, help="sequence length")
1132
+ parser.add_argument("--total_batch_size", type=int, default=256, help="total desired batch size, in units of #tokens")
1133
+ # workload (number of steps)
1134
+ parser.add_argument("--num_iterations", type=int, default=10, help="number of iterations to run")
1135
+ parser.add_argument("--inference_only", type=int, default=0, help="only run inference")
1136
+ # optimization
1137
+ parser.add_argument("--adam_lr", type=float, default=1e-4, help="learning rate warmup iterations")
1138
+ parser.add_argument("--warmup_iters", type=int, default=0, help="learning rate warmup iterations")
1139
+ parser.add_argument("--lr_decay_frac", type=float, default=1.0, help="learning rate warmup iterations")
1140
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="weight decay")
1141
+ parser.add_argument("--grad_clip", type=float, default=1.0, help="maximum gradient magnitude")
1142
+ # evaluation
1143
+ parser.add_argument("--val_loss_every", type=int, default=0, help="every how mant steps to evaluate val loss?")
1144
+ parser.add_argument("--val_max_steps", type=int, default=20, help="how many batches of val to average?")
1145
+ parser.add_argument("--sample_every", type=int, default=0, help="how often to sample from the model?")
1146
+ # debugging
1147
+ parser.add_argument("--overfit_single_batch", type=int, default=0, help="overfit just one batch of data")
1148
+ parser.add_argument("--shuffle_files", action="store_true")
1149
+ # numerics
1150
+ parser.add_argument("--tensorcores", type=int, default=0, help="use tensorcores")
1151
+ # memory management
1152
+ parser.add_argument("--device", type=str, default="", help="by default we autodetect, or set it here")
1153
+ parser.add_argument("--compile", type=int, default=0, help="torch.compile the model")
1154
+ parser.add_argument("--flash", type=int, default=0, help="use flash attention")
1155
+ parser.add_argument("--dtype", type=str, default="float32", help="float32|float16|bfloat16")
1156
+ parser.add_argument("--zero_stage", type=int, default=0, help="zero redundancy optimizer stage (0/1/2/3)")
1157
+ # Muon optimizer specific arguments
1158
+ parser.add_argument("--optimizer", type=str, default="adam", help="optimizer to use: adam|muon")
1159
+ parser.add_argument("--muon_lr", type=float, default=0.02, help="learning rate for Muon optimizer")
1160
+ parser.add_argument("--muon_momentum", type=float, default=0.95, help="momentum for Muon optimizer")
1161
+ parser.add_argument("--muon_weight_decay", type=float, default=0.00, help="weight decay for Muon optimizer")
1162
+ parser.add_argument("--muon_ns_steps", type=int, default=5, help="number of Newton-Schulz steps for Muon")
1163
+ parser.add_argument("--muon_nesterov", type=bool, default=False, help="use Nesterov momentum for Muon (0/1)")
1164
+ # python -> C bridge
1165
+ parser.add_argument("--write_tensors", type=int, default=1, help="write tensors to disk")
1166
+ parser.add_argument("--seed", type=int, default=42, help="random seed")
1167
+ # Sharpness analysis arguments
1168
+ parser.add_argument("--analyze_sharpness", action="store_true", help="Enable comprehensive sharpness analysis")
1169
+ parser.add_argument("--sharpness_analysis_interval", type=int, default=500, help="Interval for sharpness analysis")
1170
+ args = parser.parse_args()
1171
+
1172
+ # args error checking and convenience variables
1173
+ B, T = args.batch_size, args.sequence_length
1174
+ assert 1 <= T <= 1024
1175
+ assert args.dtype in {"float32", "float16", "bfloat16"}
1176
+ assert args.model in {"gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl", "d8", "d12", "d24", "d36", "d48"}
1177
+ assert args.optimizer in {"adam", "muon"}
1178
+
1179
+ set_seed(args.seed)
1180
+
1181
+ # set up DDP (distributed data parallel). torchrun sets this env variable
1182
+ ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
1183
+ if ddp:
1184
+ # use of DDP atm demands CUDA, we set the device appropriately according to rank
1185
+ assert torch.cuda.is_available(), "for now i think we need CUDA for DDP"
1186
+ init_process_group(backend='nccl')
1187
+ ddp_rank = int(os.environ['RANK'])
1188
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
1189
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
1190
+ device = f'cuda:{ddp_local_rank}'
1191
+ torch.cuda.set_device(device)
1192
+ master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
1193
+ seed_offset = 0 # each process gets the exact same seed
1194
+ zero_stage = args.zero_stage
1195
+ else:
1196
+ ddp_rank = 0
1197
+ ddp_local_rank = 0
1198
+ zero_stage = 0
1199
+ ddp_world_size = 1
1200
+ master_process = True
1201
+ seed_offset = 0
1202
+ # select the device
1203
+ if args.device:
1204
+ # provided explicitly by the user
1205
+ device = args.device
1206
+ else:
1207
+ # attempt to autodetect the device
1208
+ device = "cpu"
1209
+ if torch.cuda.is_available():
1210
+ device = "cuda"
1211
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
1212
+ device = "mps"
1213
+ print(f"using device: {device}")
1214
+ device_type = 'cuda' if 'cuda' in device else 'cpu'
1215
+
1216
+ # Setup debugpy for remote debugging (only activates if DEBUGPY env var is set)
1217
+ # setup_debugpy(rank=ddp_rank, force=True)
1218
+
1219
+ # calculate gradient accumulation from the desired total batch size and the current run configuration
1220
+ tokens_per_fwdbwd = B * T * ddp_world_size
1221
+ assert args.total_batch_size % tokens_per_fwdbwd == 0
1222
+ grad_accum_steps = args.total_batch_size // tokens_per_fwdbwd
1223
+ print0(f"total desired batch size: {args.total_batch_size}")
1224
+ print0(f"=> calculated gradient accumulation steps: {grad_accum_steps}")
1225
+
1226
+ # set up a context manager following the desired dtype and device
1227
+ ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[args.dtype]
1228
+ ctx = torch.amp.autocast(device_type=device_type, dtype=ptdtype) if device_type == "cuda" else nullcontext()
1229
+
1230
+ # rng / reproducibility
1231
+ torch.manual_seed(42)
1232
+ if torch.cuda.is_available():
1233
+ torch.cuda.manual_seed(42)
1234
+
1235
+ # set the torch precision mode to use TensorFloat32 (TF32) for matmuls
1236
+ # docs https://pytorch.org/docs/stable/generated/torch.set_float32_matmul_precision.html
1237
+ if args.tensorcores:
1238
+ torch.set_float32_matmul_precision('high')
1239
+
1240
+ # turn on/off flash attention
1241
+ assert args.flash in {0, 1}
1242
+ nano_GPT_qkvonorm_pure.FLASH = args.flash # Set module-level FLASH for training
1243
+
1244
+ # init (and write) the tokenizer
1245
+ enc = tiktoken.get_encoding("gpt2")
1246
+ if master_process and args.write_tensors: # tokenizer is technically not tensors but ok
1247
+ write_tokenizer(enc, "gpt2_tokenizer.bin")
1248
+
1249
+ # init the model, either from scratch or from OpenAI pretrained checkpoint
1250
+ if args.model[0] == "d":
1251
+ # from scratch (random weights)
1252
+ model_config = {
1253
+ "d8": GPTConfig(block_size=1024, vocab_size=50257, n_layer=8, n_head=8, n_embd=512),
1254
+ "d12": GPTConfig(block_size=1024, vocab_size=50257, n_layer=12, n_head=12, n_embd=768),
1255
+ "d24": GPTConfig(block_size=1024, vocab_size=50257, n_layer=24, n_head=16, n_embd=1024),
1256
+ "d36": GPTConfig(block_size=1024, vocab_size=50257, n_layer=36, n_head=20, n_embd=1280),
1257
+ "d48": GPTConfig(block_size=1024, vocab_size=50257, n_layer=48, n_head=25, n_embd=1600),
1258
+ }[args.model]
1259
+ model = GPT(model_config)
1260
+ else:
1261
+ # load the GPT-2 model weights
1262
+ model = GPT.from_pretrained(args.model)
1263
+ model.train()
1264
+ model.to(device)
1265
+
1266
+ # Save uncompiled model reference for sharpness analysis (needs double backward)
1267
+ raw_model_uncompiled = model
1268
+
1269
+ if args.compile:
1270
+ if hasattr(config, "coordinate_descent_tuning"):
1271
+ config.coordinate_descent_tuning = True # suggested by @Chillee
1272
+ print0("compiling the model...")
1273
+ model = torch.compile(model)
1274
+
1275
+ # -------------------------------------------------------------------------
1276
+ # Our own version of a simple DistributedDataLoader
1277
+
1278
+ # load tokens
1279
+ train_loader = DistributedDataLoader(
1280
+ args.input_bin, B, T, ddp_rank, ddp_world_size,
1281
+ shuffle_files=args.shuffle_files, random_seed=args.seed
1282
+ )
1283
+ val_loader = None
1284
+ if args.input_val_bin:
1285
+ val_loader = DistributedDataLoader(args.input_val_bin, B, T, ddp_rank, ddp_world_size)
1286
+
1287
+ # -------------------------------------------------------------------------
1288
+ # PyTorch -> C bridge: save some weights and state for C to load later as reference
1289
+
1290
+ # do one forward pass to generate ground truth for our C tests
1291
+ if master_process and args.write_tensors and (not args.inference_only):
1292
+ x, y = train_loader.next_batch()
1293
+ x, y = x.to(device), y.to(device)
1294
+ logits, loss = model(x, y, return_logits=True) # Need logits for write_state
1295
+ loss.backward()
1296
+ # save model params, in both float32 and bfloat16
1297
+ model_to_size = {"gpt2": "124M", "gpt2-medium": "355M", "gpt2-large": "774M", "gpt2-xl": "1558M"}
1298
+ model_to_size.update({f"d{d}": f"d{d}" for d in [12, 24, 36, 48]})
1299
+ model_size_str = model_to_size[args.model] # e.g. "124M", or "d12"
1300
+ write_model(model, f"gpt2_{model_size_str}.bin", dtype="float32")
1301
+ write_model(model, f"gpt2_{model_size_str}_bf16.bin", dtype="bfloat16")
1302
+ # save x, y, logits, loss, and parameter gradients, for debugging C
1303
+ # always store these in fp32 to have an accurate reference (?)
1304
+ write_state(model, x, y, logits, loss, f"gpt2_{model_size_str}_debug_state.bin")
1305
+ # reset the train_loader for the optimization below
1306
+ train_loader.reset()
1307
+
1308
+ # -------------------------------------------------------------------------
1309
+ # main training loop
1310
+
1311
+ # here we wrap model into DDP container
1312
+ if ddp:
1313
+ model = DDP(model, device_ids=[ddp_local_rank])
1314
+ raw_model = model.module if ddp else model # always contains the "raw" unwrapped model
1315
+
1316
+ base_module = model.module if ddp else model
1317
+ # If compiled, unwrap to get the original module
1318
+ if hasattr(base_module, "_orig_mod"):
1319
+ base_module = base_module._orig_mod
1320
+
1321
+ raw_params = list(raw_model_uncompiled.parameters())
1322
+ train_params = list(base_module.parameters())
1323
+
1324
+ assert len(raw_params) == len(train_params), \
1325
+ f"Parameter count mismatch: raw_model_uncompiled has {len(raw_params)}, training model has {len(train_params)}"
1326
+ for i, (rp, tp) in enumerate(zip(raw_params, train_params)):
1327
+ assert rp.data_ptr() == tp.data_ptr(), \
1328
+ f"Parameter {i} has different data_ptr: raw_model_uncompiled and training model do not share parameters!"
1329
+ print0(f"[Verified] raw_model_uncompiled and training model share the same {len(raw_params)} Parameter objects")
1330
+
1331
+ last_training_update = None
1332
+ last_training_gradient = None # Store the original gradient that produced the update
1333
+ last_training_batches = None # Store ALL microbatches (x, y) for consistent HVP calculation
1334
+
1335
+
1336
+ def configure_adam(model, weight_decay, learning_rate, betas, device_type, zero_stage):
1337
+ # start with all of the candidate parameters
1338
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1339
+ # filter out those that do not require grad
1340
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1341
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
1342
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
1343
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
1344
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
1345
+ optim_groups = [
1346
+ {'params': decay_params, 'weight_decay': weight_decay},
1347
+ {'params': nodecay_params, 'weight_decay': 0.0}
1348
+ ]
1349
+ num_decay_params = sum(p.numel() for p in decay_params)
1350
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
1351
+ print0(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
1352
+ print0(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
1353
+ # Create AdamW optimizer and use the fused version if it is available
1354
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1355
+ use_fused = fused_available and device_type == 'cuda'
1356
+ print0(f"using fused AdamW: {use_fused}")
1357
+ if zero_stage == 1:
1358
+ print0("using ZeroRedundancyOptimizer")
1359
+ optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1360
+ lr=learning_rate, betas=betas, fused=use_fused)
1361
+ optimizer.add_param_group(optim_groups[1])
1362
+ else:
1363
+ print0("using regular AdamW")
1364
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=use_fused)
1365
+ return [optimizer]
1366
+
1367
+ def configure_muon(model, weight_decay, adam_lr, muon_lr, momentum, nesterov, ns_steps, device_type, zero_stage, ddp_rank, ddp_world_size):
1368
+ # start with all of the candidate parameters
1369
+ param_dict = {pn: p for pn, p in model.named_parameters()}
1370
+ # filter out those that do not require grad
1371
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
1372
+
1373
+ # For Muon, we need to separate 2D parameters (which can be orthogonalized)
1374
+ # from other parameters (which should use standard optimization)
1375
+ muon_params = [] # 2D parameters for Muon
1376
+ other_params = [] # other parameters for AdamW
1377
+
1378
+ muon_name = []
1379
+ other_name = []
1380
+ for n, p in param_dict.items():
1381
+ if "wte.weight" in n :
1382
+ other_params.append(p)
1383
+ other_name.append(n)
1384
+ continue
1385
+
1386
+ if p.dim() >= 2: # 2D parameters (weight matrices)
1387
+ muon_params.append(p)
1388
+ muon_name.append(n)
1389
+ else: # 1D parameters (biases, embeddings, etc.)
1390
+ other_params.append(p)
1391
+ other_name.append(n)
1392
+
1393
+ # print("================================================\n")
1394
+ # print(f"Muon parameters: {muon_name}\n")
1395
+ # print(f"Other parameters: {other_name}\n")
1396
+ # print("================================================\n")
1397
+
1398
+ print0(f"Muon parameters (2D): {len(muon_params)} tensors")
1399
+ print0(f"Other parameters (non-2D): {len(other_params)} tensors")
1400
+
1401
+ # Create Muon optimizer for 2D parameters
1402
+ muon_optimizer = None
1403
+ if muon_params:
1404
+ muon_optimizer = Muon(
1405
+ params=muon_params,
1406
+ lr=muon_lr,
1407
+ weight_decay=weight_decay,
1408
+ momentum=momentum,
1409
+ nesterov=nesterov,
1410
+ ns_steps=ns_steps,
1411
+ rank=ddp_rank,
1412
+ world_size=ddp_world_size
1413
+ )
1414
+
1415
+ # Create AdamW optimizer for non-2D parameters
1416
+ adam_optimizer = None
1417
+ if other_params:
1418
+ # create optim groups for AdamW
1419
+ # decay_params = [p for p in other_params if p.dim() >= 2]
1420
+ # nodecay_params = [p for p in other_params if p.dim() < 2]
1421
+ optim_groups = [
1422
+ {'params': other_params, 'weight_decay': weight_decay},
1423
+ # {'params': nodecay_params, 'weight_decay': 0.0}
1424
+ ]
1425
+
1426
+ # Create AdamW optimizer
1427
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
1428
+ use_fused = fused_available and device_type == 'cuda'
1429
+ print0(f"using fused AdamW for non-Muon params: {use_fused}")
1430
+
1431
+ if zero_stage == 1:
1432
+ print0("using ZeroRedundancyOptimizer for non-Muon params")
1433
+ adam_optimizer = ZeroRedundancyOptimizer(**optim_groups[0], optimizer_class=torch.optim.AdamW,
1434
+ lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1435
+ # adam_optimizer.add_param_group(optim_groups[1])
1436
+ else:
1437
+ print0("using regular AdamW for non-Muon params")
1438
+ adam_optimizer = torch.optim.AdamW(optim_groups, lr=adam_lr, betas=(0.9, 0.95), fused=use_fused)
1439
+
1440
+ return [muon_optimizer, adam_optimizer]
1441
+
1442
+ # init the optimizer
1443
+ if args.optimizer == "adam":
1444
+ optimizers = configure_adam(model=raw_model_uncompiled, weight_decay=args.weight_decay,
1445
+ learning_rate=args.adam_lr, betas=(0.9, 0.95),
1446
+ device_type=device, zero_stage=zero_stage)
1447
+ elif args.optimizer == "muon":
1448
+ optimizers = configure_muon(
1449
+ model=raw_model_uncompiled,
1450
+ weight_decay=args.muon_weight_decay,
1451
+ muon_lr=args.muon_lr,
1452
+ adam_lr=args.adam_lr,
1453
+ momentum=args.muon_momentum,
1454
+ nesterov=bool(args.muon_nesterov),
1455
+ ns_steps=args.muon_ns_steps,
1456
+ device_type=device,
1457
+ zero_stage=zero_stage,
1458
+ ddp_rank=ddp_rank,
1459
+ ddp_world_size=ddp_world_size
1460
+ )
1461
+ # We'll use muon_optimizer and adam_optimizer separately
1462
+
1463
+ # learning rate decay scheduler (cosine with warmup)
1464
+ def get_lr(it,base_lr):
1465
+ # if args.optimizer == "adam":
1466
+ # base_lr = args.adam_lr
1467
+ # else: # muon
1468
+ # base_lr = args.muon_lr
1469
+ min_lr = base_lr * args.lr_decay_frac
1470
+ # 1) linear warmup for warmup_iters steps
1471
+ if it < args.warmup_iters:
1472
+ return base_lr * (it+1) / args.warmup_iters
1473
+ # 2) if it > lr_decay_iters, return min learning rate
1474
+ if it > args.num_iterations:
1475
+ return min_lr
1476
+ # 3) in between, use cosine decay down to min learning rate
1477
+ decay_ratio = (it - args.warmup_iters) / (args.num_iterations - args.warmup_iters)
1478
+ assert 0 <= decay_ratio <= 1
1479
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff starts at 1 and goes to 0
1480
+ return min_lr + coeff * (base_lr - min_lr)
1481
+
1482
+ def get_wsd_lr(it, base_lr):
1483
+ min_lr = base_lr * args.lr_decay_frac
1484
+ # cooldown_iters = int(args.num_iterations * 0.2)
1485
+ cooldown_iters = int(0)
1486
+ # 1) Warmup: linear warmup for warmup_iters steps
1487
+ if it < args.warmup_iters:
1488
+ return base_lr * (it + 1) / args.warmup_iters
1489
+ # 3) Decay: linear decay from base_lr to min_lr in the last cooldown_iters steps
1490
+ cooldown_start = args.num_iterations - cooldown_iters
1491
+ if it >= cooldown_start:
1492
+ decay_ratio = (it - cooldown_start) / cooldown_iters
1493
+ return base_lr - decay_ratio * (base_lr - min_lr)
1494
+ # 2) Stable: constant learning rate at base_lr
1495
+ return base_lr
1496
+
1497
+ # create the logging directory if it does not exist
1498
+ logfile = None
1499
+ run_dir_path = None
1500
+
1501
+ file_name = f"mode_{args.optimizer}_adam_lr_{args.adam_lr}_muon_lr_{args.muon_lr}_seed_{args.seed}.log"
1502
+ if args.output_dir:
1503
+ base_log_dir = Path(args.output_dir)
1504
+ base_log_dir.mkdir(parents=True, exist_ok=True)
1505
+
1506
+ # Create run-specific directory
1507
+ # Generate UUID on master process and broadcast to all ranks
1508
+ if master_process:
1509
+ run_uuid = uuid.uuid4()
1510
+ uuid_str = str(run_uuid)
1511
+ else:
1512
+ uuid_str = None
1513
+
1514
+ # Broadcast UUID from rank 0 to all other ranks
1515
+ if ddp:
1516
+ # Create a tensor to hold the UUID string length and content
1517
+ if master_process:
1518
+ uuid_bytes = uuid_str.encode('utf-8')
1519
+ uuid_len = len(uuid_bytes)
1520
+ else:
1521
+ uuid_len = 0
1522
+
1523
+ # Broadcast length
1524
+ uuid_len_tensor = torch.tensor(uuid_len, dtype=torch.long, device=device)
1525
+ dist.broadcast(uuid_len_tensor, src=0)
1526
+
1527
+ # Broadcast UUID string
1528
+ if master_process:
1529
+ uuid_tensor = torch.ByteTensor(list(uuid_bytes)).to(device)
1530
+ else:
1531
+ uuid_tensor = torch.ByteTensor([0] * uuid_len_tensor.item()).to(device)
1532
+ dist.broadcast(uuid_tensor, src=0)
1533
+
1534
+ # Decode on non-master processes
1535
+ if not master_process:
1536
+ uuid_str = bytes(uuid_tensor.cpu().numpy()).decode('utf-8')
1537
+ run_uuid = uuid.UUID(uuid_str)
1538
+ else:
1539
+ run_uuid = uuid.UUID(uuid_str)
1540
+ else:
1541
+ run_uuid = uuid.uuid4()
1542
+
1543
+ # run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}_{run_uuid}"
1544
+ run_folder_name = f"opt_{args.optimizer}_alr_{args.adam_lr}_mlr_{args.muon_lr}_seed_{args.seed}"
1545
+ run_dir_path = base_log_dir / run_folder_name
1546
+ if run_dir_path.exists():
1547
+ run_flag = False
1548
+ else:
1549
+ run_flag = True
1550
+ torch.cuda.synchronize()
1551
+
1552
+
1553
+ # Only master process creates the directory
1554
+ if master_process:
1555
+ run_dir_path.mkdir(parents=True, exist_ok=True)
1556
+
1557
+ logfile = str(run_dir_path / "training_log.txt")
1558
+
1559
+ # Save configuration
1560
+
1561
+ if run_flag:
1562
+ if master_process:
1563
+ config_to_save = {
1564
+ "cli_args": vars(args),
1565
+ "run_uuid": str(run_uuid),
1566
+ "script_code_logged_at_start": True
1567
+ }
1568
+ config_file_path = run_dir_path / "config.json"
1569
+ with open(config_file_path, "w") as f:
1570
+ json.dump(config_to_save, f, indent=4)
1571
+ print0(f"Saved configuration to: {config_file_path}")
1572
+
1573
+ if master_process and logfile:
1574
+ with open(logfile, "w") as f:
1575
+ pass # Create/clear the file
1576
+ with open(logfile, "a") as f:
1577
+ f.write(code)
1578
+
1579
+ if device == "cuda":
1580
+ torch.cuda.reset_peak_memory_stats()
1581
+ timings = []
1582
+ norm = -1.0 # dummy value to print in inference-only mode
1583
+ for step in range(args.num_iterations + 1):
1584
+ t0 = time.time()
1585
+ last_step = (step == args.num_iterations)
1586
+
1587
+ # once in a while evaluate the validation dataset
1588
+ if (args.val_loss_every > 0 \
1589
+ and (step % args.val_loss_every == 0 or last_step)) \
1590
+ and (val_loader is not None):
1591
+ model.eval()
1592
+ val_loader.reset()
1593
+ with torch.no_grad():
1594
+ val_loss = 0.0
1595
+ for _ in range(args.val_max_steps):
1596
+ x, y = val_loader.next_batch()
1597
+ x, y = x.to(device), y.to(device)
1598
+ _, loss = model(x, y, return_logits=False)
1599
+ val_loss += loss.item()
1600
+ val_loss /= args.val_max_steps
1601
+
1602
+ # --- Comprehensive Sharpness Analysis ---
1603
+ sharpness_log_str = ""
1604
+ # Skip step 0 since we don't have a previous training update yet
1605
+ if args.analyze_sharpness and step > 0 and (step % args.sharpness_analysis_interval == 0 or last_step):
1606
+ print0(f"[Sharpness @ Step {step}] Starting comprehensive sharpness analysis...")
1607
+ for optimizer in optimizers:
1608
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1609
+ optimizer.zero_grad(set_to_none=True)
1610
+ elif isinstance(optimizer, Muon):
1611
+ optimizer.zero_grad()
1612
+ comprehensive_results = calculate_comprehensive_sharpness(
1613
+ model=raw_model_uncompiled, # Use uncompiled model for HVP (double backward)
1614
+ model_for_forward=model, # Use compiled+DDP model for forward pass
1615
+ optimizers=optimizers,
1616
+ step=step,
1617
+ train_loader=train_loader,
1618
+ val_loader=val_loader,
1619
+ rank=ddp_rank,
1620
+ world_size=ddp_world_size,
1621
+ device=device,
1622
+ B=B,
1623
+ T=T,
1624
+ ptdtype=ptdtype,
1625
+ grad_accum_steps=grad_accum_steps, # Pass grad accumulation steps to scale loss correctly
1626
+ last_training_update=last_training_update, # Pass the real update captured from training
1627
+ last_training_gradient=last_training_gradient, # Pass the original gradient g_t
1628
+ last_training_batches=last_training_batches # Pass ALL microbatches for consistent HVP
1629
+ )
1630
+ sharpness_log_str = format_comprehensive_results(comprehensive_results)
1631
+
1632
+ # Save sharpness results to file
1633
+ if master_process and run_dir_path:
1634
+ sharpness_file = run_dir_path / f"sharpness_step_{step}.json"
1635
+ with open(sharpness_file, "w") as f:
1636
+ json.dump(comprehensive_results, f, indent=4)
1637
+ print0(f"[Sharpness @ Step {step}] Results saved to {sharpness_file}")
1638
+
1639
+ # Clean up memory after sharpness analysis
1640
+ del comprehensive_results
1641
+ # Ensure all CUDA operations are complete before cleaning up
1642
+ if device == "cuda":
1643
+ torch.cuda.synchronize()
1644
+ torch.cuda.empty_cache()
1645
+ gc.collect()
1646
+ if ddp:
1647
+ dist.barrier() # Sync all ranks after cleanup
1648
+ print0(f"[Step {step}] Memory cleaned up after sharpness analysis")
1649
+
1650
+ # log to console and to file
1651
+ if sharpness_log_str:
1652
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f} | {sharpness_log_str}")
1653
+ else:
1654
+ print0(f"step {step}/{args.num_iterations} | val loss {val_loss:.6f}")
1655
+
1656
+ if master_process and logfile is not None:
1657
+ with open(logfile, "a") as f:
1658
+ f.write("step:%d validation loss:%f" % (step, val_loss))
1659
+ if sharpness_log_str:
1660
+ f.write(" %s" % sharpness_log_str)
1661
+ f.write("\n")
1662
+
1663
+ # once in a while perform model inference on the master process
1664
+ if (args.sample_every > 0 \
1665
+ and (step % args.sample_every == 0 or last_step)) \
1666
+ and master_process:
1667
+ model.eval()
1668
+ # before we end, let's also do one round of inference
1669
+ # we'll kick off the generation with "<|endoftext|>", which designates the start of a new sequence
1670
+ start_ids = [enc.eot_token]
1671
+ xg = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
1672
+ max_new_tokens = 32
1673
+ temperature = 1.0
1674
+ top_k = 40
1675
+ yg = raw_model.generate(xg, max_new_tokens, temperature=temperature, top_k=top_k)
1676
+ print0('---------------')
1677
+ print0(enc.decode(yg[0].tolist()))
1678
+ print0('---------------')
1679
+
1680
+ # bit confusing: we want to make sure to eval and sample on 0th iteration
1681
+ # but also after the very last iteration. so we loop for step <= num_iterations
1682
+ # instead of just < num_iterations (one extra due to <=), only to do
1683
+ # the validation/sampling one last time, and then we break right here as we're done.
1684
+ if last_step:
1685
+ break
1686
+
1687
+ # --------------- TRAINING SECTION BEGIN -----------------
1688
+ model.train()
1689
+ # Zero gradients for the appropriate optimizer(s)
1690
+
1691
+ for optimizer in optimizers:
1692
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1693
+ optimizer.zero_grad(set_to_none=True)
1694
+ elif isinstance(optimizer, Muon):
1695
+ optimizer.zero_grad()
1696
+ # if args.optimizer == "adam":
1697
+ # optimizer.zero_grad(set_to_none=True)
1698
+ # else: # muon
1699
+ # if muon_optimizer is not None:
1700
+ # muon_optimizer.zero_grad()
1701
+ # if adam_optimizer is not None:
1702
+ # adam_optimizer.zero_grad(set_to_none=True)
1703
+ # if we are trying to overfit a single batch, we reset the loader here
1704
+ if args.overfit_single_batch:
1705
+ train_loader.reset()
1706
+ # micro-batch loop where we do gradient accumulation to reach desired total batch size
1707
+ lossf = 0.0 # for getting the mean loss (as simple float) over the accumulation steps
1708
+
1709
+ # Pre-check if we need to collect microbatches for sharpness analysis
1710
+ next_step = step + 1
1711
+ will_analyze_sharpness_next = args.analyze_sharpness and next_step > 0 and (
1712
+ (next_step % args.sharpness_analysis_interval == 0) or
1713
+ (next_step == args.num_iterations)
1714
+ )
1715
+
1716
+
1717
+ microbatches_this_step = [] if will_analyze_sharpness_next else None
1718
+
1719
+ for micro_step in range(grad_accum_steps):
1720
+ # fetch a batch
1721
+ x, y = train_loader.next_batch()
1722
+ x, y = x.to(device), y.to(device)
1723
+
1724
+ # Store ALL microbatches for memory-efficient HVP calculation
1725
+ if will_analyze_sharpness_next:
1726
+ microbatches_this_step.append((x.detach().clone(), y.detach().clone()))
1727
+
1728
+ if ddp:
1729
+ model.require_backward_grad_sync = (micro_step == grad_accum_steps - 1)
1730
+ # forward pass
1731
+ with ctx:
1732
+ _, loss = model(x, y, return_logits=False)
1733
+ loss = loss / grad_accum_steps
1734
+ lossf += loss.detach() # keep track of the mean loss
1735
+ # backward pass
1736
+ if not args.inference_only:
1737
+ loss.backward()
1738
+ if ddp:
1739
+ dist.all_reduce(lossf, op=dist.ReduceOp.AVG)
1740
+ lossf = lossf.item()
1741
+
1742
+ #no clipping
1743
+ norm = torch.nn.utils.clip_grad_norm_(raw_model_uncompiled.parameters(), args.grad_clip)
1744
+
1745
+
1746
+ if will_analyze_sharpness_next:
1747
+ # Use raw_model_uncompiled's parameter order so it matches sharpness analysis codepaths.
1748
+ # (DDP/torch.compile wrappers can be a footgun if parameter iteration order ever diverges.)
1749
+ print(raw_model_uncompiled.transformer.h[0].attn.q_w.weight[:5,:5])
1750
+ params_before_optimizer_step = [p.detach().clone() for p in raw_model_uncompiled.parameters()]
1751
+ # Save the original gradient g_t that will produce the update v
1752
+ last_training_gradient = [
1753
+ p.grad.detach().clone() if p.grad is not None else torch.zeros_like(p)
1754
+ for p in raw_model_uncompiled.parameters()
1755
+ ]
1756
+ # Capture ALL microbatches for consistent HVP calculation
1757
+ # This ensures H is computed on the exact same objective as g_t and v
1758
+ last_training_batches = microbatches_this_step # Already cloned above
1759
+ else:
1760
+ params_before_optimizer_step = None
1761
+ last_training_batches = None
1762
+
1763
+ # Update learning rate and step optimizers
1764
+ for optimizer in optimizers:
1765
+ if isinstance(optimizer, ZeroRedundancyOptimizer) or isinstance(optimizer, torch.optim.AdamW):
1766
+ adam_lr = get_wsd_lr(step,args.adam_lr)
1767
+ for param_group in optimizer.param_groups:
1768
+ param_group['lr'] = adam_lr
1769
+ optimizer.step()
1770
+ elif isinstance(optimizer, Muon):
1771
+ muon_lr = get_wsd_lr(step,args.muon_lr)
1772
+ for param_group in optimizer.param_groups:
1773
+ param_group['lr'] = muon_lr
1774
+ optimizer.step()
1775
+ else:
1776
+ raise ValueError(f"Unsupported optimizer: {type(optimizer)}")
1777
+
1778
+
1779
+ if params_before_optimizer_step is not None:
1780
+ # Clean up old update to save memory
1781
+ if last_training_update is not None:
1782
+ del last_training_update
1783
+
1784
+ last_training_update = [
1785
+ p.detach() - p_before
1786
+ for p_before, p in zip(params_before_optimizer_step, raw_model_uncompiled.parameters())
1787
+ ]
1788
+ del params_before_optimizer_step
1789
+
1790
+ # --------------- TRAINING SECTION END -------------------
1791
+
1792
+ # wait on the CPU for all device work to end so we get accurate per-iteration timings below
1793
+ if device == "mps":
1794
+ torch.mps.synchronize()
1795
+ elif device == "cuda":
1796
+ torch.cuda.synchronize()
1797
+ # time and print
1798
+ t1 = time.time()
1799
+ # the 0th iteration is often an outlier (much slower) => skip logging it
1800
+ tokens_per_second = grad_accum_steps * ddp_world_size * B * T / (t1-t0)
1801
+ print0(f"step {step+1:4d}/{args.num_iterations} | train loss {lossf:.6f} | norm {norm:.4f} | ({(t1-t0)*1000:.2f} ms | {tokens_per_second:.0f} tok/s)")
1802
+ # log to logile
1803
+ if master_process and logfile is not None:
1804
+ with open(logfile, "a") as f:
1805
+ f.write("step:%d train loss:%f\n" % (step, lossf))
1806
+
1807
+ # keep track of smooth timings, last 20 iterations
1808
+ if step > 0 and step > args.num_iterations - 20:
1809
+ timings.append(t1-t0)
1810
+
1811
+ # print the average of the last 20 timings, to get something smooth-ish
1812
+ timings = timings[-20:]
1813
+ print0(f"final {len(timings)} iters avg: {np.mean(timings)*1000:.3f}ms")
1814
+ print0(f"peak memory consumption: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB")
1815
+
1816
+ # -------------------------------------------------------------------------
1817
+ # clean up nice
1818
+ if ddp:
1819
+ destroy_process_group()step:0 validation loss:11.020914
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_42/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.02,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 42,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "79e4918e-522c-4139-af5b-d80a5252170a",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_42/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_43/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.02,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 43,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "72adc14c-d1ef-4cb4-893e-7d9a24a84f90",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_43/training_log.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_44/config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
4
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
5
+ "output_dir": "/home/aiops/zhangfz/MUON_sharpness/logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm",
6
+ "model": "d12",
7
+ "batch_size": 4,
8
+ "sequence_length": 1024,
9
+ "total_batch_size": 524288,
10
+ "num_iterations": 10000,
11
+ "inference_only": 0,
12
+ "adam_lr": 0.02,
13
+ "warmup_iters": 1500,
14
+ "lr_decay_frac": 0.0,
15
+ "weight_decay": 0.0,
16
+ "grad_clip": 100000.0,
17
+ "val_loss_every": 250,
18
+ "val_max_steps": 20,
19
+ "sample_every": 0,
20
+ "overfit_single_batch": 0,
21
+ "shuffle_files": true,
22
+ "tensorcores": 1,
23
+ "device": "",
24
+ "compile": 1,
25
+ "flash": 1,
26
+ "dtype": "bfloat16",
27
+ "zero_stage": 1,
28
+ "optimizer": "adam",
29
+ "muon_lr": 0.01,
30
+ "muon_momentum": 0.95,
31
+ "muon_weight_decay": 0.0,
32
+ "muon_ns_steps": 5,
33
+ "muon_nesterov": false,
34
+ "write_tensors": 0,
35
+ "seed": 44,
36
+ "analyze_sharpness": false,
37
+ "sharpness_analysis_interval": 500
38
+ },
39
+ "run_uuid": "2b74613f-a927-4188-a403-f44fd7612f1e",
40
+ "script_code_logged_at_start": true
41
+ }
logs_sharpness_pure_qk_nonorm_no_clip_small_bsz/adam_lr_search_longwarm/opt_adam_alr_0.02_mlr_0.01_seed_44/training_log.txt ADDED
The diff for this file is too large to render. See raw diff