w-ahmad commited on
Commit
bd199de
·
verified ·
1 Parent(s): afeec66

Auto upload zain 2026-08-18T15:12:06.051058

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. zain/Activation/README.md +1 -0
  2. zain/Activation/__pycache__/exp.cpython-311.pyc +0 -0
  3. zain/Activation/exp.py +953 -0
  4. zain/Activation/grad.py +571 -0
  5. zain/Activation/llm_analyzer_wandb.py +1307 -0
  6. zain/Activation/out/glu-relu-21L_run/checkpoint-100/config.json +37 -0
  7. zain/Activation/out/glu-relu-21L_run/checkpoint-100/model.safetensors +3 -0
  8. zain/Activation/out/glu-relu-21L_run/checkpoint-100/optimizer.pt +3 -0
  9. zain/Activation/out/glu-relu-21L_run/checkpoint-100/rng_state.pth +3 -0
  10. zain/Activation/out/glu-relu-21L_run/checkpoint-100/scheduler.pt +3 -0
  11. zain/Activation/out/glu-relu-21L_run/checkpoint-100/tokenizer.json +0 -0
  12. zain/Activation/out/glu-relu-21L_run/checkpoint-100/tokenizer_config.json +13 -0
  13. zain/Activation/out/glu-relu-21L_run/checkpoint-100/trainer_state.json +77 -0
  14. zain/Activation/out/glu-relu-21L_run/checkpoint-100/training_args.bin +3 -0
  15. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/config.json +37 -0
  16. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/model.safetensors +3 -0
  17. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/optimizer.pt +3 -0
  18. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/rng_state.pth +3 -0
  19. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/scheduler.pt +3 -0
  20. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/tokenizer.json +0 -0
  21. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/tokenizer_config.json +13 -0
  22. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/trainer_state.json +464 -0
  23. zain/Activation/out/glu-relu-21L_run/checkpoint-1000/training_args.bin +3 -0
  24. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/config.json +37 -0
  25. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/model.safetensors +3 -0
  26. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/optimizer.pt +3 -0
  27. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/rng_state.pth +3 -0
  28. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/scheduler.pt +3 -0
  29. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/tokenizer.json +0 -0
  30. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/tokenizer_config.json +13 -0
  31. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/trainer_state.json +507 -0
  32. zain/Activation/out/glu-relu-21L_run/checkpoint-1100/training_args.bin +3 -0
  33. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/config.json +37 -0
  34. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/model.safetensors +3 -0
  35. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/optimizer.pt +3 -0
  36. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/rng_state.pth +3 -0
  37. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/scheduler.pt +3 -0
  38. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/tokenizer.json +0 -0
  39. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/tokenizer_config.json +13 -0
  40. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/trainer_state.json +550 -0
  41. zain/Activation/out/glu-relu-21L_run/checkpoint-1200/training_args.bin +3 -0
  42. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/config.json +37 -0
  43. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/model.safetensors +3 -0
  44. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/optimizer.pt +3 -0
  45. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/rng_state.pth +3 -0
  46. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/scheduler.pt +3 -0
  47. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/tokenizer.json +0 -0
  48. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/tokenizer_config.json +13 -0
  49. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/trainer_state.json +593 -0
  50. zain/Activation/out/glu-relu-21L_run/checkpoint-1300/training_args.bin +3 -0
zain/Activation/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # Activation
zain/Activation/__pycache__/exp.cpython-311.pyc ADDED
Binary file (63.7 kB). View file
 
zain/Activation/exp.py ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================================
2
+ # exp.py
3
+ # =====================================================================
4
+
5
+ import math
6
+ import os
7
+ import time
8
+ import json
9
+ import re
10
+ from pathlib import Path
11
+ from itertools import chain
12
+ from typing import Dict, Callable, Optional, List, Any, Tuple
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ from transformers import (
17
+ LlamaConfig,
18
+ LlamaPreTrainedModel,
19
+ Trainer,
20
+ TrainerCallback,
21
+ TrainingArguments,
22
+ DataCollatorForLanguageModeling,
23
+ AutoTokenizer,
24
+ set_seed,
25
+ )
26
+ from transformers.models.llama.modeling_llama import (
27
+ LlamaAttention,
28
+ LlamaRMSNorm,
29
+ LlamaRotaryEmbedding,
30
+ )
31
+ from transformers.modeling_outputs import CausalLMOutputWithPast
32
+ from datasets import load_dataset
33
+ from huggingface_hub import snapshot_download
34
+
35
+
36
+ # =============================================================================
37
+ # 1. ACTIVATION REGISTRY
38
+ # =============================================================================
39
+
40
+ class GLUActivationRegistry:
41
+ _registry: Dict[str, Callable[[torch.Tensor], torch.Tensor]] = {}
42
+
43
+ @classmethod
44
+ def register(cls, name: str, fn: Callable[[torch.Tensor], torch.Tensor]) -> None:
45
+ cls._registry[name] = fn
46
+
47
+ @classmethod
48
+ def get(cls, name: str) -> Callable[[torch.Tensor], torch.Tensor]:
49
+ if name not in cls._registry:
50
+ raise KeyError(
51
+ f"Activation '{name}' not found. Available: {list(cls._registry.keys())}"
52
+ )
53
+ return cls._registry[name]
54
+
55
+ # Built-ins
56
+ GLUActivationRegistry.register("silu", nn.functional.silu)
57
+ GLUActivationRegistry.register("swish", nn.functional.silu)
58
+ GLUActivationRegistry.register("relu", nn.functional.relu)
59
+ GLUActivationRegistry.register("gelu", nn.functional.gelu)
60
+ GLUActivationRegistry.register("sigmoid", torch.sigmoid)
61
+ GLUActivationRegistry.register("tanh", torch.tanh)
62
+ GLUActivationRegistry.register("softplus", nn.functional.softplus)
63
+ GLUActivationRegistry.register("linear", lambda x: x)
64
+ GLUActivationRegistry.register("s10", lambda x: x * x * torch.sigmoid(x))
65
+ GLUActivationRegistry.register("w1a", lambda x: x * torch.tanh(x))
66
+
67
+
68
+ # =============================================================================
69
+ # 2. CONFIG
70
+ # =============================================================================
71
+
72
+ class TinyLlamaConfig(LlamaConfig):
73
+ model_type = "tiny_llama"
74
+
75
+ def __init__(
76
+ self,
77
+ mlp_type: str = "glu",
78
+ activation: str = "silu",
79
+ waleed_beta: float = 10.0,
80
+ powlu_m: float = 3.0, # <-- NEW: PowLU hyperparameter
81
+ **kwargs
82
+ ):
83
+ super().__init__(**kwargs)
84
+ self.mlp_type = mlp_type
85
+ self.activation = activation
86
+ self.waleed_beta = waleed_beta
87
+ self.powlu_m = powlu_m # <-- store it
88
+ if self.num_key_value_heads != self.num_attention_heads:
89
+ raise ValueError(
90
+ f"Pure MHA required: num_key_value_heads ({self.num_key_value_heads}) "
91
+ f"must equal num_attention_heads ({self.num_attention_heads})."
92
+ )
93
+
94
+
95
+ # =============================================================================
96
+ # 3. MODEL (with PowLU)
97
+ # =============================================================================
98
+
99
+ class TinyLlamaMLP(nn.Module):
100
+ override_active = False
101
+ override_value = -100.0
102
+
103
+ def __init__(self, config: TinyLlamaConfig):
104
+ super().__init__()
105
+ self.hidden_size = config.hidden_size
106
+ self.intermediate_size = config.intermediate_size
107
+ self.mlp_type = config.mlp_type
108
+ self.activation_name = config.activation
109
+ self.waleed_beta = getattr(config, "waleed_beta", 10.0)
110
+ self.powlu_m = getattr(config, "powlu_m", 3.0) # <-- store m
111
+
112
+ if self.mlp_type == "glu":
113
+ effective_intermediate = self.intermediate_size
114
+ elif self.mlp_type == "mlp":
115
+ effective_intermediate = int(self.intermediate_size * 1.5)
116
+ print(f"[MLP] Auto‑scaled intermediate_size from {self.intermediate_size} to {effective_intermediate}")
117
+ else:
118
+ raise ValueError(f"Unknown mlp_type: {self.mlp_type}")
119
+
120
+ self.effective_intermediate = effective_intermediate
121
+
122
+ if self.mlp_type == "glu":
123
+ self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
124
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
125
+ else:
126
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
127
+
128
+ self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
129
+
130
+ # ---- Activation flags ----
131
+ self.is_powlu = (self.activation_name == "powlu") # <-- NEW
132
+ self.is_situglu = self.activation_name in ("situglu", "situglu_low")
133
+ self.is_waleed = self.activation_name in ("waleed", "waleedglu_low")
134
+ self.is_waleed10 = self.activation_name in ("waleed10", "silu-waleed10")
135
+ self.has_sigmoid_gate = self.activation_name.startswith("situglu")
136
+
137
+ # ---- Activation function (for non-PowLU) ----
138
+ if self.mlp_type == "glu":
139
+ if self.is_powlu:
140
+ # PowLU handled in forward, no act_fn needed
141
+ self.act_fn = None
142
+ elif self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
143
+ self.act_fn = None # custom handling
144
+ elif self.activation_name == "waleed10":
145
+ self.act_fn = GLUActivationRegistry.get("linear")
146
+ elif self.activation_name == "silu-waleed10":
147
+ self.act_fn = GLUActivationRegistry.get("silu")
148
+ else:
149
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
150
+ else: # mlp
151
+ if self.is_powlu:
152
+ raise ValueError("PowLU is only supported with mlp_type='glu'")
153
+ if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
154
+ raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
155
+ elif self.activation_name == "waleed10":
156
+ self.act_fn = GLUActivationRegistry.get("linear")
157
+ elif self.activation_name == "silu-waleed10":
158
+ self.act_fn = GLUActivationRegistry.get("silu")
159
+ else:
160
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
161
+
162
+ # beta values for situglu/waleed
163
+ if self.activation_name in ("situglu_low", "waleedglu_low"):
164
+ self.beta1 = 2.5
165
+ self.beta2 = 4.0
166
+ else:
167
+ self.beta1 = 4.0
168
+ self.beta2 = 25.0
169
+
170
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
171
+ if self.mlp_type == "glu":
172
+ gate = self.gate_proj(x)
173
+ up = self.up_proj(x)
174
+
175
+ # ----- PowLU branch (FIXED: safe sqrt/pow to avoid NaN-gradient leak) -----
176
+ if self.is_powlu:
177
+ m = self.powlu_m
178
+ sig_gate = torch.sigmoid(gate)
179
+ pos_mask = gate > 0
180
+
181
+ # Clamp ONLY for the pow/sqrt computation so negative values never
182
+ # reach sqrt(); the real `gate` tensor is left untouched everywhere else.
183
+ safe_gate = torch.clamp(gate, min=1e-6)
184
+
185
+ # For positive: gate^(m/(sqrt(gate)+1)) * sigmoid(gate)
186
+ powlu_pos = safe_gate ** (m / (torch.sqrt(safe_gate) + 1)) * sig_gate
187
+ # For non-positive: gate * sigmoid(gate) (= SiLU)
188
+ powlu_neg = gate * sig_gate
189
+ activated_gate = torch.where(pos_mask, powlu_pos, powlu_neg)
190
+ hidden = activated_gate * up
191
+
192
+ # ----- situglu / waleed branches (unchanged) -----
193
+ elif self.is_situglu or self.is_waleed:
194
+ if self.has_sigmoid_gate:
195
+ gate = self.beta1 * torch.tanh(gate / self.beta1) * torch.sigmoid(gate)
196
+ else:
197
+ gate = self.beta1 * torch.tanh(gate / self.beta1)
198
+ up = self.beta2 * torch.tanh(up / self.beta2)
199
+ hidden = gate * up
200
+
201
+ # ----- Standard GLU (ReLU, GELU, SiLU, etc.) -----
202
+ else:
203
+ hidden = self.act_fn(gate) * up
204
+
205
+ out = self.down_proj(hidden)
206
+
207
+ else: # mlp
208
+ hidden = self.act_fn(self.up_proj(x))
209
+ out = self.down_proj(hidden)
210
+
211
+ # Optional Waleed clipping after down projection
212
+ if self.is_waleed10:
213
+ out = self.waleed_beta * torch.tanh(out / self.waleed_beta)
214
+
215
+ # Override hook (unchanged)
216
+ if TinyLlamaMLP.override_active and out.requires_grad:
217
+ out.register_hook(lambda grad: TinyLlamaMLP.override_value * torch.ones_like(grad))
218
+
219
+ return out
220
+
221
+
222
+ # ----------------------------------------------------------------------------
223
+ # DECODER LAYER, ATTENTION MASK, MODEL (unchanged)
224
+ # ----------------------------------------------------------------------------
225
+
226
+ class TinyLlamaDecoderLayer(nn.Module):
227
+ def __init__(self, config: TinyLlamaConfig, layer_idx: int):
228
+ super().__init__()
229
+ self.hidden_size = config.hidden_size
230
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
231
+ self.mlp = TinyLlamaMLP(config)
232
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
233
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
234
+ self.residual_pre_attn = nn.Identity()
235
+ self.residual_post_attn = nn.Identity()
236
+ self.residual_post_mlp = nn.Identity()
237
+
238
+ def forward(self, hidden_states, attention_mask=None, position_ids=None, position_embeddings=None, **kwargs):
239
+ residual = hidden_states
240
+ hidden_states = self.residual_pre_attn(hidden_states)
241
+ hidden_states = self.input_layernorm(hidden_states)
242
+ attn_out = self.self_attn(
243
+ hidden_states=hidden_states,
244
+ attention_mask=attention_mask,
245
+ position_ids=position_ids,
246
+ position_embeddings=position_embeddings,
247
+ )[0]
248
+ hidden_states = residual + attn_out
249
+ hidden_states = self.residual_post_attn(hidden_states)
250
+
251
+ residual = hidden_states
252
+ hidden_states = self.post_attention_layernorm(hidden_states)
253
+ hidden_states = self.mlp(hidden_states)
254
+ hidden_states = residual + hidden_states
255
+ hidden_states = self.residual_post_mlp(hidden_states)
256
+ return (hidden_states,)
257
+
258
+
259
+ def _build_causal_mask(attention_mask, seq_len, dtype, device):
260
+ min_value = torch.finfo(dtype).min
261
+ causal = torch.full((seq_len, seq_len), fill_value=min_value, dtype=dtype, device=device)
262
+ causal = torch.triu(causal, diagonal=1)
263
+ causal = causal[None, None, :, :]
264
+ if attention_mask is None:
265
+ batch_size = 1
266
+ return causal.expand(batch_size, 1, seq_len, seq_len)
267
+ batch_size = attention_mask.shape[0]
268
+ causal = causal.expand(batch_size, 1, seq_len, seq_len).clone()
269
+ padding = attention_mask[:, None, None, :].to(device) == 0
270
+ causal = causal.masked_fill(padding, min_value)
271
+ return causal
272
+
273
+
274
+ _MASK_PRINTED = False
275
+
276
+
277
+ class TinyLlamaModel(LlamaPreTrainedModel):
278
+ config_class = TinyLlamaConfig
279
+
280
+ def __init__(self, config: TinyLlamaConfig):
281
+ super().__init__(config)
282
+ self.padding_idx = config.pad_token_id
283
+ self.vocab_size = config.vocab_size
284
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
285
+ self.layers = nn.ModuleList([TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
286
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
287
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
288
+ self.post_init()
289
+
290
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None, return_dict=None, **kwargs):
291
+ global _MASK_PRINTED
292
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
293
+ if inputs_embeds is None:
294
+ inputs_embeds = self.embed_tokens(input_ids)
295
+ if position_ids is None:
296
+ seq_len = inputs_embeds.shape[1]
297
+ position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0).expand(inputs_embeds.shape[0], -1)
298
+ hidden_states = inputs_embeds
299
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
300
+ seq_len = hidden_states.shape[1]
301
+ causal_mask = _build_causal_mask(attention_mask, seq_len, hidden_states.dtype, hidden_states.device)
302
+ if not _MASK_PRINTED:
303
+ print("[INFO] Causal mask (float with -inf) applied to all attention layers.")
304
+ _MASK_PRINTED = True
305
+ for decoder_layer in self.layers:
306
+ layer_outputs = decoder_layer(
307
+ hidden_states,
308
+ attention_mask=causal_mask,
309
+ position_ids=position_ids,
310
+ position_embeddings=position_embeddings,
311
+ )
312
+ hidden_states = layer_outputs[0]
313
+ hidden_states = self.norm(hidden_states)
314
+ if not return_dict:
315
+ return (hidden_states,)
316
+ return {"last_hidden_state": hidden_states, "hidden_states": None, "attentions": None}
317
+
318
+
319
+ class TinyLlamaForCausalLM(LlamaPreTrainedModel):
320
+ config_class = TinyLlamaConfig
321
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
322
+
323
+ def __init__(self, config: TinyLlamaConfig):
324
+ super().__init__(config)
325
+ self.model = TinyLlamaModel(config)
326
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
327
+ if config.tie_word_embeddings:
328
+ self.lm_head.weight = self.model.embed_tokens.weight
329
+ self.post_init()
330
+
331
+ def get_input_embeddings(self):
332
+ return self.model.embed_tokens
333
+
334
+ def set_input_embeddings(self, value):
335
+ self.model.embed_tokens = value
336
+
337
+ def get_output_embeddings(self):
338
+ return self.lm_head
339
+
340
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
341
+ labels=None, return_dict=None, **kwargs):
342
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
343
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids,
344
+ inputs_embeds=inputs_embeds, return_dict=return_dict)
345
+ hidden_states = outputs["last_hidden_state"] if return_dict else outputs[0]
346
+ logits = self.lm_head(hidden_states)
347
+ loss = None
348
+ if labels is not None:
349
+ shift_logits = logits[..., :-1, :].contiguous()
350
+ shift_labels = labels[..., 1:].contiguous()
351
+ loss_fct = nn.CrossEntropyLoss()
352
+ loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
353
+ if not return_dict:
354
+ output = (logits,) + outputs[1:]
355
+ return (loss,) + output if loss is not None else output
356
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None, hidden_states=None, attentions=None)
357
+
358
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
359
+ if past_key_values:
360
+ input_ids = input_ids[:, -1:]
361
+ position_ids = kwargs.get("position_ids")
362
+ if attention_mask is not None and position_ids is None:
363
+ position_ids = attention_mask.long().cumsum(-1) - 1
364
+ position_ids.masked_fill_(attention_mask == 0, 1)
365
+ if past_key_values:
366
+ position_ids = position_ids[:, -1].unsqueeze(-1)
367
+ return {
368
+ "input_ids": input_ids,
369
+ "position_ids": position_ids,
370
+ "past_key_values": past_key_values,
371
+ "attention_mask": attention_mask,
372
+ }
373
+
374
+
375
+ # =============================================================================
376
+ # 4. HF CHECKPOINT FETCHER (unchanged)
377
+ # =============================================================================
378
+
379
+ def fetch_latest_checkpoint_from_hub(
380
+ repo_id: str,
381
+ subpath: str,
382
+ variant: str,
383
+ checkpoint_step: Optional[int] = None
384
+ ) -> str:
385
+ remote_prefix = f"{subpath}/{variant}_run" if subpath else f"{variant}_run"
386
+ if checkpoint_step is not None:
387
+ full_remote_path = f"{remote_prefix}/checkpoint-{checkpoint_step}"
388
+ print(f"[Hub] Fetching specific checkpoint: {repo_id}/{full_remote_path}")
389
+ local_root = snapshot_download(
390
+ repo_id=repo_id,
391
+ allow_patterns=[f"{full_remote_path}/*"],
392
+ local_dir_use_symlinks=False,
393
+ )
394
+ checkpoint_local_path = os.path.join(local_root, full_remote_path)
395
+ if not os.path.exists(checkpoint_local_path):
396
+ raise RuntimeError(f"Downloaded checkpoint not found at {checkpoint_local_path}")
397
+ return checkpoint_local_path
398
+
399
+ print(f"[Hub] Downloading entire run folder: {repo_id}/{remote_prefix}")
400
+ local_root = snapshot_download(
401
+ repo_id=repo_id,
402
+ allow_patterns=[f"{remote_prefix}/*"],
403
+ local_dir_use_symlinks=False,
404
+ )
405
+ run_local_path = os.path.join(local_root, remote_prefix)
406
+ if not os.path.exists(run_local_path):
407
+ raise RuntimeError(f"Run folder not found at {run_local_path}")
408
+
409
+ checkpoints = []
410
+ for item in os.listdir(run_local_path):
411
+ if item.startswith("checkpoint-") and os.path.isdir(os.path.join(run_local_path, item)):
412
+ match = re.match(r"checkpoint-(\d+)", item)
413
+ if match:
414
+ step = int(match.group(1))
415
+ checkpoints.append((step, item))
416
+
417
+ if not checkpoints:
418
+ raise RuntimeError(f"No checkpoint folders found in {run_local_path}")
419
+
420
+ latest_step, latest_name = max(checkpoints, key=lambda x: x[0])
421
+ print(f"[Hub] Latest checkpoint found: step {latest_step}")
422
+ return os.path.join(run_local_path, latest_name)
423
+
424
+
425
+ # =============================================================================
426
+ # 5. RESUME + FREEZE + OVERRIDE CALLBACK (unchanged)
427
+ # =============================================================================
428
+
429
+ class ResumeFreezeOverrideCallback(TrainerCallback):
430
+ def __init__(self, override_value: Optional[float] = None):
431
+ self.override_value = override_value
432
+ self._trainer = None # Will be set manually
433
+
434
+ def on_train_begin(self, args, state, control, **kwargs):
435
+ # Try multiple ways to get the trainer
436
+ trainer = kwargs.get('trainer')
437
+ if trainer is None:
438
+ trainer = getattr(self, '_trainer', None)
439
+ if trainer is None:
440
+ trainer = getattr(self, 'trainer', None)
441
+ if trainer is None:
442
+ raise ValueError("Trainer not accessible in callback")
443
+
444
+ model = trainer.model
445
+
446
+ # ----- FREEZE ALL EXCEPT MLP PROJECTIONS -----
447
+ for name, param in model.named_parameters():
448
+ if any(x in name for x in ["gate_proj", "up_proj", "down_proj"]):
449
+ param.requires_grad = True
450
+ else:
451
+ param.requires_grad = False
452
+
453
+ trainable_params = [p for p in model.parameters() if p.requires_grad]
454
+
455
+ # ----- REBUILD OPTIMIZER -----
456
+ from torch.optim import AdamW
457
+ new_optimizer = AdamW(
458
+ trainable_params,
459
+ lr=args.learning_rate,
460
+ weight_decay=args.weight_decay,
461
+ betas=(args.adam_beta1, args.adam_beta2),
462
+ eps=args.adam_epsilon,
463
+ )
464
+ trainer.optimizer = new_optimizer
465
+
466
+ # ----- KEEP EXISTING SCHEDULER (re‑attach) -----
467
+ if trainer.lr_scheduler is not None:
468
+ trainer.lr_scheduler.optimizer = new_optimizer
469
+
470
+ # ----- ACTIVATE OVERRIDE -----
471
+ if self.override_value is not None:
472
+ TinyLlamaMLP.override_active = True
473
+ TinyLlamaMLP.override_value = self.override_value
474
+ print(f"[Override] Activated with value = {self.override_value}")
475
+ else:
476
+ print("[Freeze] MLP projections frozen; no gradient override.")
477
+
478
+
479
+ # =============================================================================
480
+ # 6. MONITORING (unchanged)
481
+ # =============================================================================
482
+
483
+ class StatsEngine:
484
+ @staticmethod
485
+ def compute(tensor: torch.Tensor, user_limit: float, dtype_ratio: float) -> Dict[str, float]:
486
+ with torch.no_grad():
487
+ abs_t = tensor.abs()
488
+ dtype_info = torch.finfo(tensor.dtype)
489
+ dtype_limit = dtype_ratio * dtype_info.max if not torch.isinf(torch.tensor(dtype_info.max)) else float("inf")
490
+ return {
491
+ "norm": tensor.norm(2).item(),
492
+ "mean": tensor.mean().item(),
493
+ "std": tensor.std().item(),
494
+ "max_abs": abs_t.max().item(),
495
+ "frac_near_dtype_limit": (abs_t > dtype_limit).float().mean().item() if not math.isinf(dtype_limit) else 0.0,
496
+ "frac_near_user_limit": (abs_t > user_limit).float().mean().item(),
497
+ "min": tensor.min().item(),
498
+ "max": tensor.max().item(),
499
+ "range": tensor.max().item() - tensor.min().item(),
500
+ }
501
+
502
+
503
+ class StepAccumulator:
504
+ def __init__(self):
505
+ self.tensors: Dict[str, Dict[str, float]] = {}
506
+
507
+ def add(self, name: str, numel: int, stats: Dict[str, float]):
508
+ new_entry = {"numel": numel, **stats}
509
+ existing = self.tensors.get(name)
510
+ self.tensors[name] = new_entry if existing is None else self._merge_entry(existing, new_entry)
511
+
512
+ @staticmethod
513
+ def _merge_entry(a: Dict[str, float], b: Dict[str, float]) -> Dict[str, float]:
514
+ total_n = a["numel"] + b["numel"]
515
+ if total_n == 0:
516
+ return a
517
+ norm = math.sqrt(a["norm"] ** 2 + b["norm"] ** 2)
518
+ max_abs = max(a["max_abs"], b["max_abs"])
519
+ mean = (a["mean"] * a["numel"] + b["mean"] * b["numel"]) / total_n
520
+ ex2 = (a["numel"] * (a["std"] ** 2 + a["mean"] ** 2) + b["numel"] * (b["std"] ** 2 + b["mean"] ** 2)) / total_n
521
+ std = math.sqrt(max(0.0, ex2 - mean ** 2))
522
+ frac_dtype = (a["frac_near_dtype_limit"] * a["numel"] + b["frac_near_dtype_limit"] * b["numel"]) / total_n
523
+ frac_user = (a["frac_near_user_limit"] * a["numel"] + b["frac_near_user_limit"] * b["numel"]) / total_n
524
+ t_min = min(a.get("min", float("inf")), b.get("min", float("inf")))
525
+ t_max = max(a.get("max", float("-inf")), b.get("max", float("-inf")))
526
+ return {
527
+ "numel": total_n,
528
+ "norm": norm,
529
+ "mean": mean,
530
+ "std": std,
531
+ "max_abs": max_abs,
532
+ "frac_near_dtype_limit": frac_dtype,
533
+ "frac_near_user_limit": frac_user,
534
+ "min": t_min,
535
+ "max": t_max,
536
+ "range": t_max - t_min,
537
+ }
538
+
539
+ def clear(self):
540
+ self.tensors.clear()
541
+
542
+ def _aggregate(self, entries: Dict[str, Dict[str, float]]) -> Dict[str, float]:
543
+ if not entries:
544
+ return {}
545
+ numels = [e["numel"] for e in entries.values()]
546
+ total_n = sum(numels)
547
+ norm = math.sqrt(sum(e["norm"] ** 2 for e in entries.values()))
548
+ max_abs = max(e["max_abs"] for e in entries.values())
549
+ mean = sum(e["mean"] * e["numel"] for e in entries.values()) / total_n
550
+ ex2 = sum(e["numel"] * (e["std"] ** 2 + e["mean"] ** 2) for e in entries.values()) / total_n
551
+ std = math.sqrt(max(0.0, ex2 - mean ** 2))
552
+ frac_dtype = sum(e["frac_near_dtype_limit"] * e["numel"] for e in entries.values()) / total_n
553
+ frac_user = sum(e["frac_near_user_limit"] * e["numel"] for e in entries.values()) / total_n
554
+ t_min = min(e.get("min", float("inf")) for e in entries.values())
555
+ t_max = max(e.get("max", float("-inf")) for e in entries.values())
556
+ return {
557
+ "norm": norm,
558
+ "mean": mean,
559
+ "std": std,
560
+ "max_abs": max_abs,
561
+ "frac_near_dtype_limit": frac_dtype,
562
+ "frac_near_user_limit": frac_user,
563
+ "min": t_min,
564
+ "max": t_max,
565
+ "range": t_max - t_min,
566
+ }
567
+
568
+ def get_global_stats(self) -> Dict[str, float]:
569
+ return self._aggregate(self.tensors)
570
+
571
+ def get_layer_stats(self, layer_prefix: str) -> Dict[str, float]:
572
+ entries = {k: v for k, v in self.tensors.items() if k.startswith(layer_prefix + ".")}
573
+ return self._aggregate(entries)
574
+
575
+
576
+ class HookRegistry:
577
+ def __init__(self, model: nn.Module):
578
+ self.model = model
579
+ self.handles = []
580
+ self.active = False
581
+
582
+ def attach_forward(self, module_patterns, accumulator, user_limit, dtype_ratio):
583
+ for name, module in self.model.named_modules():
584
+ if any(re.search(p, name) for p in module_patterns):
585
+ h = module.register_forward_hook(
586
+ self._make_forward_hook(name, accumulator, user_limit, dtype_ratio)
587
+ )
588
+ self.handles.append(h)
589
+
590
+ def attach_backward(self, param_patterns, accumulator, user_limit, dtype_ratio):
591
+ for name, param in self.model.named_parameters():
592
+ if not param.requires_grad:
593
+ continue
594
+ if param_patterns and not any(re.search(p, name) for p in param_patterns):
595
+ continue
596
+ h = param.register_hook(
597
+ self._make_backward_hook(f"grad.{name}", accumulator, user_limit, dtype_ratio)
598
+ )
599
+ self.handles.append(h)
600
+
601
+ def _make_forward_hook(self, module_name, accumulator, user_limit, dtype_ratio):
602
+ def hook(module, inp, out):
603
+ if not self.active:
604
+ return
605
+ if isinstance(out, dict):
606
+ out = out.get("last_hidden_state")
607
+ if not torch.is_tensor(out):
608
+ return
609
+ stats = StatsEngine.compute(out.detach(), user_limit, dtype_ratio)
610
+ accumulator.add(f"act.{module_name}", out.numel(), stats)
611
+ return hook
612
+
613
+ def _make_backward_hook(self, param_name, accumulator, user_limit, dtype_ratio):
614
+ def hook(grad):
615
+ if not self.active:
616
+ return
617
+ stats = StatsEngine.compute(grad.detach(), user_limit, dtype_ratio)
618
+ accumulator.add(param_name, grad.numel(), stats)
619
+ return hook
620
+
621
+ def set_active(self, active: bool):
622
+ self.active = active
623
+
624
+ def clear(self):
625
+ for h in self.handles:
626
+ h.remove()
627
+ self.handles.clear()
628
+
629
+
630
+ class StabilityMonitorCallback(TrainerCallback):
631
+ def __init__(
632
+ self,
633
+ model: nn.Module,
634
+ monitor_every_n_steps: int = 10,
635
+ module_patterns: Optional[List[str]] = None,
636
+ param_patterns: Optional[List[str]] = None,
637
+ user_limits: Optional[Dict[str, float]] = None,
638
+ dtype_proximity_ratio: float = 0.9,
639
+ log_scope: Optional[Dict[str, bool]] = None,
640
+ monitor_during_eval: bool = False,
641
+ ):
642
+ self.model = model
643
+ self.monitor_every_n_steps = monitor_every_n_steps
644
+ self.module_patterns = module_patterns or [".*mlp.*", ".*residual.*"]
645
+ self.param_patterns = param_patterns or self.module_patterns
646
+ self.user_limits = user_limits or {"grad": 1.0, "param": 100.0, "act": 50.0}
647
+ self.dtype_ratio = dtype_proximity_ratio
648
+ self.log_scope = log_scope or {"global": True, "per_layer": True, "per_tensor": False}
649
+ self.monitor_during_eval = monitor_during_eval
650
+
651
+ self.accumulator = StepAccumulator()
652
+ self.hooks = HookRegistry(model)
653
+ self.hooks.attach_forward(
654
+ self.module_patterns,
655
+ self.accumulator,
656
+ self.user_limits["act"],
657
+ self.dtype_ratio,
658
+ )
659
+ self.hooks.attach_backward(
660
+ self.param_patterns,
661
+ self.accumulator,
662
+ self.user_limits["grad"],
663
+ self.dtype_ratio,
664
+ )
665
+ self.pending_metrics = None
666
+
667
+ def _should_monitor(self, state):
668
+ return state.global_step % self.monitor_every_n_steps == 0
669
+
670
+ def on_step_begin(self, args, state, control, **kwargs):
671
+ if self._should_monitor(state):
672
+ self.accumulator.clear()
673
+ self.hooks.set_active(True)
674
+
675
+ def on_step_end(self, args, state, control, **kwargs):
676
+ if not self.hooks.active:
677
+ return
678
+ for name, param in self.model.named_parameters():
679
+ if self.param_patterns and not any(re.search(p, name) for p in self.param_patterns):
680
+ continue
681
+ stats = StatsEngine.compute(param.data, self.user_limits["param"], self.dtype_ratio)
682
+ self.accumulator.add(f"param.{name}", param.numel(), stats)
683
+ self.hooks.set_active(False)
684
+ self.pending_metrics = self._build_metrics()
685
+
686
+ def _kind_of(self, name: str) -> str:
687
+ if name.startswith("act."):
688
+ return "act"
689
+ if name.startswith("grad."):
690
+ return "grad"
691
+ if name.startswith("param."):
692
+ return "param"
693
+ return "other"
694
+
695
+ def _strip_kind(self, name: str) -> str:
696
+ if name.startswith("act."):
697
+ return name[4:]
698
+ if name.startswith(("grad.", "param.")):
699
+ return name[5:]
700
+ return name
701
+
702
+ def _build_metrics(self, scope: str = "train") -> Dict[str, float]:
703
+ metrics = {}
704
+ if self.log_scope.get("global", True):
705
+ by_kind = {}
706
+ for k, v in self.accumulator.tensors.items():
707
+ by_kind.setdefault(self._kind_of(k), {})[k] = v
708
+ for kind, entries in by_kind.items():
709
+ stats = self.accumulator._aggregate(entries)
710
+ for kk, vv in stats.items():
711
+ metrics[f"{scope}/global/{kind}/{kk}"] = vv
712
+
713
+ if self.log_scope.get("per_layer", True):
714
+ layer_prefixes = set()
715
+ for name in self.accumulator.tensors:
716
+ clean = self._strip_kind(name)
717
+ parts = clean.split(".")
718
+ for i, p in enumerate(parts):
719
+ if p == "layers" and i + 1 < len(parts):
720
+ prefix = ".".join(parts[: i + 2])
721
+ layer_prefixes.add(prefix)
722
+ for prefix in layer_prefixes:
723
+ by_kind = {}
724
+ for k, v in self.accumulator.tensors.items():
725
+ clean = self._strip_kind(k)
726
+ if clean.startswith(prefix + ".") or clean == prefix:
727
+ by_kind.setdefault(self._kind_of(k), {})[k] = v
728
+ safe = prefix.replace(".", "_")
729
+ for kind, entries in by_kind.items():
730
+ if not entries:
731
+ continue
732
+ stats = self.accumulator._aggregate(entries)
733
+ for kk, vv in stats.items():
734
+ metrics[f"{scope}/layer_{safe}/{kind}/{kk}"] = vv
735
+
736
+ if self.log_scope.get("per_tensor", False):
737
+ for name, stats in self.accumulator.tensors.items():
738
+ safe = name.replace(".", "_")
739
+ for kk, vv in stats.items():
740
+ if kk == "numel":
741
+ continue
742
+ metrics[f"{scope}/tensor_{safe}/{kk}"] = vv
743
+ return metrics
744
+
745
+ def on_log(self, args, state, control, logs=None, **kwargs):
746
+ if logs is not None and self.pending_metrics is not None:
747
+ logs.update(self.pending_metrics)
748
+ try:
749
+ import wandb
750
+ if wandb.run is not None:
751
+ wandb.log(self.pending_metrics, step=state.global_step)
752
+ except ImportError:
753
+ pass
754
+ self.pending_metrics = None
755
+
756
+ def on_prediction_step(self, args, state, control, **kwargs):
757
+ if not self.monitor_during_eval:
758
+ return
759
+ if not self.hooks.active:
760
+ self.accumulator.clear()
761
+ self.hooks.set_active(True)
762
+ for name, param in self.model.named_parameters():
763
+ if self.param_patterns and not any(re.search(p, name) for p in self.param_patterns):
764
+ continue
765
+ stats = StatsEngine.compute(param.data, self.user_limits["param"], self.dtype_ratio)
766
+ self.accumulator.add(f"param.{name}", param.numel(), stats)
767
+ self.pending_metrics = self._build_metrics(scope="eval")
768
+
769
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
770
+ self.hooks.set_active(False)
771
+ self.accumulator.clear()
772
+
773
+
774
+ # =============================================================================
775
+ # 7. TIME TRACKER (unchanged)
776
+ # =============================================================================
777
+
778
+ class TimeTrackerCallback(TrainerCallback):
779
+ def __init__(self):
780
+ self.step_start = None
781
+ self.epoch_start = None
782
+ self.total_train_time = 0.0
783
+ self.step_times = []
784
+
785
+ def on_epoch_begin(self, args, state, control, **kwargs):
786
+ self.epoch_start = time.perf_counter()
787
+
788
+ def on_step_begin(self, args, state, control, **kwargs):
789
+ self.step_start = time.perf_counter()
790
+
791
+ def on_step_end(self, args, state, control, **kwargs):
792
+ if self.step_start is not None:
793
+ dt = time.perf_counter() - self.step_start
794
+ self.step_times.append(dt)
795
+ self.total_train_time += dt
796
+ self.step_start = None
797
+
798
+ def on_log(self, args, state, control, logs=None, **kwargs):
799
+ if logs is None:
800
+ return
801
+ logs["train/total_time_seconds"] = self.total_train_time
802
+ if self.step_times:
803
+ recent = self.step_times[-100:]
804
+ logs["train/time_per_step_avg"] = sum(recent) / len(recent)
805
+ if self.epoch_start is not None:
806
+ logs["train/epoch_time_elapsed"] = time.perf_counter() - self.epoch_start
807
+ if state.max_steps and state.global_step > 0:
808
+ avg = self.total_train_time / state.global_step
809
+ remaining = (state.max_steps - state.global_step) * avg
810
+ logs["train/estimated_remaining_minutes"] = remaining / 60.0
811
+
812
+
813
+ # =============================================================================
814
+ # 8. METRICS LOGGER (unchanged)
815
+ # =============================================================================
816
+
817
+ class MetricsLoggerCallback(TrainerCallback):
818
+ def __init__(self, output_dir: str):
819
+ self.output_dir = Path(output_dir)
820
+ self.output_dir.mkdir(parents=True, exist_ok=True)
821
+ self.log_file = self.output_dir / "training_log.jsonl"
822
+
823
+ def on_log(self, args, state, control, logs=None, **kwargs):
824
+ if logs is None:
825
+ return
826
+ entry = {"step": state.global_step, "epoch": state.epoch, "timestamp": time.time(), **logs}
827
+ with open(self.log_file, "a") as f:
828
+ f.write(json.dumps(entry, default=str) + "\n")
829
+
830
+
831
+ # =============================================================================
832
+ # 9. DATA & TRAINER FACTORY (unchanged)
833
+ # =============================================================================
834
+
835
+ def build_dataset(
836
+ tokenizer,
837
+ max_seq_len: int = 512,
838
+ split: str = "train",
839
+ dataset_name: str = "roneneldan/TinyStories",
840
+ max_samples: Optional[int] = None,
841
+ ):
842
+ ds = load_dataset(dataset_name, split=split)
843
+ if max_samples is not None and split == "train":
844
+ ds = ds.select(range(min(max_samples, len(ds))))
845
+
846
+ def tokenize(examples):
847
+ out = tokenizer(examples["text"], add_special_tokens=False)
848
+ eos_id = tokenizer.eos_token_id
849
+ out["input_ids"] = [ids + [eos_id] for ids in out["input_ids"]]
850
+ if "attention_mask" in out:
851
+ out["attention_mask"] = [mask + [1] for mask in out["attention_mask"]]
852
+ return out
853
+
854
+ tokenized = ds.map(tokenize, batched=True, num_proc=4, remove_columns=ds.column_names)
855
+
856
+ def group_texts(examples):
857
+ concatenated = {k: list(chain.from_iterable(examples[k])) for k in examples.keys()}
858
+ total_length = len(concatenated[list(examples.keys())[0]])
859
+ total_length = (total_length // max_seq_len) * max_seq_len
860
+ result = {
861
+ k: [t[i:i + max_seq_len] for i in range(0, total_length, max_seq_len)]
862
+ for k, t in concatenated.items()
863
+ }
864
+ result["labels"] = result["input_ids"].copy()
865
+ return result
866
+
867
+ return tokenized.map(group_texts, batched=True, batch_size=10000, num_proc=4)
868
+
869
+
870
+ def create_trainer(
871
+ model,
872
+ tokenizer,
873
+ config: Dict[str, Any],
874
+ train_dataset,
875
+ eval_dataset=None,
876
+ ):
877
+ tc = config.get("training", {})
878
+ mc = config.get("monitor", {})
879
+ go = config.get("gradient_override", {})
880
+
881
+ wandb_project = tc.get("wandb_project")
882
+ if wandb_project:
883
+ os.environ["WANDB_PROJECT"] = wandb_project
884
+
885
+ args = TrainingArguments(
886
+ output_dir=tc.get("output_dir", "./out"),
887
+ run_name=tc.get("run_name", None),
888
+ num_train_epochs=tc.get("num_train_epochs", 3),
889
+ per_device_train_batch_size=tc.get("per_device_train_batch_size", 16),
890
+ per_device_eval_batch_size=tc.get("per_device_eval_batch_size", 16),
891
+ gradient_accumulation_steps=tc.get("gradient_accumulation_steps", 4),
892
+ learning_rate=tc.get("learning_rate", 3e-4),
893
+ weight_decay=tc.get("weight_decay", 0.0),
894
+ max_grad_norm=tc.get("max_grad_norm", 1.0),
895
+ optim=tc.get("optim", "adamw_torch"),
896
+ warmup_steps=tc.get("warmup_steps", 0),
897
+ lr_scheduler_type=tc.get("lr_scheduler_type", "cosine"),
898
+ bf16=tc.get("bf16", True),
899
+ logging_steps=tc.get("logging_steps", 10),
900
+ eval_strategy=tc.get("eval_strategy", "steps"),
901
+ eval_steps=tc.get("eval_steps", 500),
902
+ save_strategy=tc.get("save_strategy", "steps"),
903
+ save_steps=tc.get("save_steps", 1000),
904
+ load_best_model_at_end=tc.get("load_best_model_at_end", False),
905
+ report_to=tc.get("report_to", "tensorboard"),
906
+ push_to_hub=tc.get("push_to_hub", False),
907
+ hub_model_id=tc.get("hub_model_id", None),
908
+ hub_token=tc.get("hub_token") or os.environ.get("HF_TOKEN"),
909
+ max_steps=tc.get("max_steps", -1),
910
+ seed=tc.get("seed", 42),
911
+ data_seed=tc.get("data_seed", 42),
912
+ remove_unused_columns=False,
913
+ )
914
+
915
+ callbacks = [TimeTrackerCallback()]
916
+
917
+ # ---- FREEZE + OVERRIDE CALLBACK ----
918
+ freeze_mlp = tc.get("freeze_mlp", False)
919
+ override_enabled = go.get("enabled", False)
920
+ if freeze_mlp or override_enabled:
921
+ override_value = go.get("value", -100.0) if override_enabled else None
922
+ callbacks.append(ResumeFreezeOverrideCallback(override_value=override_value))
923
+
924
+ # ---- MONITORING ----
925
+ if mc.get("enabled", True):
926
+ module_patterns = mc.get("module_patterns", [".*mlp.*", ".*residual.*"])
927
+ callbacks.append(
928
+ StabilityMonitorCallback(
929
+ model=model,
930
+ monitor_every_n_steps=mc.get("monitor_every_n_steps", 10),
931
+ module_patterns=module_patterns,
932
+ param_patterns=module_patterns,
933
+ user_limits=mc.get("user_limits", {"grad": 1.0, "param": 100.0, "act": 50.0}),
934
+ dtype_proximity_ratio=mc.get("dtype_proximity_ratio", 0.9),
935
+ log_scope=mc.get("log_scope", {"global": True, "per_layer": True, "per_tensor": False}),
936
+ monitor_during_eval=mc.get("monitor_during_eval", False),
937
+ )
938
+ )
939
+
940
+ callbacks.append(MetricsLoggerCallback(args.output_dir))
941
+
942
+ collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
943
+
944
+ trainer = Trainer(
945
+ model=model,
946
+ args=args,
947
+ train_dataset=train_dataset,
948
+ eval_dataset=eval_dataset,
949
+ data_collator=collator,
950
+ callbacks=callbacks,
951
+ )
952
+
953
+ return trainer
zain/Activation/grad.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Standalone script to extract Adam RMS and SNR from HF Hub checkpoints.
4
+ Uses exact model definitions from the activation analyzer (exp.py).
5
+ Normalizes names to match the analyzer's naming (gate_proj, up_proj, etc.).
6
+ Configured for: w-ahmad/STRESS-TEST2 / zain/Activation/out
7
+ """
8
+
9
+ import math
10
+ import os
11
+ import json
12
+ import tempfile
13
+ import shutil
14
+ from pathlib import Path
15
+ from typing import Dict, List, Optional, Tuple, Any
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import wandb
20
+ from huggingface_hub import HfApi, hf_hub_download, list_repo_tree
21
+ from transformers import LlamaConfig, LlamaPreTrainedModel
22
+ from transformers.models.llama.modeling_llama import (
23
+ LlamaAttention, LlamaRMSNorm, LlamaRotaryEmbedding,
24
+ )
25
+
26
+ # ============================================================================
27
+ # EXACT MODEL DEFINITIONS (copied from the activation analyzer)
28
+ # ============================================================================
29
+
30
+ class GLUActivationRegistry:
31
+ _registry: Dict[str, callable] = {}
32
+
33
+ @classmethod
34
+ def register(cls, name: str, fn: callable) -> None:
35
+ cls._registry[name] = fn
36
+
37
+ @classmethod
38
+ def get(cls, name: str) -> callable:
39
+ if name not in cls._registry:
40
+ raise KeyError(f"Activation '{name}' not found")
41
+ return cls._registry[name]
42
+
43
+ # Register all activations used in the analyzer
44
+ GLUActivationRegistry.register("silu", nn.functional.silu)
45
+ GLUActivationRegistry.register("swish", nn.functional.silu)
46
+ GLUActivationRegistry.register("relu", nn.functional.relu)
47
+ GLUActivationRegistry.register("gelu", nn.functional.gelu)
48
+ GLUActivationRegistry.register("mish", nn.functional.mish)
49
+ GLUActivationRegistry.register("sigmoid", torch.sigmoid)
50
+ GLUActivationRegistry.register("tanh", torch.tanh)
51
+ GLUActivationRegistry.register("elu", nn.functional.elu)
52
+ GLUActivationRegistry.register("softplus", nn.functional.softplus)
53
+ GLUActivationRegistry.register("linear", lambda x: x)
54
+ GLUActivationRegistry.register("s10", lambda x: x * x * torch.sigmoid(x))
55
+ GLUActivationRegistry.register("w1a", lambda x: x * torch.tanh(x))
56
+ GLUActivationRegistry.register("powlu", lambda x: x) # dummy for param extraction
57
+
58
+
59
+ class TinyLlamaConfig(LlamaConfig):
60
+ model_type = "tiny_llama"
61
+
62
+ def __init__(
63
+ self,
64
+ mlp_type: str = "glu",
65
+ activation: str = "silu",
66
+ waleed_beta: float = 10.0,
67
+ powlu_m: float = 3.0,
68
+ **kwargs
69
+ ):
70
+ super().__init__(**kwargs)
71
+ self.mlp_type = mlp_type
72
+ self.activation = activation
73
+ self.waleed_beta = waleed_beta
74
+ self.powlu_m = powlu_m
75
+ if self.num_key_value_heads != self.num_attention_heads:
76
+ raise ValueError("Pure MHA required.")
77
+
78
+
79
+ class SiTUGLU(nn.Module):
80
+ def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
81
+ super().__init__()
82
+ self.beta1 = beta1
83
+ self.beta2 = beta2
84
+ self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
85
+ self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ g = self.W_g(x)
89
+ gate = self.beta1 * torch.tanh(g / self.beta1) * torch.sigmoid(g)
90
+ up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
91
+ return gate * up
92
+
93
+
94
+ class WaleedGLU(nn.Module):
95
+ def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
96
+ super().__init__()
97
+ self.beta1 = beta1
98
+ self.beta2 = beta2
99
+ self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
100
+ self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
101
+
102
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
103
+ g = self.W_g(x)
104
+ gate = self.beta1 * torch.tanh(g / self.beta1)
105
+ up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
106
+ return gate * up
107
+
108
+
109
+ class TinyLlamaMLP(nn.Module):
110
+ def __init__(self, config: TinyLlamaConfig):
111
+ super().__init__()
112
+ self.hidden_size = config.hidden_size
113
+ self.intermediate_size = config.intermediate_size
114
+ self.mlp_type = config.mlp_type
115
+ self.activation_name = config.activation
116
+
117
+ if self.mlp_type == "glu":
118
+ effective_intermediate = self.intermediate_size
119
+ else:
120
+ effective_intermediate = int(self.intermediate_size * 1.5)
121
+
122
+ self.effective_intermediate = effective_intermediate
123
+ self.situglu = None
124
+ self.waleed = None
125
+ self.gate_proj = None
126
+ self.up_proj = None
127
+ self.act_fn = None
128
+
129
+ if self.mlp_type == "glu":
130
+ if self.activation_name == "situglu":
131
+ self.situglu = SiTUGLU(self.hidden_size, effective_intermediate)
132
+ elif self.activation_name == "waleed":
133
+ self.waleed = WaleedGLU(self.hidden_size, effective_intermediate)
134
+ else:
135
+ # Standard GLU (including waleed10, silu-waleed10, powlu, situglu_low, waleedglu_low)
136
+ self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
137
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
138
+ # Activation handling (not needed for param extraction, but avoid errors)
139
+ if self.activation_name == "waleed10":
140
+ self.act_fn = GLUActivationRegistry.get("linear")
141
+ elif self.activation_name == "silu-waleed10":
142
+ self.act_fn = GLUActivationRegistry.get("silu")
143
+ elif self.activation_name in ("situglu_low", "waleedglu_low"):
144
+ self.act_fn = None
145
+ else:
146
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
147
+ else:
148
+ # MLP (non-GLU) – not used in your runs, but kept for completeness
149
+ if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
150
+ raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
151
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
152
+ if self.activation_name == "waleed10":
153
+ self.act_fn = GLUActivationRegistry.get("linear")
154
+ elif self.activation_name == "silu-waleed10":
155
+ self.act_fn = GLUActivationRegistry.get("silu")
156
+ else:
157
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
158
+
159
+ self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
160
+
161
+ def forward(self, x):
162
+ raise NotImplementedError
163
+
164
+
165
+ class TinyLlamaDecoderLayer(nn.Module):
166
+ def __init__(self, config: TinyLlamaConfig, layer_idx: int):
167
+ super().__init__()
168
+ self.hidden_size = config.hidden_size
169
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
170
+ self.mlp = TinyLlamaMLP(config)
171
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
172
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
173
+
174
+ def forward(self, *args, **kwargs):
175
+ raise NotImplementedError
176
+
177
+
178
+ class TinyLlamaModel(LlamaPreTrainedModel):
179
+ config_class = TinyLlamaConfig
180
+
181
+ def __init__(self, config: TinyLlamaConfig):
182
+ super().__init__(config)
183
+ self.padding_idx = config.pad_token_id
184
+ self.vocab_size = config.vocab_size
185
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
186
+ self.layers = nn.ModuleList(
187
+ [TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
188
+ )
189
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
190
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
191
+ self.post_init()
192
+
193
+
194
+ class TinyLlamaForCausalLM(LlamaPreTrainedModel):
195
+ config_class = TinyLlamaConfig
196
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
197
+
198
+ def __init__(self, config: TinyLlamaConfig):
199
+ super().__init__(config)
200
+ self.model = TinyLlamaModel(config)
201
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
202
+ if config.tie_word_embeddings:
203
+ self.lm_head.weight = self.model.embed_tokens.weight
204
+ self.post_init()
205
+
206
+ def get_input_embeddings(self):
207
+ return self.model.embed_tokens
208
+
209
+ def set_input_embeddings(self, value):
210
+ self.model.embed_tokens = value
211
+
212
+ def get_output_embeddings(self):
213
+ return self.lm_head
214
+
215
+ def forward(self, **kwargs):
216
+ raise NotImplementedError
217
+
218
+
219
+ # ============================================================================
220
+ # NAME NORMALIZATION – matches activation analyzer exactly
221
+ # ============================================================================
222
+
223
+ def canonical_param_name(name: str) -> str:
224
+ """
225
+ Normalize parameter names to match the activation analyzer's naming.
226
+ - W_g -> gate_proj, W_u -> up_proj (for situglu/waleed)
227
+ - Keep gate_proj and up_proj unchanged (they already are canonical)
228
+ - Leave all other names as-is.
229
+ This allows direct overlays between RMS/SNR and activation stats.
230
+ """
231
+ # WaleedGLU → use gate_proj/up_proj
232
+ if "mlp.waleed.W_g" in name:
233
+ return name.replace("mlp.waleed.W_g", "mlp.waleed.gate_proj")
234
+ if "mlp.waleed.W_u" in name:
235
+ return name.replace("mlp.waleed.W_u", "mlp.waleed.up_proj")
236
+
237
+ # SiTUGLU → use gate_proj/up_proj
238
+ if "mlp.situglu.W_g" in name:
239
+ return name.replace("mlp.situglu.W_g", "mlp.situglu.gate_proj")
240
+ if "mlp.situglu.W_u" in name:
241
+ return name.replace("mlp.situglu.W_u", "mlp.situglu.up_proj")
242
+
243
+ # For standard GLU, names already have gate_proj/up_proj – keep them.
244
+ # Everything else (attention, norms, embeddings, lm_head) stays as-is.
245
+ return name
246
+
247
+
248
+ # ============================================================================
249
+ # Stats helpers
250
+ # ============================================================================
251
+
252
+ def tensor_stats(tensor: torch.Tensor) -> Dict[str, float]:
253
+ with torch.no_grad():
254
+ return {
255
+ "numel": tensor.numel(),
256
+ "mean": tensor.mean().item(),
257
+ "std": tensor.std().item(),
258
+ "max_abs": tensor.abs().max().item(),
259
+ "norm": tensor.norm().item(),
260
+ }
261
+
262
+
263
+ def aggregate_stats(stats_list: List[Dict[str, float]]) -> Dict[str, float]:
264
+ if not stats_list:
265
+ return {"numel": 0, "mean": 0.0, "std": 0.0, "max_abs": 0.0, "norm": 0.0}
266
+
267
+ total_numel = sum(s["numel"] for s in stats_list)
268
+ if total_numel == 0:
269
+ return {"numel": 0, "mean": 0.0, "std": 0.0, "max_abs": 0.0, "norm": 0.0}
270
+
271
+ mean = sum(s["mean"] * s["numel"] for s in stats_list) / total_numel
272
+ ex2 = sum(s["numel"] * (s["std"]**2 + s["mean"]**2) for s in stats_list) / total_numel
273
+ std = math.sqrt(max(0.0, ex2 - mean**2))
274
+ norm = math.sqrt(sum(s["norm"]**2 for s in stats_list))
275
+ max_abs = max(s["max_abs"] for s in stats_list)
276
+
277
+ return {"numel": total_numel, "mean": mean, "std": std, "max_abs": max_abs, "norm": norm}
278
+
279
+
280
+ def get_param_names_from_model(config: TinyLlamaConfig) -> List[str]:
281
+ model = TinyLlamaForCausalLM(config)
282
+ return [name for name, _ in model.named_parameters()]
283
+
284
+
285
+ # ============================================================================
286
+ # HF Hub helpers – configured for your repo
287
+ # ============================================================================
288
+
289
+ REPO_ID = "w-ahmad/art"
290
+ BASE_PATH = "out"
291
+
292
+
293
+ def list_run_directories() -> List[str]:
294
+ api = HfApi()
295
+ items = list_repo_tree(repo_id=REPO_ID, path_in_repo=BASE_PATH, recursive=False)
296
+ return [item.path for item in items if item.path.endswith("_run")]
297
+
298
+
299
+ def list_checkpoints_for_run(run_path: str) -> List[str]:
300
+ api = HfApi()
301
+ items = list_repo_tree(repo_id=REPO_ID, path_in_repo=run_path, recursive=False)
302
+ ckpts = [item.path for item in items if item.path.split("/")[-1].startswith("checkpoint-")]
303
+ ckpts.sort(key=lambda x: int(x.split("-")[-1]))
304
+ return ckpts
305
+
306
+
307
+ def download_file_from_hub(file_path: str, local_dir: str) -> str:
308
+ return hf_hub_download(
309
+ repo_id=REPO_ID,
310
+ filename=file_path,
311
+ local_dir=local_dir,
312
+ local_dir_use_symlinks=False,
313
+ )
314
+
315
+
316
+ # ============================================================================
317
+ # Core analysis
318
+ # ============================================================================
319
+
320
+ def analyze_checkpoint_from_hub(
321
+ ckpt_path: str,
322
+ config: TinyLlamaConfig,
323
+ param_names: List[str],
324
+ temp_dir: str,
325
+ ) -> Dict[str, Any]:
326
+ opt_file = download_file_from_hub(f"{ckpt_path}/optimizer.pt", temp_dir)
327
+ opt_state = torch.load(opt_file, map_location="cpu")
328
+ state = opt_state["state"]
329
+ param_groups = opt_state["param_groups"]
330
+
331
+ param_ids = []
332
+ for group in param_groups:
333
+ param_ids.extend(group["params"])
334
+
335
+ if len(param_ids) != len(param_names):
336
+ raise ValueError(
337
+ f"Param ID mismatch: {len(param_ids)} vs {len(param_names)}"
338
+ )
339
+
340
+ id_to_name = {pid: param_names[i] for i, pid in enumerate(param_ids)}
341
+
342
+ # Per-tensor RMS + SNR (canonical names)
343
+ per_tensor_rms: Dict[str, Dict[str, float]] = {}
344
+ per_tensor_snr: Dict[str, Dict[str, float]] = {}
345
+
346
+ for pid, raw_name in id_to_name.items():
347
+ if pid not in state:
348
+ continue
349
+
350
+ name = canonical_param_name(raw_name)
351
+
352
+ # RMS
353
+ v_t = state[pid]["exp_avg_sq"]
354
+ rms = torch.sqrt(v_t + 1e-8)
355
+ per_tensor_rms[name] = tensor_stats(rms)
356
+
357
+ # SNR = |m_t| / (rms + eps)
358
+ m_t = state[pid]["exp_avg"]
359
+ snr = m_t.abs() / (rms + 1e-8)
360
+ snr = snr.clamp(max=1e4)
361
+ per_tensor_snr[name] = tensor_stats(snr)
362
+
363
+ # Layer aggregation
364
+ def build_layer_stats(per_tensor_dict: Dict[str, Dict[str, float]]) -> Dict[str, Dict[str, float]]:
365
+ layers: Dict[str, List[Dict[str, float]]] = {}
366
+ for name, stats in per_tensor_dict.items():
367
+ parts = name.split(".")
368
+ layer_key = None
369
+ for i, p in enumerate(parts):
370
+ if p == "layers" and i + 1 < len(parts):
371
+ layer_key = f"layers.{parts[i+1]}"
372
+ break
373
+ if layer_key is None:
374
+ layer_key = "root"
375
+ layers.setdefault(layer_key, []).append(stats)
376
+ return {k: aggregate_stats(v) for k, v in layers.items()}
377
+
378
+ layer_rms = build_layer_stats(per_tensor_rms)
379
+ layer_snr = build_layer_stats(per_tensor_snr)
380
+
381
+ global_rms = aggregate_stats(list(per_tensor_rms.values()))
382
+ global_snr = aggregate_stats(list(per_tensor_snr.values()))
383
+
384
+ return {
385
+ "step": int(ckpt_path.split("-")[-1]),
386
+ "per_tensor_rms": per_tensor_rms,
387
+ "per_tensor_snr": per_tensor_snr,
388
+ "per_layer_rms": layer_rms,
389
+ "per_layer_snr": layer_snr,
390
+ "global_rms": global_rms,
391
+ "global_snr": global_snr,
392
+ }
393
+
394
+
395
+ # ============================================================================
396
+ # Main
397
+ # ============================================================================
398
+
399
+ def main():
400
+ import argparse
401
+ parser = argparse.ArgumentParser()
402
+ parser.add_argument("--wandb_project", type=str, default="llm-gradient-rms-analysis")
403
+ parser.add_argument("--wandb_entity", type=str, default=None)
404
+ parser.add_argument("--limit_runs", type=str, nargs="+", default=None)
405
+ parser.add_argument("--limit_checkpoints", type=str, nargs="+", default=None)
406
+ parser.add_argument("--cache_dir", type=str, default=None)
407
+ parser.add_argument("--log_all_tensors", action="store_true", default=False,
408
+ help="Log every tensor's RMS/SNR (may hit WandB limits).")
409
+ args = parser.parse_args()
410
+
411
+ print(f"Listing run directories in {REPO_ID}/{BASE_PATH} ...")
412
+ run_paths = list_run_directories()
413
+ print(f"Found {len(run_paths)} run directories.")
414
+
415
+ if args.limit_runs:
416
+ run_paths = [r for r in run_paths if r.split("/")[-1] in args.limit_runs]
417
+ print(f"Filtered to {len(run_paths)} runs.")
418
+
419
+ if args.cache_dir:
420
+ cache_dir = Path(args.cache_dir)
421
+ cache_dir.mkdir(parents=True, exist_ok=True)
422
+ use_temp = False
423
+ else:
424
+ cache_dir = Path(tempfile.mkdtemp(prefix="hf_cache_"))
425
+ use_temp = True
426
+
427
+ try:
428
+ for run_path in run_paths:
429
+ run_name = run_path.split("/")[-1]
430
+ print(f"\nProcessing run: {run_name}")
431
+
432
+ ckpt_paths = list_checkpoints_for_run(run_path)
433
+ if not ckpt_paths:
434
+ print(f" No checkpoints found, skipping.")
435
+ continue
436
+
437
+ first_ckpt = ckpt_paths[0]
438
+ config_file = download_file_from_hub(f"{first_ckpt}/config.json", str(cache_dir))
439
+ config = TinyLlamaConfig.from_pretrained(config_file)
440
+ param_names = get_param_names_from_model(config)
441
+ print(f" Model: {len(param_names)} params, {config.num_hidden_layers} layers.")
442
+ print(f" waleed_beta: {config.waleed_beta}, powlu_m: {config.powlu_m}")
443
+
444
+ if args.log_all_tensors and len(param_names) > 200:
445
+ print(f" ⚠️ {len(param_names)} tensors — may hit WandB limits.")
446
+
447
+ wandb.init(
448
+ project=args.wandb_project,
449
+ entity=args.wandb_entity,
450
+ name=run_name,
451
+ config={
452
+ "run_name": run_name,
453
+ "mlp_type": config.mlp_type,
454
+ "activation": config.activation,
455
+ "num_layers": config.num_hidden_layers,
456
+ "hidden_size": config.hidden_size,
457
+ "waleed_beta": config.waleed_beta,
458
+ "powlu_m": config.powlu_m,
459
+ },
460
+ reinit=True,
461
+ )
462
+
463
+ for ckpt in ckpt_paths:
464
+ step = int(ckpt.split("-")[-1])
465
+ if args.limit_checkpoints and str(step) not in args.limit_checkpoints:
466
+ continue
467
+ print(f" Analyzing {ckpt} ...")
468
+ try:
469
+ result = analyze_checkpoint_from_hub(ckpt, config, param_names, str(cache_dir))
470
+ except Exception as e:
471
+ print(f" Error: {e}, skipping.")
472
+ continue
473
+
474
+ log_dict: Dict[str, Any] = {}
475
+
476
+ # GLOBAL (RMS + SNR)
477
+ gr = result["global_rms"]
478
+ gs = result["global_snr"]
479
+
480
+ log_dict["global/rms_norm"] = gr["norm"]
481
+ log_dict["global/rms_mean"] = gr["mean"]
482
+ log_dict["global/rms_std"] = gr["std"]
483
+ log_dict["global/rms_max_abs"] = gr["max_abs"]
484
+
485
+ log_dict["global/snr_mean"] = gs["mean"]
486
+ log_dict["global/snr_std"] = gs["std"]
487
+ log_dict["global/snr_max_abs"] = gs["max_abs"]
488
+ log_dict["global/snr_norm"] = gs["norm"]
489
+
490
+ # PER-LAYER
491
+ for layer_name, stats in result["per_layer_rms"].items():
492
+ safe = layer_name.replace(".", "_")
493
+ log_dict[f"layers/{safe}/rms_norm"] = stats["norm"]
494
+
495
+ for layer_name, stats in result["per_layer_snr"].items():
496
+ safe = layer_name.replace(".", "_")
497
+ log_dict[f"layers/{safe}/snr_mean"] = stats["mean"]
498
+
499
+ # PER-TENSOR (canonical names → all variants overlay)
500
+ if args.log_all_tensors:
501
+ # RMS
502
+ for name, stats in result["per_tensor_rms"].items():
503
+ safe = name.replace(".", "_")
504
+ log_dict[f"tensors/{safe}/rms_norm"] = stats["norm"]
505
+ log_dict[f"tensors/{safe}/rms_mean"] = stats["mean"]
506
+ log_dict[f"tensors/{safe}/rms_std"] = stats["std"]
507
+ log_dict[f"tensors/{safe}/rms_max_abs"] = stats["max_abs"]
508
+
509
+ # SNR
510
+ for name, stats in result["per_tensor_snr"].items():
511
+ safe = name.replace(".", "_")
512
+ log_dict[f"tensors/{safe}/snr_mean"] = stats["mean"]
513
+ log_dict[f"tensors/{safe}/snr_std"] = stats["std"]
514
+ log_dict[f"tensors/{safe}/snr_max_abs"] = stats["max_abs"]
515
+ log_dict[f"tensors/{safe}/snr_norm"] = stats["norm"]
516
+ else:
517
+ # Top/bottom 5 by RMS norm
518
+ sorted_tensors = sorted(
519
+ result["per_tensor_rms"].items(),
520
+ key=lambda x: x[1]["norm"],
521
+ reverse=True,
522
+ )
523
+ top5 = sorted_tensors[:5]
524
+ bottom5 = sorted_tensors[-5:] if len(sorted_tensors) >= 5 else sorted_tensors
525
+
526
+ for i, (name, stats) in enumerate(top5):
527
+ log_dict[f"top_{i+1}/name"] = name
528
+ log_dict[f"top_{i+1}/rms_norm"] = stats["norm"]
529
+ log_dict[f"top_{i+1}/rms_mean"] = stats["mean"]
530
+ for i, (name, stats) in enumerate(bottom5):
531
+ log_dict[f"bottom_{i+1}/name"] = name
532
+ log_dict[f"bottom_{i+1}/rms_norm"] = stats["norm"]
533
+
534
+ # TABLES
535
+ rms_table_data = []
536
+ for name, stats in result["per_tensor_rms"].items():
537
+ rms_table_data.append([
538
+ name, stats["mean"], stats["std"],
539
+ stats["max_abs"], stats["norm"], stats["numel"],
540
+ ])
541
+ if rms_table_data:
542
+ log_dict["rms_table"] = wandb.Table(
543
+ columns=["param_name", "mean", "std", "max_abs", "norm", "numel"],
544
+ data=rms_table_data,
545
+ )
546
+
547
+ snr_table_data = []
548
+ for name, stats in result["per_tensor_snr"].items():
549
+ snr_table_data.append([
550
+ name, stats["mean"], stats["std"],
551
+ stats["max_abs"], stats["norm"], stats["numel"],
552
+ ])
553
+ if snr_table_data:
554
+ log_dict["snr_table"] = wandb.Table(
555
+ columns=["param_name", "mean", "std", "max_abs", "norm", "numel"],
556
+ data=snr_table_data,
557
+ )
558
+
559
+ wandb.log(log_dict, step=step)
560
+
561
+ wandb.finish()
562
+
563
+ finally:
564
+ if use_temp and cache_dir.exists():
565
+ shutil.rmtree(cache_dir, ignore_errors=True)
566
+
567
+ print("\nAll done.")
568
+
569
+
570
+ if __name__ == "__main__":
571
+ main()
zain/Activation/llm_analyzer_wandb.py ADDED
@@ -0,0 +1,1307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multi-LLM Activation & Loss Analyzer with WandB Logging
3
+ GPU-only, FP32, exact training‑style tokenization (concatenate + chunk).
4
+ Supports PowLU, custom name normalization, full‑dataset evaluation,
5
+ and now captures pre‑down_proj inputs & layer outputs.
6
+ """
7
+
8
+ import math
9
+ import os
10
+ import tempfile
11
+ import shutil
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn as nn
15
+ from transformers import (
16
+ LlamaConfig,
17
+ LlamaPreTrainedModel,
18
+ AutoTokenizer,
19
+ AutoConfig,
20
+ AutoModelForCausalLM,
21
+ )
22
+ from transformers.models.llama.modeling_llama import (
23
+ LlamaAttention,
24
+ LlamaRMSNorm,
25
+ LlamaRotaryEmbedding,
26
+ )
27
+ from transformers.modeling_outputs import CausalLMOutputWithPast
28
+ from datasets import load_dataset as hf_load_dataset
29
+ from typing import List, Dict, Optional, Tuple
30
+ from dataclasses import dataclass, asdict
31
+ from collections import defaultdict
32
+ import json
33
+ import warnings
34
+ import os
35
+ from tqdm import tqdm
36
+ import wandb
37
+
38
+ warnings.filterwarnings("ignore")
39
+
40
+ # ============================================================================
41
+ # REPO CONFIGURATION
42
+ # ============================================================================
43
+
44
+ REPO_ID = "w-ahmad/STRESS-TEST3"
45
+ BASE_PATH = "zain/Activation/out" # <-- NO trailing slash
46
+
47
+ # ============================================================================
48
+ # 1. ACTIVATION REGISTRY (exact copy from exp.py)
49
+ # ============================================================================
50
+
51
+ class GLUActivationRegistry:
52
+ _registry: Dict[str, callable] = {}
53
+
54
+ @classmethod
55
+ def register(cls, name: str, fn: callable) -> None:
56
+ cls._registry[name] = fn
57
+
58
+ @classmethod
59
+ def get(cls, name: str) -> callable:
60
+ if name not in cls._registry:
61
+ raise KeyError(f"Activation '{name}' not found.")
62
+ return cls._registry[name]
63
+
64
+ # Register built-ins
65
+ GLUActivationRegistry.register("silu", nn.functional.silu)
66
+ GLUActivationRegistry.register("swish", nn.functional.silu)
67
+ GLUActivationRegistry.register("relu", nn.functional.relu)
68
+ GLUActivationRegistry.register("gelu", nn.functional.gelu)
69
+ GLUActivationRegistry.register("sigmoid", torch.sigmoid)
70
+ GLUActivationRegistry.register("tanh", torch.tanh)
71
+ GLUActivationRegistry.register("softplus", nn.functional.softplus)
72
+ GLUActivationRegistry.register("linear", lambda x: x)
73
+ GLUActivationRegistry.register("s10", lambda x: x * x * torch.sigmoid(x))
74
+ GLUActivationRegistry.register("w1a", lambda x: x * torch.tanh(x))
75
+
76
+ # ============================================================================
77
+ # 2. CUSTOM CONFIG & MODEL (with PowLU)
78
+ # ============================================================================
79
+
80
+ class TinyLlamaConfig(LlamaConfig):
81
+ model_type = "tiny_llama"
82
+
83
+ def __init__(
84
+ self,
85
+ mlp_type: str = "glu",
86
+ activation: str = "silu",
87
+ waleed_beta: float = 10.0,
88
+ powlu_m: float = 3.0,
89
+ **kwargs
90
+ ):
91
+ super().__init__(**kwargs)
92
+ self.mlp_type = mlp_type
93
+ self.activation = activation
94
+ self.waleed_beta = waleed_beta
95
+ self.powlu_m = powlu_m
96
+ if self.num_key_value_heads != self.num_attention_heads:
97
+ raise ValueError("Pure MHA required.")
98
+
99
+
100
+ class SiTUGLU(nn.Module):
101
+ def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
102
+ super().__init__()
103
+ self.beta1 = beta1
104
+ self.beta2 = beta2
105
+ self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
106
+ self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
107
+
108
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
109
+ g = self.W_g(x)
110
+ gate = self.beta1 * torch.tanh(g / self.beta1) * torch.sigmoid(g)
111
+ up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
112
+ return gate * up
113
+
114
+
115
+ class WaleedGLU(nn.Module):
116
+ def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
117
+ super().__init__()
118
+ self.beta1 = beta1
119
+ self.beta2 = beta2
120
+ self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
121
+ self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
122
+
123
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
124
+ g = self.W_g(x)
125
+ gate = self.beta1 * torch.tanh(g / self.beta1)
126
+ up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
127
+ return gate * up
128
+
129
+
130
+ class TinyLlamaMLP(nn.Module):
131
+ def __init__(self, config: TinyLlamaConfig):
132
+ super().__init__()
133
+ self.hidden_size = config.hidden_size
134
+ self.intermediate_size = config.intermediate_size
135
+ self.mlp_type = config.mlp_type
136
+ self.activation_name = config.activation
137
+ self.waleed_beta = getattr(config, "waleed_beta", 10.0)
138
+ self.powlu_m = getattr(config, "powlu_m", 3.0)
139
+
140
+ if self.mlp_type == "glu":
141
+ effective_intermediate = self.intermediate_size
142
+ elif self.mlp_type == "mlp":
143
+ effective_intermediate = int(self.intermediate_size * 1.5)
144
+ else:
145
+ raise ValueError(f"Unknown mlp_type: {self.mlp_type}")
146
+
147
+ self.effective_intermediate = effective_intermediate
148
+
149
+ if self.mlp_type == "glu":
150
+ self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
151
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
152
+ else:
153
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
154
+ self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
155
+
156
+ # ---- Activation flags ----
157
+ self.is_powlu = (self.activation_name == "powlu")
158
+ self.is_situglu = self.activation_name in ("situglu", "situglu_low")
159
+ self.is_waleed = self.activation_name in ("waleed", "waleedglu_low")
160
+ self.is_waleed10 = self.activation_name in ("waleed10", "silu-waleed10")
161
+ self.has_sigmoid_gate = self.activation_name.startswith("situglu")
162
+
163
+ # ---- Activation function (for non-PowLU) ----
164
+ if self.mlp_type == "glu":
165
+ if self.is_powlu:
166
+ self.act_fn = None
167
+ elif self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
168
+ self.act_fn = None
169
+ elif self.activation_name == "waleed10":
170
+ self.act_fn = GLUActivationRegistry.get("linear")
171
+ elif self.activation_name == "silu-waleed10":
172
+ self.act_fn = GLUActivationRegistry.get("silu")
173
+ else:
174
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
175
+ else: # mlp
176
+ if self.is_powlu:
177
+ raise ValueError("PowLU is only supported with mlp_type='glu'")
178
+ if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
179
+ raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
180
+ elif self.activation_name == "waleed10":
181
+ self.act_fn = GLUActivationRegistry.get("linear")
182
+ elif self.activation_name == "silu-waleed10":
183
+ self.act_fn = GLUActivationRegistry.get("silu")
184
+ else:
185
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
186
+
187
+ # beta values for situglu/waleed
188
+ if self.activation_name in ("situglu_low", "waleedglu_low"):
189
+ self.beta1 = 2.5
190
+ self.beta2 = 4.0
191
+ else:
192
+ self.beta1 = 4.0
193
+ self.beta2 = 25.0
194
+
195
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
196
+ if self.mlp_type == "glu":
197
+ gate = self.gate_proj(x)
198
+ up = self.up_proj(x)
199
+
200
+ # ----- PowLU branch -----
201
+ if self.is_powlu:
202
+ m = self.powlu_m
203
+ sig_gate = torch.sigmoid(gate)
204
+ pos_mask = gate > 0
205
+ powlu_pos = gate ** (m / (torch.sqrt(gate) + 1)) * sig_gate
206
+ powlu_neg = gate * sig_gate
207
+ activated_gate = torch.where(pos_mask, powlu_pos, powlu_neg)
208
+ hidden = activated_gate * up
209
+
210
+ # ----- situglu / waleed branches -----
211
+ elif self.is_situglu or self.is_waleed:
212
+ if self.has_sigmoid_gate:
213
+ gate = self.beta1 * torch.tanh(gate / self.beta1) * torch.sigmoid(gate)
214
+ else:
215
+ gate = self.beta1 * torch.tanh(gate / self.beta1)
216
+ up = self.beta2 * torch.tanh(up / self.beta2)
217
+ hidden = gate * up
218
+
219
+ # ----- Standard GLU -----
220
+ else:
221
+ hidden = self.act_fn(gate) * up
222
+
223
+ out = self.down_proj(hidden)
224
+
225
+ else: # mlp
226
+ hidden = self.act_fn(self.up_proj(x))
227
+ out = self.down_proj(hidden)
228
+
229
+ # Optional Waleed clipping
230
+ if self.is_waleed10:
231
+ out = self.waleed_beta * torch.tanh(out / self.waleed_beta)
232
+
233
+ return out
234
+
235
+
236
+ class TinyLlamaDecoderLayer(nn.Module):
237
+ def __init__(self, config: TinyLlamaConfig, layer_idx: int):
238
+ super().__init__()
239
+ self.hidden_size = config.hidden_size
240
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
241
+ self.mlp = TinyLlamaMLP(config)
242
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
243
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
244
+
245
+ def forward(self, hidden_states, attention_mask=None, position_ids=None,
246
+ position_embeddings=None, **kwargs):
247
+ residual = hidden_states
248
+ hidden_states = self.input_layernorm(hidden_states)
249
+ attn_out = self.self_attn(
250
+ hidden_states=hidden_states,
251
+ attention_mask=attention_mask,
252
+ position_ids=position_ids,
253
+ position_embeddings=position_embeddings,
254
+ )[0]
255
+ hidden_states = residual + attn_out
256
+
257
+ residual = hidden_states
258
+ hidden_states = self.post_attention_layernorm(hidden_states)
259
+ hidden_states = self.mlp(hidden_states)
260
+ hidden_states = residual + hidden_states
261
+ return (hidden_states,)
262
+
263
+
264
+ def _build_causal_mask(attention_mask, seq_len, dtype, device):
265
+ min_value = torch.finfo(dtype).min
266
+ causal = torch.full((seq_len, seq_len), min_value, dtype=dtype, device=device)
267
+ causal = torch.triu(causal, diagonal=1)
268
+ causal = causal[None, None, :, :]
269
+ if attention_mask is None:
270
+ return causal
271
+ batch_size = attention_mask.shape[0]
272
+ causal = causal.expand(batch_size, 1, seq_len, seq_len).clone()
273
+ padding = attention_mask[:, None, None, :].to(device) == 0
274
+ causal = causal.masked_fill(padding, min_value)
275
+ return causal
276
+
277
+
278
+ class TinyLlamaModel(LlamaPreTrainedModel):
279
+ config_class = TinyLlamaConfig
280
+
281
+ def __init__(self, config: TinyLlamaConfig):
282
+ super().__init__(config)
283
+ self.padding_idx = config.pad_token_id
284
+ self.vocab_size = config.vocab_size
285
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
286
+ self.layers = nn.ModuleList(
287
+ [TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
288
+ )
289
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
290
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
291
+ self.post_init()
292
+
293
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None,
294
+ inputs_embeds=None, return_dict=None, **kwargs):
295
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
296
+ if inputs_embeds is None:
297
+ inputs_embeds = self.embed_tokens(input_ids)
298
+ if position_ids is None:
299
+ seq_len = inputs_embeds.shape[1]
300
+ position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0).expand(
301
+ inputs_embeds.shape[0], -1
302
+ )
303
+ hidden_states = inputs_embeds
304
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
305
+
306
+ seq_len = hidden_states.shape[1]
307
+ causal_mask = _build_causal_mask(
308
+ attention_mask, seq_len, hidden_states.dtype, hidden_states.device
309
+ )
310
+
311
+ for decoder_layer in self.layers:
312
+ layer_outputs = decoder_layer(
313
+ hidden_states,
314
+ attention_mask=causal_mask,
315
+ position_ids=position_ids,
316
+ position_embeddings=position_embeddings,
317
+ )
318
+ hidden_states = layer_outputs[0]
319
+
320
+ hidden_states = self.norm(hidden_states)
321
+ if not return_dict:
322
+ return (hidden_states,)
323
+ return {"last_hidden_state": hidden_states, "hidden_states": None, "attentions": None}
324
+
325
+
326
+ class TinyLlamaForCausalLM(LlamaPreTrainedModel):
327
+ config_class = TinyLlamaConfig
328
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
329
+
330
+ def __init__(self, config: TinyLlamaConfig):
331
+ super().__init__(config)
332
+ self.model = TinyLlamaModel(config)
333
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
334
+ if config.tie_word_embeddings:
335
+ self.lm_head.weight = self.model.embed_tokens.weight
336
+ self.post_init()
337
+
338
+ def get_input_embeddings(self):
339
+ return self.model.embed_tokens
340
+
341
+ def set_input_embeddings(self, value):
342
+ self.model.embed_tokens = value
343
+
344
+ def get_output_embeddings(self):
345
+ return self.lm_head
346
+
347
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None,
348
+ inputs_embeds=None, labels=None, return_dict=None, **kwargs):
349
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
350
+ outputs = self.model(
351
+ input_ids=input_ids,
352
+ attention_mask=attention_mask,
353
+ position_ids=position_ids,
354
+ inputs_embeds=inputs_embeds,
355
+ return_dict=return_dict,
356
+ )
357
+ hidden_states = outputs["last_hidden_state"] if return_dict else outputs[0]
358
+ logits = self.lm_head(hidden_states)
359
+
360
+ loss = None
361
+ if labels is not None:
362
+ shift_logits = logits[..., :-1, :].contiguous()
363
+ shift_labels = labels[..., 1:].contiguous()
364
+ loss_fct = nn.CrossEntropyLoss()
365
+ loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
366
+
367
+ if not return_dict:
368
+ output = (logits,) + outputs[1:]
369
+ return (loss,) + output if loss is not None else output
370
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None,
371
+ hidden_states=None, attentions=None)
372
+
373
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
374
+ attention_mask=None, **kwargs):
375
+ if past_key_values:
376
+ input_ids = input_ids[:, -1:]
377
+ position_ids = kwargs.get("position_ids")
378
+ if attention_mask is not None and position_ids is None:
379
+ position_ids = attention_mask.long().cumsum(-1) - 1
380
+ position_ids.masked_fill_(attention_mask == 0, 1)
381
+ if past_key_values:
382
+ position_ids = position_ids[:, -1].unsqueeze(-1)
383
+ return {
384
+ "input_ids": input_ids,
385
+ "position_ids": position_ids,
386
+ "past_key_values": past_key_values,
387
+ "attention_mask": attention_mask,
388
+ }
389
+
390
+ # ============================================================================
391
+ # END OF MODEL DEFINITIONS
392
+ # ============================================================================
393
+
394
+ # Percentiles we report everywhere
395
+ PERCENTILES = [25.0, 50.0, 90.0, 99.0, 99.9]
396
+
397
+
398
+ @dataclass
399
+ class TensorStats:
400
+ mean: float
401
+ max_abs: float
402
+ std: float
403
+ norm: float
404
+ numel: int
405
+ min_val: float
406
+ max_val: float
407
+ range_val: float
408
+ p25: float
409
+ p50: float
410
+ p90: float
411
+ p99: float
412
+ p999: float
413
+
414
+ @staticmethod
415
+ def zero() -> "TensorStats":
416
+ return TensorStats(
417
+ mean=0.0, max_abs=0.0, std=0.0, norm=0.0, numel=0,
418
+ min_val=0.0, max_val=0.0, range_val=0.0,
419
+ p25=0.0, p50=0.0, p90=0.0, p99=0.0, p999=0.0,
420
+ )
421
+
422
+
423
+ @dataclass
424
+ class ModelResult:
425
+ model_name: str
426
+ dataset_name: str
427
+ loss: float
428
+ perplexity: float
429
+ global_act: TensorStats
430
+ layer_acts: Dict[str, TensorStats]
431
+ num_tokens: int
432
+ num_layers: int
433
+ hidden_size: int
434
+ num_params: int
435
+ checkpoint_step: int = 0
436
+
437
+
438
+ # ============================================================================
439
+ # ACTIVATION HOOK MANAGER — with name normalization & extra hooks
440
+ # ============================================================================
441
+
442
+ class ActivationHookManager:
443
+ def __init__(
444
+ self,
445
+ store_dtype: torch.dtype = torch.float16,
446
+ exclude_substrings: Optional[List[str]] = None,
447
+ max_elements_per_tensor: Optional[int] = 500_000,
448
+ disk_offload: bool = False,
449
+ disk_dir: Optional[str] = None,
450
+ capture_pre_down: bool = True,
451
+ capture_layer_output: bool = True,
452
+ ):
453
+ self.raw_values: Dict[str, List[torch.Tensor]] = defaultdict(list)
454
+ self.hooks = []
455
+ self._attention_mask: Optional[torch.Tensor] = None
456
+ self.store_dtype = store_dtype
457
+ self.exclude_substrings = exclude_substrings if exclude_substrings is not None else ["lm_head"]
458
+ self.max_elements_per_tensor = max_elements_per_tensor
459
+ self._per_batch_quota: Optional[int] = None
460
+ self._counts: Dict[str, int] = defaultdict(int)
461
+ self.disk_offload = disk_offload
462
+ self.disk_dir = disk_dir
463
+ self._file_handles: Dict[str, "object"] = {}
464
+ self.capture_pre_down = capture_pre_down
465
+ self.capture_layer_output = capture_layer_output
466
+ if self.disk_offload:
467
+ self.disk_dir = disk_dir or tempfile.mkdtemp(prefix="act_cache_")
468
+ os.makedirs(self.disk_dir, exist_ok=True)
469
+
470
+ @staticmethod
471
+ def _safe_filename(name: str) -> str:
472
+ return name.replace("/", "__").replace(".", "_") + ".bin"
473
+
474
+ def set_expected_batches(self, num_batches: int):
475
+ if self.max_elements_per_tensor is not None:
476
+ self._per_batch_quota = max(1, self.max_elements_per_tensor // max(1, num_batches))
477
+ else:
478
+ self._per_batch_quota = None
479
+
480
+ def set_attention_mask(self, attention_mask: Optional[torch.Tensor]):
481
+ self._attention_mask = attention_mask
482
+
483
+ def _make_hook(self, name: str, is_pre: bool = False):
484
+ """Factory for hook functions. If is_pre, captures input; otherwise output."""
485
+ def hook(module, input_or_output, output=None):
486
+ # For pre_hook: input_or_output is the input tuple, output is None.
487
+ # For post_hook: input_or_output is the input tuple (ignored), output is the module output.
488
+ if is_pre:
489
+ # Capture the first input tensor (usually the only one)
490
+ tensor = input_or_output[0] if isinstance(input_or_output, tuple) else input_or_output
491
+ else:
492
+ # For post hook, we capture output
493
+ if isinstance(output, torch.Tensor):
494
+ tensor = output
495
+ elif isinstance(output, tuple) and len(output) > 0 and isinstance(output[0], torch.Tensor):
496
+ tensor = output[0]
497
+ else:
498
+ return
499
+
500
+ if not torch.is_tensor(tensor):
501
+ return
502
+
503
+ # Apply attention mask if available (only for post hooks that have matching shape)
504
+ mask = self._attention_mask
505
+ if not is_pre and mask is not None and tensor.dim() >= 2 and tensor.shape[0] == mask.shape[0] and tensor.shape[1] == mask.shape[1]:
506
+ flat = tensor[mask.bool()].reshape(-1)
507
+ else:
508
+ flat = tensor.reshape(-1)
509
+
510
+ if flat.numel() == 0:
511
+ return
512
+
513
+ if self._per_batch_quota is not None and flat.numel() > self._per_batch_quota:
514
+ idx = torch.randperm(flat.numel(), device=flat.device)[:self._per_batch_quota]
515
+ sampled = flat[idx]
516
+ else:
517
+ sampled = flat
518
+
519
+ if self.disk_offload:
520
+ self._write_to_disk(name, sampled)
521
+ else:
522
+ self.raw_values[name].append(sampled.detach().to(self.store_dtype))
523
+ self._counts[name] += sampled.numel()
524
+ return hook
525
+
526
+ def _write_to_disk(self, name: str, flat: torch.Tensor):
527
+ arr = flat.detach().to(self.store_dtype).cpu().numpy()
528
+ fh = self._file_handles.get(name)
529
+ if fh is None:
530
+ path = os.path.join(self.disk_dir, self._safe_filename(name))
531
+ fh = open(path, "ab")
532
+ self._file_handles[name] = fh
533
+ arr.tofile(fh)
534
+
535
+ def register_hooks(self, model: torch.nn.Module):
536
+ """Register hooks for MLP activations, pre-down, and layer outputs."""
537
+ # 1. Standard hooks on gate_proj, up_proj, down_proj (post-activation)
538
+ for name, module in model.named_modules():
539
+ if any(x in name for x in ["gate_proj", "up_proj", "down_proj"]):
540
+ # Normalize: W_g/W_u already handled in canonical names; for down_proj keep as is
541
+ # For down_proj we also want a pre-hook separately
542
+ # For post-hook we use the original name (already canonical for gate/up)
543
+ norm_name = name.replace("W_g", "gate_proj").replace("W_u", "up_proj")
544
+ hook = module.register_forward_hook(self._make_hook(norm_name, is_pre=False))
545
+ self.hooks.append(hook)
546
+
547
+ # 2. Pre-down_proj hook (captures input to down_proj)
548
+ if self.capture_pre_down:
549
+ for name, module in model.named_modules():
550
+ if "down_proj" in name:
551
+ # Name: replace "down_proj" with "pre_down"
552
+ pre_name = name.replace("down_proj", "pre_down")
553
+ hook = module.register_forward_pre_hook(self._make_hook(pre_name, is_pre=True))
554
+ self.hooks.append(hook)
555
+
556
+ # 3. Layer output hook (captures final hidden_states from each decoder layer)
557
+ if self.capture_layer_output:
558
+ for name, module in model.named_modules():
559
+ if isinstance(module, TinyLlamaDecoderLayer):
560
+ # Use the module's full name, e.g., model.layers.0
561
+ out_name = f"{name}.output"
562
+ hook = module.register_forward_hook(self._make_hook(out_name, is_pre=False))
563
+ self.hooks.append(hook)
564
+
565
+ def clear(self):
566
+ self.raw_values.clear()
567
+ self._counts.clear()
568
+ for fh in self._file_handles.values():
569
+ try:
570
+ fh.close()
571
+ except Exception:
572
+ pass
573
+ self._file_handles.clear()
574
+ if self.disk_offload and self.disk_dir:
575
+ shutil.rmtree(self.disk_dir, ignore_errors=True)
576
+
577
+ def remove_hooks(self):
578
+ for hook in self.hooks:
579
+ hook.remove()
580
+ self.hooks.clear()
581
+
582
+ @staticmethod
583
+ def _compute_stats_from_tensor(flat: torch.Tensor) -> TensorStats:
584
+ flat32 = flat.to(torch.float32)
585
+ numel = flat32.numel()
586
+ mean = flat32.mean().item()
587
+ std = flat32.std(unbiased=False).item()
588
+ norm = flat32.norm().item()
589
+ min_val = flat32.min().item()
590
+ max_val = flat32.max().item()
591
+ max_abs = max(abs(min_val), abs(max_val))
592
+
593
+ q = torch.tensor([p / 100.0 for p in PERCENTILES], device=flat32.device, dtype=torch.float32)
594
+ try:
595
+ quantiles = torch.quantile(flat32, q).tolist()
596
+ except RuntimeError:
597
+ import numpy as np
598
+ arr = flat32.cpu().numpy()
599
+ quantiles = np.percentile(arr, PERCENTILES).tolist()
600
+
601
+ p25, p50, p90, p99, p999 = quantiles
602
+
603
+ return TensorStats(
604
+ mean=mean, max_abs=max_abs, std=std, norm=norm, numel=numel,
605
+ min_val=min_val, max_val=max_val, range_val=max_val - min_val,
606
+ p25=p25, p50=p50, p90=p90, p99=p99, p999=p999,
607
+ )
608
+
609
+ def get_all_stats(self) -> Tuple[Dict[str, "TensorStats"], "TensorStats"]:
610
+ if self.disk_offload:
611
+ return self._get_all_stats_from_disk()
612
+
613
+ layer_stats: Dict[str, TensorStats] = {}
614
+ for name, chunks in self.raw_values.items():
615
+ if not chunks:
616
+ continue
617
+ flat = torch.cat(chunks)
618
+ layer_stats[name] = self._compute_stats_from_tensor(flat)
619
+ del chunks, flat
620
+ self.raw_values[name] = []
621
+
622
+ global_stats = TensorStats.zero()
623
+ return layer_stats, global_stats
624
+
625
+ def _get_all_stats_from_disk(self) -> Tuple[Dict[str, "TensorStats"], "TensorStats"]:
626
+ for fh in self._file_handles.values():
627
+ try:
628
+ fh.close()
629
+ except Exception:
630
+ pass
631
+ self._file_handles.clear()
632
+
633
+ np_dtype = np.float16 if self.store_dtype == torch.float16 else np.float32
634
+ layer_stats: Dict[str, TensorStats] = {}
635
+
636
+ for name in list(self._counts.keys()):
637
+ path = os.path.join(self.disk_dir, self._safe_filename(name))
638
+ if not os.path.exists(path):
639
+ continue
640
+ arr = np.fromfile(path, dtype=np_dtype)
641
+ os.remove(path)
642
+ if arr.size == 0:
643
+ continue
644
+ t = torch.from_numpy(arr.astype(np.float32))
645
+ layer_stats[name] = self._compute_stats_from_tensor(t)
646
+ del t, arr
647
+
648
+ shutil.rmtree(self.disk_dir, ignore_errors=True)
649
+ global_stats = TensorStats.zero()
650
+ return layer_stats, global_stats
651
+
652
+
653
+ # ============================================================================
654
+ # LLM ANALYZER — TRAINING‑STYLE TOKENIZATION, FULL DATASET SUPPORT
655
+ # ============================================================================
656
+
657
+ class LLMAnalyzer:
658
+ def __init__(
659
+ self,
660
+ max_length: int = 512,
661
+ max_samples: Optional[int] = 1000,
662
+ batch_size: int = 4,
663
+ wandb_project: Optional[str] = None,
664
+ cbt_simple_max_chars: int = 120,
665
+ min_line_chars: int = 20,
666
+ activation_store_dtype: torch.dtype = torch.float16,
667
+ track_activations: bool = True,
668
+ activation_hook_exclude: Optional[List[str]] = None,
669
+ max_elements_per_tensor: Optional[int] = 500_000,
670
+ activation_disk_offload: bool = False,
671
+ activation_disk_dir: Optional[str] = None,
672
+ capture_pre_down: bool = True,
673
+ capture_layer_output: bool = True,
674
+ ):
675
+ if not torch.cuda.is_available():
676
+ raise RuntimeError("This script requires a GPU. CUDA is not available.")
677
+ self.device = "cuda"
678
+ self.dtype = torch.float32
679
+
680
+ self.max_length = max_length
681
+ self.max_samples = max_samples
682
+ self.batch_size = batch_size
683
+ self.wandb_project = wandb_project or os.environ.get("WANDB_PROJECT", "llm-activation-analysis")
684
+ self.cbt_simple_max_chars = cbt_simple_max_chars
685
+ self.min_line_chars = min_line_chars
686
+ self.activation_store_dtype = activation_store_dtype
687
+ self.track_activations = track_activations
688
+ self.activation_hook_exclude = activation_hook_exclude if activation_hook_exclude is not None else ["lm_head"]
689
+ self.max_elements_per_tensor = max_elements_per_tensor
690
+ self.activation_disk_offload = activation_disk_offload
691
+ self.activation_disk_dir = activation_disk_dir
692
+ self.capture_pre_down = capture_pre_down
693
+ self.capture_layer_output = capture_layer_output
694
+ self._cache = {}
695
+ self._dataset_cache: Dict[str, List[str]] = {}
696
+
697
+ # ------------------------------------------------------------------
698
+ # Dataset loaders – now respect max_samples=None (load all)
699
+ # ------------------------------------------------------------------
700
+
701
+ def _load_tinystories(self, split: str = "validation") -> List[str]:
702
+ print(f"[Dataset] Loading TinyStories (split='{split}')...")
703
+ ds = hf_load_dataset("roneneldan/TinyStories", split=split)
704
+ lines = []
705
+ for example in ds:
706
+ text = (example.get("text") or "").strip()
707
+ if len(text) >= self.min_line_chars:
708
+ lines.append(text)
709
+ if self.max_samples is not None and len(lines) >= self.max_samples:
710
+ break
711
+ print(f"[Dataset] Loaded {len(lines)} TinyStories examples")
712
+ return lines
713
+
714
+ def _load_simplestories(self, split: str = "test") -> List[str]:
715
+ print(f"[Dataset] Loading SimpleStories (split='{split}')...")
716
+ ds = hf_load_dataset("SimpleStories/SimpleStories", split=split)
717
+ lines = []
718
+ for example in ds:
719
+ text = (example.get("story") or "").strip()
720
+ if len(text) >= self.min_line_chars:
721
+ lines.append(text)
722
+ if self.max_samples is not None and len(lines) >= self.max_samples:
723
+ break
724
+ print(f"[Dataset] Loaded {len(lines)} SimpleStories examples")
725
+ return lines
726
+
727
+ def _load_cbt_simple(self, split: str = "test") -> List[str]:
728
+ print(f"[Dataset] Loading CBT-simple (cam-cst/cbt, raw, split='{split}', "
729
+ f"max_chars={self.cbt_simple_max_chars})...")
730
+ ds = hf_load_dataset("cam-cst/cbt", "raw", split=split)
731
+ lines = []
732
+ for example in ds:
733
+ content = example.get("content", "")
734
+ if not content:
735
+ continue
736
+ for chunk in content.replace("\r\n", "\n").split("\n"):
737
+ chunk = chunk.strip()
738
+ if self.min_line_chars <= len(chunk) <= self.cbt_simple_max_chars:
739
+ lines.append(chunk)
740
+ if self.max_samples is not None and len(lines) >= self.max_samples:
741
+ break
742
+ print(f"[Dataset] Loaded {len(lines)} simple CBT sentences")
743
+ return lines[:self.max_samples] if self.max_samples is not None else lines
744
+
745
+ DATASET_LOADERS = {
746
+ "tinystories": lambda self, split: self._load_tinystories(split or "validation"),
747
+ "simplestories": lambda self, split: self._load_simplestories(split or "test"),
748
+ "cbt_simple": lambda self, split: self._load_cbt_simple(split or "test"),
749
+ }
750
+
751
+ def load_dataset(self, dataset_name: str, split: Optional[str] = None) -> List[str]:
752
+ cache_key = f"{dataset_name}:{split}"
753
+ if cache_key in self._dataset_cache:
754
+ return self._dataset_cache[cache_key]
755
+ if dataset_name not in self.DATASET_LOADERS:
756
+ raise ValueError(f"Unknown dataset '{dataset_name}'. Options: {list(self.DATASET_LOADERS)}")
757
+ texts = self.DATASET_LOADERS[dataset_name](self, split)
758
+ self._dataset_cache[cache_key] = texts
759
+ return texts
760
+
761
+ # ------------------------------------------------------------------
762
+ # Training‑style block preparation (no padding, no BOS)
763
+ # ------------------------------------------------------------------
764
+
765
+ def _prepare_blocks(self, texts: List[str], tokenizer, max_seq_len: int) -> List[List[int]]:
766
+ """
767
+ Tokenize texts exactly as in training:
768
+ - add_special_tokens=False
769
+ - append EOS token (tokenizer.eos_token_id)
770
+ - concatenate all stories into one flat list
771
+ - split into blocks of size max_seq_len, discarding any remainder
772
+ Returns a list of token ID lists, each exactly max_seq_len long.
773
+ """
774
+ eos_id = tokenizer.eos_token_id # should be 0 for this tokenizer
775
+ flat_tokens = []
776
+ for text in texts:
777
+ ids = tokenizer.encode(text, add_special_tokens=False)
778
+ ids.append(eos_id)
779
+ flat_tokens.extend(ids)
780
+
781
+ num_blocks = len(flat_tokens) // max_seq_len
782
+ blocks = []
783
+ for i in range(num_blocks):
784
+ start = i * max_seq_len
785
+ end = start + max_seq_len
786
+ blocks.append(flat_tokens[start:end])
787
+ return blocks
788
+
789
+ # ------------------------------------------------------------------
790
+ # Model loading – reads waleed_beta and powlu_m from config
791
+ # ------------------------------------------------------------------
792
+
793
+ def load_model(self, model_name: str):
794
+ if model_name in self._cache:
795
+ return self._cache[model_name]
796
+
797
+ print(f"[Loading] {model_name} ...")
798
+ parts = model_name.split("/")
799
+ if len(parts) > 2:
800
+ repo_id = "/".join(parts[:2])
801
+ subfolder = "/".join(parts[2:])
802
+ else:
803
+ repo_id = model_name
804
+ subfolder = None
805
+
806
+ tokenizer = AutoTokenizer.from_pretrained(
807
+ "w-ahmad/tiny-stories-tokenizer",
808
+ trust_remote_code=True,
809
+ padding_side="left"
810
+ )
811
+ if tokenizer.pad_token is None:
812
+ tokenizer.pad_token = tokenizer.eos_token
813
+
814
+ config = TinyLlamaConfig.from_pretrained(
815
+ repo_id, subfolder=subfolder, trust_remote_code=True
816
+ )
817
+
818
+ model = TinyLlamaForCausalLM.from_pretrained(
819
+ repo_id,
820
+ config=config,
821
+ subfolder=subfolder,
822
+ torch_dtype=self.dtype,
823
+ trust_remote_code=True,
824
+ )
825
+ model = model.to(self.device)
826
+ model.eval()
827
+ num_params = sum(p.numel() for p in model.parameters())
828
+
829
+ self._cache[model_name] = (tokenizer, model, config, num_params)
830
+ print(f"[Loaded] {model_name} | Params: {num_params/1e6:.1f}M | Layers: {config.num_hidden_layers} | Hidden: {config.hidden_size} | waleed_beta: {config.waleed_beta} | powlu_m: {config.powlu_m}")
831
+ return tokenizer, model, config, num_params
832
+
833
+ # ------------------------------------------------------------------
834
+ # Discover checkpoints (unchanged)
835
+ # ------------------------------------------------------------------
836
+
837
+ def discover_checkpoints(self) -> Dict[str, List[Tuple[int, str]]]:
838
+ from huggingface_hub import list_repo_files
839
+ print(f"🔍 Scanning Hugging Face repo: {REPO_ID}/{BASE_PATH} ...")
840
+ try:
841
+ all_files = list_repo_files(REPO_ID)
842
+ except Exception as e:
843
+ print(f"❌ Failed to fetch from Hugging Face Hub: {e}")
844
+ print("💡 Falling back to manual list.")
845
+ return {
846
+ "glu-silu-waleed10_run": [(100, "checkpoint-100")],
847
+ }
848
+
849
+ run_checkpoints = defaultdict(list)
850
+ prefix = BASE_PATH + "/"
851
+ for file_path in all_files:
852
+ if not file_path.startswith(prefix):
853
+ continue
854
+ rel_path = file_path[len(prefix):]
855
+ parts = rel_path.split("/")
856
+ if len(parts) < 2:
857
+ continue
858
+ run_folder = parts[0]
859
+ ckpt_folder = parts[1]
860
+ if not ckpt_folder.startswith("checkpoint-"):
861
+ continue
862
+ if not (file_path.endswith("config.json") or file_path.endswith("model.safetensors")):
863
+ continue
864
+ try:
865
+ ckpt_num = int(ckpt_folder.replace("checkpoint-", ""))
866
+ except ValueError:
867
+ continue
868
+ run_checkpoints[run_folder].append((ckpt_num, ckpt_folder))
869
+
870
+ result = {}
871
+ for run_folder, ckpts in run_checkpoints.items():
872
+ seen = set()
873
+ unique = []
874
+ for ckpt_num, ckpt_folder in sorted(ckpts, key=lambda x: x[0]):
875
+ if ckpt_num not in seen:
876
+ seen.add(ckpt_num)
877
+ unique.append((ckpt_num, ckpt_folder))
878
+ result[run_folder] = unique
879
+
880
+ print(f"✅ Found {len(result)} run folders:")
881
+ for run_folder, ckpts in sorted(result.items()):
882
+ print(f" - {run_folder}: {len(ckpts)} checkpoints ({ckpts[0][0]}...{ckpts[-1][0]})")
883
+ return result
884
+
885
+ # ------------------------------------------------------------------
886
+ # Single checkpoint evaluation
887
+ # ------------------------------------------------------------------
888
+
889
+ def _evaluate_checkpoint(
890
+ self,
891
+ model_name: str,
892
+ dataset_name: str,
893
+ blocks: List[List[int]],
894
+ ) -> ModelResult:
895
+ tokenizer, model, config, num_params = self.load_model(model_name)
896
+
897
+ total_loss = 0.0
898
+ total_tokens = 0
899
+ num_batches = (len(blocks) + self.batch_size - 1) // self.batch_size
900
+
901
+ hook_mgr = None
902
+ if self.track_activations:
903
+ hook_mgr = ActivationHookManager(
904
+ store_dtype=self.activation_store_dtype,
905
+ exclude_substrings=self.activation_hook_exclude,
906
+ max_elements_per_tensor=self.max_elements_per_tensor,
907
+ disk_offload=self.activation_disk_offload,
908
+ disk_dir=self.activation_disk_dir,
909
+ capture_pre_down=self.capture_pre_down,
910
+ capture_layer_output=self.capture_layer_output,
911
+ )
912
+ hook_mgr.register_hooks(model)
913
+ hook_mgr.set_expected_batches(num_batches)
914
+
915
+ if hook_mgr is not None:
916
+ n_hooks = len(hook_mgr.hooks)
917
+ mode = "disk" if self.activation_disk_offload else "in-memory"
918
+ if self.max_elements_per_tensor is None:
919
+ print(f"[Memory] ⚠️ {n_hooks} modules hooked ({mode}) with NO cap.")
920
+ else:
921
+ est_mb = (n_hooks * self.max_elements_per_tensor * 2) / (1024 ** 2)
922
+ where = f"on disk at {hook_mgr.disk_dir}" if self.activation_disk_offload else "in RAM/VRAM"
923
+ print(f"[Memory] {n_hooks} modules hooked, capped at {self.max_elements_per_tensor:,} elements/tensor (~{est_mb:.0f} MB ceiling, stored {where}).")
924
+
925
+ try:
926
+ desc = f"Eval {model_name.split('/')[-2]}/{model_name.split('/')[-1]}"
927
+ for batch_idx, i in enumerate(tqdm(range(0, len(blocks), self.batch_size), desc=desc, total=num_batches)):
928
+ batch_blocks = blocks[i:i+self.batch_size]
929
+ input_ids = torch.tensor(batch_blocks, dtype=torch.long, device=self.device)
930
+ attention_mask = None
931
+ labels = input_ids.clone()
932
+
933
+ if hook_mgr is not None:
934
+ hook_mgr.set_attention_mask(None)
935
+
936
+ with torch.no_grad():
937
+ outputs = model(
938
+ input_ids=input_ids,
939
+ attention_mask=attention_mask,
940
+ labels=labels,
941
+ )
942
+
943
+ logits = outputs.logits
944
+ shift_logits = logits[..., :-1, :].contiguous()
945
+ shift_labels = labels[..., 1:].contiguous()
946
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
947
+ token_losses = loss_fct(
948
+ shift_logits.view(-1, shift_logits.size(-1)),
949
+ shift_labels.view(-1)
950
+ )
951
+ num_valid_tokens = token_losses.numel()
952
+ batch_loss = token_losses.sum().item()
953
+ total_loss += batch_loss
954
+ total_tokens += num_valid_tokens
955
+
956
+ if batch_idx % 20 == 19:
957
+ torch.cuda.empty_cache()
958
+
959
+ if hook_mgr is not None:
960
+ hook_mgr.remove_hooks()
961
+ final_layer_stats, global_stats = hook_mgr.get_all_stats()
962
+ else:
963
+ final_layer_stats, global_stats = {}, TensorStats.zero()
964
+ except Exception:
965
+ if hook_mgr is not None:
966
+ hook_mgr.remove_hooks()
967
+ hook_mgr.clear()
968
+ raise
969
+
970
+ avg_loss = total_loss / max(total_tokens, 1)
971
+ perplexity = torch.exp(torch.tensor(avg_loss)).item()
972
+
973
+ checkpoint_step = 0
974
+ for part in model_name.split("/"):
975
+ if part.startswith("checkpoint-"):
976
+ try:
977
+ checkpoint_step = int(part.replace("checkpoint-", ""))
978
+ except ValueError:
979
+ pass
980
+
981
+ result = ModelResult(
982
+ model_name=model_name,
983
+ dataset_name=dataset_name,
984
+ loss=avg_loss,
985
+ perplexity=perplexity,
986
+ global_act=global_stats,
987
+ layer_acts=final_layer_stats,
988
+ num_tokens=total_tokens,
989
+ num_layers=config.num_hidden_layers,
990
+ hidden_size=config.hidden_size,
991
+ num_params=num_params,
992
+ checkpoint_step=checkpoint_step,
993
+ )
994
+
995
+ self._cache.pop(model_name, None)
996
+ del model
997
+ torch.cuda.empty_cache()
998
+
999
+ return result
1000
+
1001
+ # ------------------------------------------------------------------
1002
+ # Logging (updated to include new stats)
1003
+ # ------------------------------------------------------------------
1004
+
1005
+ def _log_checkpoint_to_wandb(self, result: ModelResult, step: int):
1006
+ wandb.log({
1007
+ "final/loss": result.loss,
1008
+ "final/perplexity": result.perplexity,
1009
+ "final/num_tokens": result.num_tokens,
1010
+ }, step=step)
1011
+
1012
+ if not self.track_activations:
1013
+ return
1014
+
1015
+ # Log per-tensor stats
1016
+ for tensor_name, stats in result.layer_acts.items():
1017
+ clean_name = tensor_name.replace(".", "/")
1018
+ # Determine the kind from the name: pre_down, output, or others (gate/up/down)
1019
+ if "pre_down" in tensor_name:
1020
+ prefix = f"train/{clean_name}/pre_down"
1021
+ elif "output" in tensor_name and "layers" in tensor_name:
1022
+ prefix = f"train/{clean_name}/output"
1023
+ else:
1024
+ prefix = f"train/{clean_name}/act" # existing activation stats
1025
+
1026
+ wandb.log({
1027
+ f"{prefix}/mean": stats.mean,
1028
+ f"{prefix}/max_abs": stats.max_abs,
1029
+ f"{prefix}/std": stats.std,
1030
+ f"{prefix}/norm": stats.norm,
1031
+ f"{prefix}/min": stats.min_val,
1032
+ f"{prefix}/max": stats.max_val,
1033
+ f"{prefix}/range": stats.range_val,
1034
+ f"{prefix}/p25": stats.p25,
1035
+ f"{prefix}/p50": stats.p50,
1036
+ f"{prefix}/p90": stats.p90,
1037
+ f"{prefix}/p99": stats.p99,
1038
+ f"{prefix}/p999": stats.p999,
1039
+ }, step=step)
1040
+
1041
+ # Tables: include all tensors with a column indicating the type
1042
+ table_data = []
1043
+ for tensor_name, stats in sorted(result.layer_acts.items()):
1044
+ # Determine type for table
1045
+ if "pre_down" in tensor_name:
1046
+ ttype = "pre_down"
1047
+ elif "output" in tensor_name and "layers" in tensor_name:
1048
+ ttype = "output"
1049
+ else:
1050
+ ttype = "activation"
1051
+ table_data.append([
1052
+ tensor_name,
1053
+ ttype,
1054
+ stats.mean,
1055
+ stats.max_abs,
1056
+ stats.std,
1057
+ stats.norm,
1058
+ stats.min_val,
1059
+ stats.max_val,
1060
+ stats.range_val,
1061
+ stats.p25,
1062
+ stats.p50,
1063
+ stats.p90,
1064
+ stats.p99,
1065
+ stats.p999,
1066
+ stats.numel,
1067
+ ])
1068
+
1069
+ if table_data:
1070
+ table = wandb.Table(
1071
+ columns=["tensor_name", "type", "mean", "max_abs", "std", "norm",
1072
+ "min", "max", "range", "p25", "p50", "p90", "p99", "p999", "numel"],
1073
+ data=table_data
1074
+ )
1075
+ wandb.log({"activation_table": table}, step=step)
1076
+
1077
+ # ------------------------------------------------------------------
1078
+ # Run‑folder evaluation – includes waleed_beta and powlu_m in name
1079
+ # ------------------------------------------------------------------
1080
+
1081
+ def _evaluate_run_folder(
1082
+ self,
1083
+ run_folder: str,
1084
+ dataset_name: str,
1085
+ blocks: List[List[int]],
1086
+ checkpoints: List[Tuple[int, str]],
1087
+ ) -> List[ModelResult]:
1088
+ first_model_name = f"{REPO_ID}/{BASE_PATH}/{run_folder}/{checkpoints[0][1]}"
1089
+ _, _, first_config, first_num_params = self.load_model(first_model_name)
1090
+
1091
+ effective_beta = first_config.waleed_beta
1092
+ powlu_m = first_config.powlu_m
1093
+ beta_str = f"_beta{effective_beta}" if effective_beta is not None else ""
1094
+ powlu_str = f"_powlu{powlu_m}" if powlu_m is not None else ""
1095
+
1096
+ run_name = f"{run_folder}__{dataset_name}{beta_str}{powlu_str}"
1097
+
1098
+ wandb.init(
1099
+ project=self.wandb_project,
1100
+ name=run_name,
1101
+ config={
1102
+ "run_folder": run_folder,
1103
+ "dataset": dataset_name,
1104
+ "max_length": self.max_length,
1105
+ "max_samples": self.max_samples,
1106
+ "batch_size": self.batch_size,
1107
+ "dtype": "float32",
1108
+ "num_params": first_num_params,
1109
+ "num_layers": first_config.num_hidden_layers,
1110
+ "hidden_size": first_config.hidden_size,
1111
+ "waleed_beta": effective_beta,
1112
+ "powlu_m": powlu_m,
1113
+ "checkpoints": [c[0] for c in checkpoints],
1114
+ "capture_pre_down": self.capture_pre_down,
1115
+ "capture_layer_output": self.capture_layer_output,
1116
+ },
1117
+ reinit=True
1118
+ )
1119
+
1120
+ self._cache.pop(first_model_name, None)
1121
+ torch.cuda.empty_cache()
1122
+
1123
+ results = []
1124
+ for ckpt_num, ckpt_folder in checkpoints:
1125
+ model_name = f"{REPO_ID}/{BASE_PATH}/{run_folder}/{ckpt_folder}"
1126
+ try:
1127
+ result = self._evaluate_checkpoint(model_name, dataset_name, blocks)
1128
+ self._log_checkpoint_to_wandb(result, step=ckpt_num)
1129
+ results.append(result)
1130
+ print(f" ✅ checkpoint-{ckpt_num}: loss={result.loss:.4f} ppl={result.perplexity:.2f}")
1131
+ except Exception as e:
1132
+ print(f" ❌ checkpoint-{ckpt_num} failed: {e}")
1133
+ import traceback
1134
+ traceback.print_exc()
1135
+ continue
1136
+
1137
+ wandb.finish()
1138
+ return results
1139
+
1140
+ # ------------------------------------------------------------------
1141
+ # Main compute – prepares training‑style blocks once per dataset
1142
+ # ------------------------------------------------------------------
1143
+
1144
+ def compute(
1145
+ self,
1146
+ dataset_names: List[str],
1147
+ run_folders: Optional[List[str]] = None,
1148
+ ) -> Dict[str, Dict[str, List[ModelResult]]]:
1149
+ all_run_folders = self.discover_checkpoints()
1150
+
1151
+ if run_folders is not None:
1152
+ filtered = {}
1153
+ for name in run_folders:
1154
+ if name in all_run_folders:
1155
+ filtered[name] = all_run_folders[name]
1156
+ else:
1157
+ print(f"⚠️ Run folder '{name}' not found. Skipping.")
1158
+ all_run_folders = filtered
1159
+ if not all_run_folders:
1160
+ print("❌ No valid run folders to evaluate. Exiting.")
1161
+ return {}
1162
+
1163
+ # Load tokenizer once (same for all datasets)
1164
+ tokenizer = AutoTokenizer.from_pretrained("w-ahmad/tiny-stories-tokenizer", trust_remote_code=True)
1165
+ if tokenizer.pad_token is None:
1166
+ tokenizer.pad_token = tokenizer.eos_token
1167
+
1168
+ blocks_by_dataset = {}
1169
+ for dataset_name in dataset_names:
1170
+ texts = self.load_dataset(dataset_name)
1171
+ blocks = self._prepare_blocks(texts, tokenizer, self.max_length)
1172
+ blocks_by_dataset[dataset_name] = blocks
1173
+ print(f"[Dataset] {dataset_name} → {len(blocks)} blocks of length {self.max_length}")
1174
+
1175
+ results_by_dataset: Dict[str, Dict[str, List[ModelResult]]] = {
1176
+ name: {} for name in dataset_names
1177
+ }
1178
+
1179
+ for dataset_name in dataset_names:
1180
+ blocks = blocks_by_dataset[dataset_name]
1181
+ for run_folder, checkpoints in sorted(all_run_folders.items()):
1182
+ print(f"\n🚀 Evaluating {run_folder} on {dataset_name} ({len(checkpoints)} checkpoints)...")
1183
+ results = self._evaluate_run_folder(run_folder, dataset_name, blocks, checkpoints)
1184
+ results_by_dataset[dataset_name][run_folder] = results
1185
+
1186
+ return results_by_dataset
1187
+
1188
+ # ------------------------------------------------------------------
1189
+ # Reporting (updated to include new stats in the top‑5 summary)
1190
+ # ------------------------------------------------------------------
1191
+
1192
+ def print_report(self, results_by_dataset: Dict[str, Dict[str, List[ModelResult]]]):
1193
+ for dataset_name, run_results in results_by_dataset.items():
1194
+ print("\n" + "=" * 150)
1195
+ print(f" Dataset: {dataset_name}")
1196
+ print("=" * 150)
1197
+
1198
+ print(f"{'Run Folder':<38} {'Ckpt':>7} {'Loss':>9} {'PPL':>9} {'Tokens':>8} {'Num Layers':>10}")
1199
+ print("-" * 90)
1200
+
1201
+ for run_folder, results in sorted(run_results.items()):
1202
+ if not results:
1203
+ continue
1204
+ latest = max(results, key=lambda r: r.checkpoint_step)
1205
+ name = run_folder[:36]
1206
+ print(
1207
+ f"{name:<38} "
1208
+ f"{latest.checkpoint_step:>7} "
1209
+ f"{latest.loss:>9.4f} "
1210
+ f"{latest.perplexity:>9.2f} "
1211
+ f"{latest.num_tokens:>8} "
1212
+ f"{latest.num_layers:>10}"
1213
+ )
1214
+
1215
+ # Show top‑5 per tensor type for the latest checkpoint
1216
+ print("\n[Per-Tensor Max Abs Top 5 (latest checkpoint per run)]")
1217
+ for dataset_name, run_results in results_by_dataset.items():
1218
+ for run_folder, results in sorted(run_results.items()):
1219
+ if not results:
1220
+ continue
1221
+ latest = max(results, key=lambda r: r.checkpoint_step)
1222
+ name = f"{run_folder} [{dataset_name}]"
1223
+ # Group by type
1224
+ activations = []
1225
+ pre_downs = []
1226
+ outputs = []
1227
+ for tensor_name, stats in latest.layer_acts.items():
1228
+ if "pre_down" in tensor_name:
1229
+ pre_downs.append((tensor_name, stats))
1230
+ elif "output" in tensor_name and "layers" in tensor_name:
1231
+ outputs.append((tensor_name, stats))
1232
+ else:
1233
+ activations.append((tensor_name, stats))
1234
+
1235
+ # Top 5 for each type
1236
+ for group_name, group_list in [
1237
+ ("Activations", activations),
1238
+ ("Pre-down", pre_downs),
1239
+ ("Layer outputs", outputs)
1240
+ ]:
1241
+ if not group_list:
1242
+ continue
1243
+ sorted_group = sorted(group_list, key=lambda x: x[1].max_abs, reverse=True)[:5]
1244
+ print(f"\n {name} (ckpt-{latest.checkpoint_step}) – {group_name}:")
1245
+ for tensor_name, stats in sorted_group:
1246
+ print(
1247
+ f" {tensor_name:<50} max_abs={stats.max_abs:>9.4f} "
1248
+ f"mean={stats.mean:>9.4f} std={stats.std:>9.4f} norm={stats.norm:>9.4f}"
1249
+ )
1250
+
1251
+ def export_json(self, results_by_dataset: Dict[str, Dict[str, List[ModelResult]]], path: str):
1252
+ data = []
1253
+ for dataset_name, run_results in results_by_dataset.items():
1254
+ for run_folder, results in run_results.items():
1255
+ for r in results:
1256
+ entry = {
1257
+ "run_folder": run_folder,
1258
+ "model": r.model_name,
1259
+ "dataset": r.dataset_name,
1260
+ "checkpoint_step": r.checkpoint_step,
1261
+ "loss": r.loss,
1262
+ "perplexity": r.perplexity,
1263
+ "num_tokens": r.num_tokens,
1264
+ "num_layers": r.num_layers,
1265
+ "hidden_size": r.hidden_size,
1266
+ "num_params": r.num_params,
1267
+ "global_act": asdict(r.global_act),
1268
+ "layer_acts": {k: asdict(v) for k, v in r.layer_acts.items()}
1269
+ }
1270
+ data.append(entry)
1271
+
1272
+ with open(path, "w") as f:
1273
+ json.dump(data, f, indent=2)
1274
+ print(f"[Exported] Results saved to {path}")
1275
+
1276
+
1277
+ # ============================================================================
1278
+ # DRIVER CODE
1279
+ # ============================================================================
1280
+ if __name__ == "__main__":
1281
+ # --- HARDCODE WANDB LOGIN (optional, replace with your key) ---
1282
+ # wandb.login(key="wandb_v1_...")
1283
+ # -------------------------------------------------------------
1284
+
1285
+ analyzer = LLMAnalyzer(
1286
+ max_length=512,
1287
+ max_samples=100, # use None for all samples
1288
+ batch_size=50,
1289
+ wandb_project="RESEARCH-10",
1290
+ activation_disk_offload=False,
1291
+ max_elements_per_tensor=None,
1292
+ activation_hook_exclude=[],
1293
+ track_activations=True, # set to False to skip all activation collection
1294
+ capture_pre_down=True, # enable pre-down capture
1295
+ capture_layer_output=True, # enable layer output capture
1296
+ )
1297
+
1298
+ DATASETS = ["tinystories"]
1299
+ # RUN_FOLDERS = ["glu-powlu-100L_run"] # uncomment to limit runs
1300
+
1301
+ print(f"\n🚀 Starting evaluation across datasets: {DATASETS}...")
1302
+ results_by_dataset = analyzer.compute(dataset_names=DATASETS) # add run_folders if needed
1303
+
1304
+ analyzer.print_report(results_by_dataset)
1305
+ analyzer.export_json(results_by_dataset, "evaluation_results_powlu.json")
1306
+
1307
+ print("\n✅ Done! Pre-down and layer output stats are now captured.")
zain/Activation/out/glu-relu-21L_run/checkpoint-100/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "relu",
3
+ "architectures": [
4
+ "TinyLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 2,
11
+ "head_dim": 32,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 128,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 256,
16
+ "max_position_embeddings": 512,
17
+ "mlp_bias": false,
18
+ "mlp_type": "glu",
19
+ "model_type": "tiny_llama",
20
+ "num_attention_heads": 4,
21
+ "num_hidden_layers": 21,
22
+ "num_key_value_heads": 4,
23
+ "pad_token_id": 0,
24
+ "powlu_m": 3.0,
25
+ "pretraining_tp": 1,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_parameters": {
28
+ "rope_theta": 10000.0,
29
+ "rope_type": "default"
30
+ },
31
+ "tie_word_embeddings": true,
32
+ "tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
33
+ "transformers_version": "5.16.0.dev0",
34
+ "use_cache": false,
35
+ "vocab_size": 4096,
36
+ "waleed_beta": 10.0
37
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-100/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e730e191a76e95dbb3cd3af481bfa313a8b409bc08c68b383759023c76737bb
3
+ size 7961528
zain/Activation/out/glu-relu-21L_run/checkpoint-100/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ad6887d483dccb4e164338d0ed5b75c8adc297b17f7c5e3cec7b79a69b30aa2
3
+ size 16043962
zain/Activation/out/glu-relu-21L_run/checkpoint-100/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b66e3cc7c452b707ddac5caf0aa17618afb9bc1a0333600a22c4afb353f3165
3
+ size 14244
zain/Activation/out/glu-relu-21L_run/checkpoint-100/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3001486ba00eb51d89ef078fe70e7e37535cd4e2311d7dd589266d045c9fb892
3
+ size 1064
zain/Activation/out/glu-relu-21L_run/checkpoint-100/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/out/glu-relu-21L_run/checkpoint-100/tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "errors": "replace",
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "model_max_length": 1024,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>"
13
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-100/trainer_state.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.003370407819346141,
6
+ "eval_steps": 100,
7
+ "global_step": 100,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.0006740815638692282,
14
+ "grad_norm": 1.7578125,
15
+ "learning_rate": 2.66e-05,
16
+ "loss": 8.330369567871093,
17
+ "step": 20
18
+ },
19
+ {
20
+ "epoch": 0.0013481631277384564,
21
+ "grad_norm": 1.40625,
22
+ "learning_rate": 5.46e-05,
23
+ "loss": 8.17730255126953,
24
+ "step": 40
25
+ },
26
+ {
27
+ "epoch": 0.0020222446916076846,
28
+ "grad_norm": 1.3359375,
29
+ "learning_rate": 8.259999999999999e-05,
30
+ "loss": 7.952220916748047,
31
+ "step": 60
32
+ },
33
+ {
34
+ "epoch": 0.002696326255476913,
35
+ "grad_norm": 1.3125,
36
+ "learning_rate": 0.0001106,
37
+ "loss": 7.694232177734375,
38
+ "step": 80
39
+ },
40
+ {
41
+ "epoch": 0.003370407819346141,
42
+ "grad_norm": 1.234375,
43
+ "learning_rate": 0.0001386,
44
+ "loss": 7.353645324707031,
45
+ "step": 100
46
+ },
47
+ {
48
+ "epoch": 0.003370407819346141,
49
+ "eval_loss": 7.14666223526001,
50
+ "eval_runtime": 8.8883,
51
+ "eval_samples_per_second": 1071.854,
52
+ "eval_steps_per_second": 1.125,
53
+ "step": 100
54
+ }
55
+ ],
56
+ "logging_steps": 20,
57
+ "max_steps": 2500,
58
+ "num_input_tokens_seen": 0,
59
+ "num_train_epochs": 1,
60
+ "save_steps": 100,
61
+ "stateful_callbacks": {
62
+ "TrainerControl": {
63
+ "args": {
64
+ "should_epoch_stop": false,
65
+ "should_evaluate": false,
66
+ "should_log": false,
67
+ "should_save": true,
68
+ "should_training_stop": false
69
+ },
70
+ "attributes": {}
71
+ }
72
+ },
73
+ "total_flos": 33876973977600.0,
74
+ "train_batch_size": 32,
75
+ "trial_name": null,
76
+ "trial_params": null
77
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-100/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f75700c4e7fd25f6c775604daf3d7c3ad4d4f80aa4067cf2717dd0234a021fa
3
+ size 4920
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "relu",
3
+ "architectures": [
4
+ "TinyLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 2,
11
+ "head_dim": 32,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 128,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 256,
16
+ "max_position_embeddings": 512,
17
+ "mlp_bias": false,
18
+ "mlp_type": "glu",
19
+ "model_type": "tiny_llama",
20
+ "num_attention_heads": 4,
21
+ "num_hidden_layers": 21,
22
+ "num_key_value_heads": 4,
23
+ "pad_token_id": 0,
24
+ "powlu_m": 3.0,
25
+ "pretraining_tp": 1,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_parameters": {
28
+ "rope_theta": 10000.0,
29
+ "rope_type": "default"
30
+ },
31
+ "tie_word_embeddings": true,
32
+ "tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
33
+ "transformers_version": "5.16.0.dev0",
34
+ "use_cache": false,
35
+ "vocab_size": 4096,
36
+ "waleed_beta": 10.0
37
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54355292e0663f9ac459044c7426c78d8a80659efd7f1eec338da4dfccaeb26f
3
+ size 7961528
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a0778a7c68714355404663d10aa3f29b7d0228de8beac2be00d23cd444a6bc4
3
+ size 16043962
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1a97db8e41139aa1239ba7fb79ddeb0af5998c6305a440c1fe182e6ad02f2f5
3
+ size 14244
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf8d0c79c23f451fbfe25677a50bf40ae55d38cdf93a853c1a033c179996385d
3
+ size 1064
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "errors": "replace",
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "model_max_length": 1024,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>"
13
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/trainer_state.json ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.03370407819346141,
6
+ "eval_steps": 100,
7
+ "global_step": 1000,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.0006740815638692282,
14
+ "grad_norm": 1.7578125,
15
+ "learning_rate": 2.66e-05,
16
+ "loss": 8.330369567871093,
17
+ "step": 20
18
+ },
19
+ {
20
+ "epoch": 0.0013481631277384564,
21
+ "grad_norm": 1.40625,
22
+ "learning_rate": 5.46e-05,
23
+ "loss": 8.17730255126953,
24
+ "step": 40
25
+ },
26
+ {
27
+ "epoch": 0.0020222446916076846,
28
+ "grad_norm": 1.3359375,
29
+ "learning_rate": 8.259999999999999e-05,
30
+ "loss": 7.952220916748047,
31
+ "step": 60
32
+ },
33
+ {
34
+ "epoch": 0.002696326255476913,
35
+ "grad_norm": 1.3125,
36
+ "learning_rate": 0.0001106,
37
+ "loss": 7.694232177734375,
38
+ "step": 80
39
+ },
40
+ {
41
+ "epoch": 0.003370407819346141,
42
+ "grad_norm": 1.234375,
43
+ "learning_rate": 0.0001386,
44
+ "loss": 7.353645324707031,
45
+ "step": 100
46
+ },
47
+ {
48
+ "epoch": 0.003370407819346141,
49
+ "eval_loss": 7.14666223526001,
50
+ "eval_runtime": 8.8883,
51
+ "eval_samples_per_second": 1071.854,
52
+ "eval_steps_per_second": 1.125,
53
+ "step": 100
54
+ },
55
+ {
56
+ "epoch": 0.004044489383215369,
57
+ "grad_norm": 1.1796875,
58
+ "learning_rate": 0.00016659999999999998,
59
+ "loss": 6.9598846435546875,
60
+ "step": 120
61
+ },
62
+ {
63
+ "epoch": 0.0047185709470845974,
64
+ "grad_norm": 1.1015625,
65
+ "learning_rate": 0.00019460000000000001,
66
+ "loss": 6.568833923339843,
67
+ "step": 140
68
+ },
69
+ {
70
+ "epoch": 0.005392652510953826,
71
+ "grad_norm": 1.046875,
72
+ "learning_rate": 0.0002226,
73
+ "loss": 6.253362655639648,
74
+ "step": 160
75
+ },
76
+ {
77
+ "epoch": 0.006066734074823054,
78
+ "grad_norm": 0.86328125,
79
+ "learning_rate": 0.00025059999999999997,
80
+ "loss": 5.974322509765625,
81
+ "step": 180
82
+ },
83
+ {
84
+ "epoch": 0.006740815638692282,
85
+ "grad_norm": 0.80078125,
86
+ "learning_rate": 0.0002786,
87
+ "loss": 5.698452377319336,
88
+ "step": 200
89
+ },
90
+ {
91
+ "epoch": 0.006740815638692282,
92
+ "eval_loss": 5.558600902557373,
93
+ "eval_runtime": 9.1031,
94
+ "eval_samples_per_second": 1046.564,
95
+ "eval_steps_per_second": 1.099,
96
+ "step": 200
97
+ },
98
+ {
99
+ "epoch": 0.00741489720256151,
100
+ "grad_norm": 0.8046875,
101
+ "learning_rate": 0.00030659999999999997,
102
+ "loss": 5.451509857177735,
103
+ "step": 220
104
+ },
105
+ {
106
+ "epoch": 0.008088978766430738,
107
+ "grad_norm": 1.0078125,
108
+ "learning_rate": 0.0003346,
109
+ "loss": 5.163370895385742,
110
+ "step": 240
111
+ },
112
+ {
113
+ "epoch": 0.008763060330299966,
114
+ "grad_norm": 1.0859375,
115
+ "learning_rate": 0.00036260000000000003,
116
+ "loss": 4.929123306274414,
117
+ "step": 260
118
+ },
119
+ {
120
+ "epoch": 0.009437141894169195,
121
+ "grad_norm": 0.84765625,
122
+ "learning_rate": 0.0003906,
123
+ "loss": 4.702068710327149,
124
+ "step": 280
125
+ },
126
+ {
127
+ "epoch": 0.010111223458038422,
128
+ "grad_norm": 0.91796875,
129
+ "learning_rate": 0.0004186,
130
+ "loss": 4.501141738891602,
131
+ "step": 300
132
+ },
133
+ {
134
+ "epoch": 0.010111223458038422,
135
+ "eval_loss": 4.396740913391113,
136
+ "eval_runtime": 8.9474,
137
+ "eval_samples_per_second": 1064.782,
138
+ "eval_steps_per_second": 1.118,
139
+ "step": 300
140
+ },
141
+ {
142
+ "epoch": 0.010785305021907651,
143
+ "grad_norm": 0.9453125,
144
+ "learning_rate": 0.0004466,
145
+ "loss": 4.323627853393555,
146
+ "step": 320
147
+ },
148
+ {
149
+ "epoch": 0.011459386585776879,
150
+ "grad_norm": 0.88671875,
151
+ "learning_rate": 0.00047460000000000004,
152
+ "loss": 4.204174041748047,
153
+ "step": 340
154
+ },
155
+ {
156
+ "epoch": 0.012133468149646108,
157
+ "grad_norm": 0.92578125,
158
+ "learning_rate": 0.0005026,
159
+ "loss": 4.052695846557617,
160
+ "step": 360
161
+ },
162
+ {
163
+ "epoch": 0.012807549713515335,
164
+ "grad_norm": 0.6484375,
165
+ "learning_rate": 0.0005306,
166
+ "loss": 3.947071075439453,
167
+ "step": 380
168
+ },
169
+ {
170
+ "epoch": 0.013481631277384564,
171
+ "grad_norm": 0.73828125,
172
+ "learning_rate": 0.0005586,
173
+ "loss": 3.855146026611328,
174
+ "step": 400
175
+ },
176
+ {
177
+ "epoch": 0.013481631277384564,
178
+ "eval_loss": 3.8139851093292236,
179
+ "eval_runtime": 8.9743,
180
+ "eval_samples_per_second": 1061.59,
181
+ "eval_steps_per_second": 1.114,
182
+ "step": 400
183
+ },
184
+ {
185
+ "epoch": 0.014155712841253791,
186
+ "grad_norm": 0.80859375,
187
+ "learning_rate": 0.0005866,
188
+ "loss": 3.76041259765625,
189
+ "step": 420
190
+ },
191
+ {
192
+ "epoch": 0.01482979440512302,
193
+ "grad_norm": 0.77734375,
194
+ "learning_rate": 0.0006146,
195
+ "loss": 3.708443450927734,
196
+ "step": 440
197
+ },
198
+ {
199
+ "epoch": 0.015503875968992248,
200
+ "grad_norm": 0.7421875,
201
+ "learning_rate": 0.0006426,
202
+ "loss": 3.637612152099609,
203
+ "step": 460
204
+ },
205
+ {
206
+ "epoch": 0.016177957532861477,
207
+ "grad_norm": 0.6640625,
208
+ "learning_rate": 0.0006705999999999999,
209
+ "loss": 3.556614303588867,
210
+ "step": 480
211
+ },
212
+ {
213
+ "epoch": 0.016852039096730706,
214
+ "grad_norm": 0.7421875,
215
+ "learning_rate": 0.0006986,
216
+ "loss": 3.5122703552246093,
217
+ "step": 500
218
+ },
219
+ {
220
+ "epoch": 0.016852039096730706,
221
+ "eval_loss": 3.4916131496429443,
222
+ "eval_runtime": 8.8876,
223
+ "eval_samples_per_second": 1071.946,
224
+ "eval_steps_per_second": 1.125,
225
+ "step": 500
226
+ },
227
+ {
228
+ "epoch": 0.01752612066059993,
229
+ "grad_norm": 0.80078125,
230
+ "learning_rate": 0.0007,
231
+ "loss": 3.477622222900391,
232
+ "step": 520
233
+ },
234
+ {
235
+ "epoch": 0.01820020222446916,
236
+ "grad_norm": 0.75390625,
237
+ "learning_rate": 0.0007,
238
+ "loss": 3.4115901947021485,
239
+ "step": 540
240
+ },
241
+ {
242
+ "epoch": 0.01887428378833839,
243
+ "grad_norm": 0.60546875,
244
+ "learning_rate": 0.0007,
245
+ "loss": 3.359669876098633,
246
+ "step": 560
247
+ },
248
+ {
249
+ "epoch": 0.01954836535220762,
250
+ "grad_norm": 0.6796875,
251
+ "learning_rate": 0.0007,
252
+ "loss": 3.3188705444335938,
253
+ "step": 580
254
+ },
255
+ {
256
+ "epoch": 0.020222446916076844,
257
+ "grad_norm": 0.67578125,
258
+ "learning_rate": 0.0007,
259
+ "loss": 3.2840240478515623,
260
+ "step": 600
261
+ },
262
+ {
263
+ "epoch": 0.020222446916076844,
264
+ "eval_loss": 3.2660911083221436,
265
+ "eval_runtime": 8.9246,
266
+ "eval_samples_per_second": 1067.504,
267
+ "eval_steps_per_second": 1.121,
268
+ "step": 600
269
+ },
270
+ {
271
+ "epoch": 0.020896528479946073,
272
+ "grad_norm": 0.7421875,
273
+ "learning_rate": 0.0007,
274
+ "loss": 3.223845672607422,
275
+ "step": 620
276
+ },
277
+ {
278
+ "epoch": 0.021570610043815303,
279
+ "grad_norm": 0.67578125,
280
+ "learning_rate": 0.0007,
281
+ "loss": 3.2053298950195312,
282
+ "step": 640
283
+ },
284
+ {
285
+ "epoch": 0.022244691607684528,
286
+ "grad_norm": 0.890625,
287
+ "learning_rate": 0.0007,
288
+ "loss": 3.1749242782592773,
289
+ "step": 660
290
+ },
291
+ {
292
+ "epoch": 0.022918773171553757,
293
+ "grad_norm": 0.5859375,
294
+ "learning_rate": 0.0007,
295
+ "loss": 3.134219741821289,
296
+ "step": 680
297
+ },
298
+ {
299
+ "epoch": 0.023592854735422986,
300
+ "grad_norm": 0.6640625,
301
+ "learning_rate": 0.0007,
302
+ "loss": 3.1245954513549803,
303
+ "step": 700
304
+ },
305
+ {
306
+ "epoch": 0.023592854735422986,
307
+ "eval_loss": 3.113696575164795,
308
+ "eval_runtime": 8.8675,
309
+ "eval_samples_per_second": 1074.373,
310
+ "eval_steps_per_second": 1.128,
311
+ "step": 700
312
+ },
313
+ {
314
+ "epoch": 0.024266936299292215,
315
+ "grad_norm": 0.62890625,
316
+ "learning_rate": 0.0007,
317
+ "loss": 3.0987874984741213,
318
+ "step": 720
319
+ },
320
+ {
321
+ "epoch": 0.02494101786316144,
322
+ "grad_norm": 0.73046875,
323
+ "learning_rate": 0.0007,
324
+ "loss": 3.08369140625,
325
+ "step": 740
326
+ },
327
+ {
328
+ "epoch": 0.02561509942703067,
329
+ "grad_norm": 0.62890625,
330
+ "learning_rate": 0.0007,
331
+ "loss": 3.03726863861084,
332
+ "step": 760
333
+ },
334
+ {
335
+ "epoch": 0.0262891809908999,
336
+ "grad_norm": 0.64453125,
337
+ "learning_rate": 0.0007,
338
+ "loss": 2.9970935821533202,
339
+ "step": 780
340
+ },
341
+ {
342
+ "epoch": 0.026963262554769128,
343
+ "grad_norm": 0.625,
344
+ "learning_rate": 0.0007,
345
+ "loss": 3.006105422973633,
346
+ "step": 800
347
+ },
348
+ {
349
+ "epoch": 0.026963262554769128,
350
+ "eval_loss": 2.999389886856079,
351
+ "eval_runtime": 8.984,
352
+ "eval_samples_per_second": 1060.442,
353
+ "eval_steps_per_second": 1.113,
354
+ "step": 800
355
+ },
356
+ {
357
+ "epoch": 0.027637344118638354,
358
+ "grad_norm": 0.609375,
359
+ "learning_rate": 0.0007,
360
+ "loss": 2.9657209396362303,
361
+ "step": 820
362
+ },
363
+ {
364
+ "epoch": 0.028311425682507583,
365
+ "grad_norm": 0.67578125,
366
+ "learning_rate": 0.0007,
367
+ "loss": 2.9664005279541015,
368
+ "step": 840
369
+ },
370
+ {
371
+ "epoch": 0.028985507246376812,
372
+ "grad_norm": 0.65625,
373
+ "learning_rate": 0.0007,
374
+ "loss": 2.988846206665039,
375
+ "step": 860
376
+ },
377
+ {
378
+ "epoch": 0.02965958881024604,
379
+ "grad_norm": 0.66015625,
380
+ "learning_rate": 0.0007,
381
+ "loss": 2.9386875152587892,
382
+ "step": 880
383
+ },
384
+ {
385
+ "epoch": 0.030333670374115267,
386
+ "grad_norm": 0.7109375,
387
+ "learning_rate": 0.0007,
388
+ "loss": 2.8965709686279295,
389
+ "step": 900
390
+ },
391
+ {
392
+ "epoch": 0.030333670374115267,
393
+ "eval_loss": 2.9093611240386963,
394
+ "eval_runtime": 8.9344,
395
+ "eval_samples_per_second": 1066.332,
396
+ "eval_steps_per_second": 1.119,
397
+ "step": 900
398
+ },
399
+ {
400
+ "epoch": 0.031007751937984496,
401
+ "grad_norm": 0.62109375,
402
+ "learning_rate": 0.0007,
403
+ "loss": 2.9101829528808594,
404
+ "step": 920
405
+ },
406
+ {
407
+ "epoch": 0.031681833501853725,
408
+ "grad_norm": 0.5859375,
409
+ "learning_rate": 0.0007,
410
+ "loss": 2.8905385971069335,
411
+ "step": 940
412
+ },
413
+ {
414
+ "epoch": 0.032355915065722954,
415
+ "grad_norm": 0.74609375,
416
+ "learning_rate": 0.0007,
417
+ "loss": 2.8552478790283202,
418
+ "step": 960
419
+ },
420
+ {
421
+ "epoch": 0.03302999662959218,
422
+ "grad_norm": 0.62109375,
423
+ "learning_rate": 0.0007,
424
+ "loss": 2.8467588424682617,
425
+ "step": 980
426
+ },
427
+ {
428
+ "epoch": 0.03370407819346141,
429
+ "grad_norm": 0.60546875,
430
+ "learning_rate": 0.0007,
431
+ "loss": 2.831803894042969,
432
+ "step": 1000
433
+ },
434
+ {
435
+ "epoch": 0.03370407819346141,
436
+ "eval_loss": 2.8364417552948,
437
+ "eval_runtime": 8.9776,
438
+ "eval_samples_per_second": 1061.195,
439
+ "eval_steps_per_second": 1.114,
440
+ "step": 1000
441
+ }
442
+ ],
443
+ "logging_steps": 20,
444
+ "max_steps": 2500,
445
+ "num_input_tokens_seen": 0,
446
+ "num_train_epochs": 1,
447
+ "save_steps": 100,
448
+ "stateful_callbacks": {
449
+ "TrainerControl": {
450
+ "args": {
451
+ "should_epoch_stop": false,
452
+ "should_evaluate": false,
453
+ "should_log": false,
454
+ "should_save": true,
455
+ "should_training_stop": false
456
+ },
457
+ "attributes": {}
458
+ }
459
+ },
460
+ "total_flos": 338769739776000.0,
461
+ "train_batch_size": 32,
462
+ "trial_name": null,
463
+ "trial_params": null
464
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1000/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f75700c4e7fd25f6c775604daf3d7c3ad4d4f80aa4067cf2717dd0234a021fa
3
+ size 4920
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "relu",
3
+ "architectures": [
4
+ "TinyLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 2,
11
+ "head_dim": 32,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 128,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 256,
16
+ "max_position_embeddings": 512,
17
+ "mlp_bias": false,
18
+ "mlp_type": "glu",
19
+ "model_type": "tiny_llama",
20
+ "num_attention_heads": 4,
21
+ "num_hidden_layers": 21,
22
+ "num_key_value_heads": 4,
23
+ "pad_token_id": 0,
24
+ "powlu_m": 3.0,
25
+ "pretraining_tp": 1,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_parameters": {
28
+ "rope_theta": 10000.0,
29
+ "rope_type": "default"
30
+ },
31
+ "tie_word_embeddings": true,
32
+ "tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
33
+ "transformers_version": "5.16.0.dev0",
34
+ "use_cache": false,
35
+ "vocab_size": 4096,
36
+ "waleed_beta": 10.0
37
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a7f0f8355c0d95869b8bbbc048d09b873e6fb26d87b198483029afdecfb6ff5
3
+ size 7961528
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b5b56e3b063a7c3a88de55a8bf90da1217fc3ae393307efbda1003fbbfbb5bc
3
+ size 16043962
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2b5691046896d865f067a1958689168fc2411c74d2f82d596bd6a636b2b141b
3
+ size 14244
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88121baf7de31688d97eca5c32cb058d585673d52f936d32dcd04e8b1903dcac
3
+ size 1064
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "errors": "replace",
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "model_max_length": 1024,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>"
13
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/trainer_state.json ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.03707448601280755,
6
+ "eval_steps": 100,
7
+ "global_step": 1100,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.0006740815638692282,
14
+ "grad_norm": 1.7578125,
15
+ "learning_rate": 2.66e-05,
16
+ "loss": 8.330369567871093,
17
+ "step": 20
18
+ },
19
+ {
20
+ "epoch": 0.0013481631277384564,
21
+ "grad_norm": 1.40625,
22
+ "learning_rate": 5.46e-05,
23
+ "loss": 8.17730255126953,
24
+ "step": 40
25
+ },
26
+ {
27
+ "epoch": 0.0020222446916076846,
28
+ "grad_norm": 1.3359375,
29
+ "learning_rate": 8.259999999999999e-05,
30
+ "loss": 7.952220916748047,
31
+ "step": 60
32
+ },
33
+ {
34
+ "epoch": 0.002696326255476913,
35
+ "grad_norm": 1.3125,
36
+ "learning_rate": 0.0001106,
37
+ "loss": 7.694232177734375,
38
+ "step": 80
39
+ },
40
+ {
41
+ "epoch": 0.003370407819346141,
42
+ "grad_norm": 1.234375,
43
+ "learning_rate": 0.0001386,
44
+ "loss": 7.353645324707031,
45
+ "step": 100
46
+ },
47
+ {
48
+ "epoch": 0.003370407819346141,
49
+ "eval_loss": 7.14666223526001,
50
+ "eval_runtime": 8.8883,
51
+ "eval_samples_per_second": 1071.854,
52
+ "eval_steps_per_second": 1.125,
53
+ "step": 100
54
+ },
55
+ {
56
+ "epoch": 0.004044489383215369,
57
+ "grad_norm": 1.1796875,
58
+ "learning_rate": 0.00016659999999999998,
59
+ "loss": 6.9598846435546875,
60
+ "step": 120
61
+ },
62
+ {
63
+ "epoch": 0.0047185709470845974,
64
+ "grad_norm": 1.1015625,
65
+ "learning_rate": 0.00019460000000000001,
66
+ "loss": 6.568833923339843,
67
+ "step": 140
68
+ },
69
+ {
70
+ "epoch": 0.005392652510953826,
71
+ "grad_norm": 1.046875,
72
+ "learning_rate": 0.0002226,
73
+ "loss": 6.253362655639648,
74
+ "step": 160
75
+ },
76
+ {
77
+ "epoch": 0.006066734074823054,
78
+ "grad_norm": 0.86328125,
79
+ "learning_rate": 0.00025059999999999997,
80
+ "loss": 5.974322509765625,
81
+ "step": 180
82
+ },
83
+ {
84
+ "epoch": 0.006740815638692282,
85
+ "grad_norm": 0.80078125,
86
+ "learning_rate": 0.0002786,
87
+ "loss": 5.698452377319336,
88
+ "step": 200
89
+ },
90
+ {
91
+ "epoch": 0.006740815638692282,
92
+ "eval_loss": 5.558600902557373,
93
+ "eval_runtime": 9.1031,
94
+ "eval_samples_per_second": 1046.564,
95
+ "eval_steps_per_second": 1.099,
96
+ "step": 200
97
+ },
98
+ {
99
+ "epoch": 0.00741489720256151,
100
+ "grad_norm": 0.8046875,
101
+ "learning_rate": 0.00030659999999999997,
102
+ "loss": 5.451509857177735,
103
+ "step": 220
104
+ },
105
+ {
106
+ "epoch": 0.008088978766430738,
107
+ "grad_norm": 1.0078125,
108
+ "learning_rate": 0.0003346,
109
+ "loss": 5.163370895385742,
110
+ "step": 240
111
+ },
112
+ {
113
+ "epoch": 0.008763060330299966,
114
+ "grad_norm": 1.0859375,
115
+ "learning_rate": 0.00036260000000000003,
116
+ "loss": 4.929123306274414,
117
+ "step": 260
118
+ },
119
+ {
120
+ "epoch": 0.009437141894169195,
121
+ "grad_norm": 0.84765625,
122
+ "learning_rate": 0.0003906,
123
+ "loss": 4.702068710327149,
124
+ "step": 280
125
+ },
126
+ {
127
+ "epoch": 0.010111223458038422,
128
+ "grad_norm": 0.91796875,
129
+ "learning_rate": 0.0004186,
130
+ "loss": 4.501141738891602,
131
+ "step": 300
132
+ },
133
+ {
134
+ "epoch": 0.010111223458038422,
135
+ "eval_loss": 4.396740913391113,
136
+ "eval_runtime": 8.9474,
137
+ "eval_samples_per_second": 1064.782,
138
+ "eval_steps_per_second": 1.118,
139
+ "step": 300
140
+ },
141
+ {
142
+ "epoch": 0.010785305021907651,
143
+ "grad_norm": 0.9453125,
144
+ "learning_rate": 0.0004466,
145
+ "loss": 4.323627853393555,
146
+ "step": 320
147
+ },
148
+ {
149
+ "epoch": 0.011459386585776879,
150
+ "grad_norm": 0.88671875,
151
+ "learning_rate": 0.00047460000000000004,
152
+ "loss": 4.204174041748047,
153
+ "step": 340
154
+ },
155
+ {
156
+ "epoch": 0.012133468149646108,
157
+ "grad_norm": 0.92578125,
158
+ "learning_rate": 0.0005026,
159
+ "loss": 4.052695846557617,
160
+ "step": 360
161
+ },
162
+ {
163
+ "epoch": 0.012807549713515335,
164
+ "grad_norm": 0.6484375,
165
+ "learning_rate": 0.0005306,
166
+ "loss": 3.947071075439453,
167
+ "step": 380
168
+ },
169
+ {
170
+ "epoch": 0.013481631277384564,
171
+ "grad_norm": 0.73828125,
172
+ "learning_rate": 0.0005586,
173
+ "loss": 3.855146026611328,
174
+ "step": 400
175
+ },
176
+ {
177
+ "epoch": 0.013481631277384564,
178
+ "eval_loss": 3.8139851093292236,
179
+ "eval_runtime": 8.9743,
180
+ "eval_samples_per_second": 1061.59,
181
+ "eval_steps_per_second": 1.114,
182
+ "step": 400
183
+ },
184
+ {
185
+ "epoch": 0.014155712841253791,
186
+ "grad_norm": 0.80859375,
187
+ "learning_rate": 0.0005866,
188
+ "loss": 3.76041259765625,
189
+ "step": 420
190
+ },
191
+ {
192
+ "epoch": 0.01482979440512302,
193
+ "grad_norm": 0.77734375,
194
+ "learning_rate": 0.0006146,
195
+ "loss": 3.708443450927734,
196
+ "step": 440
197
+ },
198
+ {
199
+ "epoch": 0.015503875968992248,
200
+ "grad_norm": 0.7421875,
201
+ "learning_rate": 0.0006426,
202
+ "loss": 3.637612152099609,
203
+ "step": 460
204
+ },
205
+ {
206
+ "epoch": 0.016177957532861477,
207
+ "grad_norm": 0.6640625,
208
+ "learning_rate": 0.0006705999999999999,
209
+ "loss": 3.556614303588867,
210
+ "step": 480
211
+ },
212
+ {
213
+ "epoch": 0.016852039096730706,
214
+ "grad_norm": 0.7421875,
215
+ "learning_rate": 0.0006986,
216
+ "loss": 3.5122703552246093,
217
+ "step": 500
218
+ },
219
+ {
220
+ "epoch": 0.016852039096730706,
221
+ "eval_loss": 3.4916131496429443,
222
+ "eval_runtime": 8.8876,
223
+ "eval_samples_per_second": 1071.946,
224
+ "eval_steps_per_second": 1.125,
225
+ "step": 500
226
+ },
227
+ {
228
+ "epoch": 0.01752612066059993,
229
+ "grad_norm": 0.80078125,
230
+ "learning_rate": 0.0007,
231
+ "loss": 3.477622222900391,
232
+ "step": 520
233
+ },
234
+ {
235
+ "epoch": 0.01820020222446916,
236
+ "grad_norm": 0.75390625,
237
+ "learning_rate": 0.0007,
238
+ "loss": 3.4115901947021485,
239
+ "step": 540
240
+ },
241
+ {
242
+ "epoch": 0.01887428378833839,
243
+ "grad_norm": 0.60546875,
244
+ "learning_rate": 0.0007,
245
+ "loss": 3.359669876098633,
246
+ "step": 560
247
+ },
248
+ {
249
+ "epoch": 0.01954836535220762,
250
+ "grad_norm": 0.6796875,
251
+ "learning_rate": 0.0007,
252
+ "loss": 3.3188705444335938,
253
+ "step": 580
254
+ },
255
+ {
256
+ "epoch": 0.020222446916076844,
257
+ "grad_norm": 0.67578125,
258
+ "learning_rate": 0.0007,
259
+ "loss": 3.2840240478515623,
260
+ "step": 600
261
+ },
262
+ {
263
+ "epoch": 0.020222446916076844,
264
+ "eval_loss": 3.2660911083221436,
265
+ "eval_runtime": 8.9246,
266
+ "eval_samples_per_second": 1067.504,
267
+ "eval_steps_per_second": 1.121,
268
+ "step": 600
269
+ },
270
+ {
271
+ "epoch": 0.020896528479946073,
272
+ "grad_norm": 0.7421875,
273
+ "learning_rate": 0.0007,
274
+ "loss": 3.223845672607422,
275
+ "step": 620
276
+ },
277
+ {
278
+ "epoch": 0.021570610043815303,
279
+ "grad_norm": 0.67578125,
280
+ "learning_rate": 0.0007,
281
+ "loss": 3.2053298950195312,
282
+ "step": 640
283
+ },
284
+ {
285
+ "epoch": 0.022244691607684528,
286
+ "grad_norm": 0.890625,
287
+ "learning_rate": 0.0007,
288
+ "loss": 3.1749242782592773,
289
+ "step": 660
290
+ },
291
+ {
292
+ "epoch": 0.022918773171553757,
293
+ "grad_norm": 0.5859375,
294
+ "learning_rate": 0.0007,
295
+ "loss": 3.134219741821289,
296
+ "step": 680
297
+ },
298
+ {
299
+ "epoch": 0.023592854735422986,
300
+ "grad_norm": 0.6640625,
301
+ "learning_rate": 0.0007,
302
+ "loss": 3.1245954513549803,
303
+ "step": 700
304
+ },
305
+ {
306
+ "epoch": 0.023592854735422986,
307
+ "eval_loss": 3.113696575164795,
308
+ "eval_runtime": 8.8675,
309
+ "eval_samples_per_second": 1074.373,
310
+ "eval_steps_per_second": 1.128,
311
+ "step": 700
312
+ },
313
+ {
314
+ "epoch": 0.024266936299292215,
315
+ "grad_norm": 0.62890625,
316
+ "learning_rate": 0.0007,
317
+ "loss": 3.0987874984741213,
318
+ "step": 720
319
+ },
320
+ {
321
+ "epoch": 0.02494101786316144,
322
+ "grad_norm": 0.73046875,
323
+ "learning_rate": 0.0007,
324
+ "loss": 3.08369140625,
325
+ "step": 740
326
+ },
327
+ {
328
+ "epoch": 0.02561509942703067,
329
+ "grad_norm": 0.62890625,
330
+ "learning_rate": 0.0007,
331
+ "loss": 3.03726863861084,
332
+ "step": 760
333
+ },
334
+ {
335
+ "epoch": 0.0262891809908999,
336
+ "grad_norm": 0.64453125,
337
+ "learning_rate": 0.0007,
338
+ "loss": 2.9970935821533202,
339
+ "step": 780
340
+ },
341
+ {
342
+ "epoch": 0.026963262554769128,
343
+ "grad_norm": 0.625,
344
+ "learning_rate": 0.0007,
345
+ "loss": 3.006105422973633,
346
+ "step": 800
347
+ },
348
+ {
349
+ "epoch": 0.026963262554769128,
350
+ "eval_loss": 2.999389886856079,
351
+ "eval_runtime": 8.984,
352
+ "eval_samples_per_second": 1060.442,
353
+ "eval_steps_per_second": 1.113,
354
+ "step": 800
355
+ },
356
+ {
357
+ "epoch": 0.027637344118638354,
358
+ "grad_norm": 0.609375,
359
+ "learning_rate": 0.0007,
360
+ "loss": 2.9657209396362303,
361
+ "step": 820
362
+ },
363
+ {
364
+ "epoch": 0.028311425682507583,
365
+ "grad_norm": 0.67578125,
366
+ "learning_rate": 0.0007,
367
+ "loss": 2.9664005279541015,
368
+ "step": 840
369
+ },
370
+ {
371
+ "epoch": 0.028985507246376812,
372
+ "grad_norm": 0.65625,
373
+ "learning_rate": 0.0007,
374
+ "loss": 2.988846206665039,
375
+ "step": 860
376
+ },
377
+ {
378
+ "epoch": 0.02965958881024604,
379
+ "grad_norm": 0.66015625,
380
+ "learning_rate": 0.0007,
381
+ "loss": 2.9386875152587892,
382
+ "step": 880
383
+ },
384
+ {
385
+ "epoch": 0.030333670374115267,
386
+ "grad_norm": 0.7109375,
387
+ "learning_rate": 0.0007,
388
+ "loss": 2.8965709686279295,
389
+ "step": 900
390
+ },
391
+ {
392
+ "epoch": 0.030333670374115267,
393
+ "eval_loss": 2.9093611240386963,
394
+ "eval_runtime": 8.9344,
395
+ "eval_samples_per_second": 1066.332,
396
+ "eval_steps_per_second": 1.119,
397
+ "step": 900
398
+ },
399
+ {
400
+ "epoch": 0.031007751937984496,
401
+ "grad_norm": 0.62109375,
402
+ "learning_rate": 0.0007,
403
+ "loss": 2.9101829528808594,
404
+ "step": 920
405
+ },
406
+ {
407
+ "epoch": 0.031681833501853725,
408
+ "grad_norm": 0.5859375,
409
+ "learning_rate": 0.0007,
410
+ "loss": 2.8905385971069335,
411
+ "step": 940
412
+ },
413
+ {
414
+ "epoch": 0.032355915065722954,
415
+ "grad_norm": 0.74609375,
416
+ "learning_rate": 0.0007,
417
+ "loss": 2.8552478790283202,
418
+ "step": 960
419
+ },
420
+ {
421
+ "epoch": 0.03302999662959218,
422
+ "grad_norm": 0.62109375,
423
+ "learning_rate": 0.0007,
424
+ "loss": 2.8467588424682617,
425
+ "step": 980
426
+ },
427
+ {
428
+ "epoch": 0.03370407819346141,
429
+ "grad_norm": 0.60546875,
430
+ "learning_rate": 0.0007,
431
+ "loss": 2.831803894042969,
432
+ "step": 1000
433
+ },
434
+ {
435
+ "epoch": 0.03370407819346141,
436
+ "eval_loss": 2.8364417552948,
437
+ "eval_runtime": 8.9776,
438
+ "eval_samples_per_second": 1061.195,
439
+ "eval_steps_per_second": 1.114,
440
+ "step": 1000
441
+ },
442
+ {
443
+ "epoch": 0.034378159757330634,
444
+ "grad_norm": 0.640625,
445
+ "learning_rate": 0.0007,
446
+ "loss": 2.831756591796875,
447
+ "step": 1020
448
+ },
449
+ {
450
+ "epoch": 0.03505224132119986,
451
+ "grad_norm": 0.6796875,
452
+ "learning_rate": 0.0007,
453
+ "loss": 2.8086965560913084,
454
+ "step": 1040
455
+ },
456
+ {
457
+ "epoch": 0.03572632288506909,
458
+ "grad_norm": 0.59375,
459
+ "learning_rate": 0.0007,
460
+ "loss": 2.7877662658691404,
461
+ "step": 1060
462
+ },
463
+ {
464
+ "epoch": 0.03640040444893832,
465
+ "grad_norm": 0.71875,
466
+ "learning_rate": 0.0007,
467
+ "loss": 2.7670337677001955,
468
+ "step": 1080
469
+ },
470
+ {
471
+ "epoch": 0.03707448601280755,
472
+ "grad_norm": 0.65234375,
473
+ "learning_rate": 0.0007,
474
+ "loss": 2.762655830383301,
475
+ "step": 1100
476
+ },
477
+ {
478
+ "epoch": 0.03707448601280755,
479
+ "eval_loss": 2.7699334621429443,
480
+ "eval_runtime": 8.8675,
481
+ "eval_samples_per_second": 1074.369,
482
+ "eval_steps_per_second": 1.128,
483
+ "step": 1100
484
+ }
485
+ ],
486
+ "logging_steps": 20,
487
+ "max_steps": 2500,
488
+ "num_input_tokens_seen": 0,
489
+ "num_train_epochs": 1,
490
+ "save_steps": 100,
491
+ "stateful_callbacks": {
492
+ "TrainerControl": {
493
+ "args": {
494
+ "should_epoch_stop": false,
495
+ "should_evaluate": false,
496
+ "should_log": false,
497
+ "should_save": true,
498
+ "should_training_stop": false
499
+ },
500
+ "attributes": {}
501
+ }
502
+ },
503
+ "total_flos": 372646713753600.0,
504
+ "train_batch_size": 32,
505
+ "trial_name": null,
506
+ "trial_params": null
507
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1100/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f75700c4e7fd25f6c775604daf3d7c3ad4d4f80aa4067cf2717dd0234a021fa
3
+ size 4920
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "relu",
3
+ "architectures": [
4
+ "TinyLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 2,
11
+ "head_dim": 32,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 128,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 256,
16
+ "max_position_embeddings": 512,
17
+ "mlp_bias": false,
18
+ "mlp_type": "glu",
19
+ "model_type": "tiny_llama",
20
+ "num_attention_heads": 4,
21
+ "num_hidden_layers": 21,
22
+ "num_key_value_heads": 4,
23
+ "pad_token_id": 0,
24
+ "powlu_m": 3.0,
25
+ "pretraining_tp": 1,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_parameters": {
28
+ "rope_theta": 10000.0,
29
+ "rope_type": "default"
30
+ },
31
+ "tie_word_embeddings": true,
32
+ "tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
33
+ "transformers_version": "5.16.0.dev0",
34
+ "use_cache": false,
35
+ "vocab_size": 4096,
36
+ "waleed_beta": 10.0
37
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cd3ebe7db4a3c192f69c15fd73cd7dbc23dade94d7abef52878fb464367ea3a
3
+ size 7961528
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da2db86bffb780305366c2ea91f659f699741c4a620767fcf12e825c9bb1eb06
3
+ size 16043962
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0b8a6e3878f9402461193b241d8f1ee8546c6ad03f43e5b9dab8f4fc8c4d065
3
+ size 14244
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8543afc9166865219cadbba29db865d839ec4102a4f9ddeffc962b9fdba3b028
3
+ size 1064
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "errors": "replace",
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "model_max_length": 1024,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>"
13
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/trainer_state.json ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.04044489383215369,
6
+ "eval_steps": 100,
7
+ "global_step": 1200,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.0006740815638692282,
14
+ "grad_norm": 1.7578125,
15
+ "learning_rate": 2.66e-05,
16
+ "loss": 8.330369567871093,
17
+ "step": 20
18
+ },
19
+ {
20
+ "epoch": 0.0013481631277384564,
21
+ "grad_norm": 1.40625,
22
+ "learning_rate": 5.46e-05,
23
+ "loss": 8.17730255126953,
24
+ "step": 40
25
+ },
26
+ {
27
+ "epoch": 0.0020222446916076846,
28
+ "grad_norm": 1.3359375,
29
+ "learning_rate": 8.259999999999999e-05,
30
+ "loss": 7.952220916748047,
31
+ "step": 60
32
+ },
33
+ {
34
+ "epoch": 0.002696326255476913,
35
+ "grad_norm": 1.3125,
36
+ "learning_rate": 0.0001106,
37
+ "loss": 7.694232177734375,
38
+ "step": 80
39
+ },
40
+ {
41
+ "epoch": 0.003370407819346141,
42
+ "grad_norm": 1.234375,
43
+ "learning_rate": 0.0001386,
44
+ "loss": 7.353645324707031,
45
+ "step": 100
46
+ },
47
+ {
48
+ "epoch": 0.003370407819346141,
49
+ "eval_loss": 7.14666223526001,
50
+ "eval_runtime": 8.8883,
51
+ "eval_samples_per_second": 1071.854,
52
+ "eval_steps_per_second": 1.125,
53
+ "step": 100
54
+ },
55
+ {
56
+ "epoch": 0.004044489383215369,
57
+ "grad_norm": 1.1796875,
58
+ "learning_rate": 0.00016659999999999998,
59
+ "loss": 6.9598846435546875,
60
+ "step": 120
61
+ },
62
+ {
63
+ "epoch": 0.0047185709470845974,
64
+ "grad_norm": 1.1015625,
65
+ "learning_rate": 0.00019460000000000001,
66
+ "loss": 6.568833923339843,
67
+ "step": 140
68
+ },
69
+ {
70
+ "epoch": 0.005392652510953826,
71
+ "grad_norm": 1.046875,
72
+ "learning_rate": 0.0002226,
73
+ "loss": 6.253362655639648,
74
+ "step": 160
75
+ },
76
+ {
77
+ "epoch": 0.006066734074823054,
78
+ "grad_norm": 0.86328125,
79
+ "learning_rate": 0.00025059999999999997,
80
+ "loss": 5.974322509765625,
81
+ "step": 180
82
+ },
83
+ {
84
+ "epoch": 0.006740815638692282,
85
+ "grad_norm": 0.80078125,
86
+ "learning_rate": 0.0002786,
87
+ "loss": 5.698452377319336,
88
+ "step": 200
89
+ },
90
+ {
91
+ "epoch": 0.006740815638692282,
92
+ "eval_loss": 5.558600902557373,
93
+ "eval_runtime": 9.1031,
94
+ "eval_samples_per_second": 1046.564,
95
+ "eval_steps_per_second": 1.099,
96
+ "step": 200
97
+ },
98
+ {
99
+ "epoch": 0.00741489720256151,
100
+ "grad_norm": 0.8046875,
101
+ "learning_rate": 0.00030659999999999997,
102
+ "loss": 5.451509857177735,
103
+ "step": 220
104
+ },
105
+ {
106
+ "epoch": 0.008088978766430738,
107
+ "grad_norm": 1.0078125,
108
+ "learning_rate": 0.0003346,
109
+ "loss": 5.163370895385742,
110
+ "step": 240
111
+ },
112
+ {
113
+ "epoch": 0.008763060330299966,
114
+ "grad_norm": 1.0859375,
115
+ "learning_rate": 0.00036260000000000003,
116
+ "loss": 4.929123306274414,
117
+ "step": 260
118
+ },
119
+ {
120
+ "epoch": 0.009437141894169195,
121
+ "grad_norm": 0.84765625,
122
+ "learning_rate": 0.0003906,
123
+ "loss": 4.702068710327149,
124
+ "step": 280
125
+ },
126
+ {
127
+ "epoch": 0.010111223458038422,
128
+ "grad_norm": 0.91796875,
129
+ "learning_rate": 0.0004186,
130
+ "loss": 4.501141738891602,
131
+ "step": 300
132
+ },
133
+ {
134
+ "epoch": 0.010111223458038422,
135
+ "eval_loss": 4.396740913391113,
136
+ "eval_runtime": 8.9474,
137
+ "eval_samples_per_second": 1064.782,
138
+ "eval_steps_per_second": 1.118,
139
+ "step": 300
140
+ },
141
+ {
142
+ "epoch": 0.010785305021907651,
143
+ "grad_norm": 0.9453125,
144
+ "learning_rate": 0.0004466,
145
+ "loss": 4.323627853393555,
146
+ "step": 320
147
+ },
148
+ {
149
+ "epoch": 0.011459386585776879,
150
+ "grad_norm": 0.88671875,
151
+ "learning_rate": 0.00047460000000000004,
152
+ "loss": 4.204174041748047,
153
+ "step": 340
154
+ },
155
+ {
156
+ "epoch": 0.012133468149646108,
157
+ "grad_norm": 0.92578125,
158
+ "learning_rate": 0.0005026,
159
+ "loss": 4.052695846557617,
160
+ "step": 360
161
+ },
162
+ {
163
+ "epoch": 0.012807549713515335,
164
+ "grad_norm": 0.6484375,
165
+ "learning_rate": 0.0005306,
166
+ "loss": 3.947071075439453,
167
+ "step": 380
168
+ },
169
+ {
170
+ "epoch": 0.013481631277384564,
171
+ "grad_norm": 0.73828125,
172
+ "learning_rate": 0.0005586,
173
+ "loss": 3.855146026611328,
174
+ "step": 400
175
+ },
176
+ {
177
+ "epoch": 0.013481631277384564,
178
+ "eval_loss": 3.8139851093292236,
179
+ "eval_runtime": 8.9743,
180
+ "eval_samples_per_second": 1061.59,
181
+ "eval_steps_per_second": 1.114,
182
+ "step": 400
183
+ },
184
+ {
185
+ "epoch": 0.014155712841253791,
186
+ "grad_norm": 0.80859375,
187
+ "learning_rate": 0.0005866,
188
+ "loss": 3.76041259765625,
189
+ "step": 420
190
+ },
191
+ {
192
+ "epoch": 0.01482979440512302,
193
+ "grad_norm": 0.77734375,
194
+ "learning_rate": 0.0006146,
195
+ "loss": 3.708443450927734,
196
+ "step": 440
197
+ },
198
+ {
199
+ "epoch": 0.015503875968992248,
200
+ "grad_norm": 0.7421875,
201
+ "learning_rate": 0.0006426,
202
+ "loss": 3.637612152099609,
203
+ "step": 460
204
+ },
205
+ {
206
+ "epoch": 0.016177957532861477,
207
+ "grad_norm": 0.6640625,
208
+ "learning_rate": 0.0006705999999999999,
209
+ "loss": 3.556614303588867,
210
+ "step": 480
211
+ },
212
+ {
213
+ "epoch": 0.016852039096730706,
214
+ "grad_norm": 0.7421875,
215
+ "learning_rate": 0.0006986,
216
+ "loss": 3.5122703552246093,
217
+ "step": 500
218
+ },
219
+ {
220
+ "epoch": 0.016852039096730706,
221
+ "eval_loss": 3.4916131496429443,
222
+ "eval_runtime": 8.8876,
223
+ "eval_samples_per_second": 1071.946,
224
+ "eval_steps_per_second": 1.125,
225
+ "step": 500
226
+ },
227
+ {
228
+ "epoch": 0.01752612066059993,
229
+ "grad_norm": 0.80078125,
230
+ "learning_rate": 0.0007,
231
+ "loss": 3.477622222900391,
232
+ "step": 520
233
+ },
234
+ {
235
+ "epoch": 0.01820020222446916,
236
+ "grad_norm": 0.75390625,
237
+ "learning_rate": 0.0007,
238
+ "loss": 3.4115901947021485,
239
+ "step": 540
240
+ },
241
+ {
242
+ "epoch": 0.01887428378833839,
243
+ "grad_norm": 0.60546875,
244
+ "learning_rate": 0.0007,
245
+ "loss": 3.359669876098633,
246
+ "step": 560
247
+ },
248
+ {
249
+ "epoch": 0.01954836535220762,
250
+ "grad_norm": 0.6796875,
251
+ "learning_rate": 0.0007,
252
+ "loss": 3.3188705444335938,
253
+ "step": 580
254
+ },
255
+ {
256
+ "epoch": 0.020222446916076844,
257
+ "grad_norm": 0.67578125,
258
+ "learning_rate": 0.0007,
259
+ "loss": 3.2840240478515623,
260
+ "step": 600
261
+ },
262
+ {
263
+ "epoch": 0.020222446916076844,
264
+ "eval_loss": 3.2660911083221436,
265
+ "eval_runtime": 8.9246,
266
+ "eval_samples_per_second": 1067.504,
267
+ "eval_steps_per_second": 1.121,
268
+ "step": 600
269
+ },
270
+ {
271
+ "epoch": 0.020896528479946073,
272
+ "grad_norm": 0.7421875,
273
+ "learning_rate": 0.0007,
274
+ "loss": 3.223845672607422,
275
+ "step": 620
276
+ },
277
+ {
278
+ "epoch": 0.021570610043815303,
279
+ "grad_norm": 0.67578125,
280
+ "learning_rate": 0.0007,
281
+ "loss": 3.2053298950195312,
282
+ "step": 640
283
+ },
284
+ {
285
+ "epoch": 0.022244691607684528,
286
+ "grad_norm": 0.890625,
287
+ "learning_rate": 0.0007,
288
+ "loss": 3.1749242782592773,
289
+ "step": 660
290
+ },
291
+ {
292
+ "epoch": 0.022918773171553757,
293
+ "grad_norm": 0.5859375,
294
+ "learning_rate": 0.0007,
295
+ "loss": 3.134219741821289,
296
+ "step": 680
297
+ },
298
+ {
299
+ "epoch": 0.023592854735422986,
300
+ "grad_norm": 0.6640625,
301
+ "learning_rate": 0.0007,
302
+ "loss": 3.1245954513549803,
303
+ "step": 700
304
+ },
305
+ {
306
+ "epoch": 0.023592854735422986,
307
+ "eval_loss": 3.113696575164795,
308
+ "eval_runtime": 8.8675,
309
+ "eval_samples_per_second": 1074.373,
310
+ "eval_steps_per_second": 1.128,
311
+ "step": 700
312
+ },
313
+ {
314
+ "epoch": 0.024266936299292215,
315
+ "grad_norm": 0.62890625,
316
+ "learning_rate": 0.0007,
317
+ "loss": 3.0987874984741213,
318
+ "step": 720
319
+ },
320
+ {
321
+ "epoch": 0.02494101786316144,
322
+ "grad_norm": 0.73046875,
323
+ "learning_rate": 0.0007,
324
+ "loss": 3.08369140625,
325
+ "step": 740
326
+ },
327
+ {
328
+ "epoch": 0.02561509942703067,
329
+ "grad_norm": 0.62890625,
330
+ "learning_rate": 0.0007,
331
+ "loss": 3.03726863861084,
332
+ "step": 760
333
+ },
334
+ {
335
+ "epoch": 0.0262891809908999,
336
+ "grad_norm": 0.64453125,
337
+ "learning_rate": 0.0007,
338
+ "loss": 2.9970935821533202,
339
+ "step": 780
340
+ },
341
+ {
342
+ "epoch": 0.026963262554769128,
343
+ "grad_norm": 0.625,
344
+ "learning_rate": 0.0007,
345
+ "loss": 3.006105422973633,
346
+ "step": 800
347
+ },
348
+ {
349
+ "epoch": 0.026963262554769128,
350
+ "eval_loss": 2.999389886856079,
351
+ "eval_runtime": 8.984,
352
+ "eval_samples_per_second": 1060.442,
353
+ "eval_steps_per_second": 1.113,
354
+ "step": 800
355
+ },
356
+ {
357
+ "epoch": 0.027637344118638354,
358
+ "grad_norm": 0.609375,
359
+ "learning_rate": 0.0007,
360
+ "loss": 2.9657209396362303,
361
+ "step": 820
362
+ },
363
+ {
364
+ "epoch": 0.028311425682507583,
365
+ "grad_norm": 0.67578125,
366
+ "learning_rate": 0.0007,
367
+ "loss": 2.9664005279541015,
368
+ "step": 840
369
+ },
370
+ {
371
+ "epoch": 0.028985507246376812,
372
+ "grad_norm": 0.65625,
373
+ "learning_rate": 0.0007,
374
+ "loss": 2.988846206665039,
375
+ "step": 860
376
+ },
377
+ {
378
+ "epoch": 0.02965958881024604,
379
+ "grad_norm": 0.66015625,
380
+ "learning_rate": 0.0007,
381
+ "loss": 2.9386875152587892,
382
+ "step": 880
383
+ },
384
+ {
385
+ "epoch": 0.030333670374115267,
386
+ "grad_norm": 0.7109375,
387
+ "learning_rate": 0.0007,
388
+ "loss": 2.8965709686279295,
389
+ "step": 900
390
+ },
391
+ {
392
+ "epoch": 0.030333670374115267,
393
+ "eval_loss": 2.9093611240386963,
394
+ "eval_runtime": 8.9344,
395
+ "eval_samples_per_second": 1066.332,
396
+ "eval_steps_per_second": 1.119,
397
+ "step": 900
398
+ },
399
+ {
400
+ "epoch": 0.031007751937984496,
401
+ "grad_norm": 0.62109375,
402
+ "learning_rate": 0.0007,
403
+ "loss": 2.9101829528808594,
404
+ "step": 920
405
+ },
406
+ {
407
+ "epoch": 0.031681833501853725,
408
+ "grad_norm": 0.5859375,
409
+ "learning_rate": 0.0007,
410
+ "loss": 2.8905385971069335,
411
+ "step": 940
412
+ },
413
+ {
414
+ "epoch": 0.032355915065722954,
415
+ "grad_norm": 0.74609375,
416
+ "learning_rate": 0.0007,
417
+ "loss": 2.8552478790283202,
418
+ "step": 960
419
+ },
420
+ {
421
+ "epoch": 0.03302999662959218,
422
+ "grad_norm": 0.62109375,
423
+ "learning_rate": 0.0007,
424
+ "loss": 2.8467588424682617,
425
+ "step": 980
426
+ },
427
+ {
428
+ "epoch": 0.03370407819346141,
429
+ "grad_norm": 0.60546875,
430
+ "learning_rate": 0.0007,
431
+ "loss": 2.831803894042969,
432
+ "step": 1000
433
+ },
434
+ {
435
+ "epoch": 0.03370407819346141,
436
+ "eval_loss": 2.8364417552948,
437
+ "eval_runtime": 8.9776,
438
+ "eval_samples_per_second": 1061.195,
439
+ "eval_steps_per_second": 1.114,
440
+ "step": 1000
441
+ },
442
+ {
443
+ "epoch": 0.034378159757330634,
444
+ "grad_norm": 0.640625,
445
+ "learning_rate": 0.0007,
446
+ "loss": 2.831756591796875,
447
+ "step": 1020
448
+ },
449
+ {
450
+ "epoch": 0.03505224132119986,
451
+ "grad_norm": 0.6796875,
452
+ "learning_rate": 0.0007,
453
+ "loss": 2.8086965560913084,
454
+ "step": 1040
455
+ },
456
+ {
457
+ "epoch": 0.03572632288506909,
458
+ "grad_norm": 0.59375,
459
+ "learning_rate": 0.0007,
460
+ "loss": 2.7877662658691404,
461
+ "step": 1060
462
+ },
463
+ {
464
+ "epoch": 0.03640040444893832,
465
+ "grad_norm": 0.71875,
466
+ "learning_rate": 0.0007,
467
+ "loss": 2.7670337677001955,
468
+ "step": 1080
469
+ },
470
+ {
471
+ "epoch": 0.03707448601280755,
472
+ "grad_norm": 0.65234375,
473
+ "learning_rate": 0.0007,
474
+ "loss": 2.762655830383301,
475
+ "step": 1100
476
+ },
477
+ {
478
+ "epoch": 0.03707448601280755,
479
+ "eval_loss": 2.7699334621429443,
480
+ "eval_runtime": 8.8675,
481
+ "eval_samples_per_second": 1074.369,
482
+ "eval_steps_per_second": 1.128,
483
+ "step": 1100
484
+ },
485
+ {
486
+ "epoch": 0.03774856757667678,
487
+ "grad_norm": 0.640625,
488
+ "learning_rate": 0.0007,
489
+ "loss": 2.762282371520996,
490
+ "step": 1120
491
+ },
492
+ {
493
+ "epoch": 0.03842264914054601,
494
+ "grad_norm": 0.546875,
495
+ "learning_rate": 0.0007,
496
+ "loss": 2.734586715698242,
497
+ "step": 1140
498
+ },
499
+ {
500
+ "epoch": 0.03909673070441524,
501
+ "grad_norm": 0.59765625,
502
+ "learning_rate": 0.0007,
503
+ "loss": 2.72774658203125,
504
+ "step": 1160
505
+ },
506
+ {
507
+ "epoch": 0.03977081226828446,
508
+ "grad_norm": 0.65625,
509
+ "learning_rate": 0.0007,
510
+ "loss": 2.7388858795166016,
511
+ "step": 1180
512
+ },
513
+ {
514
+ "epoch": 0.04044489383215369,
515
+ "grad_norm": 0.625,
516
+ "learning_rate": 0.0007,
517
+ "loss": 2.7111089706420897,
518
+ "step": 1200
519
+ },
520
+ {
521
+ "epoch": 0.04044489383215369,
522
+ "eval_loss": 2.7126073837280273,
523
+ "eval_runtime": 8.8945,
524
+ "eval_samples_per_second": 1071.112,
525
+ "eval_steps_per_second": 1.124,
526
+ "step": 1200
527
+ }
528
+ ],
529
+ "logging_steps": 20,
530
+ "max_steps": 2500,
531
+ "num_input_tokens_seen": 0,
532
+ "num_train_epochs": 1,
533
+ "save_steps": 100,
534
+ "stateful_callbacks": {
535
+ "TrainerControl": {
536
+ "args": {
537
+ "should_epoch_stop": false,
538
+ "should_evaluate": false,
539
+ "should_log": false,
540
+ "should_save": true,
541
+ "should_training_stop": false
542
+ },
543
+ "attributes": {}
544
+ }
545
+ },
546
+ "total_flos": 406523687731200.0,
547
+ "train_batch_size": 32,
548
+ "trial_name": null,
549
+ "trial_params": null
550
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1200/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f75700c4e7fd25f6c775604daf3d7c3ad4d4f80aa4067cf2717dd0234a021fa
3
+ size 4920
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "relu",
3
+ "architectures": [
4
+ "TinyLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 2,
11
+ "head_dim": 32,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 128,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 256,
16
+ "max_position_embeddings": 512,
17
+ "mlp_bias": false,
18
+ "mlp_type": "glu",
19
+ "model_type": "tiny_llama",
20
+ "num_attention_heads": 4,
21
+ "num_hidden_layers": 21,
22
+ "num_key_value_heads": 4,
23
+ "pad_token_id": 0,
24
+ "powlu_m": 3.0,
25
+ "pretraining_tp": 1,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_parameters": {
28
+ "rope_theta": 10000.0,
29
+ "rope_type": "default"
30
+ },
31
+ "tie_word_embeddings": true,
32
+ "tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
33
+ "transformers_version": "5.16.0.dev0",
34
+ "use_cache": false,
35
+ "vocab_size": 4096,
36
+ "waleed_beta": 10.0
37
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b632700bd0b2f5e1c65db79bd9369cf45d07bd846070a11d7d36b336759fe12e
3
+ size 7961528
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35ae82e5c66d8fd650b22105f7795d4f658775666c5b8abfb79964d4242f2c64
3
+ size 16043962
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad578a43d11126d2531a957d968233fceac13bb258b4a43a2e2c3ad855ce9084
3
+ size 14244
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6166e4e25b157aeaf4765c80f04dab16e63f8ec3cd6ab3637d77b940e7dfcfe1
3
+ size 1064
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "eos_token": "<|endoftext|>",
6
+ "errors": "replace",
7
+ "is_local": false,
8
+ "local_files_only": false,
9
+ "model_max_length": 1024,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "GPT2Tokenizer",
12
+ "unk_token": "<|endoftext|>"
13
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/trainer_state.json ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.043815301651499834,
6
+ "eval_steps": 100,
7
+ "global_step": 1300,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.0006740815638692282,
14
+ "grad_norm": 1.7578125,
15
+ "learning_rate": 2.66e-05,
16
+ "loss": 8.330369567871093,
17
+ "step": 20
18
+ },
19
+ {
20
+ "epoch": 0.0013481631277384564,
21
+ "grad_norm": 1.40625,
22
+ "learning_rate": 5.46e-05,
23
+ "loss": 8.17730255126953,
24
+ "step": 40
25
+ },
26
+ {
27
+ "epoch": 0.0020222446916076846,
28
+ "grad_norm": 1.3359375,
29
+ "learning_rate": 8.259999999999999e-05,
30
+ "loss": 7.952220916748047,
31
+ "step": 60
32
+ },
33
+ {
34
+ "epoch": 0.002696326255476913,
35
+ "grad_norm": 1.3125,
36
+ "learning_rate": 0.0001106,
37
+ "loss": 7.694232177734375,
38
+ "step": 80
39
+ },
40
+ {
41
+ "epoch": 0.003370407819346141,
42
+ "grad_norm": 1.234375,
43
+ "learning_rate": 0.0001386,
44
+ "loss": 7.353645324707031,
45
+ "step": 100
46
+ },
47
+ {
48
+ "epoch": 0.003370407819346141,
49
+ "eval_loss": 7.14666223526001,
50
+ "eval_runtime": 8.8883,
51
+ "eval_samples_per_second": 1071.854,
52
+ "eval_steps_per_second": 1.125,
53
+ "step": 100
54
+ },
55
+ {
56
+ "epoch": 0.004044489383215369,
57
+ "grad_norm": 1.1796875,
58
+ "learning_rate": 0.00016659999999999998,
59
+ "loss": 6.9598846435546875,
60
+ "step": 120
61
+ },
62
+ {
63
+ "epoch": 0.0047185709470845974,
64
+ "grad_norm": 1.1015625,
65
+ "learning_rate": 0.00019460000000000001,
66
+ "loss": 6.568833923339843,
67
+ "step": 140
68
+ },
69
+ {
70
+ "epoch": 0.005392652510953826,
71
+ "grad_norm": 1.046875,
72
+ "learning_rate": 0.0002226,
73
+ "loss": 6.253362655639648,
74
+ "step": 160
75
+ },
76
+ {
77
+ "epoch": 0.006066734074823054,
78
+ "grad_norm": 0.86328125,
79
+ "learning_rate": 0.00025059999999999997,
80
+ "loss": 5.974322509765625,
81
+ "step": 180
82
+ },
83
+ {
84
+ "epoch": 0.006740815638692282,
85
+ "grad_norm": 0.80078125,
86
+ "learning_rate": 0.0002786,
87
+ "loss": 5.698452377319336,
88
+ "step": 200
89
+ },
90
+ {
91
+ "epoch": 0.006740815638692282,
92
+ "eval_loss": 5.558600902557373,
93
+ "eval_runtime": 9.1031,
94
+ "eval_samples_per_second": 1046.564,
95
+ "eval_steps_per_second": 1.099,
96
+ "step": 200
97
+ },
98
+ {
99
+ "epoch": 0.00741489720256151,
100
+ "grad_norm": 0.8046875,
101
+ "learning_rate": 0.00030659999999999997,
102
+ "loss": 5.451509857177735,
103
+ "step": 220
104
+ },
105
+ {
106
+ "epoch": 0.008088978766430738,
107
+ "grad_norm": 1.0078125,
108
+ "learning_rate": 0.0003346,
109
+ "loss": 5.163370895385742,
110
+ "step": 240
111
+ },
112
+ {
113
+ "epoch": 0.008763060330299966,
114
+ "grad_norm": 1.0859375,
115
+ "learning_rate": 0.00036260000000000003,
116
+ "loss": 4.929123306274414,
117
+ "step": 260
118
+ },
119
+ {
120
+ "epoch": 0.009437141894169195,
121
+ "grad_norm": 0.84765625,
122
+ "learning_rate": 0.0003906,
123
+ "loss": 4.702068710327149,
124
+ "step": 280
125
+ },
126
+ {
127
+ "epoch": 0.010111223458038422,
128
+ "grad_norm": 0.91796875,
129
+ "learning_rate": 0.0004186,
130
+ "loss": 4.501141738891602,
131
+ "step": 300
132
+ },
133
+ {
134
+ "epoch": 0.010111223458038422,
135
+ "eval_loss": 4.396740913391113,
136
+ "eval_runtime": 8.9474,
137
+ "eval_samples_per_second": 1064.782,
138
+ "eval_steps_per_second": 1.118,
139
+ "step": 300
140
+ },
141
+ {
142
+ "epoch": 0.010785305021907651,
143
+ "grad_norm": 0.9453125,
144
+ "learning_rate": 0.0004466,
145
+ "loss": 4.323627853393555,
146
+ "step": 320
147
+ },
148
+ {
149
+ "epoch": 0.011459386585776879,
150
+ "grad_norm": 0.88671875,
151
+ "learning_rate": 0.00047460000000000004,
152
+ "loss": 4.204174041748047,
153
+ "step": 340
154
+ },
155
+ {
156
+ "epoch": 0.012133468149646108,
157
+ "grad_norm": 0.92578125,
158
+ "learning_rate": 0.0005026,
159
+ "loss": 4.052695846557617,
160
+ "step": 360
161
+ },
162
+ {
163
+ "epoch": 0.012807549713515335,
164
+ "grad_norm": 0.6484375,
165
+ "learning_rate": 0.0005306,
166
+ "loss": 3.947071075439453,
167
+ "step": 380
168
+ },
169
+ {
170
+ "epoch": 0.013481631277384564,
171
+ "grad_norm": 0.73828125,
172
+ "learning_rate": 0.0005586,
173
+ "loss": 3.855146026611328,
174
+ "step": 400
175
+ },
176
+ {
177
+ "epoch": 0.013481631277384564,
178
+ "eval_loss": 3.8139851093292236,
179
+ "eval_runtime": 8.9743,
180
+ "eval_samples_per_second": 1061.59,
181
+ "eval_steps_per_second": 1.114,
182
+ "step": 400
183
+ },
184
+ {
185
+ "epoch": 0.014155712841253791,
186
+ "grad_norm": 0.80859375,
187
+ "learning_rate": 0.0005866,
188
+ "loss": 3.76041259765625,
189
+ "step": 420
190
+ },
191
+ {
192
+ "epoch": 0.01482979440512302,
193
+ "grad_norm": 0.77734375,
194
+ "learning_rate": 0.0006146,
195
+ "loss": 3.708443450927734,
196
+ "step": 440
197
+ },
198
+ {
199
+ "epoch": 0.015503875968992248,
200
+ "grad_norm": 0.7421875,
201
+ "learning_rate": 0.0006426,
202
+ "loss": 3.637612152099609,
203
+ "step": 460
204
+ },
205
+ {
206
+ "epoch": 0.016177957532861477,
207
+ "grad_norm": 0.6640625,
208
+ "learning_rate": 0.0006705999999999999,
209
+ "loss": 3.556614303588867,
210
+ "step": 480
211
+ },
212
+ {
213
+ "epoch": 0.016852039096730706,
214
+ "grad_norm": 0.7421875,
215
+ "learning_rate": 0.0006986,
216
+ "loss": 3.5122703552246093,
217
+ "step": 500
218
+ },
219
+ {
220
+ "epoch": 0.016852039096730706,
221
+ "eval_loss": 3.4916131496429443,
222
+ "eval_runtime": 8.8876,
223
+ "eval_samples_per_second": 1071.946,
224
+ "eval_steps_per_second": 1.125,
225
+ "step": 500
226
+ },
227
+ {
228
+ "epoch": 0.01752612066059993,
229
+ "grad_norm": 0.80078125,
230
+ "learning_rate": 0.0007,
231
+ "loss": 3.477622222900391,
232
+ "step": 520
233
+ },
234
+ {
235
+ "epoch": 0.01820020222446916,
236
+ "grad_norm": 0.75390625,
237
+ "learning_rate": 0.0007,
238
+ "loss": 3.4115901947021485,
239
+ "step": 540
240
+ },
241
+ {
242
+ "epoch": 0.01887428378833839,
243
+ "grad_norm": 0.60546875,
244
+ "learning_rate": 0.0007,
245
+ "loss": 3.359669876098633,
246
+ "step": 560
247
+ },
248
+ {
249
+ "epoch": 0.01954836535220762,
250
+ "grad_norm": 0.6796875,
251
+ "learning_rate": 0.0007,
252
+ "loss": 3.3188705444335938,
253
+ "step": 580
254
+ },
255
+ {
256
+ "epoch": 0.020222446916076844,
257
+ "grad_norm": 0.67578125,
258
+ "learning_rate": 0.0007,
259
+ "loss": 3.2840240478515623,
260
+ "step": 600
261
+ },
262
+ {
263
+ "epoch": 0.020222446916076844,
264
+ "eval_loss": 3.2660911083221436,
265
+ "eval_runtime": 8.9246,
266
+ "eval_samples_per_second": 1067.504,
267
+ "eval_steps_per_second": 1.121,
268
+ "step": 600
269
+ },
270
+ {
271
+ "epoch": 0.020896528479946073,
272
+ "grad_norm": 0.7421875,
273
+ "learning_rate": 0.0007,
274
+ "loss": 3.223845672607422,
275
+ "step": 620
276
+ },
277
+ {
278
+ "epoch": 0.021570610043815303,
279
+ "grad_norm": 0.67578125,
280
+ "learning_rate": 0.0007,
281
+ "loss": 3.2053298950195312,
282
+ "step": 640
283
+ },
284
+ {
285
+ "epoch": 0.022244691607684528,
286
+ "grad_norm": 0.890625,
287
+ "learning_rate": 0.0007,
288
+ "loss": 3.1749242782592773,
289
+ "step": 660
290
+ },
291
+ {
292
+ "epoch": 0.022918773171553757,
293
+ "grad_norm": 0.5859375,
294
+ "learning_rate": 0.0007,
295
+ "loss": 3.134219741821289,
296
+ "step": 680
297
+ },
298
+ {
299
+ "epoch": 0.023592854735422986,
300
+ "grad_norm": 0.6640625,
301
+ "learning_rate": 0.0007,
302
+ "loss": 3.1245954513549803,
303
+ "step": 700
304
+ },
305
+ {
306
+ "epoch": 0.023592854735422986,
307
+ "eval_loss": 3.113696575164795,
308
+ "eval_runtime": 8.8675,
309
+ "eval_samples_per_second": 1074.373,
310
+ "eval_steps_per_second": 1.128,
311
+ "step": 700
312
+ },
313
+ {
314
+ "epoch": 0.024266936299292215,
315
+ "grad_norm": 0.62890625,
316
+ "learning_rate": 0.0007,
317
+ "loss": 3.0987874984741213,
318
+ "step": 720
319
+ },
320
+ {
321
+ "epoch": 0.02494101786316144,
322
+ "grad_norm": 0.73046875,
323
+ "learning_rate": 0.0007,
324
+ "loss": 3.08369140625,
325
+ "step": 740
326
+ },
327
+ {
328
+ "epoch": 0.02561509942703067,
329
+ "grad_norm": 0.62890625,
330
+ "learning_rate": 0.0007,
331
+ "loss": 3.03726863861084,
332
+ "step": 760
333
+ },
334
+ {
335
+ "epoch": 0.0262891809908999,
336
+ "grad_norm": 0.64453125,
337
+ "learning_rate": 0.0007,
338
+ "loss": 2.9970935821533202,
339
+ "step": 780
340
+ },
341
+ {
342
+ "epoch": 0.026963262554769128,
343
+ "grad_norm": 0.625,
344
+ "learning_rate": 0.0007,
345
+ "loss": 3.006105422973633,
346
+ "step": 800
347
+ },
348
+ {
349
+ "epoch": 0.026963262554769128,
350
+ "eval_loss": 2.999389886856079,
351
+ "eval_runtime": 8.984,
352
+ "eval_samples_per_second": 1060.442,
353
+ "eval_steps_per_second": 1.113,
354
+ "step": 800
355
+ },
356
+ {
357
+ "epoch": 0.027637344118638354,
358
+ "grad_norm": 0.609375,
359
+ "learning_rate": 0.0007,
360
+ "loss": 2.9657209396362303,
361
+ "step": 820
362
+ },
363
+ {
364
+ "epoch": 0.028311425682507583,
365
+ "grad_norm": 0.67578125,
366
+ "learning_rate": 0.0007,
367
+ "loss": 2.9664005279541015,
368
+ "step": 840
369
+ },
370
+ {
371
+ "epoch": 0.028985507246376812,
372
+ "grad_norm": 0.65625,
373
+ "learning_rate": 0.0007,
374
+ "loss": 2.988846206665039,
375
+ "step": 860
376
+ },
377
+ {
378
+ "epoch": 0.02965958881024604,
379
+ "grad_norm": 0.66015625,
380
+ "learning_rate": 0.0007,
381
+ "loss": 2.9386875152587892,
382
+ "step": 880
383
+ },
384
+ {
385
+ "epoch": 0.030333670374115267,
386
+ "grad_norm": 0.7109375,
387
+ "learning_rate": 0.0007,
388
+ "loss": 2.8965709686279295,
389
+ "step": 900
390
+ },
391
+ {
392
+ "epoch": 0.030333670374115267,
393
+ "eval_loss": 2.9093611240386963,
394
+ "eval_runtime": 8.9344,
395
+ "eval_samples_per_second": 1066.332,
396
+ "eval_steps_per_second": 1.119,
397
+ "step": 900
398
+ },
399
+ {
400
+ "epoch": 0.031007751937984496,
401
+ "grad_norm": 0.62109375,
402
+ "learning_rate": 0.0007,
403
+ "loss": 2.9101829528808594,
404
+ "step": 920
405
+ },
406
+ {
407
+ "epoch": 0.031681833501853725,
408
+ "grad_norm": 0.5859375,
409
+ "learning_rate": 0.0007,
410
+ "loss": 2.8905385971069335,
411
+ "step": 940
412
+ },
413
+ {
414
+ "epoch": 0.032355915065722954,
415
+ "grad_norm": 0.74609375,
416
+ "learning_rate": 0.0007,
417
+ "loss": 2.8552478790283202,
418
+ "step": 960
419
+ },
420
+ {
421
+ "epoch": 0.03302999662959218,
422
+ "grad_norm": 0.62109375,
423
+ "learning_rate": 0.0007,
424
+ "loss": 2.8467588424682617,
425
+ "step": 980
426
+ },
427
+ {
428
+ "epoch": 0.03370407819346141,
429
+ "grad_norm": 0.60546875,
430
+ "learning_rate": 0.0007,
431
+ "loss": 2.831803894042969,
432
+ "step": 1000
433
+ },
434
+ {
435
+ "epoch": 0.03370407819346141,
436
+ "eval_loss": 2.8364417552948,
437
+ "eval_runtime": 8.9776,
438
+ "eval_samples_per_second": 1061.195,
439
+ "eval_steps_per_second": 1.114,
440
+ "step": 1000
441
+ },
442
+ {
443
+ "epoch": 0.034378159757330634,
444
+ "grad_norm": 0.640625,
445
+ "learning_rate": 0.0007,
446
+ "loss": 2.831756591796875,
447
+ "step": 1020
448
+ },
449
+ {
450
+ "epoch": 0.03505224132119986,
451
+ "grad_norm": 0.6796875,
452
+ "learning_rate": 0.0007,
453
+ "loss": 2.8086965560913084,
454
+ "step": 1040
455
+ },
456
+ {
457
+ "epoch": 0.03572632288506909,
458
+ "grad_norm": 0.59375,
459
+ "learning_rate": 0.0007,
460
+ "loss": 2.7877662658691404,
461
+ "step": 1060
462
+ },
463
+ {
464
+ "epoch": 0.03640040444893832,
465
+ "grad_norm": 0.71875,
466
+ "learning_rate": 0.0007,
467
+ "loss": 2.7670337677001955,
468
+ "step": 1080
469
+ },
470
+ {
471
+ "epoch": 0.03707448601280755,
472
+ "grad_norm": 0.65234375,
473
+ "learning_rate": 0.0007,
474
+ "loss": 2.762655830383301,
475
+ "step": 1100
476
+ },
477
+ {
478
+ "epoch": 0.03707448601280755,
479
+ "eval_loss": 2.7699334621429443,
480
+ "eval_runtime": 8.8675,
481
+ "eval_samples_per_second": 1074.369,
482
+ "eval_steps_per_second": 1.128,
483
+ "step": 1100
484
+ },
485
+ {
486
+ "epoch": 0.03774856757667678,
487
+ "grad_norm": 0.640625,
488
+ "learning_rate": 0.0007,
489
+ "loss": 2.762282371520996,
490
+ "step": 1120
491
+ },
492
+ {
493
+ "epoch": 0.03842264914054601,
494
+ "grad_norm": 0.546875,
495
+ "learning_rate": 0.0007,
496
+ "loss": 2.734586715698242,
497
+ "step": 1140
498
+ },
499
+ {
500
+ "epoch": 0.03909673070441524,
501
+ "grad_norm": 0.59765625,
502
+ "learning_rate": 0.0007,
503
+ "loss": 2.72774658203125,
504
+ "step": 1160
505
+ },
506
+ {
507
+ "epoch": 0.03977081226828446,
508
+ "grad_norm": 0.65625,
509
+ "learning_rate": 0.0007,
510
+ "loss": 2.7388858795166016,
511
+ "step": 1180
512
+ },
513
+ {
514
+ "epoch": 0.04044489383215369,
515
+ "grad_norm": 0.625,
516
+ "learning_rate": 0.0007,
517
+ "loss": 2.7111089706420897,
518
+ "step": 1200
519
+ },
520
+ {
521
+ "epoch": 0.04044489383215369,
522
+ "eval_loss": 2.7126073837280273,
523
+ "eval_runtime": 8.8945,
524
+ "eval_samples_per_second": 1071.112,
525
+ "eval_steps_per_second": 1.124,
526
+ "step": 1200
527
+ },
528
+ {
529
+ "epoch": 0.04111897539602292,
530
+ "grad_norm": 0.6328125,
531
+ "learning_rate": 0.0007,
532
+ "loss": 2.681635856628418,
533
+ "step": 1220
534
+ },
535
+ {
536
+ "epoch": 0.04179305695989215,
537
+ "grad_norm": 0.609375,
538
+ "learning_rate": 0.0007,
539
+ "loss": 2.699861526489258,
540
+ "step": 1240
541
+ },
542
+ {
543
+ "epoch": 0.042467138523761376,
544
+ "grad_norm": 0.7109375,
545
+ "learning_rate": 0.0007,
546
+ "loss": 2.704066848754883,
547
+ "step": 1260
548
+ },
549
+ {
550
+ "epoch": 0.043141220087630605,
551
+ "grad_norm": 0.6328125,
552
+ "learning_rate": 0.0007,
553
+ "loss": 2.675613784790039,
554
+ "step": 1280
555
+ },
556
+ {
557
+ "epoch": 0.043815301651499834,
558
+ "grad_norm": 0.6171875,
559
+ "learning_rate": 0.0007,
560
+ "loss": 2.6731496810913087,
561
+ "step": 1300
562
+ },
563
+ {
564
+ "epoch": 0.043815301651499834,
565
+ "eval_loss": 2.6630420684814453,
566
+ "eval_runtime": 8.9026,
567
+ "eval_samples_per_second": 1070.134,
568
+ "eval_steps_per_second": 1.123,
569
+ "step": 1300
570
+ }
571
+ ],
572
+ "logging_steps": 20,
573
+ "max_steps": 2500,
574
+ "num_input_tokens_seen": 0,
575
+ "num_train_epochs": 1,
576
+ "save_steps": 100,
577
+ "stateful_callbacks": {
578
+ "TrainerControl": {
579
+ "args": {
580
+ "should_epoch_stop": false,
581
+ "should_evaluate": false,
582
+ "should_log": false,
583
+ "should_save": true,
584
+ "should_training_stop": false
585
+ },
586
+ "attributes": {}
587
+ }
588
+ },
589
+ "total_flos": 440400661708800.0,
590
+ "train_batch_size": 32,
591
+ "trial_name": null,
592
+ "trial_params": null
593
+ }
zain/Activation/out/glu-relu-21L_run/checkpoint-1300/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f75700c4e7fd25f6c775604daf3d7c3ad4d4f80aa4067cf2717dd0234a021fa
3
+ size 4920