zhangfz commited on
Commit
de44cb9
·
1 Parent(s): 58ceb06
Files changed (14) hide show
  1. logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json +1 -1
  2. logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_01057053-d2d8-460a-ab4b-8f0dcb45709c.txt +0 -0
  3. logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/config.json +27 -0
  4. logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/training_log_039021ab-4477-44e2-9121-ce92354d757a.txt +0 -0
  5. logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json +27 -0
  6. logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_62c86858-e544-45fa-8e10-20927225390f.txt +0 -0
  7. logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/config.json +27 -0
  8. logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/training_log_9ebd0b66-cbf1-499b-a4e8-6a3e8c6248a9.txt +0 -0
  9. logs_new_MUON_large_reshape_svd_gated/svd/mode_0_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json +27 -0
  10. logs_new_MUON_large_reshape_svd_gated/svd/mode_0_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_533563b5-4895-416e-8ea4-9baaf8e74134.txt +856 -0
  11. logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json +27 -0
  12. logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_c51a87f3-6af4-417a-86fa-83dd74e4e135.txt +0 -0
  13. logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/config.json +27 -0
  14. logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/training_log_ba9ae92f-719c-4f06-8489-a3fe9a80096d.txt +856 -0
logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json CHANGED
@@ -22,6 +22,6 @@
22
  "val_tokens": 10420224,
23
  "save_every": 0
24
  },
25
- "run_uuid_for_log": "de92121d-9f3a-4470-a944-fb1adf4c28d0",
26
  "script_code_logged_at_start": true
27
  }
 
22
  "val_tokens": 10420224,
23
  "save_every": 0
24
  },
25
+ "run_uuid_for_log": "01057053-d2d8-460a-ab4b-8f0dcb45709c",
26
  "script_code_logged_at_start": true
27
  }
logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_01057053-d2d8-460a-ab4b-8f0dcb45709c.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "seed": 43,
4
+ "optimizer_mode": 7,
5
+ "model_parameterization": "gated",
6
+ "adam_lr": 0.0002,
7
+ "muon_lr": 0.0005,
8
+ "base_dir": "logs_new_MUON_large_reshape_svd_gated/ori"
9
+ },
10
+ "hyperparameters": {
11
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
12
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
13
+ "batch_size": 960,
14
+ "device_batch_size": 24,
15
+ "sequence_length": 1024,
16
+ "num_iterations": 6000,
17
+ "learning_rate": 0.0018,
18
+ "warmup_iters": 0,
19
+ "warmdown_iters": 0,
20
+ "weight_decay": 0,
21
+ "val_loss_every": 125,
22
+ "val_tokens": 10420224,
23
+ "save_every": 0
24
+ },
25
+ "run_uuid_for_log": "039021ab-4477-44e2-9121-ce92354d757a",
26
+ "script_code_logged_at_start": true
27
+ }
logs_new_MUON_large_reshape_svd_gated/ori/mode_7_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/training_log_039021ab-4477-44e2-9121-ce92354d757a.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "seed": 42,
4
+ "optimizer_mode": 9,
5
+ "model_parameterization": "gated",
6
+ "adam_lr": 0.0002,
7
+ "muon_lr": 0.0005,
8
+ "base_dir": "logs_new_MUON_large_reshape_svd_gated/ori"
9
+ },
10
+ "hyperparameters": {
11
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
12
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
13
+ "batch_size": 960,
14
+ "device_batch_size": 24,
15
+ "sequence_length": 1024,
16
+ "num_iterations": 6000,
17
+ "learning_rate": 0.0018,
18
+ "warmup_iters": 0,
19
+ "warmdown_iters": 0,
20
+ "weight_decay": 0,
21
+ "val_loss_every": 125,
22
+ "val_tokens": 10420224,
23
+ "save_every": 0
24
+ },
25
+ "run_uuid_for_log": "62c86858-e544-45fa-8e10-20927225390f",
26
+ "script_code_logged_at_start": true
27
+ }
logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_62c86858-e544-45fa-8e10-20927225390f.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "seed": 43,
4
+ "optimizer_mode": 9,
5
+ "model_parameterization": "gated",
6
+ "adam_lr": 0.0002,
7
+ "muon_lr": 0.0005,
8
+ "base_dir": "logs_new_MUON_large_reshape_svd_gated/ori"
9
+ },
10
+ "hyperparameters": {
11
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
12
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
13
+ "batch_size": 960,
14
+ "device_batch_size": 24,
15
+ "sequence_length": 1024,
16
+ "num_iterations": 6000,
17
+ "learning_rate": 0.0018,
18
+ "warmup_iters": 0,
19
+ "warmdown_iters": 0,
20
+ "weight_decay": 0,
21
+ "val_loss_every": 125,
22
+ "val_tokens": 10420224,
23
+ "save_every": 0
24
+ },
25
+ "run_uuid_for_log": "9ebd0b66-cbf1-499b-a4e8-6a3e8c6248a9",
26
+ "script_code_logged_at_start": true
27
+ }
logs_new_MUON_large_reshape_svd_gated/ori/mode_9_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/training_log_9ebd0b66-cbf1-499b-a4e8-6a3e8c6248a9.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_new_MUON_large_reshape_svd_gated/svd/mode_0_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "seed": 42,
4
+ "optimizer_mode": 0,
5
+ "model_parameterization": "gated",
6
+ "adam_lr": 0.0002,
7
+ "muon_lr": 0.0005,
8
+ "base_dir": "logs_new_MUON_large_reshape_svd_gated/svd"
9
+ },
10
+ "hyperparameters": {
11
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
12
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
13
+ "batch_size": 960,
14
+ "device_batch_size": 24,
15
+ "sequence_length": 1024,
16
+ "num_iterations": 6000,
17
+ "learning_rate": 0.0018,
18
+ "warmup_iters": 0,
19
+ "warmdown_iters": 0,
20
+ "weight_decay": 0,
21
+ "val_loss_every": 125,
22
+ "val_tokens": 10420224,
23
+ "save_every": 0
24
+ },
25
+ "run_uuid_for_log": "533563b5-4895-416e-8ea4-9baaf8e74134",
26
+ "script_code_logged_at_start": true
27
+ }
logs_new_MUON_large_reshape_svd_gated/svd/mode_0_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_533563b5-4895-416e-8ea4-9baaf8e74134.txt ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os
3
+ import sys
4
+ with open(sys.argv[0]) as f:
5
+ code = f.read() # read the code of this file ASAP, for logging
6
+ import uuid
7
+ import time
8
+ import copy
9
+ import glob
10
+ from dataclasses import dataclass, asdict
11
+ from functools import lru_cache
12
+ from pathlib import Path
13
+ import argparse # Keep argparse for --unet and potentially --optimizer_mode
14
+ import json
15
+ import random
16
+ import numpy as np
17
+
18
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
19
+ import torch
20
+ torch.empty(1, device="cuda", requires_grad=True).backward() # prevents a bug on some systems
21
+ from torch import Tensor, nn
22
+ import torch.nn.functional as F
23
+ import torch.distributed as dist
24
+ # use of FlexAttention contributed by @KoszarskyB
25
+ from torch.nn.attention.flex_attention import BlockMask, flex_attention
26
+ sys.path.append("/home/aiops/zhangfz/MUON_theory/modded-nanogpt") # Already present
27
+ from optimizers.MUON_new_large_nes import Muon
28
+ from utils.float_compute import mm_op, backward as mm_backward_custom, setup_context as mm_setup_context_custom # Renamed
29
+ import torch._inductor.config as config
30
+ from torch.nn.parallel import DistributedDataParallel as DDP
31
+ from kn_util.utils import setup_debugpy
32
+
33
+
34
+ # -----------------------------------------------------------------------------
35
+ # Seeding Function
36
+ def set_seed(seed):
37
+ random.seed(seed)
38
+ np.random.seed(seed)
39
+ torch.manual_seed(seed)
40
+ if torch.cuda.is_available():
41
+ torch.cuda.manual_seed_all(seed)
42
+ print(f"PRINT: Set seed to {seed}", flush=True) # Print immediately for all ranks
43
+
44
+
45
+ # ---- ADD: spectral metrics helper ----
46
+ def calculate_svd_metrics(matrix: torch.Tensor, *, topk: int = 10):
47
+ """
48
+ Returns dict with:
49
+ - entropy_norm: normalized SVD entropy
50
+ - erank: effective rank = exp(Shannon entropy of p)
51
+ - topk_energy: sum of top-k p_i (energy fraction in the top-k singular values)
52
+ - q75_q25: ratio of 75th to 25th percentile of eigenvalues (sigma^2)
53
+ """
54
+ with torch.no_grad():
55
+ s = torch.linalg.svdvals(matrix.detach().to('cpu', torch.float32))
56
+ s = s[s > 1e-9]
57
+ n = s.numel()
58
+ if n == 0:
59
+ return dict(entropy_norm=0.0, erank=0.0, topk_energy=0.0, q75_q25=float('inf'))
60
+
61
+ s2 = s * s
62
+ S2_sum = float(torch.sum(s2))
63
+ if S2_sum == 0.0:
64
+ return dict(entropy_norm=0.0, erank=0.0, topk_energy=0.0, q75_q25=float('inf'))
65
+
66
+ p = s2 / S2_sum # energy distribution
67
+ # Shannon entropy H (natural log)
68
+ H = float(torch.sum(torch.special.entr(p)))
69
+ entropy_norm = H / np.log(max(n, 2))
70
+ erank = float(np.exp(H))
71
+
72
+ k = min(topk, n)
73
+ topk_energy = float(torch.topk(p, k).values.sum())
74
+
75
+ # eigenvalues = s^2, use quantiles on s^2
76
+ q25 = float(torch.quantile(s2, 0.25))
77
+ q75 = float(torch.quantile(s2, 0.75))
78
+ q75_q25 = (q75 / q25) if q25 > 0 else float('inf')
79
+
80
+ return dict(
81
+ entropy_norm=entropy_norm,
82
+ erank=erank,
83
+ topk_energy=topk_energy,
84
+ q75_q25=q75_q25,
85
+ )
86
+
87
+
88
+ # -----------------------------------------------------------------------------
89
+ # Our own simple Distributed Data Loader
90
+
91
+ def _peek_data_shard(filename):
92
+ # only reads the header, returns header data
93
+ with open(filename, "rb") as f:
94
+ # first read the header, which is 256 int32 integers (4 bytes each)
95
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
96
+ if header[0] != 20240520:
97
+ print("ERROR: magic number mismatch in the data .bin file!")
98
+ print("---> HINT: Are you passing in a correct file with --input_bin?")
99
+ print("---> HINT: Dataset encoding changed recently, re-run data prepro or refer again to README")
100
+ print("---> HINT: For example re-run: `python dev/data/tinyshakespeare.py`, then re-try")
101
+ exit(1)
102
+ assert header[1] == 1, "unsupported version"
103
+ ntok = header[2] # number of tokens (claimed)
104
+ return ntok # for now just return the number of tokens
105
+
106
+ def _load_data_shard(filename):
107
+ with open(filename, "rb") as f:
108
+ # first read the header, which is 256 int32 integers (4 bytes each)
109
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
110
+ assert header[0] == 20240520, "magic number mismatch in the data .bin file"
111
+ assert header[1] == 1, "unsupported version"
112
+ ntok = header[2] # number of tokens (claimed)
113
+ # the rest of it are tokens, stored as uint16
114
+ tokens = np.frombuffer(f.read(), dtype=np.uint16)
115
+ assert len(tokens) == ntok, "number of tokens read does not match header?"
116
+ return tokens
117
+
118
+ class DistributedDataLoader:
119
+ def __init__(self, filename_pattern, B, T, process_rank, num_processes):
120
+ self.process_rank = process_rank
121
+ self.num_processes = num_processes
122
+ self.B = B
123
+ self.T = T
124
+
125
+ # glob files that match the pattern
126
+ self.files = sorted(glob.glob(filename_pattern))
127
+ assert len(self.files) > 0, f"did not find any files that match the pattern {filename_pattern}"
128
+
129
+ # load and validate all data shards, count number of tokens in total
130
+ ntok_total = 0
131
+ for fname in self.files:
132
+ shard_ntok = _peek_data_shard(fname)
133
+ assert shard_ntok >= num_processes * B * T + 1
134
+ ntok_total += int(shard_ntok)
135
+ self.ntok_total = ntok_total
136
+
137
+ # kick things off
138
+ self.reset()
139
+
140
+ def reset(self):
141
+ self.current_shard = 0
142
+ self.current_position = self.process_rank * self.B * self.T
143
+ self.tokens = _load_data_shard(self.files[self.current_shard])
144
+
145
+ def advance(self): # advance to next data shard
146
+ self.current_shard = (self.current_shard + 1) % len(self.files)
147
+ self.current_position = self.process_rank * self.B * self.T
148
+ self.tokens = _load_data_shard(self.files[self.current_shard])
149
+
150
+ def next_batch(self):
151
+ B = self.B
152
+ T = self.T
153
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
154
+ buf = torch.tensor(buf.astype(np.int32), dtype=torch.long)
155
+ x = (buf[:-1]).view(B, T) # inputs
156
+ y = (buf[1:]).view(B, T) # targets
157
+ # advance current position and load next shard if necessary
158
+ self.current_position += B * T * self.num_processes
159
+ if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
160
+ self.advance()
161
+ return x.cuda(), y.cuda()
162
+
163
+ # -----------------------------------------------------------------------------
164
+ # int main
165
+
166
+ @dataclass
167
+ class Hyperparameters:
168
+ # data hyperparams
169
+ input_bin : str = "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin"
170
+ input_val_bin : str = "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin"
171
+ # optimization hyperparams
172
+ batch_size : int = 8*120 # 8*120 # batch size, in sequences, across all devices
173
+ device_batch_size : int = 24 # batch size, in sequences, per device
174
+ sequence_length : int = 1024 # sequence length, in tokens
175
+ num_iterations : int = 6000 # number of iterations to run
176
+ learning_rate : float = 0.0036 / 2
177
+ warmup_iters : int = 0
178
+ warmdown_iters : int = 0 # number of iterations of linear warmup/warmdown for triangular or trapezoidal schedule
179
+ weight_decay : float = 0
180
+ # evaluation and logging hyperparams
181
+ val_loss_every : int = 125 # every how many steps to evaluate val loss? 0 for only at the end
182
+ val_tokens : int = 10420224 # how many tokens of validation data? it's important to keep this fixed for consistent comparisons
183
+ save_every : int = 0 # every how many steps to save the checkpoint? 0 for only at the end
184
+ args = Hyperparameters()
185
+
186
+
187
+
188
+ # -----------------------------------------------------------------------------
189
+ # int main
190
+ # setup_debugpy(force=True)
191
+ parser = argparse.ArgumentParser(description="NanoGPT Training Script with Muon")
192
+ parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility")
193
+ # --- MODIFICATION: Add optimizer_mode as a CLI argument ---
194
+ parser.add_argument("--optimizer_mode", type=int, default=0,
195
+ help="Defines how Muon is applied. "
196
+ "0: Muon(All Hidden Attn+MLP - original); "
197
+ "1: Muon(QK Attn)/Adam(VO Attn,MLP); "
198
+ "2: Muon(VO Attn)/Adam(QK Attn,MLP); "
199
+ "3: Muon(All Attn)/Adam(MLP); "
200
+ "4: Muon(MLP)/Adam(All Attn)"
201
+ "5: All Adam (No Muon, all applicable matrices to Adam)."
202
+ "6: Muon(W_2 MLP)/Adam(attn, W_1 MLP)."
203
+ "7: Muon(VO Attn, MLP)/Adam(QK Attn)."
204
+ "8: Muon(VO Attn, W_2 MLP)/Adam(QK Attn, W_1 MLP)."
205
+ )
206
+ parser.add_argument("--model_parameterization", type=str, default="whole",choices=["whole","qkvo", "norope", "gated"])
207
+ parser.add_argument("--adam_lr", type=float, default=0.008, help="Learning rate for Adam matrices")
208
+ parser.add_argument("--muon_lr", type=float, default=0.05, help="Learning rate for Muon matrices")
209
+ parser.add_argument("--base_dir", type=str, default="logs_new_MUON_large/test", help="Base directory for logs")
210
+ exp_args = parser.parse_args()
211
+ set_seed(exp_args.seed)
212
+
213
+
214
+
215
+ # set up DDP (distributed data parallel). torchrun sets this env variable
216
+ assert torch.cuda.is_available()
217
+ dist.init_process_group(backend='nccl')
218
+ ddp_rank = int(os.environ['RANK'])
219
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
220
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
221
+ device = f'cuda:{ddp_local_rank}'
222
+ torch.cuda.set_device(device)
223
+ print(f"using device: {device}")
224
+ master_process = (ddp_rank == 0) # this process will do logging, checkpointing etc.
225
+
226
+ logfile = None
227
+ run_dir_path_str = None
228
+ base_log_dir = Path(exp_args.base_dir)
229
+
230
+
231
+ if master_process:
232
+ import subprocess
233
+ set_seed(exp_args.seed)
234
+
235
+ # Construct folder name based on config and seed
236
+ # run_folder_name = f"mode_{exp_args.optimizer_mode}_param_{exp_args.model_parameterization}_adam_lr_{exp_args.adam_lr}_seed_{exp_args.seed}"
237
+ run_folder_name = f"mode_{exp_args.optimizer_mode}_param_{exp_args.model_parameterization}_muon_lr_{exp_args.muon_lr}_adam_lr_{exp_args.adam_lr}_seed_{exp_args.seed}"
238
+ run_dir_path = base_log_dir / run_folder_name
239
+ run_dir_path.mkdir(parents=True, exist_ok=True)
240
+ run_dir_path_str = str(run_dir_path)
241
+
242
+ run_uuid = uuid.uuid4()
243
+ logfile = run_dir_path / f"training_log_{run_uuid}.txt"
244
+ print(f"Logging to: {logfile}")
245
+
246
+ # Save configuration
247
+ config_to_save = {
248
+ "cli_args": vars(exp_args),
249
+ "hyperparameters": {k: v for k, v in args.__class__.__dict__.items() if not k.startswith('__') and not callable(v)},
250
+ "run_uuid_for_log": str(run_uuid),
251
+ "script_code_logged_at_start": True
252
+ }
253
+ config_file_path = run_dir_path / "config.json"
254
+ with open(config_file_path, "w") as f:
255
+ json.dump(config_to_save, f, indent=4)
256
+ print(f"Saved configuration to: {config_file_path}")
257
+
258
+ # convenience variables
259
+ B, T = args.device_batch_size, args.sequence_length
260
+ # calculate the number of steps to take in the val loop.
261
+ print(f"args.val_tokens: {args.val_tokens}, args.batch_size: {args.batch_size}, B: {B}, T: {T}, ddp_world_size: {ddp_world_size}")
262
+ assert args.val_tokens % (B * T * ddp_world_size) == 0
263
+ val_steps = args.val_tokens // (B * T * ddp_world_size)
264
+ # calculate the steps of gradient accumulation required to attain the desired global batch size.
265
+ assert args.batch_size % (B * ddp_world_size) == 0
266
+ train_accumulation_steps = args.batch_size // (B * ddp_world_size)
267
+
268
+ # load tokens
269
+ train_loader = DistributedDataLoader(args.input_bin, B, T, ddp_rank, ddp_world_size)
270
+ val_loader = DistributedDataLoader(args.input_val_bin, B, T, ddp_rank, ddp_world_size)
271
+ if master_process:
272
+ print(f"Training DataLoader: total number of tokens: {train_loader.ntok_total} across {len(train_loader.files)} files")
273
+ print(f"Validation DataLoader: total number of tokens: {val_loader.ntok_total} across {len(val_loader.files)} files")
274
+ x, y = train_loader.next_batch()
275
+
276
+ # there are only 50257 unique GPT-2 tokens; we extend to nearest multiple of 128 for efficiency. suggested to me by @Grad62304977.
277
+ # this originates from Karpathy's experiments.
278
+ num_vocab = 50304
279
+
280
+
281
+
282
+ if exp_args.model_parameterization == "qkvo":
283
+ from models.nano_GPT_qkvo_large import GPT, GPTConfig
284
+ # model = GPT(GPTConfig(vocab_size=num_vocab, n_layer=25, n_head=12, n_embd=1536))
285
+ model = GPT(GPTConfig(vocab_size=num_vocab, n_layer=36, n_head=20, n_embd=1280))
286
+ elif exp_args.model_parameterization == "gated":
287
+ from models.nano_GPT_gated_large import GPT, GPTConfig
288
+ model = GPT(GPTConfig(vocab_size=num_vocab, n_layer=27, n_head=20, n_embd=1280))
289
+
290
+ if master_process:
291
+ print(sum(p.numel() for p in model.parameters()))
292
+ model = model.cuda()
293
+ if hasattr(config, "coordinate_descent_tuning"):
294
+ config.coordinate_descent_tuning = True # suggested by @Chillee
295
+ model = torch.compile(model)
296
+ # here we wrap model into DDP container
297
+ model = DDP(model, device_ids=[ddp_local_rank])
298
+ raw_model = model.module # always contains the "raw" unwrapped model
299
+ ctx = torch.amp.autocast(device_type='cuda', dtype=torch.bfloat16)
300
+
301
+ # for name, param in raw_model.named_parameters():
302
+ # print(name, param.shape)
303
+
304
+ if exp_args.model_parameterization == "qkvo" :
305
+ print("PRINT: Collecting parameters for optimizers...")
306
+ head_params = [raw_model.lm_head.weight]
307
+ # embed_params = [raw_model.transformer.wte.weight]
308
+
309
+ # Granular collection for attention and MLP parts
310
+ attn_q_params = []
311
+ attn_k_params = []
312
+ attn_v_params = []
313
+ attn_o_params = [] # W_O from c_proj
314
+ mlp_fc_params = []
315
+ mlp_proj_params = []
316
+
317
+ for block_module in raw_model.transformer.h:
318
+ if block_module.attn is not None:
319
+ # These attributes (c_q, c_k, c_v) MUST exist in your CausalSelfAttention class
320
+ if hasattr(block_module.attn, 'c_q'): attn_q_params.append(block_module.attn.c_q.weight)
321
+ else:
322
+ print(f"PRINT: Warning: c_q not found in attn module of a block.")
323
+ if hasattr(block_module.attn, 'c_k'): attn_k_params.append(block_module.attn.c_k.weight)
324
+ else: print(f"PRINT: Warning: c_k not found in attn module of a block.")
325
+ if hasattr(block_module.attn, 'c_v'): attn_v_params.append(block_module.attn.c_v.weight)
326
+ else: print(f"PRINT: Warning: c_v not found in attn module of a block.")
327
+ attn_o_params.append(block_module.attn.c_proj.weight)
328
+ if block_module.mlp is not None:
329
+ mlp_fc_params.append(block_module.mlp.c_fc.weight)
330
+ mlp_proj_params.append(block_module.mlp.c_proj.weight)
331
+
332
+ # Combine into logical groups for experiments
333
+ attn_qk_group = attn_q_params + attn_k_params
334
+ attn_vo_group = attn_v_params + attn_o_params
335
+ all_attn_matrices = attn_qk_group + attn_vo_group
336
+ mlp_w1_group = mlp_fc_params
337
+ mlp_w2_group = mlp_proj_params
338
+ all_mlp_matrices = mlp_fc_params + mlp_proj_params
339
+
340
+ # Scalar parameters (all others not explicitly grouped as matrices)
341
+ # matrix_params_for_scalar_check = set(head_params + embed_params + all_attn_matrices + all_mlp_matrices)
342
+ matrix_params_for_scalar_check = set(head_params + all_attn_matrices + all_mlp_matrices)
343
+ scalar_params = [p for n, p in raw_model.named_parameters() if p not in matrix_params_for_scalar_check]
344
+ for p_scalar in scalar_params: # Sanity check
345
+ if p_scalar.ndim >=2:
346
+ print(f"PRINT: Warning - Parameter {p_scalar.shape} ended up in scalar_params but has ndim >= 2. Check grouping.")
347
+
348
+
349
+ # Determine parameter distribution based on optimizer_mode
350
+ muon_params_target_list = []
351
+ adam_matrix_target_list = [] # Matrices that Adam will handle specifically
352
+ adam_matrix_lr = exp_args.adam_lr # LR for matrices if Adam handles them (can be tuned)
353
+
354
+ current_optimizer_mode = exp_args.optimizer_mode
355
+
356
+ print(f"PRINT: Configuring optimizers for EXPERIMENT_MODE = {current_optimizer_mode}")
357
+
358
+ if current_optimizer_mode == 0: # Original behavior: Muon on all "hidden_matrix_params"
359
+ print(f"PRINT: Mode 0: Muon on ALL Attention (QKVO) and ALL MLP matrices.")
360
+ muon_params_target_list = all_attn_matrices + all_mlp_matrices
361
+ # Adam handles embeds, head, scalars by default. No extra matrices for Adam here.
362
+ elif current_optimizer_mode == 1: # Muon on QK, Adam on VO and MLP
363
+ print(f"PRINT: Mode 1: Muon on QK Attn. Adam on VO Attn, MLP (Adam LR: {adam_matrix_lr}).")
364
+ muon_params_target_list = attn_qk_group
365
+ adam_matrix_target_list = attn_vo_group + all_mlp_matrices
366
+ elif current_optimizer_mode == 2: # Muon on VO, Adam on QK and MLP
367
+ print(f"PRINT: Mode 2: Muon on VO Attn. Adam on QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
368
+ muon_params_target_list = attn_vo_group
369
+ adam_matrix_target_list = attn_qk_group + all_mlp_matrices
370
+ elif current_optimizer_mode == 3: # Muon on All Attn (QKVO), Adam on MLP
371
+ print(f"PRINT: Mode 3: Muon on ALL Attn (QKVO). Adam on MLP (Adam LR: {adam_matrix_lr}).")
372
+ muon_params_target_list = all_attn_matrices
373
+ adam_matrix_target_list = all_mlp_matrices
374
+ elif current_optimizer_mode == 4: # Muon on MLP, Adam on All Attn (QKVO)
375
+ print(f"PRINT: Mode 4: Muon on MLP. Adam on ALL Attn (QKVO) (Adam LR: {adam_matrix_lr}).")
376
+ muon_params_target_list = all_mlp_matrices
377
+ adam_matrix_target_list = all_attn_matrices
378
+ elif current_optimizer_mode == 5: # NEW MODE 5 - All Adam
379
+ print(f"PRINT: Mode 5: All Adam. All Attn and MLP matrices to Adam (Adam LR: {adam_matrix_lr}).")
380
+ muon_params_target_list = []
381
+ adam_matrix_target_list = all_attn_matrices + all_mlp_matrices # All matrices to Adam
382
+ elif current_optimizer_mode == 6: # Muon on W_2 MLP, Adam on attn, W_1 MLP
383
+ print(f"PRINT: Mode 6: Muon on W_2 MLP. Adam on attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
384
+ muon_params_target_list = mlp_w2_group
385
+ adam_matrix_target_list = all_attn_matrices + mlp_w1_group
386
+ elif current_optimizer_mode == 7: # Muon on VO Attn, MLP, Adam on QK Attn
387
+ print(f"PRINT: Mode 7: Muon on VO Attn, MLP. Adam on QK Attn (Adam LR: {adam_matrix_lr}).")
388
+ muon_params_target_list = attn_vo_group + all_mlp_matrices
389
+ adam_matrix_target_list = attn_qk_group
390
+ elif current_optimizer_mode == 8: # Muon on VO Attn, W_2 MLP, Adam on QK Attn, W_1 MLP
391
+ print(f"PRINT: Mode 8: Muon on VO Attn, W_2 MLP. Adam on QK Attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
392
+ muon_params_target_list = attn_vo_group + mlp_w2_group
393
+ adam_matrix_target_list = attn_qk_group + mlp_w1_group
394
+ elif current_optimizer_mode == 9: # Muon on V Attn, MLP
395
+ print(f"PRINT: Mode 9: Muon on V Attn, MLP (Adam LR: {adam_matrix_lr}).")
396
+ muon_params_target_list = attn_v_params + all_mlp_matrices
397
+ adam_matrix_target_list = attn_o_params + attn_qk_group
398
+ elif current_optimizer_mode == 10: # Muon on O Attn, MLP
399
+ print(f"PRINT: Mode 10: Muon on O Attn, MLP (Adam LR: {adam_matrix_lr}).")
400
+ muon_params_target_list = attn_o_params + all_mlp_matrices
401
+ adam_matrix_target_list = attn_v_params + attn_qk_group
402
+ elif current_optimizer_mode == 11: # Muon on W_1, Adam on O Attn, QK Attn
403
+ print(f"PRINT: Mode 11: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
404
+ muon_params_target_list = mlp_w1_group
405
+ adam_matrix_target_list = all_attn_matrices + mlp_w2_group
406
+ elif current_optimizer_mode == 12: # Muon on W_1, VO, Adam on others
407
+ print(f"PRINT: Mode 12: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
408
+ muon_params_target_list = attn_vo_group + mlp_w1_group
409
+ adam_matrix_target_list = attn_qk_group + mlp_w2_group
410
+ elif current_optimizer_mode == 13:
411
+ print(f"PRINT: Mode 13: Muon on W_2, W_O. Adam on V Attn, QK Attn, W_1 (Adam LR: {adam_matrix_lr}).")
412
+ muon_params_target_list = attn_o_params + mlp_w2_group
413
+ adam_matrix_target_list = attn_qk_group + attn_v_params + mlp_w1_group
414
+ elif current_optimizer_mode == 14:
415
+ print(f"PRINT: Mode 14: Muon on W_O. Adam on V Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
416
+ muon_params_target_list = attn_o_params
417
+ adam_matrix_target_list = attn_qk_group + attn_v_params +all_mlp_matrices
418
+ elif current_optimizer_mode == 15:
419
+ print(f"PRINT: Mode 15: Muon on W_V. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
420
+ muon_params_target_list = attn_v_params
421
+ adam_matrix_target_list = attn_qk_group + attn_o_params +all_mlp_matrices
422
+ elif current_optimizer_mode == 16:
423
+ print(f"PRINT: Mode 15: Muon on QKV. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
424
+ muon_params_target_list = attn_v_params + attn_qk_group
425
+ adam_matrix_target_list = attn_o_params +all_mlp_matrices
426
+ else:
427
+ raise ValueError(f"Unsupported EXPERIMENT_MODE: {current_optimizer_mode}")
428
+
429
+ # Adam optimizer setup
430
+ adam_param_groups_config = [
431
+ dict(params=head_params, lr=adam_matrix_lr),
432
+ # dict(params=embed_params, lr=adam_matrix_lr),
433
+ dict(params=scalar_params, lr=adam_matrix_lr) # Scalar params always go to Adam
434
+ ]
435
+ # Add matrices specifically assigned to Adam for this experiment mode
436
+ if adam_matrix_target_list:
437
+ # Ensure adam_matrix_target_list is flat and contains Parameters
438
+ flat_adam_matrices = [p for sublist_or_p in adam_matrix_target_list for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]) if p is not None]
439
+ if flat_adam_matrices: # Only add group if there are params
440
+ adam_param_groups_config.append(dict(params=flat_adam_matrices, lr=adam_matrix_lr))
441
+
442
+ # Filter out any Adam groups that might be empty (e.g., if scalar_params was empty)
443
+ adam_param_groups_config = [g for g in adam_param_groups_config if g['params']]
444
+ optimizer1 = torch.optim.Adam(adam_param_groups_config, betas=(0.9, 0.95), eps=1e-10, fused=True)
445
+ optimizers = [optimizer1] # Start with Adam
446
+
447
+ # Muon optimizer setup
448
+ # if muon_params_target_list:
449
+ # # Ensure muon_params_target_list is flat, unique, and contains Parameters
450
+ # flat_unique_muon_params = []
451
+ # seen_muon_ids = set()
452
+ # for sublist_or_p in muon_params_target_list:
453
+ # for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]):
454
+ # if p is not None and id(p) not in seen_muon_ids:
455
+ # flat_unique_muon_params.append(p)
456
+ # seen_muon_ids.add(id(p))
457
+
458
+ # muon_param_groups_config = []
459
+ # if flat_unique_muon_params:
460
+ # muon_param_groups_config.append(dict(params=flat_unique_muon_params, lr=exp_args.muon_lr))
461
+
462
+ # if flat_unique_muon_params: # Only create Muon if it has parameters
463
+ # optimizer2 = Muon(muon_param_groups_config, lr=exp_args.muon_lr, momentum=0.95,rank=ddp_rank, world_size=ddp_world_size) # Pass nesterov, ns_steps
464
+ # optimizers.append(optimizer2)
465
+ # else:
466
+ # print("PRINT: Muon optimizer not created as its target parameter list was empty.")
467
+ # optimizer2 = None # Explicitly set to None if not created
468
+ # else:
469
+ # print("PRINT: Muon optimizer not created as muon_params_target_list was empty (e.g. mode where Adam handles all matrices).")
470
+ # optimizer2 = None # Explicitly set to None
471
+ # Muon optimizer setup
472
+ if muon_params_target_list:
473
+ # Ensure muon_params_target_list is flat, unique, and contains Parameters
474
+ flat_unique_muon_params = []
475
+ seen_muon_ids = set()
476
+ for sublist_or_p in muon_params_target_list:
477
+ for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]):
478
+ if p is not None and id(p) not in seen_muon_ids:
479
+ flat_unique_muon_params.append(p)
480
+ seen_muon_ids.add(id(p))
481
+
482
+ if flat_unique_muon_params: # Only create Muon if it has parameters
483
+ optimizer2 = Muon(flat_unique_muon_params, lr=exp_args.muon_lr, momentum=0.95,rank=ddp_rank, world_size=ddp_world_size) # Pass nesterov, ns_steps
484
+ optimizers.append(optimizer2)
485
+ else:
486
+ print("PRINT: Muon optimizer not created as its target parameter list was empty.")
487
+ optimizer2 = None # Explicitly set to None if not created
488
+ else:
489
+ print("PRINT: Muon optimizer not created as muon_params_target_list was empty (e.g. mode where Adam handles all matrices).")
490
+ optimizer2 = None # Explicitly set to None
491
+
492
+ print(f"PRINT: Optimizers configured. Total optimizers: {len(optimizers)}")
493
+ if optimizer2:
494
+ print(f"PRINT: Muon optimizer is active with {len(flat_unique_muon_params)} parameters.")
495
+
496
+ # Set up parameter groups for SVD analysis
497
+ matrix_groups_for_svd = {}
498
+ if master_process:
499
+ matrix_groups_for_svd = {
500
+ "attn_qk": attn_qk_group,
501
+ "attn_vo": attn_vo_group,
502
+ "mlp_w1": mlp_w1_group,
503
+ "mlp_w2": mlp_w2_group
504
+ }
505
+
506
+ elif exp_args.model_parameterization == "gated":
507
+ print("PRINT: Collecting parameters for optimizers...")
508
+ head_params = [raw_model.lm_head.weight]
509
+ # embed_params = [raw_model.transformer.wte.weight]
510
+
511
+ # Granular collection for attention and MLP parts
512
+ attn_q_params = []
513
+ attn_k_params = []
514
+ attn_v_params = []
515
+ attn_o_params = [] # W_O from c_proj
516
+ mlp_fc_params = []
517
+ mlp_proj_params = []
518
+ mlp_up_params = []
519
+
520
+ for block_module in raw_model.transformer.h:
521
+ if block_module.attn is not None:
522
+ # These attributes (c_q, c_k, c_v) MUST exist in your CausalSelfAttention class
523
+ if hasattr(block_module.attn, 'c_q'): attn_q_params.append(block_module.attn.c_q.weight)
524
+ else:
525
+ print(f"PRINT: Warning: c_q not found in attn module of a block.")
526
+ if hasattr(block_module.attn, 'c_k'): attn_k_params.append(block_module.attn.c_k.weight)
527
+ else: print(f"PRINT: Warning: c_k not found in attn module of a block.")
528
+ if hasattr(block_module.attn, 'c_v'): attn_v_params.append(block_module.attn.c_v.weight)
529
+ else: print(f"PRINT: Warning: c_v not found in attn module of a block.")
530
+ attn_o_params.append(block_module.attn.c_proj.weight)
531
+ if block_module.mlp is not None:
532
+ mlp_fc_params.append(block_module.mlp.c_fc.weight)
533
+ mlp_proj_params.append(block_module.mlp.c_proj.weight)
534
+ mlp_up_params.append(block_module.mlp.c_up.weight)
535
+
536
+ # Combine into logical groups for experiments
537
+ attn_qk_group = attn_q_params + attn_k_params
538
+ attn_vo_group = attn_v_params + attn_o_params
539
+ all_attn_matrices = attn_qk_group + attn_vo_group
540
+ mlp_w1_group = mlp_fc_params
541
+ mlp_w2_group = mlp_proj_params
542
+ mlp_up_group = mlp_up_params
543
+ all_mlp_matrices = mlp_fc_params + mlp_proj_params+ mlp_up_params
544
+
545
+ # Scalar parameters (all others not explicitly grouped as matrices)
546
+ # matrix_params_for_scalar_check = set(head_params + embed_params + all_attn_matrices + all_mlp_matrices)
547
+ matrix_params_for_scalar_check = set(head_params + all_attn_matrices + all_mlp_matrices)
548
+ scalar_params = [p for n, p in raw_model.named_parameters() if p not in matrix_params_for_scalar_check]
549
+ for p_scalar in scalar_params: # Sanity check
550
+ if p_scalar.ndim >=2:
551
+ print(f"PRINT: Warning - Parameter {p_scalar.shape} ended up in scalar_params but has ndim >= 2. Check grouping.")
552
+
553
+
554
+ # Determine parameter distribution based on optimizer_mode
555
+ muon_params_target_list = []
556
+ adam_matrix_target_list = [] # Matrices that Adam will handle specifically
557
+ adam_matrix_lr = exp_args.adam_lr # LR for matrices if Adam handles them (can be tuned)
558
+
559
+ current_optimizer_mode = exp_args.optimizer_mode
560
+
561
+ print(f"PRINT: Configuring optimizers for EXPERIMENT_MODE = {current_optimizer_mode}")
562
+
563
+ if current_optimizer_mode == 0: # Original behavior: Muon on all "hidden_matrix_params"
564
+ print(f"PRINT: Mode 0: Muon on ALL Attention (QKVO) and ALL MLP matrices.")
565
+ muon_params_target_list = all_attn_matrices + all_mlp_matrices
566
+ # Adam handles embeds, head, scalars by default. No extra matrices for Adam here.
567
+ elif current_optimizer_mode == 1: # Muon on QK, Adam on VO and MLP
568
+ print(f"PRINT: Mode 1: Muon on QK Attn. Adam on VO Attn, MLP (Adam LR: {adam_matrix_lr}).")
569
+ muon_params_target_list = attn_qk_group
570
+ adam_matrix_target_list = attn_vo_group + all_mlp_matrices
571
+ elif current_optimizer_mode == 2: # Muon on VO, Adam on QK and MLP
572
+ print(f"PRINT: Mode 2: Muon on VO Attn. Adam on QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
573
+ muon_params_target_list = attn_vo_group
574
+ adam_matrix_target_list = attn_qk_group + all_mlp_matrices
575
+ elif current_optimizer_mode == 3: # Muon on All Attn (QKVO), Adam on MLP
576
+ print(f"PRINT: Mode 3: Muon on ALL Attn (QKVO). Adam on MLP (Adam LR: {adam_matrix_lr}).")
577
+ muon_params_target_list = all_attn_matrices
578
+ adam_matrix_target_list = all_mlp_matrices
579
+ elif current_optimizer_mode == 4: # Muon on MLP, Adam on All Attn (QKVO)
580
+ print(f"PRINT: Mode 4: Muon on MLP. Adam on ALL Attn (QKVO) (Adam LR: {adam_matrix_lr}).")
581
+ muon_params_target_list = all_mlp_matrices
582
+ adam_matrix_target_list = all_attn_matrices
583
+ elif current_optimizer_mode == 5: # NEW MODE 5 - All Adam
584
+ print(f"PRINT: Mode 5: All Adam. All Attn and MLP matrices to Adam (Adam LR: {adam_matrix_lr}).")
585
+ muon_params_target_list = []
586
+ adam_matrix_target_list = all_attn_matrices + all_mlp_matrices # All matrices to Adam
587
+ elif current_optimizer_mode == 6: # Muon on W_2 MLP, Adam on attn, W_1 MLP
588
+ print(f"PRINT: Mode 6: Muon on W_2 MLP. Adam on attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
589
+ muon_params_target_list = mlp_w2_group
590
+ adam_matrix_target_list = all_attn_matrices + mlp_w1_group
591
+ elif current_optimizer_mode == 7: # Muon on VO Attn, MLP, Adam on QK Attn
592
+ print(f"PRINT: Mode 7: Muon on VO Attn, MLP. Adam on QK Attn (Adam LR: {adam_matrix_lr}).")
593
+ muon_params_target_list = attn_vo_group + all_mlp_matrices
594
+ adam_matrix_target_list = attn_qk_group
595
+ elif current_optimizer_mode == 8: # Muon on VO Attn, W_2 MLP, Adam on QK Attn, W_1 MLP
596
+ print(f"PRINT: Mode 8: Muon on VO Attn, W_2 MLP. Adam on QK Attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
597
+ muon_params_target_list = attn_vo_group + mlp_w2_group
598
+ adam_matrix_target_list = attn_qk_group + mlp_w1_group
599
+ elif current_optimizer_mode == 9: # Muon on V Attn, MLP
600
+ print(f"PRINT: Mode 9: Muon on V Attn, MLP (Adam LR: {adam_matrix_lr}).")
601
+ muon_params_target_list = attn_v_params + all_mlp_matrices
602
+ adam_matrix_target_list = attn_o_params + attn_qk_group
603
+ elif current_optimizer_mode == 10: # Muon on O Attn, MLP
604
+ print(f"PRINT: Mode 10: Muon on O Attn, MLP (Adam LR: {adam_matrix_lr}).")
605
+ muon_params_target_list = attn_o_params + all_mlp_matrices
606
+ adam_matrix_target_list = attn_v_params + attn_qk_group
607
+ elif current_optimizer_mode == 11: # Muon on W_1, Adam on O Attn, QK Attn
608
+ print(f"PRINT: Mode 11: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
609
+ muon_params_target_list = mlp_w1_group
610
+ adam_matrix_target_list = all_attn_matrices + mlp_w2_group
611
+ elif current_optimizer_mode == 12: # Muon on W_1, VO, Adam on others
612
+ print(f"PRINT: Mode 11: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
613
+ muon_params_target_list = attn_vo_group + mlp_w1_group
614
+ adam_matrix_target_list = attn_qk_group + mlp_w2_group
615
+ elif current_optimizer_mode == 13:
616
+ print(f"PRINT: Mode 13: Muon on W_2, W_O. Adam on V Attn, QK Attn, W_1 (Adam LR: {adam_matrix_lr}).")
617
+ muon_params_target_list = attn_o_params + mlp_w2_group
618
+ adam_matrix_target_list = attn_qk_group + attn_v_params + mlp_w1_group
619
+ elif current_optimizer_mode == 14:
620
+ print(f"PRINT: Mode 14: Muon on W_O. Adam on V Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
621
+ muon_params_target_list = attn_o_params
622
+ adam_matrix_target_list = attn_qk_group + attn_v_params +all_mlp_matrices
623
+ elif current_optimizer_mode == 15:
624
+ print(f"PRINT: Mode 15: Muon on W_V. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
625
+ muon_params_target_list = attn_v_params
626
+ adam_matrix_target_list = attn_qk_group + attn_o_params +all_mlp_matrices
627
+ elif current_optimizer_mode == 16:
628
+ print(f"PRINT: Mode 15: Muon on QKV. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
629
+ muon_params_target_list = attn_v_params + attn_qk_group
630
+ adam_matrix_target_list = attn_o_params +all_mlp_matrices
631
+ else:
632
+ raise ValueError(f"Unsupported EXPERIMENT_MODE: {current_optimizer_mode}")
633
+
634
+ # Adam optimizer setup
635
+ adam_param_groups_config = [
636
+ dict(params=head_params, lr=adam_matrix_lr),
637
+ # dict(params=embed_params, lr=adam_matrix_lr),
638
+ dict(params=scalar_params, lr=adam_matrix_lr) # Scalar params always go to Adam
639
+ ]
640
+
641
+ # Add matrices specifically assigned to Adam for this experiment mode
642
+ if adam_matrix_target_list:
643
+ # Ensure adam_matrix_target_list is flat and contains Parameters
644
+ flat_adam_matrices = [p for sublist_or_p in adam_matrix_target_list for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]) if p is not None]
645
+ if flat_adam_matrices: # Only add group if there are params
646
+ adam_param_groups_config.append(dict(params=flat_adam_matrices, lr=adam_matrix_lr))
647
+
648
+ # Filter out any Adam groups that might be empty (e.g., if scalar_params was empty)
649
+ adam_param_groups_config = [g for g in adam_param_groups_config if g['params']]
650
+ # print(f"PRINT: The length of Adam param groups config: {len(adam_param_groups_config)}")
651
+ optimizer1 = torch.optim.Adam(adam_param_groups_config, betas=(0.9, 0.95), eps=1e-10, fused=True)
652
+ optimizers = [optimizer1] # Start with Adam
653
+
654
+
655
+ if muon_params_target_list:
656
+ # Ensure muon_params_target_list is flat, unique, and contains Parameters
657
+ flat_unique_muon_params = []
658
+ seen_muon_ids = set()
659
+ for sublist_or_p in muon_params_target_list:
660
+ for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]):
661
+ if p is not None and id(p) not in seen_muon_ids:
662
+ flat_unique_muon_params.append(p)
663
+ seen_muon_ids.add(id(p))
664
+
665
+ if flat_unique_muon_params: # Only create Muon if it has parameters
666
+ optimizer2 = Muon(flat_unique_muon_params, lr=exp_args.muon_lr, momentum=0.95,rank=ddp_rank, world_size=ddp_world_size) # Pass nesterov, ns_steps
667
+ optimizers.append(optimizer2)
668
+ else:
669
+ print("PRINT: Muon optimizer not created as its target parameter list was empty.")
670
+ optimizer2 = None # Explicitly set to None if not created
671
+ else:
672
+ print("PRINT: Muon optimizer not created as muon_params_target_list was empty (e.g. mode where Adam handles all matrices).")
673
+ optimizer2 = None # Explicitly set to None
674
+
675
+ print(f"PRINT: Optimizers configured. Total optimizers: {len(optimizers)}")
676
+ if optimizer2:
677
+ print(f"PRINT: Muon optimizer is active with {len(flat_unique_muon_params)} parameters.")
678
+
679
+ # Set up parameter groups for SVD analysis
680
+ matrix_groups_for_svd = {
681
+ "attn_qk": attn_qk_group,
682
+ "attn_vo": attn_vo_group,
683
+ "mlp_w1": mlp_w1_group, # c_fc only
684
+ "mlp_up": mlp_up_group, # c_up only
685
+ "mlp_w2": mlp_proj_params
686
+ }
687
+
688
+ # optimizer1 = torch.optim.AdamW(raw_model.lm_head.parameters(), lr=args.learning_rate, betas=(0.9, 0.95),
689
+ # weight_decay=args.weight_decay, fused=True)
690
+ # optimizer2 = Muon(raw_model.transformer.h.parameters(), lr=0.1*args.learning_rate, momentum=0.95,
691
+ # rank=ddp_rank, world_size=ddp_world_size)
692
+
693
+ # optimizers = [optimizer1, optimizer2]
694
+ # learning rate decay scheduler (linear warmup and warmdown)
695
+ def get_lr(it):
696
+ assert it <= args.num_iterations
697
+ # 1) linear warmup for warmup_iters steps
698
+ if it < args.warmup_iters:
699
+ return (it+1) / args.warmup_iters
700
+ # 2) constant lr for a while
701
+ elif it < args.num_iterations - args.warmdown_iters:
702
+ return 1.0
703
+ # 3) linear warmdown
704
+ else:
705
+ decay_ratio = (args.num_iterations - it) / args.warmdown_iters
706
+ return decay_ratio
707
+ schedulers = [torch.optim.lr_scheduler.LambdaLR(opt, get_lr) for opt in optimizers]
708
+
709
+ if master_process:
710
+ with open(logfile, "a") as f:
711
+ f.write(code)
712
+
713
+ training_time_ms = 0
714
+ # start the clock
715
+ torch.cuda.synchronize()
716
+ t0 = time.time()
717
+ # begin training
718
+ train_loader.reset()
719
+ for step in range(args.num_iterations + 1):
720
+ last_step = (step == args.num_iterations)
721
+ # This effectively ignores timing first 10 steps, which are slower for weird reasons.
722
+ # Alternately, and slightly more correctly in terms of benchmarking, we could do 10
723
+ # steps with dummy data first, and then re-initialize the model and reset the loader.
724
+ if step == 10:
725
+ training_time_ms = 0
726
+ t0 = time.time()
727
+ timed_steps = float('nan') if step <= 11 else (step - 10) + 1 # <= 11 to avoid bug in val
728
+
729
+ # once in a while evaluate the validation dataset
730
+ if (last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0)):
731
+ # stop the clock
732
+ torch.cuda.synchronize()
733
+ training_time_ms += 1000 * (time.time() - t0)
734
+ # run validation batches
735
+ with torch.no_grad():
736
+ val_loader.reset()
737
+ val_loss = 0.0
738
+ for _ in range(val_steps):
739
+ x_val, y_val = val_loader.next_batch()
740
+ with ctx: # of course, we'd like to use no_grad() here too, but that creates a torch.compile error for some reason
741
+ _, loss = model(x_val, y_val, return_logits=False)
742
+ val_loss += loss.detach()
743
+ del loss
744
+ dist.all_reduce(val_loss, op=dist.ReduceOp.AVG)
745
+ val_loss /= val_steps
746
+
747
+ # SVD metrics calculation
748
+ svd_log_str = ""
749
+ if master_process and 'matrix_groups_for_svd' in locals() and matrix_groups_for_svd:
750
+ TOPK = 10
751
+ svd_results_by_category = {}
752
+
753
+ with torch.no_grad():
754
+ # per-category metrics (average over matrices in the group)
755
+ for name, group_params in matrix_groups_for_svd.items():
756
+ if not group_params:
757
+ continue
758
+ mets = [calculate_svd_metrics(p, topk=TOPK) for p in group_params]
759
+ if mets:
760
+ avg_entropy = float(np.mean([m['entropy_norm'] for m in mets]))
761
+ avg_erank = float(np.mean([m['erank'] for m in mets]))
762
+ avg_topkE = float(np.mean([m['topk_energy'] for m in mets]))
763
+ avg_qratio = float(np.mean([m['q75_q25'] for m in mets]))
764
+ svd_results_by_category[name] = dict(
765
+ entropy=avg_entropy, erank=avg_erank, topkE=avg_topkE, q75_q25=avg_qratio
766
+ )
767
+
768
+ # VO product as another category
769
+ if attn_v_params and attn_o_params:
770
+ vo_mets = []
771
+ num_layers = len(attn_v_params)
772
+ for i in range(num_layers):
773
+ w_v = attn_v_params[i]
774
+ w_o = attn_o_params[i]
775
+ w_ov_product = torch.matmul(w_o, w_v)
776
+ vo_mets.append(calculate_svd_metrics(w_ov_product, topk=TOPK))
777
+ if vo_mets:
778
+ svd_results_by_category['vo_prod'] = dict(
779
+ entropy=float(np.mean([m['entropy_norm'] for m in vo_mets])),
780
+ erank=float(np.mean([m['erank'] for m in vo_mets])),
781
+ topkE=float(np.mean([m['topk_energy'] for m in vo_mets])),
782
+ q75_q25=float(np.mean([m['q75_q25'] for m in vo_mets])),
783
+ )
784
+
785
+ # format logging string (append metrics after entropy)
786
+ svd_log_parts = []
787
+ for name, vals in svd_results_by_category.items():
788
+ svd_log_parts.append(
789
+ f"{name}:H={vals['entropy']:.4f},top{TOPK}E={vals['topkE']:.2f},eRank={vals['erank']:.1f},q75/q25={vals['q75_q25']:.2f}"
790
+ )
791
+ svd_log_str = " ".join(svd_log_parts)
792
+
793
+ # log val loss to console and to logfile
794
+ if master_process:
795
+ print(f'step:{step}/{args.num_iterations} val_loss:{val_loss:.4f} svd_entropy: {svd_log_str} train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms/(timed_steps-1):.2f}ms')
796
+ with open(logfile, "a") as f:
797
+ f.write(f'step:{step}/{args.num_iterations} val_loss:{val_loss:.4f} svd_entropy: {svd_log_str} train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms/(timed_steps-1):.2f}ms\n')
798
+ # start the clock again
799
+ torch.cuda.synchronize()
800
+ t0 = time.time()
801
+
802
+ if master_process and (last_step or (args.save_every > 0 and step % args.save_every == 0)):
803
+ # stop the clock
804
+ torch.cuda.synchronize()
805
+ training_time_ms += 1000 * (time.time() - t0)
806
+ # save the state of the training process
807
+ log = dict(step=step, code=code, model=raw_model.state_dict(), optimizers=[opt.state_dict() for opt in optimizers])
808
+ if run_dir_path_str:
809
+ save_path = f'{run_dir_path_str}/state_step{step:06d}.pt'
810
+ torch.save(log, save_path)
811
+ # start the clock again
812
+ torch.cuda.synchronize()
813
+ t0 = time.time()
814
+
815
+ # bit confusing: we want to make sure to eval on 0th iteration
816
+ # but also after the very last iteration. so we loop for step <= num_iterations
817
+ # instead of just < num_iterations (one extra due to <=), only to do
818
+ # the validation/sampling one last time, and then we break right here as we're done.
819
+ if last_step:
820
+ break
821
+
822
+ # --------------- TRAINING SECTION BEGIN -----------------
823
+ model.train()
824
+ for i in range(1, train_accumulation_steps+1):
825
+ # forward pass
826
+ with ctx:
827
+ _, loss = model(x, y, return_logits=False)
828
+ train_loss = loss.detach()
829
+ # advance the dataset for the next batch
830
+ x, y = train_loader.next_batch()
831
+ # backward pass
832
+ if i < train_accumulation_steps:
833
+ with model.no_sync(): # there's no need to sync gradients every accumulation step
834
+ loss.backward()
835
+ else:
836
+ loss.backward() # just sync on the last step
837
+ for p in model.parameters():
838
+ p.grad /= train_accumulation_steps
839
+ # step the optimizers and schedulers
840
+ for opt, sched in zip(optimizers, schedulers):
841
+ opt.step()
842
+ sched.step()
843
+ # null the gradients
844
+ model.zero_grad(set_to_none=True)
845
+ # --------------- TRAINING SECTION END -------------------
846
+ # everything that follows now is just diagnostics, prints, logging, etc.
847
+
848
+ #dist.all_reduce(train_loss, op=dist.ReduceOp.AVG) # all-reducing the training loss would be more correct in terms of logging, but slower
849
+ if master_process:
850
+ approx_time = training_time_ms + 1000 * (time.time() - t0)
851
+ print(f"step:{step+1}/{args.num_iterations} train_loss:{train_loss.item():.4f} train_time:{approx_time:.0f}ms step_avg:{approx_time/timed_steps:.2f}ms")
852
+ with open(logfile, "a") as f:
853
+ f.write(f"step:{step+1}/{args.num_iterations} train_loss:{train_loss.item():.4f} train_time:{approx_time:.0f}ms step_avg:{approx_time/timed_steps:.2f}ms\n")
854
+
855
+ if master_process:
856
+ print(f"peak memory consumption: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB")
logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "seed": 42,
4
+ "optimizer_mode": 5,
5
+ "model_parameterization": "gated",
6
+ "adam_lr": 0.0002,
7
+ "muon_lr": 0.0005,
8
+ "base_dir": "logs_new_MUON_large_reshape_svd_gated/svd"
9
+ },
10
+ "hyperparameters": {
11
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
12
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
13
+ "batch_size": 960,
14
+ "device_batch_size": 24,
15
+ "sequence_length": 1024,
16
+ "num_iterations": 6000,
17
+ "learning_rate": 0.0018,
18
+ "warmup_iters": 0,
19
+ "warmdown_iters": 0,
20
+ "weight_decay": 0,
21
+ "val_loss_every": 125,
22
+ "val_tokens": 10420224,
23
+ "save_every": 0
24
+ },
25
+ "run_uuid_for_log": "c51a87f3-6af4-417a-86fa-83dd74e4e135",
26
+ "script_code_logged_at_start": true
27
+ }
logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_42/training_log_c51a87f3-6af4-417a-86fa-83dd74e4e135.txt ADDED
The diff for this file is too large to render. See raw diff
 
logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cli_args": {
3
+ "seed": 43,
4
+ "optimizer_mode": 5,
5
+ "model_parameterization": "gated",
6
+ "adam_lr": 0.0002,
7
+ "muon_lr": 0.0005,
8
+ "base_dir": "logs_new_MUON_large_reshape_svd_gated/svd"
9
+ },
10
+ "hyperparameters": {
11
+ "input_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin",
12
+ "input_val_bin": "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin",
13
+ "batch_size": 960,
14
+ "device_batch_size": 24,
15
+ "sequence_length": 1024,
16
+ "num_iterations": 6000,
17
+ "learning_rate": 0.0018,
18
+ "warmup_iters": 0,
19
+ "warmdown_iters": 0,
20
+ "weight_decay": 0,
21
+ "val_loss_every": 125,
22
+ "val_tokens": 10420224,
23
+ "save_every": 0
24
+ },
25
+ "run_uuid_for_log": "ba9ae92f-719c-4f06-8489-a3fe9a80096d",
26
+ "script_code_logged_at_start": true
27
+ }
logs_new_MUON_large_reshape_svd_gated/svd/mode_5_param_gated_muon_lr_0.0005_adam_lr_0.0002_seed_43/training_log_ba9ae92f-719c-4f06-8489-a3fe9a80096d.txt ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os
3
+ import sys
4
+ with open(sys.argv[0]) as f:
5
+ code = f.read() # read the code of this file ASAP, for logging
6
+ import uuid
7
+ import time
8
+ import copy
9
+ import glob
10
+ from dataclasses import dataclass, asdict
11
+ from functools import lru_cache
12
+ from pathlib import Path
13
+ import argparse # Keep argparse for --unet and potentially --optimizer_mode
14
+ import json
15
+ import random
16
+ import numpy as np
17
+
18
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
19
+ import torch
20
+ torch.empty(1, device="cuda", requires_grad=True).backward() # prevents a bug on some systems
21
+ from torch import Tensor, nn
22
+ import torch.nn.functional as F
23
+ import torch.distributed as dist
24
+ # use of FlexAttention contributed by @KoszarskyB
25
+ from torch.nn.attention.flex_attention import BlockMask, flex_attention
26
+ sys.path.append("/home/aiops/zhangfz/MUON_theory/modded-nanogpt") # Already present
27
+ from optimizers.MUON_new_large_nes import Muon
28
+ from utils.float_compute import mm_op, backward as mm_backward_custom, setup_context as mm_setup_context_custom # Renamed
29
+ import torch._inductor.config as config
30
+ from torch.nn.parallel import DistributedDataParallel as DDP
31
+ from kn_util.utils import setup_debugpy
32
+
33
+
34
+ # -----------------------------------------------------------------------------
35
+ # Seeding Function
36
+ def set_seed(seed):
37
+ random.seed(seed)
38
+ np.random.seed(seed)
39
+ torch.manual_seed(seed)
40
+ if torch.cuda.is_available():
41
+ torch.cuda.manual_seed_all(seed)
42
+ print(f"PRINT: Set seed to {seed}", flush=True) # Print immediately for all ranks
43
+
44
+
45
+ # ---- ADD: spectral metrics helper ----
46
+ def calculate_svd_metrics(matrix: torch.Tensor, *, topk: int = 10):
47
+ """
48
+ Returns dict with:
49
+ - entropy_norm: normalized SVD entropy
50
+ - erank: effective rank = exp(Shannon entropy of p)
51
+ - topk_energy: sum of top-k p_i (energy fraction in the top-k singular values)
52
+ - q75_q25: ratio of 75th to 25th percentile of eigenvalues (sigma^2)
53
+ """
54
+ with torch.no_grad():
55
+ s = torch.linalg.svdvals(matrix.detach().to('cpu', torch.float32))
56
+ s = s[s > 1e-9]
57
+ n = s.numel()
58
+ if n == 0:
59
+ return dict(entropy_norm=0.0, erank=0.0, topk_energy=0.0, q75_q25=float('inf'))
60
+
61
+ s2 = s * s
62
+ S2_sum = float(torch.sum(s2))
63
+ if S2_sum == 0.0:
64
+ return dict(entropy_norm=0.0, erank=0.0, topk_energy=0.0, q75_q25=float('inf'))
65
+
66
+ p = s2 / S2_sum # energy distribution
67
+ # Shannon entropy H (natural log)
68
+ H = float(torch.sum(torch.special.entr(p)))
69
+ entropy_norm = H / np.log(max(n, 2))
70
+ erank = float(np.exp(H))
71
+
72
+ k = min(topk, n)
73
+ topk_energy = float(torch.topk(p, k).values.sum())
74
+
75
+ # eigenvalues = s^2, use quantiles on s^2
76
+ q25 = float(torch.quantile(s2, 0.25))
77
+ q75 = float(torch.quantile(s2, 0.75))
78
+ q75_q25 = (q75 / q25) if q25 > 0 else float('inf')
79
+
80
+ return dict(
81
+ entropy_norm=entropy_norm,
82
+ erank=erank,
83
+ topk_energy=topk_energy,
84
+ q75_q25=q75_q25,
85
+ )
86
+
87
+
88
+ # -----------------------------------------------------------------------------
89
+ # Our own simple Distributed Data Loader
90
+
91
+ def _peek_data_shard(filename):
92
+ # only reads the header, returns header data
93
+ with open(filename, "rb") as f:
94
+ # first read the header, which is 256 int32 integers (4 bytes each)
95
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
96
+ if header[0] != 20240520:
97
+ print("ERROR: magic number mismatch in the data .bin file!")
98
+ print("---> HINT: Are you passing in a correct file with --input_bin?")
99
+ print("---> HINT: Dataset encoding changed recently, re-run data prepro or refer again to README")
100
+ print("---> HINT: For example re-run: `python dev/data/tinyshakespeare.py`, then re-try")
101
+ exit(1)
102
+ assert header[1] == 1, "unsupported version"
103
+ ntok = header[2] # number of tokens (claimed)
104
+ return ntok # for now just return the number of tokens
105
+
106
+ def _load_data_shard(filename):
107
+ with open(filename, "rb") as f:
108
+ # first read the header, which is 256 int32 integers (4 bytes each)
109
+ header = np.frombuffer(f.read(256*4), dtype=np.int32)
110
+ assert header[0] == 20240520, "magic number mismatch in the data .bin file"
111
+ assert header[1] == 1, "unsupported version"
112
+ ntok = header[2] # number of tokens (claimed)
113
+ # the rest of it are tokens, stored as uint16
114
+ tokens = np.frombuffer(f.read(), dtype=np.uint16)
115
+ assert len(tokens) == ntok, "number of tokens read does not match header?"
116
+ return tokens
117
+
118
+ class DistributedDataLoader:
119
+ def __init__(self, filename_pattern, B, T, process_rank, num_processes):
120
+ self.process_rank = process_rank
121
+ self.num_processes = num_processes
122
+ self.B = B
123
+ self.T = T
124
+
125
+ # glob files that match the pattern
126
+ self.files = sorted(glob.glob(filename_pattern))
127
+ assert len(self.files) > 0, f"did not find any files that match the pattern {filename_pattern}"
128
+
129
+ # load and validate all data shards, count number of tokens in total
130
+ ntok_total = 0
131
+ for fname in self.files:
132
+ shard_ntok = _peek_data_shard(fname)
133
+ assert shard_ntok >= num_processes * B * T + 1
134
+ ntok_total += int(shard_ntok)
135
+ self.ntok_total = ntok_total
136
+
137
+ # kick things off
138
+ self.reset()
139
+
140
+ def reset(self):
141
+ self.current_shard = 0
142
+ self.current_position = self.process_rank * self.B * self.T
143
+ self.tokens = _load_data_shard(self.files[self.current_shard])
144
+
145
+ def advance(self): # advance to next data shard
146
+ self.current_shard = (self.current_shard + 1) % len(self.files)
147
+ self.current_position = self.process_rank * self.B * self.T
148
+ self.tokens = _load_data_shard(self.files[self.current_shard])
149
+
150
+ def next_batch(self):
151
+ B = self.B
152
+ T = self.T
153
+ buf = self.tokens[self.current_position : self.current_position+B*T+1]
154
+ buf = torch.tensor(buf.astype(np.int32), dtype=torch.long)
155
+ x = (buf[:-1]).view(B, T) # inputs
156
+ y = (buf[1:]).view(B, T) # targets
157
+ # advance current position and load next shard if necessary
158
+ self.current_position += B * T * self.num_processes
159
+ if self.current_position + (B * T * self.num_processes + 1) > len(self.tokens):
160
+ self.advance()
161
+ return x.cuda(), y.cuda()
162
+
163
+ # -----------------------------------------------------------------------------
164
+ # int main
165
+
166
+ @dataclass
167
+ class Hyperparameters:
168
+ # data hyperparams
169
+ input_bin : str = "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_train_*.bin"
170
+ input_val_bin : str = "/home/aiops/zhangfz/MUON_theory/modded-nanogpt/data/fineweb10B/fineweb_val_*.bin"
171
+ # optimization hyperparams
172
+ batch_size : int = 8*120 # 8*120 # batch size, in sequences, across all devices
173
+ device_batch_size : int = 24 # batch size, in sequences, per device
174
+ sequence_length : int = 1024 # sequence length, in tokens
175
+ num_iterations : int = 6000 # number of iterations to run
176
+ learning_rate : float = 0.0036 / 2
177
+ warmup_iters : int = 0
178
+ warmdown_iters : int = 0 # number of iterations of linear warmup/warmdown for triangular or trapezoidal schedule
179
+ weight_decay : float = 0
180
+ # evaluation and logging hyperparams
181
+ val_loss_every : int = 125 # every how many steps to evaluate val loss? 0 for only at the end
182
+ val_tokens : int = 10420224 # how many tokens of validation data? it's important to keep this fixed for consistent comparisons
183
+ save_every : int = 0 # every how many steps to save the checkpoint? 0 for only at the end
184
+ args = Hyperparameters()
185
+
186
+
187
+
188
+ # -----------------------------------------------------------------------------
189
+ # int main
190
+ # setup_debugpy(force=True)
191
+ parser = argparse.ArgumentParser(description="NanoGPT Training Script with Muon")
192
+ parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility")
193
+ # --- MODIFICATION: Add optimizer_mode as a CLI argument ---
194
+ parser.add_argument("--optimizer_mode", type=int, default=0,
195
+ help="Defines how Muon is applied. "
196
+ "0: Muon(All Hidden Attn+MLP - original); "
197
+ "1: Muon(QK Attn)/Adam(VO Attn,MLP); "
198
+ "2: Muon(VO Attn)/Adam(QK Attn,MLP); "
199
+ "3: Muon(All Attn)/Adam(MLP); "
200
+ "4: Muon(MLP)/Adam(All Attn)"
201
+ "5: All Adam (No Muon, all applicable matrices to Adam)."
202
+ "6: Muon(W_2 MLP)/Adam(attn, W_1 MLP)."
203
+ "7: Muon(VO Attn, MLP)/Adam(QK Attn)."
204
+ "8: Muon(VO Attn, W_2 MLP)/Adam(QK Attn, W_1 MLP)."
205
+ )
206
+ parser.add_argument("--model_parameterization", type=str, default="whole",choices=["whole","qkvo", "norope", "gated"])
207
+ parser.add_argument("--adam_lr", type=float, default=0.008, help="Learning rate for Adam matrices")
208
+ parser.add_argument("--muon_lr", type=float, default=0.05, help="Learning rate for Muon matrices")
209
+ parser.add_argument("--base_dir", type=str, default="logs_new_MUON_large/test", help="Base directory for logs")
210
+ exp_args = parser.parse_args()
211
+ set_seed(exp_args.seed)
212
+
213
+
214
+
215
+ # set up DDP (distributed data parallel). torchrun sets this env variable
216
+ assert torch.cuda.is_available()
217
+ dist.init_process_group(backend='nccl')
218
+ ddp_rank = int(os.environ['RANK'])
219
+ ddp_local_rank = int(os.environ['LOCAL_RANK'])
220
+ ddp_world_size = int(os.environ['WORLD_SIZE'])
221
+ device = f'cuda:{ddp_local_rank}'
222
+ torch.cuda.set_device(device)
223
+ print(f"using device: {device}")
224
+ master_process = (ddp_rank == 0) # this process will do logging, checkpointing etc.
225
+
226
+ logfile = None
227
+ run_dir_path_str = None
228
+ base_log_dir = Path(exp_args.base_dir)
229
+
230
+
231
+ if master_process:
232
+ import subprocess
233
+ set_seed(exp_args.seed)
234
+
235
+ # Construct folder name based on config and seed
236
+ # run_folder_name = f"mode_{exp_args.optimizer_mode}_param_{exp_args.model_parameterization}_adam_lr_{exp_args.adam_lr}_seed_{exp_args.seed}"
237
+ run_folder_name = f"mode_{exp_args.optimizer_mode}_param_{exp_args.model_parameterization}_muon_lr_{exp_args.muon_lr}_adam_lr_{exp_args.adam_lr}_seed_{exp_args.seed}"
238
+ run_dir_path = base_log_dir / run_folder_name
239
+ run_dir_path.mkdir(parents=True, exist_ok=True)
240
+ run_dir_path_str = str(run_dir_path)
241
+
242
+ run_uuid = uuid.uuid4()
243
+ logfile = run_dir_path / f"training_log_{run_uuid}.txt"
244
+ print(f"Logging to: {logfile}")
245
+
246
+ # Save configuration
247
+ config_to_save = {
248
+ "cli_args": vars(exp_args),
249
+ "hyperparameters": {k: v for k, v in args.__class__.__dict__.items() if not k.startswith('__') and not callable(v)},
250
+ "run_uuid_for_log": str(run_uuid),
251
+ "script_code_logged_at_start": True
252
+ }
253
+ config_file_path = run_dir_path / "config.json"
254
+ with open(config_file_path, "w") as f:
255
+ json.dump(config_to_save, f, indent=4)
256
+ print(f"Saved configuration to: {config_file_path}")
257
+
258
+ # convenience variables
259
+ B, T = args.device_batch_size, args.sequence_length
260
+ # calculate the number of steps to take in the val loop.
261
+ print(f"args.val_tokens: {args.val_tokens}, args.batch_size: {args.batch_size}, B: {B}, T: {T}, ddp_world_size: {ddp_world_size}")
262
+ assert args.val_tokens % (B * T * ddp_world_size) == 0
263
+ val_steps = args.val_tokens // (B * T * ddp_world_size)
264
+ # calculate the steps of gradient accumulation required to attain the desired global batch size.
265
+ assert args.batch_size % (B * ddp_world_size) == 0
266
+ train_accumulation_steps = args.batch_size // (B * ddp_world_size)
267
+
268
+ # load tokens
269
+ train_loader = DistributedDataLoader(args.input_bin, B, T, ddp_rank, ddp_world_size)
270
+ val_loader = DistributedDataLoader(args.input_val_bin, B, T, ddp_rank, ddp_world_size)
271
+ if master_process:
272
+ print(f"Training DataLoader: total number of tokens: {train_loader.ntok_total} across {len(train_loader.files)} files")
273
+ print(f"Validation DataLoader: total number of tokens: {val_loader.ntok_total} across {len(val_loader.files)} files")
274
+ x, y = train_loader.next_batch()
275
+
276
+ # there are only 50257 unique GPT-2 tokens; we extend to nearest multiple of 128 for efficiency. suggested to me by @Grad62304977.
277
+ # this originates from Karpathy's experiments.
278
+ num_vocab = 50304
279
+
280
+
281
+
282
+ if exp_args.model_parameterization == "qkvo":
283
+ from models.nano_GPT_qkvo_large import GPT, GPTConfig
284
+ # model = GPT(GPTConfig(vocab_size=num_vocab, n_layer=25, n_head=12, n_embd=1536))
285
+ model = GPT(GPTConfig(vocab_size=num_vocab, n_layer=36, n_head=20, n_embd=1280))
286
+ elif exp_args.model_parameterization == "gated":
287
+ from models.nano_GPT_gated_large import GPT, GPTConfig
288
+ model = GPT(GPTConfig(vocab_size=num_vocab, n_layer=27, n_head=20, n_embd=1280))
289
+
290
+ if master_process:
291
+ print(sum(p.numel() for p in model.parameters()))
292
+ model = model.cuda()
293
+ if hasattr(config, "coordinate_descent_tuning"):
294
+ config.coordinate_descent_tuning = True # suggested by @Chillee
295
+ model = torch.compile(model)
296
+ # here we wrap model into DDP container
297
+ model = DDP(model, device_ids=[ddp_local_rank])
298
+ raw_model = model.module # always contains the "raw" unwrapped model
299
+ ctx = torch.amp.autocast(device_type='cuda', dtype=torch.bfloat16)
300
+
301
+ # for name, param in raw_model.named_parameters():
302
+ # print(name, param.shape)
303
+
304
+ if exp_args.model_parameterization == "qkvo" :
305
+ print("PRINT: Collecting parameters for optimizers...")
306
+ head_params = [raw_model.lm_head.weight]
307
+ # embed_params = [raw_model.transformer.wte.weight]
308
+
309
+ # Granular collection for attention and MLP parts
310
+ attn_q_params = []
311
+ attn_k_params = []
312
+ attn_v_params = []
313
+ attn_o_params = [] # W_O from c_proj
314
+ mlp_fc_params = []
315
+ mlp_proj_params = []
316
+
317
+ for block_module in raw_model.transformer.h:
318
+ if block_module.attn is not None:
319
+ # These attributes (c_q, c_k, c_v) MUST exist in your CausalSelfAttention class
320
+ if hasattr(block_module.attn, 'c_q'): attn_q_params.append(block_module.attn.c_q.weight)
321
+ else:
322
+ print(f"PRINT: Warning: c_q not found in attn module of a block.")
323
+ if hasattr(block_module.attn, 'c_k'): attn_k_params.append(block_module.attn.c_k.weight)
324
+ else: print(f"PRINT: Warning: c_k not found in attn module of a block.")
325
+ if hasattr(block_module.attn, 'c_v'): attn_v_params.append(block_module.attn.c_v.weight)
326
+ else: print(f"PRINT: Warning: c_v not found in attn module of a block.")
327
+ attn_o_params.append(block_module.attn.c_proj.weight)
328
+ if block_module.mlp is not None:
329
+ mlp_fc_params.append(block_module.mlp.c_fc.weight)
330
+ mlp_proj_params.append(block_module.mlp.c_proj.weight)
331
+
332
+ # Combine into logical groups for experiments
333
+ attn_qk_group = attn_q_params + attn_k_params
334
+ attn_vo_group = attn_v_params + attn_o_params
335
+ all_attn_matrices = attn_qk_group + attn_vo_group
336
+ mlp_w1_group = mlp_fc_params
337
+ mlp_w2_group = mlp_proj_params
338
+ all_mlp_matrices = mlp_fc_params + mlp_proj_params
339
+
340
+ # Scalar parameters (all others not explicitly grouped as matrices)
341
+ # matrix_params_for_scalar_check = set(head_params + embed_params + all_attn_matrices + all_mlp_matrices)
342
+ matrix_params_for_scalar_check = set(head_params + all_attn_matrices + all_mlp_matrices)
343
+ scalar_params = [p for n, p in raw_model.named_parameters() if p not in matrix_params_for_scalar_check]
344
+ for p_scalar in scalar_params: # Sanity check
345
+ if p_scalar.ndim >=2:
346
+ print(f"PRINT: Warning - Parameter {p_scalar.shape} ended up in scalar_params but has ndim >= 2. Check grouping.")
347
+
348
+
349
+ # Determine parameter distribution based on optimizer_mode
350
+ muon_params_target_list = []
351
+ adam_matrix_target_list = [] # Matrices that Adam will handle specifically
352
+ adam_matrix_lr = exp_args.adam_lr # LR for matrices if Adam handles them (can be tuned)
353
+
354
+ current_optimizer_mode = exp_args.optimizer_mode
355
+
356
+ print(f"PRINT: Configuring optimizers for EXPERIMENT_MODE = {current_optimizer_mode}")
357
+
358
+ if current_optimizer_mode == 0: # Original behavior: Muon on all "hidden_matrix_params"
359
+ print(f"PRINT: Mode 0: Muon on ALL Attention (QKVO) and ALL MLP matrices.")
360
+ muon_params_target_list = all_attn_matrices + all_mlp_matrices
361
+ # Adam handles embeds, head, scalars by default. No extra matrices for Adam here.
362
+ elif current_optimizer_mode == 1: # Muon on QK, Adam on VO and MLP
363
+ print(f"PRINT: Mode 1: Muon on QK Attn. Adam on VO Attn, MLP (Adam LR: {adam_matrix_lr}).")
364
+ muon_params_target_list = attn_qk_group
365
+ adam_matrix_target_list = attn_vo_group + all_mlp_matrices
366
+ elif current_optimizer_mode == 2: # Muon on VO, Adam on QK and MLP
367
+ print(f"PRINT: Mode 2: Muon on VO Attn. Adam on QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
368
+ muon_params_target_list = attn_vo_group
369
+ adam_matrix_target_list = attn_qk_group + all_mlp_matrices
370
+ elif current_optimizer_mode == 3: # Muon on All Attn (QKVO), Adam on MLP
371
+ print(f"PRINT: Mode 3: Muon on ALL Attn (QKVO). Adam on MLP (Adam LR: {adam_matrix_lr}).")
372
+ muon_params_target_list = all_attn_matrices
373
+ adam_matrix_target_list = all_mlp_matrices
374
+ elif current_optimizer_mode == 4: # Muon on MLP, Adam on All Attn (QKVO)
375
+ print(f"PRINT: Mode 4: Muon on MLP. Adam on ALL Attn (QKVO) (Adam LR: {adam_matrix_lr}).")
376
+ muon_params_target_list = all_mlp_matrices
377
+ adam_matrix_target_list = all_attn_matrices
378
+ elif current_optimizer_mode == 5: # NEW MODE 5 - All Adam
379
+ print(f"PRINT: Mode 5: All Adam. All Attn and MLP matrices to Adam (Adam LR: {adam_matrix_lr}).")
380
+ muon_params_target_list = []
381
+ adam_matrix_target_list = all_attn_matrices + all_mlp_matrices # All matrices to Adam
382
+ elif current_optimizer_mode == 6: # Muon on W_2 MLP, Adam on attn, W_1 MLP
383
+ print(f"PRINT: Mode 6: Muon on W_2 MLP. Adam on attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
384
+ muon_params_target_list = mlp_w2_group
385
+ adam_matrix_target_list = all_attn_matrices + mlp_w1_group
386
+ elif current_optimizer_mode == 7: # Muon on VO Attn, MLP, Adam on QK Attn
387
+ print(f"PRINT: Mode 7: Muon on VO Attn, MLP. Adam on QK Attn (Adam LR: {adam_matrix_lr}).")
388
+ muon_params_target_list = attn_vo_group + all_mlp_matrices
389
+ adam_matrix_target_list = attn_qk_group
390
+ elif current_optimizer_mode == 8: # Muon on VO Attn, W_2 MLP, Adam on QK Attn, W_1 MLP
391
+ print(f"PRINT: Mode 8: Muon on VO Attn, W_2 MLP. Adam on QK Attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
392
+ muon_params_target_list = attn_vo_group + mlp_w2_group
393
+ adam_matrix_target_list = attn_qk_group + mlp_w1_group
394
+ elif current_optimizer_mode == 9: # Muon on V Attn, MLP
395
+ print(f"PRINT: Mode 9: Muon on V Attn, MLP (Adam LR: {adam_matrix_lr}).")
396
+ muon_params_target_list = attn_v_params + all_mlp_matrices
397
+ adam_matrix_target_list = attn_o_params + attn_qk_group
398
+ elif current_optimizer_mode == 10: # Muon on O Attn, MLP
399
+ print(f"PRINT: Mode 10: Muon on O Attn, MLP (Adam LR: {adam_matrix_lr}).")
400
+ muon_params_target_list = attn_o_params + all_mlp_matrices
401
+ adam_matrix_target_list = attn_v_params + attn_qk_group
402
+ elif current_optimizer_mode == 11: # Muon on W_1, Adam on O Attn, QK Attn
403
+ print(f"PRINT: Mode 11: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
404
+ muon_params_target_list = mlp_w1_group
405
+ adam_matrix_target_list = all_attn_matrices + mlp_w2_group
406
+ elif current_optimizer_mode == 12: # Muon on W_1, VO, Adam on others
407
+ print(f"PRINT: Mode 12: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
408
+ muon_params_target_list = attn_vo_group + mlp_w1_group
409
+ adam_matrix_target_list = attn_qk_group + mlp_w2_group
410
+ elif current_optimizer_mode == 13:
411
+ print(f"PRINT: Mode 13: Muon on W_2, W_O. Adam on V Attn, QK Attn, W_1 (Adam LR: {adam_matrix_lr}).")
412
+ muon_params_target_list = attn_o_params + mlp_w2_group
413
+ adam_matrix_target_list = attn_qk_group + attn_v_params + mlp_w1_group
414
+ elif current_optimizer_mode == 14:
415
+ print(f"PRINT: Mode 14: Muon on W_O. Adam on V Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
416
+ muon_params_target_list = attn_o_params
417
+ adam_matrix_target_list = attn_qk_group + attn_v_params +all_mlp_matrices
418
+ elif current_optimizer_mode == 15:
419
+ print(f"PRINT: Mode 15: Muon on W_V. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
420
+ muon_params_target_list = attn_v_params
421
+ adam_matrix_target_list = attn_qk_group + attn_o_params +all_mlp_matrices
422
+ elif current_optimizer_mode == 16:
423
+ print(f"PRINT: Mode 15: Muon on QKV. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
424
+ muon_params_target_list = attn_v_params + attn_qk_group
425
+ adam_matrix_target_list = attn_o_params +all_mlp_matrices
426
+ else:
427
+ raise ValueError(f"Unsupported EXPERIMENT_MODE: {current_optimizer_mode}")
428
+
429
+ # Adam optimizer setup
430
+ adam_param_groups_config = [
431
+ dict(params=head_params, lr=adam_matrix_lr),
432
+ # dict(params=embed_params, lr=adam_matrix_lr),
433
+ dict(params=scalar_params, lr=adam_matrix_lr) # Scalar params always go to Adam
434
+ ]
435
+ # Add matrices specifically assigned to Adam for this experiment mode
436
+ if adam_matrix_target_list:
437
+ # Ensure adam_matrix_target_list is flat and contains Parameters
438
+ flat_adam_matrices = [p for sublist_or_p in adam_matrix_target_list for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]) if p is not None]
439
+ if flat_adam_matrices: # Only add group if there are params
440
+ adam_param_groups_config.append(dict(params=flat_adam_matrices, lr=adam_matrix_lr))
441
+
442
+ # Filter out any Adam groups that might be empty (e.g., if scalar_params was empty)
443
+ adam_param_groups_config = [g for g in adam_param_groups_config if g['params']]
444
+ optimizer1 = torch.optim.Adam(adam_param_groups_config, betas=(0.9, 0.95), eps=1e-10, fused=True)
445
+ optimizers = [optimizer1] # Start with Adam
446
+
447
+ # Muon optimizer setup
448
+ # if muon_params_target_list:
449
+ # # Ensure muon_params_target_list is flat, unique, and contains Parameters
450
+ # flat_unique_muon_params = []
451
+ # seen_muon_ids = set()
452
+ # for sublist_or_p in muon_params_target_list:
453
+ # for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]):
454
+ # if p is not None and id(p) not in seen_muon_ids:
455
+ # flat_unique_muon_params.append(p)
456
+ # seen_muon_ids.add(id(p))
457
+
458
+ # muon_param_groups_config = []
459
+ # if flat_unique_muon_params:
460
+ # muon_param_groups_config.append(dict(params=flat_unique_muon_params, lr=exp_args.muon_lr))
461
+
462
+ # if flat_unique_muon_params: # Only create Muon if it has parameters
463
+ # optimizer2 = Muon(muon_param_groups_config, lr=exp_args.muon_lr, momentum=0.95,rank=ddp_rank, world_size=ddp_world_size) # Pass nesterov, ns_steps
464
+ # optimizers.append(optimizer2)
465
+ # else:
466
+ # print("PRINT: Muon optimizer not created as its target parameter list was empty.")
467
+ # optimizer2 = None # Explicitly set to None if not created
468
+ # else:
469
+ # print("PRINT: Muon optimizer not created as muon_params_target_list was empty (e.g. mode where Adam handles all matrices).")
470
+ # optimizer2 = None # Explicitly set to None
471
+ # Muon optimizer setup
472
+ if muon_params_target_list:
473
+ # Ensure muon_params_target_list is flat, unique, and contains Parameters
474
+ flat_unique_muon_params = []
475
+ seen_muon_ids = set()
476
+ for sublist_or_p in muon_params_target_list:
477
+ for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]):
478
+ if p is not None and id(p) not in seen_muon_ids:
479
+ flat_unique_muon_params.append(p)
480
+ seen_muon_ids.add(id(p))
481
+
482
+ if flat_unique_muon_params: # Only create Muon if it has parameters
483
+ optimizer2 = Muon(flat_unique_muon_params, lr=exp_args.muon_lr, momentum=0.95,rank=ddp_rank, world_size=ddp_world_size) # Pass nesterov, ns_steps
484
+ optimizers.append(optimizer2)
485
+ else:
486
+ print("PRINT: Muon optimizer not created as its target parameter list was empty.")
487
+ optimizer2 = None # Explicitly set to None if not created
488
+ else:
489
+ print("PRINT: Muon optimizer not created as muon_params_target_list was empty (e.g. mode where Adam handles all matrices).")
490
+ optimizer2 = None # Explicitly set to None
491
+
492
+ print(f"PRINT: Optimizers configured. Total optimizers: {len(optimizers)}")
493
+ if optimizer2:
494
+ print(f"PRINT: Muon optimizer is active with {len(flat_unique_muon_params)} parameters.")
495
+
496
+ # Set up parameter groups for SVD analysis
497
+ matrix_groups_for_svd = {}
498
+ if master_process:
499
+ matrix_groups_for_svd = {
500
+ "attn_qk": attn_qk_group,
501
+ "attn_vo": attn_vo_group,
502
+ "mlp_w1": mlp_w1_group,
503
+ "mlp_w2": mlp_w2_group
504
+ }
505
+
506
+ elif exp_args.model_parameterization == "gated":
507
+ print("PRINT: Collecting parameters for optimizers...")
508
+ head_params = [raw_model.lm_head.weight]
509
+ # embed_params = [raw_model.transformer.wte.weight]
510
+
511
+ # Granular collection for attention and MLP parts
512
+ attn_q_params = []
513
+ attn_k_params = []
514
+ attn_v_params = []
515
+ attn_o_params = [] # W_O from c_proj
516
+ mlp_fc_params = []
517
+ mlp_proj_params = []
518
+ mlp_up_params = []
519
+
520
+ for block_module in raw_model.transformer.h:
521
+ if block_module.attn is not None:
522
+ # These attributes (c_q, c_k, c_v) MUST exist in your CausalSelfAttention class
523
+ if hasattr(block_module.attn, 'c_q'): attn_q_params.append(block_module.attn.c_q.weight)
524
+ else:
525
+ print(f"PRINT: Warning: c_q not found in attn module of a block.")
526
+ if hasattr(block_module.attn, 'c_k'): attn_k_params.append(block_module.attn.c_k.weight)
527
+ else: print(f"PRINT: Warning: c_k not found in attn module of a block.")
528
+ if hasattr(block_module.attn, 'c_v'): attn_v_params.append(block_module.attn.c_v.weight)
529
+ else: print(f"PRINT: Warning: c_v not found in attn module of a block.")
530
+ attn_o_params.append(block_module.attn.c_proj.weight)
531
+ if block_module.mlp is not None:
532
+ mlp_fc_params.append(block_module.mlp.c_fc.weight)
533
+ mlp_proj_params.append(block_module.mlp.c_proj.weight)
534
+ mlp_up_params.append(block_module.mlp.c_up.weight)
535
+
536
+ # Combine into logical groups for experiments
537
+ attn_qk_group = attn_q_params + attn_k_params
538
+ attn_vo_group = attn_v_params + attn_o_params
539
+ all_attn_matrices = attn_qk_group + attn_vo_group
540
+ mlp_w1_group = mlp_fc_params
541
+ mlp_w2_group = mlp_proj_params
542
+ mlp_up_group = mlp_up_params
543
+ all_mlp_matrices = mlp_fc_params + mlp_proj_params+ mlp_up_params
544
+
545
+ # Scalar parameters (all others not explicitly grouped as matrices)
546
+ # matrix_params_for_scalar_check = set(head_params + embed_params + all_attn_matrices + all_mlp_matrices)
547
+ matrix_params_for_scalar_check = set(head_params + all_attn_matrices + all_mlp_matrices)
548
+ scalar_params = [p for n, p in raw_model.named_parameters() if p not in matrix_params_for_scalar_check]
549
+ for p_scalar in scalar_params: # Sanity check
550
+ if p_scalar.ndim >=2:
551
+ print(f"PRINT: Warning - Parameter {p_scalar.shape} ended up in scalar_params but has ndim >= 2. Check grouping.")
552
+
553
+
554
+ # Determine parameter distribution based on optimizer_mode
555
+ muon_params_target_list = []
556
+ adam_matrix_target_list = [] # Matrices that Adam will handle specifically
557
+ adam_matrix_lr = exp_args.adam_lr # LR for matrices if Adam handles them (can be tuned)
558
+
559
+ current_optimizer_mode = exp_args.optimizer_mode
560
+
561
+ print(f"PRINT: Configuring optimizers for EXPERIMENT_MODE = {current_optimizer_mode}")
562
+
563
+ if current_optimizer_mode == 0: # Original behavior: Muon on all "hidden_matrix_params"
564
+ print(f"PRINT: Mode 0: Muon on ALL Attention (QKVO) and ALL MLP matrices.")
565
+ muon_params_target_list = all_attn_matrices + all_mlp_matrices
566
+ # Adam handles embeds, head, scalars by default. No extra matrices for Adam here.
567
+ elif current_optimizer_mode == 1: # Muon on QK, Adam on VO and MLP
568
+ print(f"PRINT: Mode 1: Muon on QK Attn. Adam on VO Attn, MLP (Adam LR: {adam_matrix_lr}).")
569
+ muon_params_target_list = attn_qk_group
570
+ adam_matrix_target_list = attn_vo_group + all_mlp_matrices
571
+ elif current_optimizer_mode == 2: # Muon on VO, Adam on QK and MLP
572
+ print(f"PRINT: Mode 2: Muon on VO Attn. Adam on QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
573
+ muon_params_target_list = attn_vo_group
574
+ adam_matrix_target_list = attn_qk_group + all_mlp_matrices
575
+ elif current_optimizer_mode == 3: # Muon on All Attn (QKVO), Adam on MLP
576
+ print(f"PRINT: Mode 3: Muon on ALL Attn (QKVO). Adam on MLP (Adam LR: {adam_matrix_lr}).")
577
+ muon_params_target_list = all_attn_matrices
578
+ adam_matrix_target_list = all_mlp_matrices
579
+ elif current_optimizer_mode == 4: # Muon on MLP, Adam on All Attn (QKVO)
580
+ print(f"PRINT: Mode 4: Muon on MLP. Adam on ALL Attn (QKVO) (Adam LR: {adam_matrix_lr}).")
581
+ muon_params_target_list = all_mlp_matrices
582
+ adam_matrix_target_list = all_attn_matrices
583
+ elif current_optimizer_mode == 5: # NEW MODE 5 - All Adam
584
+ print(f"PRINT: Mode 5: All Adam. All Attn and MLP matrices to Adam (Adam LR: {adam_matrix_lr}).")
585
+ muon_params_target_list = []
586
+ adam_matrix_target_list = all_attn_matrices + all_mlp_matrices # All matrices to Adam
587
+ elif current_optimizer_mode == 6: # Muon on W_2 MLP, Adam on attn, W_1 MLP
588
+ print(f"PRINT: Mode 6: Muon on W_2 MLP. Adam on attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
589
+ muon_params_target_list = mlp_w2_group
590
+ adam_matrix_target_list = all_attn_matrices + mlp_w1_group
591
+ elif current_optimizer_mode == 7: # Muon on VO Attn, MLP, Adam on QK Attn
592
+ print(f"PRINT: Mode 7: Muon on VO Attn, MLP. Adam on QK Attn (Adam LR: {adam_matrix_lr}).")
593
+ muon_params_target_list = attn_vo_group + all_mlp_matrices
594
+ adam_matrix_target_list = attn_qk_group
595
+ elif current_optimizer_mode == 8: # Muon on VO Attn, W_2 MLP, Adam on QK Attn, W_1 MLP
596
+ print(f"PRINT: Mode 8: Muon on VO Attn, W_2 MLP. Adam on QK Attn, W_1 MLP (Adam LR: {adam_matrix_lr}).")
597
+ muon_params_target_list = attn_vo_group + mlp_w2_group
598
+ adam_matrix_target_list = attn_qk_group + mlp_w1_group
599
+ elif current_optimizer_mode == 9: # Muon on V Attn, MLP
600
+ print(f"PRINT: Mode 9: Muon on V Attn, MLP (Adam LR: {adam_matrix_lr}).")
601
+ muon_params_target_list = attn_v_params + all_mlp_matrices
602
+ adam_matrix_target_list = attn_o_params + attn_qk_group
603
+ elif current_optimizer_mode == 10: # Muon on O Attn, MLP
604
+ print(f"PRINT: Mode 10: Muon on O Attn, MLP (Adam LR: {adam_matrix_lr}).")
605
+ muon_params_target_list = attn_o_params + all_mlp_matrices
606
+ adam_matrix_target_list = attn_v_params + attn_qk_group
607
+ elif current_optimizer_mode == 11: # Muon on W_1, Adam on O Attn, QK Attn
608
+ print(f"PRINT: Mode 11: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
609
+ muon_params_target_list = mlp_w1_group
610
+ adam_matrix_target_list = all_attn_matrices + mlp_w2_group
611
+ elif current_optimizer_mode == 12: # Muon on W_1, VO, Adam on others
612
+ print(f"PRINT: Mode 11: Muon on W_1. Adam on O Attn, QK Attn (Adam LR: {adam_matrix_lr}).")
613
+ muon_params_target_list = attn_vo_group + mlp_w1_group
614
+ adam_matrix_target_list = attn_qk_group + mlp_w2_group
615
+ elif current_optimizer_mode == 13:
616
+ print(f"PRINT: Mode 13: Muon on W_2, W_O. Adam on V Attn, QK Attn, W_1 (Adam LR: {adam_matrix_lr}).")
617
+ muon_params_target_list = attn_o_params + mlp_w2_group
618
+ adam_matrix_target_list = attn_qk_group + attn_v_params + mlp_w1_group
619
+ elif current_optimizer_mode == 14:
620
+ print(f"PRINT: Mode 14: Muon on W_O. Adam on V Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
621
+ muon_params_target_list = attn_o_params
622
+ adam_matrix_target_list = attn_qk_group + attn_v_params +all_mlp_matrices
623
+ elif current_optimizer_mode == 15:
624
+ print(f"PRINT: Mode 15: Muon on W_V. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
625
+ muon_params_target_list = attn_v_params
626
+ adam_matrix_target_list = attn_qk_group + attn_o_params +all_mlp_matrices
627
+ elif current_optimizer_mode == 16:
628
+ print(f"PRINT: Mode 15: Muon on QKV. Adam on O Attn, QK Attn, MLP (Adam LR: {adam_matrix_lr}).")
629
+ muon_params_target_list = attn_v_params + attn_qk_group
630
+ adam_matrix_target_list = attn_o_params +all_mlp_matrices
631
+ else:
632
+ raise ValueError(f"Unsupported EXPERIMENT_MODE: {current_optimizer_mode}")
633
+
634
+ # Adam optimizer setup
635
+ adam_param_groups_config = [
636
+ dict(params=head_params, lr=adam_matrix_lr),
637
+ # dict(params=embed_params, lr=adam_matrix_lr),
638
+ dict(params=scalar_params, lr=adam_matrix_lr) # Scalar params always go to Adam
639
+ ]
640
+
641
+ # Add matrices specifically assigned to Adam for this experiment mode
642
+ if adam_matrix_target_list:
643
+ # Ensure adam_matrix_target_list is flat and contains Parameters
644
+ flat_adam_matrices = [p for sublist_or_p in adam_matrix_target_list for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]) if p is not None]
645
+ if flat_adam_matrices: # Only add group if there are params
646
+ adam_param_groups_config.append(dict(params=flat_adam_matrices, lr=adam_matrix_lr))
647
+
648
+ # Filter out any Adam groups that might be empty (e.g., if scalar_params was empty)
649
+ adam_param_groups_config = [g for g in adam_param_groups_config if g['params']]
650
+ # print(f"PRINT: The length of Adam param groups config: {len(adam_param_groups_config)}")
651
+ optimizer1 = torch.optim.Adam(adam_param_groups_config, betas=(0.9, 0.95), eps=1e-10, fused=True)
652
+ optimizers = [optimizer1] # Start with Adam
653
+
654
+
655
+ if muon_params_target_list:
656
+ # Ensure muon_params_target_list is flat, unique, and contains Parameters
657
+ flat_unique_muon_params = []
658
+ seen_muon_ids = set()
659
+ for sublist_or_p in muon_params_target_list:
660
+ for p in (sublist_or_p if isinstance(sublist_or_p, list) else [sublist_or_p]):
661
+ if p is not None and id(p) not in seen_muon_ids:
662
+ flat_unique_muon_params.append(p)
663
+ seen_muon_ids.add(id(p))
664
+
665
+ if flat_unique_muon_params: # Only create Muon if it has parameters
666
+ optimizer2 = Muon(flat_unique_muon_params, lr=exp_args.muon_lr, momentum=0.95,rank=ddp_rank, world_size=ddp_world_size) # Pass nesterov, ns_steps
667
+ optimizers.append(optimizer2)
668
+ else:
669
+ print("PRINT: Muon optimizer not created as its target parameter list was empty.")
670
+ optimizer2 = None # Explicitly set to None if not created
671
+ else:
672
+ print("PRINT: Muon optimizer not created as muon_params_target_list was empty (e.g. mode where Adam handles all matrices).")
673
+ optimizer2 = None # Explicitly set to None
674
+
675
+ print(f"PRINT: Optimizers configured. Total optimizers: {len(optimizers)}")
676
+ if optimizer2:
677
+ print(f"PRINT: Muon optimizer is active with {len(flat_unique_muon_params)} parameters.")
678
+
679
+ # Set up parameter groups for SVD analysis
680
+ matrix_groups_for_svd = {
681
+ "attn_qk": attn_qk_group,
682
+ "attn_vo": attn_vo_group,
683
+ "mlp_w1": mlp_w1_group, # c_fc only
684
+ "mlp_up": mlp_up_group, # c_up only
685
+ "mlp_w2": mlp_proj_params
686
+ }
687
+
688
+ # optimizer1 = torch.optim.AdamW(raw_model.lm_head.parameters(), lr=args.learning_rate, betas=(0.9, 0.95),
689
+ # weight_decay=args.weight_decay, fused=True)
690
+ # optimizer2 = Muon(raw_model.transformer.h.parameters(), lr=0.1*args.learning_rate, momentum=0.95,
691
+ # rank=ddp_rank, world_size=ddp_world_size)
692
+
693
+ # optimizers = [optimizer1, optimizer2]
694
+ # learning rate decay scheduler (linear warmup and warmdown)
695
+ def get_lr(it):
696
+ assert it <= args.num_iterations
697
+ # 1) linear warmup for warmup_iters steps
698
+ if it < args.warmup_iters:
699
+ return (it+1) / args.warmup_iters
700
+ # 2) constant lr for a while
701
+ elif it < args.num_iterations - args.warmdown_iters:
702
+ return 1.0
703
+ # 3) linear warmdown
704
+ else:
705
+ decay_ratio = (args.num_iterations - it) / args.warmdown_iters
706
+ return decay_ratio
707
+ schedulers = [torch.optim.lr_scheduler.LambdaLR(opt, get_lr) for opt in optimizers]
708
+
709
+ if master_process:
710
+ with open(logfile, "a") as f:
711
+ f.write(code)
712
+
713
+ training_time_ms = 0
714
+ # start the clock
715
+ torch.cuda.synchronize()
716
+ t0 = time.time()
717
+ # begin training
718
+ train_loader.reset()
719
+ for step in range(args.num_iterations + 1):
720
+ last_step = (step == args.num_iterations)
721
+ # This effectively ignores timing first 10 steps, which are slower for weird reasons.
722
+ # Alternately, and slightly more correctly in terms of benchmarking, we could do 10
723
+ # steps with dummy data first, and then re-initialize the model and reset the loader.
724
+ if step == 10:
725
+ training_time_ms = 0
726
+ t0 = time.time()
727
+ timed_steps = float('nan') if step <= 11 else (step - 10) + 1 # <= 11 to avoid bug in val
728
+
729
+ # once in a while evaluate the validation dataset
730
+ if (last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0)):
731
+ # stop the clock
732
+ torch.cuda.synchronize()
733
+ training_time_ms += 1000 * (time.time() - t0)
734
+ # run validation batches
735
+ with torch.no_grad():
736
+ val_loader.reset()
737
+ val_loss = 0.0
738
+ for _ in range(val_steps):
739
+ x_val, y_val = val_loader.next_batch()
740
+ with ctx: # of course, we'd like to use no_grad() here too, but that creates a torch.compile error for some reason
741
+ _, loss = model(x_val, y_val, return_logits=False)
742
+ val_loss += loss.detach()
743
+ del loss
744
+ dist.all_reduce(val_loss, op=dist.ReduceOp.AVG)
745
+ val_loss /= val_steps
746
+
747
+ # SVD metrics calculation
748
+ svd_log_str = ""
749
+ if master_process and 'matrix_groups_for_svd' in locals() and matrix_groups_for_svd:
750
+ TOPK = 10
751
+ svd_results_by_category = {}
752
+
753
+ with torch.no_grad():
754
+ # per-category metrics (average over matrices in the group)
755
+ for name, group_params in matrix_groups_for_svd.items():
756
+ if not group_params:
757
+ continue
758
+ mets = [calculate_svd_metrics(p, topk=TOPK) for p in group_params]
759
+ if mets:
760
+ avg_entropy = float(np.mean([m['entropy_norm'] for m in mets]))
761
+ avg_erank = float(np.mean([m['erank'] for m in mets]))
762
+ avg_topkE = float(np.mean([m['topk_energy'] for m in mets]))
763
+ avg_qratio = float(np.mean([m['q75_q25'] for m in mets]))
764
+ svd_results_by_category[name] = dict(
765
+ entropy=avg_entropy, erank=avg_erank, topkE=avg_topkE, q75_q25=avg_qratio
766
+ )
767
+
768
+ # VO product as another category
769
+ if attn_v_params and attn_o_params:
770
+ vo_mets = []
771
+ num_layers = len(attn_v_params)
772
+ for i in range(num_layers):
773
+ w_v = attn_v_params[i]
774
+ w_o = attn_o_params[i]
775
+ w_ov_product = torch.matmul(w_o, w_v)
776
+ vo_mets.append(calculate_svd_metrics(w_ov_product, topk=TOPK))
777
+ if vo_mets:
778
+ svd_results_by_category['vo_prod'] = dict(
779
+ entropy=float(np.mean([m['entropy_norm'] for m in vo_mets])),
780
+ erank=float(np.mean([m['erank'] for m in vo_mets])),
781
+ topkE=float(np.mean([m['topk_energy'] for m in vo_mets])),
782
+ q75_q25=float(np.mean([m['q75_q25'] for m in vo_mets])),
783
+ )
784
+
785
+ # format logging string (append metrics after entropy)
786
+ svd_log_parts = []
787
+ for name, vals in svd_results_by_category.items():
788
+ svd_log_parts.append(
789
+ f"{name}:H={vals['entropy']:.4f},top{TOPK}E={vals['topkE']:.2f},eRank={vals['erank']:.1f},q75/q25={vals['q75_q25']:.2f}"
790
+ )
791
+ svd_log_str = " ".join(svd_log_parts)
792
+
793
+ # log val loss to console and to logfile
794
+ if master_process:
795
+ print(f'step:{step}/{args.num_iterations} val_loss:{val_loss:.4f} svd_entropy: {svd_log_str} train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms/(timed_steps-1):.2f}ms')
796
+ with open(logfile, "a") as f:
797
+ f.write(f'step:{step}/{args.num_iterations} val_loss:{val_loss:.4f} svd_entropy: {svd_log_str} train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms/(timed_steps-1):.2f}ms\n')
798
+ # start the clock again
799
+ torch.cuda.synchronize()
800
+ t0 = time.time()
801
+
802
+ if master_process and (last_step or (args.save_every > 0 and step % args.save_every == 0)):
803
+ # stop the clock
804
+ torch.cuda.synchronize()
805
+ training_time_ms += 1000 * (time.time() - t0)
806
+ # save the state of the training process
807
+ log = dict(step=step, code=code, model=raw_model.state_dict(), optimizers=[opt.state_dict() for opt in optimizers])
808
+ if run_dir_path_str:
809
+ save_path = f'{run_dir_path_str}/state_step{step:06d}.pt'
810
+ torch.save(log, save_path)
811
+ # start the clock again
812
+ torch.cuda.synchronize()
813
+ t0 = time.time()
814
+
815
+ # bit confusing: we want to make sure to eval on 0th iteration
816
+ # but also after the very last iteration. so we loop for step <= num_iterations
817
+ # instead of just < num_iterations (one extra due to <=), only to do
818
+ # the validation/sampling one last time, and then we break right here as we're done.
819
+ if last_step:
820
+ break
821
+
822
+ # --------------- TRAINING SECTION BEGIN -----------------
823
+ model.train()
824
+ for i in range(1, train_accumulation_steps+1):
825
+ # forward pass
826
+ with ctx:
827
+ _, loss = model(x, y, return_logits=False)
828
+ train_loss = loss.detach()
829
+ # advance the dataset for the next batch
830
+ x, y = train_loader.next_batch()
831
+ # backward pass
832
+ if i < train_accumulation_steps:
833
+ with model.no_sync(): # there's no need to sync gradients every accumulation step
834
+ loss.backward()
835
+ else:
836
+ loss.backward() # just sync on the last step
837
+ for p in model.parameters():
838
+ p.grad /= train_accumulation_steps
839
+ # step the optimizers and schedulers
840
+ for opt, sched in zip(optimizers, schedulers):
841
+ opt.step()
842
+ sched.step()
843
+ # null the gradients
844
+ model.zero_grad(set_to_none=True)
845
+ # --------------- TRAINING SECTION END -------------------
846
+ # everything that follows now is just diagnostics, prints, logging, etc.
847
+
848
+ #dist.all_reduce(train_loss, op=dist.ReduceOp.AVG) # all-reducing the training loss would be more correct in terms of logging, but slower
849
+ if master_process:
850
+ approx_time = training_time_ms + 1000 * (time.time() - t0)
851
+ print(f"step:{step+1}/{args.num_iterations} train_loss:{train_loss.item():.4f} train_time:{approx_time:.0f}ms step_avg:{approx_time/timed_steps:.2f}ms")
852
+ with open(logfile, "a") as f:
853
+ f.write(f"step:{step+1}/{args.num_iterations} train_loss:{train_loss.item():.4f} train_time:{approx_time:.0f}ms step_avg:{approx_time/timed_steps:.2f}ms\n")
854
+
855
+ if master_process:
856
+ print(f"peak memory consumption: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB")