w-ahmad commited on
Commit
90ea802
·
verified ·
1 Parent(s): b6cf1ce

Auto upload zain 2026-08-13T21:15:52.507316

Browse files
Files changed (26) hide show
  1. .gitattributes +1 -0
  2. zain/Activation/README.md +1 -0
  3. zain/Activation/__pycache__/exp.cpython-311.pyc +0 -0
  4. zain/Activation/exp.py +921 -0
  5. zain/Activation/llm_analyzer_wandb.py +570 -0
  6. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/config.json +36 -0
  7. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/model.safetensors +3 -0
  8. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/optimizer.pt +3 -0
  9. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/rng_state.pth +3 -0
  10. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/scheduler.pt +3 -0
  11. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/tokenizer.json +0 -0
  12. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/tokenizer_config.json +13 -0
  13. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/trainer_state.json +960 -0
  14. zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/training_args.bin +3 -0
  15. zain/Activation/out/glu-linear-100L_trash_run/training_log.jsonl +0 -0
  16. zain/Activation/sweep.py +217 -0
  17. zain/Activation/train.py +122 -0
  18. zain/Activation/wandb/debug-internal.log +33 -0
  19. zain/Activation/wandb/debug.log +23 -0
  20. zain/Activation/wandb/run-20260813_211521-bdgno22l/files/output.log +14 -0
  21. zain/Activation/wandb/run-20260813_211521-bdgno22l/files/requirements.txt +149 -0
  22. zain/Activation/wandb/run-20260813_211521-bdgno22l/files/wandb-metadata.json +102 -0
  23. zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug-core.log +100 -0
  24. zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug-internal.log +33 -0
  25. zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug.log +23 -0
  26. zain/Activation/wandb/run-20260813_211521-bdgno22l/run-bdgno22l.wandb +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ zain/Activation/wandb/run-20260813_211521-bdgno22l/run-bdgno22l.wandb filter=lfs diff=lfs merge=lfs -text
zain/Activation/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # Activation
zain/Activation/__pycache__/exp.cpython-311.pyc ADDED
Binary file (62.8 kB). View file
 
zain/Activation/exp.py ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================================
2
+ # exp.py – FULL FILE, ALL FIXES INCLUDED (hook requires_grad check)
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
+ **kwargs
81
+ ):
82
+ super().__init__(**kwargs)
83
+ self.mlp_type = mlp_type
84
+ self.activation = activation
85
+ self.waleed_beta = waleed_beta
86
+ if self.num_key_value_heads != self.num_attention_heads:
87
+ raise ValueError(
88
+ f"Pure MHA required: num_key_value_heads ({self.num_key_value_heads}) "
89
+ f"must equal num_attention_heads ({self.num_attention_heads})."
90
+ )
91
+
92
+
93
+ # =============================================================================
94
+ # 3. MODEL (with override hook)
95
+ # =============================================================================
96
+
97
+ class TinyLlamaMLP(nn.Module):
98
+ override_active = False
99
+ override_value = -100.0
100
+
101
+ def __init__(self, config: TinyLlamaConfig):
102
+ super().__init__()
103
+ self.hidden_size = config.hidden_size
104
+ self.intermediate_size = config.intermediate_size
105
+ self.mlp_type = config.mlp_type
106
+ self.activation_name = config.activation
107
+ self.waleed_beta = getattr(config, "waleed_beta", 10.0)
108
+
109
+ if self.mlp_type == "glu":
110
+ effective_intermediate = self.intermediate_size
111
+ elif self.mlp_type == "mlp":
112
+ effective_intermediate = int(self.intermediate_size * 1.5)
113
+ print(f"[MLP] Auto‑scaled intermediate_size from {self.intermediate_size} to {effective_intermediate}")
114
+ else:
115
+ raise ValueError(f"Unknown mlp_type: {self.mlp_type}")
116
+
117
+ self.effective_intermediate = effective_intermediate
118
+
119
+ if self.mlp_type == "glu":
120
+ self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
121
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
122
+ else:
123
+ self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
124
+
125
+ self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
126
+
127
+ # Activation handling
128
+ if self.mlp_type == "glu":
129
+ if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
130
+ self.act_fn = None
131
+ elif self.activation_name == "waleed10":
132
+ self.act_fn = GLUActivationRegistry.get("linear")
133
+ elif self.activation_name == "silu-waleed10":
134
+ self.act_fn = GLUActivationRegistry.get("silu")
135
+ else:
136
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
137
+ else:
138
+ if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
139
+ raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
140
+ elif self.activation_name == "waleed10":
141
+ self.act_fn = GLUActivationRegistry.get("linear")
142
+ elif self.activation_name == "silu-waleed10":
143
+ self.act_fn = GLUActivationRegistry.get("silu")
144
+ else:
145
+ self.act_fn = GLUActivationRegistry.get(self.activation_name)
146
+
147
+ if self.activation_name in ("situglu_low", "waleedglu_low"):
148
+ self.beta1 = 2.5
149
+ self.beta2 = 4.0
150
+ else:
151
+ self.beta1 = 4.0
152
+ self.beta2 = 25.0
153
+
154
+ self.is_situglu = self.activation_name in ("situglu", "situglu_low")
155
+ self.is_waleed = self.activation_name in ("waleed", "waleedglu_low")
156
+ self.is_waleed10 = self.activation_name in ("waleed10", "silu-waleed10")
157
+ self.has_sigmoid_gate = self.activation_name.startswith("situglu")
158
+
159
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
160
+ if self.mlp_type == "glu":
161
+ gate = self.gate_proj(x)
162
+ up = self.up_proj(x)
163
+
164
+ if self.is_situglu or self.is_waleed:
165
+ if self.has_sigmoid_gate:
166
+ gate = self.beta1 * torch.tanh(gate / self.beta1) * torch.sigmoid(gate)
167
+ else:
168
+ gate = self.beta1 * torch.tanh(gate / self.beta1)
169
+ up = self.beta2 * torch.tanh(up / self.beta2)
170
+ hidden = gate * up
171
+ else:
172
+ hidden = self.act_fn(gate) * up
173
+
174
+ out = self.down_proj(hidden)
175
+
176
+ else: # mlp
177
+ hidden = self.act_fn(self.up_proj(x))
178
+ out = self.down_proj(hidden)
179
+
180
+ if self.is_waleed10:
181
+ out = self.waleed_beta * torch.tanh(out / self.waleed_beta)
182
+
183
+ # FIX: only register hook if the output tensor requires gradients
184
+ if TinyLlamaMLP.override_active and out.requires_grad:
185
+ out.register_hook(lambda grad: TinyLlamaMLP.override_value * torch.ones_like(grad))
186
+
187
+ return out
188
+
189
+
190
+ # ----------------------------------------------------------------------------
191
+ # DECODER LAYER, ATTENTION MASK, MODEL
192
+ # ----------------------------------------------------------------------------
193
+
194
+ class TinyLlamaDecoderLayer(nn.Module):
195
+ def __init__(self, config: TinyLlamaConfig, layer_idx: int):
196
+ super().__init__()
197
+ self.hidden_size = config.hidden_size
198
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
199
+ self.mlp = TinyLlamaMLP(config)
200
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
201
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
202
+ self.residual_pre_attn = nn.Identity()
203
+ self.residual_post_attn = nn.Identity()
204
+ self.residual_post_mlp = nn.Identity()
205
+
206
+ def forward(self, hidden_states, attention_mask=None, position_ids=None, position_embeddings=None, **kwargs):
207
+ residual = hidden_states
208
+ hidden_states = self.residual_pre_attn(hidden_states)
209
+ hidden_states = self.input_layernorm(hidden_states)
210
+ attn_out = self.self_attn(
211
+ hidden_states=hidden_states,
212
+ attention_mask=attention_mask,
213
+ position_ids=position_ids,
214
+ position_embeddings=position_embeddings,
215
+ )[0]
216
+ hidden_states = residual + attn_out
217
+ hidden_states = self.residual_post_attn(hidden_states)
218
+
219
+ residual = hidden_states
220
+ hidden_states = self.post_attention_layernorm(hidden_states)
221
+ hidden_states = self.mlp(hidden_states)
222
+ hidden_states = residual + hidden_states
223
+ hidden_states = self.residual_post_mlp(hidden_states)
224
+ return (hidden_states,)
225
+
226
+
227
+ def _build_causal_mask(attention_mask, seq_len, dtype, device):
228
+ min_value = torch.finfo(dtype).min
229
+ causal = torch.full((seq_len, seq_len), fill_value=min_value, dtype=dtype, device=device)
230
+ causal = torch.triu(causal, diagonal=1)
231
+ causal = causal[None, None, :, :]
232
+ if attention_mask is None:
233
+ batch_size = 1
234
+ return causal.expand(batch_size, 1, seq_len, seq_len)
235
+ batch_size = attention_mask.shape[0]
236
+ causal = causal.expand(batch_size, 1, seq_len, seq_len).clone()
237
+ padding = attention_mask[:, None, None, :].to(device) == 0
238
+ causal = causal.masked_fill(padding, min_value)
239
+ return causal
240
+
241
+
242
+ _MASK_PRINTED = False
243
+
244
+
245
+ class TinyLlamaModel(LlamaPreTrainedModel):
246
+ config_class = TinyLlamaConfig
247
+
248
+ def __init__(self, config: TinyLlamaConfig):
249
+ super().__init__(config)
250
+ self.padding_idx = config.pad_token_id
251
+ self.vocab_size = config.vocab_size
252
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
253
+ self.layers = nn.ModuleList([TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
254
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
255
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
256
+ self.post_init()
257
+
258
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None, return_dict=None, **kwargs):
259
+ global _MASK_PRINTED
260
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
261
+ if inputs_embeds is None:
262
+ inputs_embeds = self.embed_tokens(input_ids)
263
+ if position_ids is None:
264
+ seq_len = inputs_embeds.shape[1]
265
+ position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0).expand(inputs_embeds.shape[0], -1)
266
+ hidden_states = inputs_embeds
267
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
268
+ seq_len = hidden_states.shape[1]
269
+ causal_mask = _build_causal_mask(attention_mask, seq_len, hidden_states.dtype, hidden_states.device)
270
+ if not _MASK_PRINTED:
271
+ print("[INFO] Causal mask (float with -inf) applied to all attention layers.")
272
+ _MASK_PRINTED = True
273
+ for decoder_layer in self.layers:
274
+ layer_outputs = decoder_layer(
275
+ hidden_states,
276
+ attention_mask=causal_mask,
277
+ position_ids=position_ids,
278
+ position_embeddings=position_embeddings,
279
+ )
280
+ hidden_states = layer_outputs[0]
281
+ hidden_states = self.norm(hidden_states)
282
+ if not return_dict:
283
+ return (hidden_states,)
284
+ return {"last_hidden_state": hidden_states, "hidden_states": None, "attentions": None}
285
+
286
+
287
+ class TinyLlamaForCausalLM(LlamaPreTrainedModel):
288
+ config_class = TinyLlamaConfig
289
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
290
+
291
+ def __init__(self, config: TinyLlamaConfig):
292
+ super().__init__(config)
293
+ self.model = TinyLlamaModel(config)
294
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
295
+ if config.tie_word_embeddings:
296
+ self.lm_head.weight = self.model.embed_tokens.weight
297
+ self.post_init()
298
+
299
+ def get_input_embeddings(self):
300
+ return self.model.embed_tokens
301
+
302
+ def set_input_embeddings(self, value):
303
+ self.model.embed_tokens = value
304
+
305
+ def get_output_embeddings(self):
306
+ return self.lm_head
307
+
308
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
309
+ labels=None, return_dict=None, **kwargs):
310
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
311
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids,
312
+ inputs_embeds=inputs_embeds, return_dict=return_dict)
313
+ hidden_states = outputs["last_hidden_state"] if return_dict else outputs[0]
314
+ logits = self.lm_head(hidden_states)
315
+ loss = None
316
+ if labels is not None:
317
+ shift_logits = logits[..., :-1, :].contiguous()
318
+ shift_labels = labels[..., 1:].contiguous()
319
+ loss_fct = nn.CrossEntropyLoss()
320
+ loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
321
+ if not return_dict:
322
+ output = (logits,) + outputs[1:]
323
+ return (loss,) + output if loss is not None else output
324
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None, hidden_states=None, attentions=None)
325
+
326
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
327
+ if past_key_values:
328
+ input_ids = input_ids[:, -1:]
329
+ position_ids = kwargs.get("position_ids")
330
+ if attention_mask is not None and position_ids is None:
331
+ position_ids = attention_mask.long().cumsum(-1) - 1
332
+ position_ids.masked_fill_(attention_mask == 0, 1)
333
+ if past_key_values:
334
+ position_ids = position_ids[:, -1].unsqueeze(-1)
335
+ return {
336
+ "input_ids": input_ids,
337
+ "position_ids": position_ids,
338
+ "past_key_values": past_key_values,
339
+ "attention_mask": attention_mask,
340
+ }
341
+
342
+
343
+ # =============================================================================
344
+ # 4. HF CHECKPOINT FETCHER
345
+ # =============================================================================
346
+
347
+ def fetch_latest_checkpoint_from_hub(
348
+ repo_id: str,
349
+ subpath: str,
350
+ variant: str,
351
+ checkpoint_step: Optional[int] = None
352
+ ) -> str:
353
+ remote_prefix = f"{subpath}/{variant}_run" if subpath else f"{variant}_run"
354
+ if checkpoint_step is not None:
355
+ full_remote_path = f"{remote_prefix}/checkpoint-{checkpoint_step}"
356
+ print(f"[Hub] Fetching specific checkpoint: {repo_id}/{full_remote_path}")
357
+ local_root = snapshot_download(
358
+ repo_id=repo_id,
359
+ allow_patterns=[f"{full_remote_path}/*"],
360
+ local_dir_use_symlinks=False,
361
+ )
362
+ checkpoint_local_path = os.path.join(local_root, full_remote_path)
363
+ if not os.path.exists(checkpoint_local_path):
364
+ raise RuntimeError(f"Downloaded checkpoint not found at {checkpoint_local_path}")
365
+ return checkpoint_local_path
366
+
367
+ print(f"[Hub] Downloading entire run folder: {repo_id}/{remote_prefix}")
368
+ local_root = snapshot_download(
369
+ repo_id=repo_id,
370
+ allow_patterns=[f"{remote_prefix}/*"],
371
+ local_dir_use_symlinks=False,
372
+ )
373
+ run_local_path = os.path.join(local_root, remote_prefix)
374
+ if not os.path.exists(run_local_path):
375
+ raise RuntimeError(f"Run folder not found at {run_local_path}")
376
+
377
+ checkpoints = []
378
+ for item in os.listdir(run_local_path):
379
+ if item.startswith("checkpoint-") and os.path.isdir(os.path.join(run_local_path, item)):
380
+ match = re.match(r"checkpoint-(\d+)", item)
381
+ if match:
382
+ step = int(match.group(1))
383
+ checkpoints.append((step, item))
384
+
385
+ if not checkpoints:
386
+ raise RuntimeError(f"No checkpoint folders found in {run_local_path}")
387
+
388
+ latest_step, latest_name = max(checkpoints, key=lambda x: x[0])
389
+ print(f"[Hub] Latest checkpoint found: step {latest_step}")
390
+ return os.path.join(run_local_path, latest_name)
391
+
392
+
393
+ # =============================================================================
394
+ # 5. RESUME + FREEZE + OVERRIDE CALLBACK (FIXED)
395
+ # =============================================================================
396
+
397
+ class ResumeFreezeOverrideCallback(TrainerCallback):
398
+ def __init__(self, override_value: Optional[float] = None):
399
+ self.override_value = override_value
400
+ self._trainer = None # Will be set manually
401
+
402
+ def on_train_begin(self, args, state, control, **kwargs):
403
+ # Try multiple ways to get the trainer
404
+ trainer = kwargs.get('trainer')
405
+ if trainer is None:
406
+ trainer = getattr(self, '_trainer', None)
407
+ if trainer is None:
408
+ trainer = getattr(self, 'trainer', None)
409
+ if trainer is None:
410
+ raise ValueError("Trainer not accessible in callback")
411
+
412
+ model = trainer.model
413
+
414
+ # ----- FREEZE ALL EXCEPT MLP PROJECTIONS -----
415
+ for name, param in model.named_parameters():
416
+ if any(x in name for x in ["gate_proj", "up_proj", "down_proj"]):
417
+ param.requires_grad = True
418
+ else:
419
+ param.requires_grad = False
420
+
421
+ trainable_params = [p for p in model.parameters() if p.requires_grad]
422
+
423
+ # ----- REBUILD OPTIMIZER -----
424
+ from torch.optim import AdamW
425
+ new_optimizer = AdamW(
426
+ trainable_params,
427
+ lr=args.learning_rate,
428
+ weight_decay=args.weight_decay,
429
+ betas=(args.adam_beta1, args.adam_beta2),
430
+ eps=args.adam_epsilon,
431
+ )
432
+ trainer.optimizer = new_optimizer
433
+
434
+ # ----- KEEP EXISTING SCHEDULER (re‑attach) -----
435
+ if trainer.lr_scheduler is not None:
436
+ trainer.lr_scheduler.optimizer = new_optimizer
437
+
438
+ # ----- ACTIVATE OVERRIDE -----
439
+ if self.override_value is not None:
440
+ TinyLlamaMLP.override_active = True
441
+ TinyLlamaMLP.override_value = self.override_value
442
+ print(f"[Override] Activated with value = {self.override_value}")
443
+ else:
444
+ print("[Freeze] MLP projections frozen; no gradient override.")
445
+
446
+
447
+ # =============================================================================
448
+ # 6. MONITORING
449
+ # =============================================================================
450
+
451
+ class StatsEngine:
452
+ @staticmethod
453
+ def compute(tensor: torch.Tensor, user_limit: float, dtype_ratio: float) -> Dict[str, float]:
454
+ with torch.no_grad():
455
+ abs_t = tensor.abs()
456
+ dtype_info = torch.finfo(tensor.dtype)
457
+ dtype_limit = dtype_ratio * dtype_info.max if not torch.isinf(torch.tensor(dtype_info.max)) else float("inf")
458
+ return {
459
+ "norm": tensor.norm(2).item(),
460
+ "mean": tensor.mean().item(),
461
+ "std": tensor.std().item(),
462
+ "max_abs": abs_t.max().item(),
463
+ "frac_near_dtype_limit": (abs_t > dtype_limit).float().mean().item() if not math.isinf(dtype_limit) else 0.0,
464
+ "frac_near_user_limit": (abs_t > user_limit).float().mean().item(),
465
+ "min": tensor.min().item(),
466
+ "max": tensor.max().item(),
467
+ "range": tensor.max().item() - tensor.min().item(),
468
+ }
469
+
470
+
471
+ class StepAccumulator:
472
+ def __init__(self):
473
+ self.tensors: Dict[str, Dict[str, float]] = {}
474
+
475
+ def add(self, name: str, numel: int, stats: Dict[str, float]):
476
+ new_entry = {"numel": numel, **stats}
477
+ existing = self.tensors.get(name)
478
+ self.tensors[name] = new_entry if existing is None else self._merge_entry(existing, new_entry)
479
+
480
+ @staticmethod
481
+ def _merge_entry(a: Dict[str, float], b: Dict[str, float]) -> Dict[str, float]:
482
+ total_n = a["numel"] + b["numel"]
483
+ if total_n == 0:
484
+ return a
485
+ norm = math.sqrt(a["norm"] ** 2 + b["norm"] ** 2)
486
+ max_abs = max(a["max_abs"], b["max_abs"])
487
+ mean = (a["mean"] * a["numel"] + b["mean"] * b["numel"]) / total_n
488
+ ex2 = (a["numel"] * (a["std"] ** 2 + a["mean"] ** 2) + b["numel"] * (b["std"] ** 2 + b["mean"] ** 2)) / total_n
489
+ std = math.sqrt(max(0.0, ex2 - mean ** 2))
490
+ frac_dtype = (a["frac_near_dtype_limit"] * a["numel"] + b["frac_near_dtype_limit"] * b["numel"]) / total_n
491
+ frac_user = (a["frac_near_user_limit"] * a["numel"] + b["frac_near_user_limit"] * b["numel"]) / total_n
492
+ t_min = min(a.get("min", float("inf")), b.get("min", float("inf")))
493
+ t_max = max(a.get("max", float("-inf")), b.get("max", float("-inf")))
494
+ return {
495
+ "numel": total_n,
496
+ "norm": norm,
497
+ "mean": mean,
498
+ "std": std,
499
+ "max_abs": max_abs,
500
+ "frac_near_dtype_limit": frac_dtype,
501
+ "frac_near_user_limit": frac_user,
502
+ "min": t_min,
503
+ "max": t_max,
504
+ "range": t_max - t_min,
505
+ }
506
+
507
+ def clear(self):
508
+ self.tensors.clear()
509
+
510
+ def _aggregate(self, entries: Dict[str, Dict[str, float]]) -> Dict[str, float]:
511
+ if not entries:
512
+ return {}
513
+ numels = [e["numel"] for e in entries.values()]
514
+ total_n = sum(numels)
515
+ norm = math.sqrt(sum(e["norm"] ** 2 for e in entries.values()))
516
+ max_abs = max(e["max_abs"] for e in entries.values())
517
+ mean = sum(e["mean"] * e["numel"] for e in entries.values()) / total_n
518
+ ex2 = sum(e["numel"] * (e["std"] ** 2 + e["mean"] ** 2) for e in entries.values()) / total_n
519
+ std = math.sqrt(max(0.0, ex2 - mean ** 2))
520
+ frac_dtype = sum(e["frac_near_dtype_limit"] * e["numel"] for e in entries.values()) / total_n
521
+ frac_user = sum(e["frac_near_user_limit"] * e["numel"] for e in entries.values()) / total_n
522
+ t_min = min(e.get("min", float("inf")) for e in entries.values())
523
+ t_max = max(e.get("max", float("-inf")) for e in entries.values())
524
+ return {
525
+ "norm": norm,
526
+ "mean": mean,
527
+ "std": std,
528
+ "max_abs": max_abs,
529
+ "frac_near_dtype_limit": frac_dtype,
530
+ "frac_near_user_limit": frac_user,
531
+ "min": t_min,
532
+ "max": t_max,
533
+ "range": t_max - t_min,
534
+ }
535
+
536
+ def get_global_stats(self) -> Dict[str, float]:
537
+ return self._aggregate(self.tensors)
538
+
539
+ def get_layer_stats(self, layer_prefix: str) -> Dict[str, float]:
540
+ entries = {k: v for k, v in self.tensors.items() if k.startswith(layer_prefix + ".")}
541
+ return self._aggregate(entries)
542
+
543
+
544
+ class HookRegistry:
545
+ def __init__(self, model: nn.Module):
546
+ self.model = model
547
+ self.handles = []
548
+ self.active = False
549
+
550
+ def attach_forward(self, module_patterns, accumulator, user_limit, dtype_ratio):
551
+ for name, module in self.model.named_modules():
552
+ if any(re.search(p, name) for p in module_patterns):
553
+ h = module.register_forward_hook(
554
+ self._make_forward_hook(name, accumulator, user_limit, dtype_ratio)
555
+ )
556
+ self.handles.append(h)
557
+
558
+ def attach_backward(self, param_patterns, accumulator, user_limit, dtype_ratio):
559
+ for name, param in self.model.named_parameters():
560
+ if not param.requires_grad:
561
+ continue
562
+ if param_patterns and not any(re.search(p, name) for p in param_patterns):
563
+ continue
564
+ h = param.register_hook(
565
+ self._make_backward_hook(f"grad.{name}", accumulator, user_limit, dtype_ratio)
566
+ )
567
+ self.handles.append(h)
568
+
569
+ def _make_forward_hook(self, module_name, accumulator, user_limit, dtype_ratio):
570
+ def hook(module, inp, out):
571
+ if not self.active:
572
+ return
573
+ if isinstance(out, dict):
574
+ out = out.get("last_hidden_state")
575
+ if not torch.is_tensor(out):
576
+ return
577
+ stats = StatsEngine.compute(out.detach(), user_limit, dtype_ratio)
578
+ accumulator.add(f"act.{module_name}", out.numel(), stats)
579
+ return hook
580
+
581
+ def _make_backward_hook(self, param_name, accumulator, user_limit, dtype_ratio):
582
+ def hook(grad):
583
+ if not self.active:
584
+ return
585
+ stats = StatsEngine.compute(grad.detach(), user_limit, dtype_ratio)
586
+ accumulator.add(param_name, grad.numel(), stats)
587
+ return hook
588
+
589
+ def set_active(self, active: bool):
590
+ self.active = active
591
+
592
+ def clear(self):
593
+ for h in self.handles:
594
+ h.remove()
595
+ self.handles.clear()
596
+
597
+
598
+ class StabilityMonitorCallback(TrainerCallback):
599
+ def __init__(
600
+ self,
601
+ model: nn.Module,
602
+ monitor_every_n_steps: int = 10,
603
+ module_patterns: Optional[List[str]] = None,
604
+ param_patterns: Optional[List[str]] = None,
605
+ user_limits: Optional[Dict[str, float]] = None,
606
+ dtype_proximity_ratio: float = 0.9,
607
+ log_scope: Optional[Dict[str, bool]] = None,
608
+ monitor_during_eval: bool = False,
609
+ ):
610
+ self.model = model
611
+ self.monitor_every_n_steps = monitor_every_n_steps
612
+ self.module_patterns = module_patterns or [".*mlp.*", ".*residual.*"]
613
+ self.param_patterns = param_patterns or self.module_patterns
614
+ self.user_limits = user_limits or {"grad": 1.0, "param": 100.0, "act": 50.0}
615
+ self.dtype_ratio = dtype_proximity_ratio
616
+ self.log_scope = log_scope or {"global": True, "per_layer": True, "per_tensor": False}
617
+ self.monitor_during_eval = monitor_during_eval
618
+
619
+ self.accumulator = StepAccumulator()
620
+ self.hooks = HookRegistry(model)
621
+ self.hooks.attach_forward(
622
+ self.module_patterns,
623
+ self.accumulator,
624
+ self.user_limits["act"],
625
+ self.dtype_ratio,
626
+ )
627
+ self.hooks.attach_backward(
628
+ self.param_patterns,
629
+ self.accumulator,
630
+ self.user_limits["grad"],
631
+ self.dtype_ratio,
632
+ )
633
+ self.pending_metrics = None
634
+
635
+ def _should_monitor(self, state):
636
+ return state.global_step % self.monitor_every_n_steps == 0
637
+
638
+ def on_step_begin(self, args, state, control, **kwargs):
639
+ if self._should_monitor(state):
640
+ self.accumulator.clear()
641
+ self.hooks.set_active(True)
642
+
643
+ def on_step_end(self, args, state, control, **kwargs):
644
+ if not self.hooks.active:
645
+ return
646
+ for name, param in self.model.named_parameters():
647
+ if self.param_patterns and not any(re.search(p, name) for p in self.param_patterns):
648
+ continue
649
+ stats = StatsEngine.compute(param.data, self.user_limits["param"], self.dtype_ratio)
650
+ self.accumulator.add(f"param.{name}", param.numel(), stats)
651
+ self.hooks.set_active(False)
652
+ self.pending_metrics = self._build_metrics()
653
+
654
+ def _kind_of(self, name: str) -> str:
655
+ if name.startswith("act."):
656
+ return "act"
657
+ if name.startswith("grad."):
658
+ return "grad"
659
+ if name.startswith("param."):
660
+ return "param"
661
+ return "other"
662
+
663
+ def _strip_kind(self, name: str) -> str:
664
+ if name.startswith("act."):
665
+ return name[4:]
666
+ if name.startswith(("grad.", "param.")):
667
+ return name[5:]
668
+ return name
669
+
670
+ def _build_metrics(self, scope: str = "train") -> Dict[str, float]:
671
+ metrics = {}
672
+ if self.log_scope.get("global", True):
673
+ by_kind = {}
674
+ for k, v in self.accumulator.tensors.items():
675
+ by_kind.setdefault(self._kind_of(k), {})[k] = v
676
+ for kind, entries in by_kind.items():
677
+ stats = self.accumulator._aggregate(entries)
678
+ for kk, vv in stats.items():
679
+ metrics[f"{scope}/global/{kind}/{kk}"] = vv
680
+
681
+ if self.log_scope.get("per_layer", True):
682
+ layer_prefixes = set()
683
+ for name in self.accumulator.tensors:
684
+ clean = self._strip_kind(name)
685
+ parts = clean.split(".")
686
+ for i, p in enumerate(parts):
687
+ if p == "layers" and i + 1 < len(parts):
688
+ prefix = ".".join(parts[: i + 2])
689
+ layer_prefixes.add(prefix)
690
+ for prefix in layer_prefixes:
691
+ by_kind = {}
692
+ for k, v in self.accumulator.tensors.items():
693
+ clean = self._strip_kind(k)
694
+ if clean.startswith(prefix + ".") or clean == prefix:
695
+ by_kind.setdefault(self._kind_of(k), {})[k] = v
696
+ safe = prefix.replace(".", "_")
697
+ for kind, entries in by_kind.items():
698
+ if not entries:
699
+ continue
700
+ stats = self.accumulator._aggregate(entries)
701
+ for kk, vv in stats.items():
702
+ metrics[f"{scope}/layer_{safe}/{kind}/{kk}"] = vv
703
+
704
+ if self.log_scope.get("per_tensor", False):
705
+ for name, stats in self.accumulator.tensors.items():
706
+ safe = name.replace(".", "_")
707
+ for kk, vv in stats.items():
708
+ if kk == "numel":
709
+ continue
710
+ metrics[f"{scope}/tensor_{safe}/{kk}"] = vv
711
+ return metrics
712
+
713
+ def on_log(self, args, state, control, logs=None, **kwargs):
714
+ if logs is not None and self.pending_metrics is not None:
715
+ logs.update(self.pending_metrics)
716
+ try:
717
+ import wandb
718
+ if wandb.run is not None:
719
+ wandb.log(self.pending_metrics, step=state.global_step)
720
+ except ImportError:
721
+ pass
722
+ self.pending_metrics = None
723
+
724
+ def on_prediction_step(self, args, state, control, **kwargs):
725
+ if not self.monitor_during_eval:
726
+ return
727
+ if not self.hooks.active:
728
+ self.accumulator.clear()
729
+ self.hooks.set_active(True)
730
+ for name, param in self.model.named_parameters():
731
+ if self.param_patterns and not any(re.search(p, name) for p in self.param_patterns):
732
+ continue
733
+ stats = StatsEngine.compute(param.data, self.user_limits["param"], self.dtype_ratio)
734
+ self.accumulator.add(f"param.{name}", param.numel(), stats)
735
+ self.pending_metrics = self._build_metrics(scope="eval")
736
+
737
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
738
+ self.hooks.set_active(False)
739
+ self.accumulator.clear()
740
+
741
+
742
+ # =============================================================================
743
+ # 7. TIME TRACKER
744
+ # =============================================================================
745
+
746
+ class TimeTrackerCallback(TrainerCallback):
747
+ def __init__(self):
748
+ self.step_start = None
749
+ self.epoch_start = None
750
+ self.total_train_time = 0.0
751
+ self.step_times = []
752
+
753
+ def on_epoch_begin(self, args, state, control, **kwargs):
754
+ self.epoch_start = time.perf_counter()
755
+
756
+ def on_step_begin(self, args, state, control, **kwargs):
757
+ self.step_start = time.perf_counter()
758
+
759
+ def on_step_end(self, args, state, control, **kwargs):
760
+ if self.step_start is not None:
761
+ dt = time.perf_counter() - self.step_start
762
+ self.step_times.append(dt)
763
+ self.total_train_time += dt
764
+ self.step_start = None
765
+
766
+ def on_log(self, args, state, control, logs=None, **kwargs):
767
+ if logs is None:
768
+ return
769
+ logs["train/total_time_seconds"] = self.total_train_time
770
+ if self.step_times:
771
+ recent = self.step_times[-100:]
772
+ logs["train/time_per_step_avg"] = sum(recent) / len(recent)
773
+ if self.epoch_start is not None:
774
+ logs["train/epoch_time_elapsed"] = time.perf_counter() - self.epoch_start
775
+ if state.max_steps and state.global_step > 0:
776
+ avg = self.total_train_time / state.global_step
777
+ remaining = (state.max_steps - state.global_step) * avg
778
+ logs["train/estimated_remaining_minutes"] = remaining / 60.0
779
+
780
+
781
+ # =============================================================================
782
+ # 8. METRICS LOGGER
783
+ # =============================================================================
784
+
785
+ class MetricsLoggerCallback(TrainerCallback):
786
+ def __init__(self, output_dir: str):
787
+ self.output_dir = Path(output_dir)
788
+ self.output_dir.mkdir(parents=True, exist_ok=True)
789
+ self.log_file = self.output_dir / "training_log.jsonl"
790
+
791
+ def on_log(self, args, state, control, logs=None, **kwargs):
792
+ if logs is None:
793
+ return
794
+ entry = {"step": state.global_step, "epoch": state.epoch, "timestamp": time.time(), **logs}
795
+ with open(self.log_file, "a") as f:
796
+ f.write(json.dumps(entry, default=str) + "\n")
797
+
798
+
799
+ # =============================================================================
800
+ # 9. DATA & TRAINER FACTORY
801
+ # =============================================================================
802
+
803
+ def build_dataset(
804
+ tokenizer,
805
+ max_seq_len: int = 512,
806
+ split: str = "train",
807
+ dataset_name: str = "roneneldan/TinyStories",
808
+ max_samples: Optional[int] = None,
809
+ ):
810
+ ds = load_dataset(dataset_name, split=split)
811
+ if max_samples is not None and split == "train":
812
+ ds = ds.select(range(min(max_samples, len(ds))))
813
+
814
+ def tokenize(examples):
815
+ out = tokenizer(examples["text"], add_special_tokens=False)
816
+ eos_id = tokenizer.eos_token_id
817
+ out["input_ids"] = [ids + [eos_id] for ids in out["input_ids"]]
818
+ if "attention_mask" in out:
819
+ out["attention_mask"] = [mask + [1] for mask in out["attention_mask"]]
820
+ return out
821
+
822
+ tokenized = ds.map(tokenize, batched=True, num_proc=4, remove_columns=ds.column_names)
823
+
824
+ def group_texts(examples):
825
+ concatenated = {k: list(chain.from_iterable(examples[k])) for k in examples.keys()}
826
+ total_length = len(concatenated[list(examples.keys())[0]])
827
+ total_length = (total_length // max_seq_len) * max_seq_len
828
+ result = {
829
+ k: [t[i:i + max_seq_len] for i in range(0, total_length, max_seq_len)]
830
+ for k, t in concatenated.items()
831
+ }
832
+ result["labels"] = result["input_ids"].copy()
833
+ return result
834
+
835
+ return tokenized.map(group_texts, batched=True, batch_size=10000, num_proc=4)
836
+
837
+
838
+ def create_trainer(
839
+ model,
840
+ tokenizer,
841
+ config: Dict[str, Any],
842
+ train_dataset,
843
+ eval_dataset=None,
844
+ ):
845
+ tc = config.get("training", {})
846
+ mc = config.get("monitor", {})
847
+ go = config.get("gradient_override", {})
848
+
849
+ wandb_project = tc.get("wandb_project")
850
+ if wandb_project:
851
+ os.environ["WANDB_PROJECT"] = wandb_project
852
+
853
+ args = TrainingArguments(
854
+ output_dir=tc.get("output_dir", "./out"),
855
+ run_name=tc.get("run_name", None),
856
+ num_train_epochs=tc.get("num_train_epochs", 3),
857
+ per_device_train_batch_size=tc.get("per_device_train_batch_size", 16),
858
+ per_device_eval_batch_size=tc.get("per_device_eval_batch_size", 16),
859
+ gradient_accumulation_steps=tc.get("gradient_accumulation_steps", 4),
860
+ learning_rate=tc.get("learning_rate", 3e-4),
861
+ weight_decay=tc.get("weight_decay", 0.0),
862
+ max_grad_norm=tc.get("max_grad_norm", 1.0),
863
+ optim=tc.get("optim", "adamw_torch"),
864
+ warmup_steps=tc.get("warmup_steps", 0),
865
+ lr_scheduler_type=tc.get("lr_scheduler_type", "cosine"),
866
+ bf16=tc.get("bf16", True),
867
+ logging_steps=tc.get("logging_steps", 10),
868
+ eval_strategy=tc.get("eval_strategy", "steps"),
869
+ eval_steps=tc.get("eval_steps", 500),
870
+ save_strategy=tc.get("save_strategy", "steps"),
871
+ save_steps=tc.get("save_steps", 1000),
872
+ load_best_model_at_end=tc.get("load_best_model_at_end", False),
873
+ report_to=tc.get("report_to", "tensorboard"),
874
+ push_to_hub=tc.get("push_to_hub", False),
875
+ hub_model_id=tc.get("hub_model_id", None),
876
+ hub_token=tc.get("hub_token") or os.environ.get("HF_TOKEN"),
877
+ max_steps=tc.get("max_steps", -1),
878
+ seed=tc.get("seed", 42),
879
+ data_seed=tc.get("data_seed", 42),
880
+ remove_unused_columns=False,
881
+ )
882
+
883
+ callbacks = [TimeTrackerCallback()]
884
+
885
+ # ---- FREEZE + OVERRIDE CALLBACK ----
886
+ freeze_mlp = tc.get("freeze_mlp", False)
887
+ override_enabled = go.get("enabled", False)
888
+ if freeze_mlp or override_enabled:
889
+ override_value = go.get("value", -100.0) if override_enabled else None
890
+ callbacks.append(ResumeFreezeOverrideCallback(override_value=override_value))
891
+
892
+ # ---- MONITORING ----
893
+ if mc.get("enabled", True):
894
+ module_patterns = mc.get("module_patterns", [".*mlp.*", ".*residual.*"])
895
+ callbacks.append(
896
+ StabilityMonitorCallback(
897
+ model=model,
898
+ monitor_every_n_steps=mc.get("monitor_every_n_steps", 10),
899
+ module_patterns=module_patterns,
900
+ param_patterns=module_patterns,
901
+ user_limits=mc.get("user_limits", {"grad": 1.0, "param": 100.0, "act": 50.0}),
902
+ dtype_proximity_ratio=mc.get("dtype_proximity_ratio", 0.9),
903
+ log_scope=mc.get("log_scope", {"global": True, "per_layer": True, "per_tensor": False}),
904
+ monitor_during_eval=mc.get("monitor_during_eval", False),
905
+ )
906
+ )
907
+
908
+ callbacks.append(MetricsLoggerCallback(args.output_dir))
909
+
910
+ collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
911
+
912
+ trainer = Trainer(
913
+ model=model,
914
+ args=args,
915
+ train_dataset=train_dataset,
916
+ eval_dataset=eval_dataset,
917
+ data_collator=collator,
918
+ callbacks=callbacks,
919
+ )
920
+
921
+ return trainer
zain/Activation/llm_analyzer_wandb.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multi-LLM Activation & Loss Analyzer with WandB Logging
3
+
4
+ Evaluates multiple language models on WikiText dataset,
5
+ computing per-tensor and global activation statistics (mean, max_abs, std, norm)
6
+ and logging to Weights & Biases with separate runs per model.
7
+
8
+ Requirements:
9
+ pip install transformers torch datasets wandb tqdm
10
+
11
+ Usage:
12
+ export WANDB_PROJECT="llm-activation-analysis"
13
+ export WANDB_API_KEY="your-key"
14
+ python llm_analyzer_wandb.py
15
+ """
16
+
17
+ import math
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
21
+ from datasets import load_dataset
22
+ from typing import List, Dict, Optional, Union, Tuple
23
+ from dataclasses import dataclass, asdict
24
+ from collections import defaultdict
25
+ import json
26
+ import warnings
27
+ import os
28
+ from tqdm import tqdm
29
+
30
+ import wandb
31
+
32
+ warnings.filterwarnings("ignore")
33
+
34
+
35
+ @dataclass
36
+ class TensorStats:
37
+ mean: float
38
+ max_abs: float
39
+ std: float
40
+ norm: float
41
+ numel: int
42
+
43
+
44
+ @dataclass
45
+ class ModelResult:
46
+ model_name: str
47
+ loss: float
48
+ perplexity: float
49
+ global_act: TensorStats
50
+ layer_acts: Dict[str, TensorStats]
51
+ num_tokens: int
52
+ num_layers: int
53
+ hidden_size: int
54
+ num_params: int
55
+
56
+
57
+ class ActivationHookManager:
58
+ """Manages forward hooks to capture activations from every tensor."""
59
+
60
+ def __init__(self):
61
+ self.activations = {}
62
+ self.hooks = []
63
+ # Set once per batch via set_attention_mask(); used to exclude
64
+ # padding-token positions from activation statistics.
65
+ self._attention_mask: Optional[torch.Tensor] = None
66
+
67
+ def set_attention_mask(self, attention_mask: Optional[torch.Tensor]):
68
+ """Call once per batch before the forward pass so hooks can mask
69
+ out padding positions when computing stats."""
70
+ self._attention_mask = (
71
+ attention_mask.detach().cpu() if attention_mask is not None else None
72
+ )
73
+
74
+ def _make_hook(self, name: str):
75
+ def hook(module, input, output):
76
+ # Handle different output types
77
+ if isinstance(output, torch.Tensor):
78
+ tensor = output
79
+ elif isinstance(output, tuple) and isinstance(output[0], torch.Tensor):
80
+ tensor = output[0]
81
+ else:
82
+ return
83
+
84
+ # Detach and move to CPU to avoid GPU memory blowup
85
+ self.activations[name] = tensor.detach().cpu().float()
86
+ return hook
87
+
88
+ def register_hooks(self, model: torch.nn.Module):
89
+ """Register hooks on all modules that produce activations."""
90
+ for name, module in model.named_modules():
91
+ # Skip trivial containers
92
+ if len(list(module.children())) == 0 and hasattr(module, 'forward'):
93
+ hook = module.register_forward_hook(self._make_hook(name))
94
+ self.hooks.append(hook)
95
+
96
+ def clear(self):
97
+ self.activations.clear()
98
+
99
+ def remove_hooks(self):
100
+ for hook in self.hooks:
101
+ hook.remove()
102
+ self.hooks.clear()
103
+
104
+ def _select_real_tokens(self, tensor: torch.Tensor) -> torch.Tensor:
105
+ """
106
+ BUG FIX: previously every captured tensor (including activations at
107
+ padding-token positions) was flattened and used as-is. With
108
+ padding_side="left" and a small batch_size, the padding fraction
109
+ varies a lot batch-to-batch, so padding-token activations (which
110
+ are real, non-zero values — not zeros) were silently mixed into
111
+ mean/std/max_abs/norm, biasing exactly the saturation signal this
112
+ script exists to measure.
113
+
114
+ Here we mask out padding positions whenever a tensor's shape is
115
+ consistent with (batch, seq_len, ...) against the stored
116
+ attention_mask (batch, seq_len). Tensors that don't match that
117
+ shape (e.g. a module operating on the pooled/final dimension only)
118
+ are left as-is rather than guessing.
119
+ """
120
+ mask = self._attention_mask
121
+ if mask is None or tensor.dim() < 2:
122
+ return tensor.reshape(-1)
123
+ if tensor.shape[0] != mask.shape[0] or tensor.shape[1] != mask.shape[1]:
124
+ return tensor.reshape(-1)
125
+
126
+ bool_mask = mask.bool()
127
+ # Expand mask across any trailing dims (e.g. hidden_size) and select.
128
+ expand_shape = bool_mask.shape + (1,) * (tensor.dim() - 2)
129
+ bool_mask = bool_mask.view(expand_shape).expand_as(tensor)
130
+ return tensor[bool_mask].reshape(-1)
131
+
132
+ def compute_stats(self) -> Dict[str, TensorStats]:
133
+ """Compute statistics for all captured activations, excluding
134
+ padding-token positions where identifiable."""
135
+ stats = {}
136
+ for name, tensor in self.activations.items():
137
+ if tensor.numel() == 0:
138
+ continue
139
+ flat = self._select_real_tokens(tensor)
140
+ if flat.numel() == 0:
141
+ continue
142
+ stats[name] = TensorStats(
143
+ mean=flat.mean().item(),
144
+ max_abs=flat.abs().max().item(),
145
+ std=flat.std().item(),
146
+ norm=flat.norm().item(),
147
+ numel=flat.numel()
148
+ )
149
+ return stats
150
+
151
+
152
+ class LLMAnalyzer:
153
+ def __init__(
154
+ self,
155
+ device: Optional[str] = None,
156
+ max_length: int = 512,
157
+ max_samples: int = 1000, # number of wikitext samples to eval
158
+ batch_size: int = 4,
159
+ dtype: torch.dtype = torch.float16,
160
+ wandb_project: Optional[str] = None,
161
+ ):
162
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
163
+ self.max_length = max_length
164
+ self.max_samples = max_samples
165
+ self.batch_size = batch_size
166
+ self.dtype = dtype if self.device == "cuda" else torch.float32
167
+ self.wandb_project = wandb_project or os.environ.get("WANDB_PROJECT", "llm-activation-analysis")
168
+ self._cache = {}
169
+
170
+ def load_dataset(self, split: str = "test"):
171
+ """Load Salesforce/wikitext dataset."""
172
+ print(f"[Dataset] Loading Salesforce/wikitext ({split}) ...")
173
+ ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1", split=split)
174
+ # Filter out empty lines
175
+ texts = [t for t in ds["text"] if len(t.strip()) > 50]
176
+ print(f"[Dataset] Loaded {len(texts)} non-empty samples")
177
+ return texts[:self.max_samples]
178
+
179
+ def load_model(self, model_name: str):
180
+ """Load model and tokenizer with caching."""
181
+ if model_name in self._cache:
182
+ return self._cache[model_name]
183
+
184
+ print(f"[Loading] {model_name} ...")
185
+
186
+ tokenizer = AutoTokenizer.from_pretrained(
187
+ model_name,
188
+ trust_remote_code=True,
189
+ padding_side="left"
190
+ )
191
+ if tokenizer.pad_token is None:
192
+ tokenizer.pad_token = tokenizer.eos_token
193
+
194
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
195
+
196
+ model = AutoModelForCausalLM.from_pretrained(
197
+ model_name,
198
+ config=config,
199
+ torch_dtype=self.dtype,
200
+ device_map="auto" if self.device == "cuda" else None,
201
+ trust_remote_code=True,
202
+ )
203
+
204
+ if self.device == "cpu":
205
+ model = model.to(self.device)
206
+
207
+ model.eval()
208
+
209
+ num_params = sum(p.numel() for p in model.parameters())
210
+
211
+ self._cache[model_name] = (tokenizer, model, config, num_params)
212
+ print(f"[Loaded] {model_name} | Params: {num_params/1e6:.1f}M | Layers: {config.num_hidden_layers} | Hidden: {config.hidden_size}")
213
+ return tokenizer, model, config, num_params
214
+
215
+ def compute(
216
+ self,
217
+ model_names: List[str],
218
+ ) -> List[ModelResult]:
219
+ """
220
+ Compute loss and per-tensor activation statistics for multiple models.
221
+ Logs each model as a separate WandB run.
222
+ """
223
+ texts = self.load_dataset()
224
+ results = []
225
+
226
+ for model_name in model_names:
227
+ try:
228
+ result = self._evaluate_model(model_name, texts)
229
+ results.append(result)
230
+ except Exception as e:
231
+ print(f"[Error] {model_name}: {e}")
232
+ import traceback
233
+ traceback.print_exc()
234
+ continue
235
+
236
+ return results
237
+
238
+ def _evaluate_model(
239
+ self,
240
+ model_name: str,
241
+ texts: List[str],
242
+ ) -> ModelResult:
243
+ tokenizer, model, config, num_params = self.load_model(model_name)
244
+
245
+ # Initialize WandB run for this model
246
+ run_name = model_name.replace("/", "-")
247
+ wandb.init(
248
+ project=self.wandb_project,
249
+ name=run_name,
250
+ config={
251
+ "model": model_name,
252
+ "max_length": self.max_length,
253
+ "max_samples": self.max_samples,
254
+ "batch_size": self.batch_size,
255
+ "dtype": str(self.dtype),
256
+ "num_params": num_params,
257
+ "num_layers": config.num_hidden_layers,
258
+ "hidden_size": config.hidden_size,
259
+ },
260
+ reinit=True
261
+ )
262
+
263
+ hook_mgr = ActivationHookManager()
264
+ hook_mgr.register_hooks(model)
265
+
266
+ total_loss = 0.0
267
+ total_tokens = 0
268
+
269
+ # Global activation accumulator
270
+ global_acts = []
271
+
272
+ # Per-layer activation accumulators
273
+ # We'll aggregate stats across batches, then compute final stats
274
+ layer_act_values = defaultdict(list)
275
+
276
+ num_batches = (len(texts) + self.batch_size - 1) // self.batch_size
277
+
278
+ for i in tqdm(range(0, len(texts), self.batch_size), desc=f"Eval {run_name}", total=num_batches):
279
+ batch_texts = texts[i:i + self.batch_size]
280
+
281
+ # Tokenize
282
+ inputs = tokenizer(
283
+ batch_texts,
284
+ return_tensors="pt",
285
+ truncation=True,
286
+ max_length=self.max_length,
287
+ padding=True
288
+ )
289
+
290
+ # Move to device
291
+ if self.device == "cuda" and hasattr(model, "device"):
292
+ # model is on auto device map
293
+ input_ids = inputs["input_ids"]
294
+ if hasattr(model, "device") and model.device != torch.device("meta"):
295
+ input_ids = input_ids.to(model.device)
296
+ attention_mask = inputs.get("attention_mask")
297
+ if attention_mask is not None:
298
+ attention_mask = attention_mask.to(input_ids.device)
299
+ else:
300
+ input_ids = inputs["input_ids"].to(self.device)
301
+ attention_mask = inputs.get("attention_mask")
302
+ if attention_mask is not None:
303
+ attention_mask = attention_mask.to(self.device)
304
+
305
+ labels = input_ids.clone()
306
+
307
+ # BUG FIX: with padding_side="left" and no explicit position_ids,
308
+ # HF's default `position_ids = arange(seq_len)` is applied
309
+ # identically to every row in the batch, regardless of how much
310
+ # left-padding precedes the real tokens in that row (verified
311
+ # against transformers' LlamaModel.forward / GPT2Model.forward
312
+ # source — neither adjusts for padding when position_ids=None).
313
+ # That means a real token's absolute position (and therefore its
314
+ # RoPE rotation / absolute position embedding) depends on how
315
+ # much padding happened to precede it in this particular batch,
316
+ # not on its logical position within its own sequence. This
317
+ # silently corrupts logits -> loss -> perplexity, with the
318
+ # amount of corruption varying batch-to-batch. Fix: derive
319
+ # position_ids from attention_mask so they restart at 0 for the
320
+ # first real token of every row, and are stable (0) on padding.
321
+ if attention_mask is not None:
322
+ position_ids = attention_mask.long().cumsum(-1) - 1
323
+ position_ids.masked_fill_(attention_mask == 0, 0)
324
+ else:
325
+ position_ids = None
326
+
327
+ hook_mgr.set_attention_mask(attention_mask)
328
+
329
+ with torch.no_grad():
330
+ outputs = model(
331
+ input_ids=input_ids,
332
+ attention_mask=attention_mask,
333
+ position_ids=position_ids,
334
+ labels=labels,
335
+ )
336
+
337
+ # --- Loss Computation ---
338
+ logits = outputs.logits
339
+ shift_logits = logits[..., :-1, :].contiguous()
340
+ shift_labels = labels[..., 1:].contiguous()
341
+ shift_mask = attention_mask[..., 1:].contiguous() if attention_mask is not None else None
342
+
343
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
344
+ token_losses = loss_fct(
345
+ shift_logits.view(-1, shift_logits.size(-1)),
346
+ shift_labels.view(-1)
347
+ )
348
+
349
+ if shift_mask is not None:
350
+ token_losses = token_losses * shift_mask.view(-1)
351
+ num_valid_tokens = shift_mask.sum().item()
352
+ else:
353
+ num_valid_tokens = token_losses.numel()
354
+
355
+ batch_loss = token_losses.sum().item()
356
+ total_loss += batch_loss
357
+ total_tokens += num_valid_tokens
358
+
359
+ # --- Activation Statistics ---
360
+ # Get activations captured by hooks
361
+ act_stats = hook_mgr.compute_stats()
362
+
363
+ for name, stats in act_stats.items():
364
+ # Skip dtype-limit fraction metrics entirely
365
+ # We only log mean, max_abs, std, norm
366
+
367
+ # For global: aggregate raw values
368
+ # We can't store all raw values due to memory, so we store running sums
369
+ # But for accurate std across all batches, we need a streaming algorithm
370
+ # For simplicity and correctness, we'll store per-batch stats and weight them
371
+ layer_act_values[name].append(asdict(stats))
372
+
373
+ hook_mgr.clear()
374
+
375
+ # Log per-batch metrics to wandb
376
+ if num_valid_tokens > 0:
377
+ batch_avg_loss = batch_loss / num_valid_tokens
378
+ wandb.log({
379
+ "batch_loss": batch_avg_loss,
380
+ "batch_perplexity": torch.exp(torch.tensor(batch_avg_loss)).item(),
381
+ "batch_tokens": num_valid_tokens,
382
+ "progress": i / len(texts)
383
+ }, step=i)
384
+
385
+ hook_mgr.remove_hooks()
386
+
387
+ # --- Final Aggregation ---
388
+ avg_loss = total_loss / max(total_tokens, 1)
389
+ perplexity = torch.exp(torch.tensor(avg_loss)).item()
390
+
391
+ # Aggregate per-tensor stats across all batches
392
+ # Weighted by numel for mean, max for max_abs, pooled std, pooled norm
393
+ final_layer_stats = {}
394
+
395
+ for name, batch_stats_list in layer_act_values.items():
396
+ total_numel = sum(s["numel"] for s in batch_stats_list)
397
+ if total_numel == 0:
398
+ continue
399
+
400
+ # Weighted mean
401
+ weighted_mean = sum(s["mean"] * s["numel"] for s in batch_stats_list) / total_numel
402
+
403
+ # Max abs across all batches
404
+ max_abs = max(s["max_abs"] for s in batch_stats_list)
405
+
406
+ # BUG FIX: the previous formula (weighted average of per-batch
407
+ # variances only) drops the between-batch term that accounts for
408
+ # per-batch means differing from the global mean. Whenever batch
409
+ # means differ (they will — different texts, different lengths),
410
+ # this systematically UNDERESTIMATES the true global std — in a
411
+ # quick numeric test with two batches of different means this was
412
+ # off by ~2.8x. Correct pooled-variance formula (population form,
413
+ # matches exp.py's StepAccumulator._merge_entry):
414
+ # E[X^2] = weighted_avg(var_i + mean_i^2)
415
+ # Var(X) = E[X^2] - mean_global^2
416
+ ex2 = sum(
417
+ s["numel"] * (s["std"] ** 2 + s["mean"] ** 2) for s in batch_stats_list
418
+ ) / total_numel
419
+ pooled_std = math.sqrt(max(0.0, ex2 - weighted_mean ** 2))
420
+
421
+ # Norm: sqrt(sum of squared norms / total_numel) * sqrt(total_numel)
422
+ # Actually norm^2 = sum(x_i^2), so pooled_norm = sqrt(sum(norm_i^2))
423
+ pooled_norm = (sum(s["norm"] ** 2 for s in batch_stats_list)) ** 0.5
424
+
425
+ final_layer_stats[name] = TensorStats(
426
+ mean=weighted_mean,
427
+ max_abs=max_abs,
428
+ std=pooled_std,
429
+ norm=pooled_norm,
430
+ numel=total_numel
431
+ )
432
+
433
+ # Compute global stats across all layers
434
+ if final_layer_stats:
435
+ all_numel = sum(s.numel for s in final_layer_stats.values())
436
+ global_mean = sum(s.mean * s.numel for s in final_layer_stats.values()) / all_numel
437
+ global_max_abs = max(s.max_abs for s in final_layer_stats.values())
438
+ # Same pooled-std correction as above — same bug was present here.
439
+ global_ex2 = sum(
440
+ s.numel * (s.std ** 2 + s.mean ** 2) for s in final_layer_stats.values()
441
+ ) / all_numel
442
+ global_std = math.sqrt(max(0.0, global_ex2 - global_mean ** 2))
443
+ global_norm = (sum(s.norm ** 2 for s in final_layer_stats.values())) ** 0.5
444
+
445
+ global_stats = TensorStats(
446
+ mean=global_mean,
447
+ max_abs=global_max_abs,
448
+ std=global_std,
449
+ norm=global_norm,
450
+ numel=all_numel
451
+ )
452
+ else:
453
+ global_stats = TensorStats(0.0, 0.0, 0.0, 0.0, 0)
454
+
455
+ result = ModelResult(
456
+ model_name=model_name,
457
+ loss=avg_loss,
458
+ perplexity=perplexity,
459
+ global_act=global_stats,
460
+ layer_acts=final_layer_stats,
461
+ num_tokens=total_tokens,
462
+ num_layers=config.num_hidden_layers,
463
+ hidden_size=config.hidden_size,
464
+ num_params=num_params
465
+ )
466
+
467
+ # --- WandB Logging ---
468
+ self._log_to_wandb(result)
469
+ wandb.finish()
470
+
471
+ return result
472
+
473
+ def _log_to_wandb(self, result: ModelResult):
474
+ """Log final metrics to WandB. No frac_near_dtype_limit."""
475
+
476
+ # Global metrics
477
+ wandb.log({
478
+ "final/loss": result.loss,
479
+ "final/perplexity": result.perplexity,
480
+ "final/num_tokens": result.num_tokens,
481
+
482
+ "train/global/act/mean": result.global_act.mean,
483
+ "train/global/act/max_abs": result.global_act.max_abs,
484
+ "train/global/act/std": result.global_act.std,
485
+ "train/global/act/norm": result.global_act.norm,
486
+ # Intentionally NOT logging frac_near_dtype_limit or frac_near_user_limit
487
+ })
488
+
489
+ # Per-tensor (per-layer) metrics
490
+ # Organize by layer for cleaner WandB UI
491
+ for tensor_name, stats in result.layer_acts.items():
492
+ # Clean name for wandb: replace dots with slashes
493
+ clean_name = tensor_name.replace(".", "/")
494
+
495
+ wandb.log({
496
+ f"train/{clean_name}/act/mean": stats.mean,
497
+ f"train/{clean_name}/act/max_abs": stats.max_abs,
498
+ f"train/{clean_name}/act/std": stats.std,
499
+ f"train/{clean_name}/act/norm": stats.norm,
500
+ # No frac_near_dtype_limit
501
+ })
502
+
503
+ # Also log as a wandb.Table for easy comparison
504
+ table_data = []
505
+ for tensor_name, stats in sorted(result.layer_acts.items()):
506
+ table_data.append([
507
+ tensor_name,
508
+ stats.mean,
509
+ stats.max_abs,
510
+ stats.std,
511
+ stats.norm,
512
+ stats.numel
513
+ ])
514
+
515
+ if table_data:
516
+ table = wandb.Table(
517
+ columns=["tensor_name", "mean", "max_abs", "std", "norm", "numel"],
518
+ data=table_data
519
+ )
520
+ wandb.log({"activation_table": table})
521
+
522
+ def print_report(self, results: List[ModelResult]):
523
+ """Pretty-print comparison report."""
524
+ print("\n" + "=" * 110)
525
+ print(f"{'Model':<35} {'Loss':>10} {'PPL':>10} {'ActMean':>12} {'ActMaxAbs':>12} {'ActStd':>12} {'Tokens':>8}")
526
+ print("-" * 110)
527
+
528
+ for r in results:
529
+ name = r.model_name.split("/")[-1][:33]
530
+ print(
531
+ f"{name:<35} "
532
+ f"{r.loss:>10.4f} "
533
+ f"{r.perplexity:>10.2f} "
534
+ f"{r.global_act.mean:>12.6f} "
535
+ f"{r.global_act.max_abs:>12.6f} "
536
+ f"{r.global_act.std:>12.6f} "
537
+ f"{r.num_tokens:>8}"
538
+ )
539
+
540
+ print("=" * 110)
541
+
542
+ # Print top 5 layers by max_abs for each model
543
+ print("\n[Per-Tensor Max Abs Top 5]")
544
+ for r in results:
545
+ name = r.model_name.split("/")[-1]
546
+ sorted_layers = sorted(r.layer_acts.items(), key=lambda x: x[1].max_abs, reverse=True)[:5]
547
+ print(f"\n {name}:")
548
+ for tensor_name, stats in sorted_layers:
549
+ print(f" {tensor_name:<50} max_abs={stats.max_abs:>10.4f} mean={stats.mean:>10.6f} std={stats.std:>10.4f}")
550
+
551
+ def export_json(self, results: List[ModelResult], path: str):
552
+ """Export results to JSON."""
553
+ data = []
554
+ for r in results:
555
+ entry = {
556
+ "model": r.model_name,
557
+ "loss": r.loss,
558
+ "perplexity": r.perplexity,
559
+ "num_tokens": r.num_tokens,
560
+ "num_layers": r.num_layers,
561
+ "hidden_size": r.hidden_size,
562
+ "num_params": r.num_params,
563
+ "global_act": asdict(r.global_act),
564
+ "layer_acts": {k: asdict(v) for k, v in r.layer_acts.items()}
565
+ }
566
+ data.append(entry)
567
+
568
+ with open(path, "w") as f:
569
+ json.dump(data, f, indent=2)
570
+ print(f"[Exported] Results saved to {path}")
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "linear",
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": 100,
22
+ "num_key_value_heads": 4,
23
+ "pad_token_id": 0,
24
+ "pretraining_tp": 1,
25
+ "rms_norm_eps": 1e-06,
26
+ "rope_parameters": {
27
+ "rope_theta": 10000.0,
28
+ "rope_type": "default"
29
+ },
30
+ "tie_word_embeddings": true,
31
+ "tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
32
+ "transformers_version": "5.16.0.dev0",
33
+ "use_cache": false,
34
+ "vocab_size": 4096,
35
+ "waleed_beta": 10.0
36
+ }
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6c438add066c9d8c8969b80887156bf37aca35cc91ecce1ee9f6a226df8ef10
3
+ size 33967272
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83e3d64d4dcb33aecee4604d39254e92bc4ef7b19392e7d38889f6129c1abb67
3
+ size 39573050
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cf9097d4513154245c48236b6ec5137b7ee2a21c9f58f2cba798ea275c6026f
3
+ size 14244
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36621a4ac2b8691c903e4eb5274dfa5ddcba796f686a593c9d0bb266866d9324
3
+ size 1064
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/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-linear-100L_trash_run/checkpoint-2600/trainer_state.json ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.17526120660599934,
6
+ "eval_steps": 2498,
7
+ "global_step": 2600,
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.0013481631277384564,
14
+ "grad_norm": 2.125,
15
+ "learning_rate": 2.66e-05,
16
+ "loss": 8.29943389892578,
17
+ "step": 20
18
+ },
19
+ {
20
+ "epoch": 0.002696326255476913,
21
+ "grad_norm": 1.3046875,
22
+ "learning_rate": 5.46e-05,
23
+ "loss": 8.036395263671874,
24
+ "step": 40
25
+ },
26
+ {
27
+ "epoch": 0.004044489383215369,
28
+ "grad_norm": 1.2734375,
29
+ "learning_rate": 8.259999999999999e-05,
30
+ "loss": 7.834572601318359,
31
+ "step": 60
32
+ },
33
+ {
34
+ "epoch": 0.005392652510953826,
35
+ "grad_norm": 1.265625,
36
+ "learning_rate": 0.0001106,
37
+ "loss": 7.5718994140625,
38
+ "step": 80
39
+ },
40
+ {
41
+ "epoch": 0.006740815638692282,
42
+ "grad_norm": 1.1953125,
43
+ "learning_rate": 0.0001386,
44
+ "loss": 7.237230682373047,
45
+ "step": 100
46
+ },
47
+ {
48
+ "epoch": 0.008088978766430738,
49
+ "grad_norm": 1.1484375,
50
+ "learning_rate": 0.00016659999999999998,
51
+ "loss": 6.864912414550782,
52
+ "step": 120
53
+ },
54
+ {
55
+ "epoch": 0.009437141894169195,
56
+ "grad_norm": 1.0234375,
57
+ "learning_rate": 0.00019460000000000001,
58
+ "loss": 6.509800720214844,
59
+ "step": 140
60
+ },
61
+ {
62
+ "epoch": 0.010785305021907651,
63
+ "grad_norm": 1.0234375,
64
+ "learning_rate": 0.0002226,
65
+ "loss": 6.20410041809082,
66
+ "step": 160
67
+ },
68
+ {
69
+ "epoch": 0.012133468149646108,
70
+ "grad_norm": 0.875,
71
+ "learning_rate": 0.00025059999999999997,
72
+ "loss": 5.940516662597656,
73
+ "step": 180
74
+ },
75
+ {
76
+ "epoch": 0.013481631277384564,
77
+ "grad_norm": 0.8203125,
78
+ "learning_rate": 0.0002786,
79
+ "loss": 5.676180267333985,
80
+ "step": 200
81
+ },
82
+ {
83
+ "epoch": 0.01482979440512302,
84
+ "grad_norm": 0.8828125,
85
+ "learning_rate": 0.00030659999999999997,
86
+ "loss": 5.412886428833008,
87
+ "step": 220
88
+ },
89
+ {
90
+ "epoch": 0.016177957532861477,
91
+ "grad_norm": 0.81640625,
92
+ "learning_rate": 0.0003346,
93
+ "loss": 5.135355377197266,
94
+ "step": 240
95
+ },
96
+ {
97
+ "epoch": 0.01752612066059993,
98
+ "grad_norm": 1.1796875,
99
+ "learning_rate": 0.00036260000000000003,
100
+ "loss": 4.882264709472656,
101
+ "step": 260
102
+ },
103
+ {
104
+ "epoch": 0.01887428378833839,
105
+ "grad_norm": 0.94921875,
106
+ "learning_rate": 0.0003906,
107
+ "loss": 4.6449634552001955,
108
+ "step": 280
109
+ },
110
+ {
111
+ "epoch": 0.020222446916076844,
112
+ "grad_norm": 1.046875,
113
+ "learning_rate": 0.0004186,
114
+ "loss": 4.446089553833008,
115
+ "step": 300
116
+ },
117
+ {
118
+ "epoch": 0.021570610043815303,
119
+ "grad_norm": 0.87890625,
120
+ "learning_rate": 0.0004466,
121
+ "loss": 4.2602802276611325,
122
+ "step": 320
123
+ },
124
+ {
125
+ "epoch": 0.022918773171553757,
126
+ "grad_norm": 0.625,
127
+ "learning_rate": 0.00047460000000000004,
128
+ "loss": 4.108924484252929,
129
+ "step": 340
130
+ },
131
+ {
132
+ "epoch": 0.024266936299292215,
133
+ "grad_norm": 0.82421875,
134
+ "learning_rate": 0.0005026,
135
+ "loss": 3.984059143066406,
136
+ "step": 360
137
+ },
138
+ {
139
+ "epoch": 0.02561509942703067,
140
+ "grad_norm": 0.78515625,
141
+ "learning_rate": 0.0005306,
142
+ "loss": 3.864672088623047,
143
+ "step": 380
144
+ },
145
+ {
146
+ "epoch": 0.026963262554769128,
147
+ "grad_norm": 0.6796875,
148
+ "learning_rate": 0.0005586,
149
+ "loss": 3.741139602661133,
150
+ "step": 400
151
+ },
152
+ {
153
+ "epoch": 0.028311425682507583,
154
+ "grad_norm": 0.63671875,
155
+ "learning_rate": 0.0005866,
156
+ "loss": 3.6620559692382812,
157
+ "step": 420
158
+ },
159
+ {
160
+ "epoch": 0.02965958881024604,
161
+ "grad_norm": 0.578125,
162
+ "learning_rate": 0.0006146,
163
+ "loss": 3.604226303100586,
164
+ "step": 440
165
+ },
166
+ {
167
+ "epoch": 0.031007751937984496,
168
+ "grad_norm": 0.484375,
169
+ "learning_rate": 0.0006426,
170
+ "loss": 3.5065567016601564,
171
+ "step": 460
172
+ },
173
+ {
174
+ "epoch": 0.032355915065722954,
175
+ "grad_norm": 0.60546875,
176
+ "learning_rate": 0.0006705999999999999,
177
+ "loss": 3.437101364135742,
178
+ "step": 480
179
+ },
180
+ {
181
+ "epoch": 0.03370407819346141,
182
+ "grad_norm": 0.57421875,
183
+ "learning_rate": 0.0006986,
184
+ "loss": 3.3709640502929688,
185
+ "step": 500
186
+ },
187
+ {
188
+ "epoch": 0.03505224132119986,
189
+ "grad_norm": 0.484375,
190
+ "learning_rate": 0.0007,
191
+ "loss": 3.3115055084228517,
192
+ "step": 520
193
+ },
194
+ {
195
+ "epoch": 0.03640040444893832,
196
+ "grad_norm": 0.578125,
197
+ "learning_rate": 0.0007,
198
+ "loss": 3.240653228759766,
199
+ "step": 540
200
+ },
201
+ {
202
+ "epoch": 0.03774856757667678,
203
+ "grad_norm": 0.48828125,
204
+ "learning_rate": 0.0007,
205
+ "loss": 3.1956838607788085,
206
+ "step": 560
207
+ },
208
+ {
209
+ "epoch": 0.03909673070441524,
210
+ "grad_norm": 0.4765625,
211
+ "learning_rate": 0.0007,
212
+ "loss": 3.1403549194335936,
213
+ "step": 580
214
+ },
215
+ {
216
+ "epoch": 0.04044489383215369,
217
+ "grad_norm": 0.484375,
218
+ "learning_rate": 0.0007,
219
+ "loss": 3.109465980529785,
220
+ "step": 600
221
+ },
222
+ {
223
+ "epoch": 0.04179305695989215,
224
+ "grad_norm": 0.498046875,
225
+ "learning_rate": 0.0007,
226
+ "loss": 3.052653121948242,
227
+ "step": 620
228
+ },
229
+ {
230
+ "epoch": 0.043141220087630605,
231
+ "grad_norm": 0.48046875,
232
+ "learning_rate": 0.0007,
233
+ "loss": 3.0361297607421873,
234
+ "step": 640
235
+ },
236
+ {
237
+ "epoch": 0.044489383215369056,
238
+ "grad_norm": 0.4765625,
239
+ "learning_rate": 0.0007,
240
+ "loss": 2.984110450744629,
241
+ "step": 660
242
+ },
243
+ {
244
+ "epoch": 0.045837546343107514,
245
+ "grad_norm": 0.51171875,
246
+ "learning_rate": 0.0007,
247
+ "loss": 2.961138153076172,
248
+ "step": 680
249
+ },
250
+ {
251
+ "epoch": 0.04718570947084597,
252
+ "grad_norm": 0.462890625,
253
+ "learning_rate": 0.0007,
254
+ "loss": 2.922393226623535,
255
+ "step": 700
256
+ },
257
+ {
258
+ "epoch": 0.04853387259858443,
259
+ "grad_norm": 0.416015625,
260
+ "learning_rate": 0.0007,
261
+ "loss": 2.892241287231445,
262
+ "step": 720
263
+ },
264
+ {
265
+ "epoch": 0.04988203572632288,
266
+ "grad_norm": 0.48828125,
267
+ "learning_rate": 0.0007,
268
+ "loss": 2.858970069885254,
269
+ "step": 740
270
+ },
271
+ {
272
+ "epoch": 0.05123019885406134,
273
+ "grad_norm": 0.486328125,
274
+ "learning_rate": 0.0007,
275
+ "loss": 2.8428062438964843,
276
+ "step": 760
277
+ },
278
+ {
279
+ "epoch": 0.0525783619817998,
280
+ "grad_norm": 0.5234375,
281
+ "learning_rate": 0.0007,
282
+ "loss": 2.837088203430176,
283
+ "step": 780
284
+ },
285
+ {
286
+ "epoch": 0.053926525109538256,
287
+ "grad_norm": 0.470703125,
288
+ "learning_rate": 0.0007,
289
+ "loss": 2.7979549407958983,
290
+ "step": 800
291
+ },
292
+ {
293
+ "epoch": 0.05527468823727671,
294
+ "grad_norm": 0.46875,
295
+ "learning_rate": 0.0007,
296
+ "loss": 2.787800979614258,
297
+ "step": 820
298
+ },
299
+ {
300
+ "epoch": 0.056622851365015166,
301
+ "grad_norm": 0.4296875,
302
+ "learning_rate": 0.0007,
303
+ "loss": 2.7603782653808593,
304
+ "step": 840
305
+ },
306
+ {
307
+ "epoch": 0.057971014492753624,
308
+ "grad_norm": 0.44140625,
309
+ "learning_rate": 0.0007,
310
+ "loss": 2.7198511123657227,
311
+ "step": 860
312
+ },
313
+ {
314
+ "epoch": 0.05931917762049208,
315
+ "grad_norm": 0.439453125,
316
+ "learning_rate": 0.0007,
317
+ "loss": 2.6977243423461914,
318
+ "step": 880
319
+ },
320
+ {
321
+ "epoch": 0.06066734074823053,
322
+ "grad_norm": 0.46484375,
323
+ "learning_rate": 0.0007,
324
+ "loss": 2.6839799880981445,
325
+ "step": 900
326
+ },
327
+ {
328
+ "epoch": 0.06201550387596899,
329
+ "grad_norm": 0.5,
330
+ "learning_rate": 0.0007,
331
+ "loss": 2.661431312561035,
332
+ "step": 920
333
+ },
334
+ {
335
+ "epoch": 0.06336366700370745,
336
+ "grad_norm": 0.423828125,
337
+ "learning_rate": 0.0007,
338
+ "loss": 2.6492240905761717,
339
+ "step": 940
340
+ },
341
+ {
342
+ "epoch": 0.06471183013144591,
343
+ "grad_norm": 0.4765625,
344
+ "learning_rate": 0.0007,
345
+ "loss": 2.6231040954589844,
346
+ "step": 960
347
+ },
348
+ {
349
+ "epoch": 0.06605999325918437,
350
+ "grad_norm": 0.4609375,
351
+ "learning_rate": 0.0007,
352
+ "loss": 2.610037422180176,
353
+ "step": 980
354
+ },
355
+ {
356
+ "epoch": 0.06740815638692282,
357
+ "grad_norm": 0.455078125,
358
+ "learning_rate": 0.0007,
359
+ "loss": 2.6107507705688477,
360
+ "step": 1000
361
+ },
362
+ {
363
+ "epoch": 0.06875631951466127,
364
+ "grad_norm": 0.42578125,
365
+ "learning_rate": 0.0007,
366
+ "loss": 2.5831680297851562,
367
+ "step": 1020
368
+ },
369
+ {
370
+ "epoch": 0.07010448264239973,
371
+ "grad_norm": 0.453125,
372
+ "learning_rate": 0.0007,
373
+ "loss": 2.5671245574951174,
374
+ "step": 1040
375
+ },
376
+ {
377
+ "epoch": 0.07145264577013818,
378
+ "grad_norm": 0.4453125,
379
+ "learning_rate": 0.0007,
380
+ "loss": 2.5532295227050783,
381
+ "step": 1060
382
+ },
383
+ {
384
+ "epoch": 0.07280080889787664,
385
+ "grad_norm": 0.4453125,
386
+ "learning_rate": 0.0007,
387
+ "loss": 2.535228729248047,
388
+ "step": 1080
389
+ },
390
+ {
391
+ "epoch": 0.0741489720256151,
392
+ "grad_norm": 0.431640625,
393
+ "learning_rate": 0.0007,
394
+ "loss": 2.5336929321289063,
395
+ "step": 1100
396
+ },
397
+ {
398
+ "epoch": 0.07549713515335356,
399
+ "grad_norm": 0.43359375,
400
+ "learning_rate": 0.0007,
401
+ "loss": 2.4990976333618162,
402
+ "step": 1120
403
+ },
404
+ {
405
+ "epoch": 0.07684529828109202,
406
+ "grad_norm": 0.4296875,
407
+ "learning_rate": 0.0007,
408
+ "loss": 2.4878835678100586,
409
+ "step": 1140
410
+ },
411
+ {
412
+ "epoch": 0.07819346140883048,
413
+ "grad_norm": 0.4296875,
414
+ "learning_rate": 0.0007,
415
+ "loss": 2.4860113143920897,
416
+ "step": 1160
417
+ },
418
+ {
419
+ "epoch": 0.07954162453656892,
420
+ "grad_norm": 0.4296875,
421
+ "learning_rate": 0.0007,
422
+ "loss": 2.4814546585083006,
423
+ "step": 1180
424
+ },
425
+ {
426
+ "epoch": 0.08088978766430738,
427
+ "grad_norm": 0.474609375,
428
+ "learning_rate": 0.0007,
429
+ "loss": 2.4764120101928713,
430
+ "step": 1200
431
+ },
432
+ {
433
+ "epoch": 0.08223795079204584,
434
+ "grad_norm": 0.43359375,
435
+ "learning_rate": 0.0007,
436
+ "loss": 2.4622081756591796,
437
+ "step": 1220
438
+ },
439
+ {
440
+ "epoch": 0.0835861139197843,
441
+ "grad_norm": 0.3984375,
442
+ "learning_rate": 0.0007,
443
+ "loss": 2.450253486633301,
444
+ "step": 1240
445
+ },
446
+ {
447
+ "epoch": 0.08493427704752275,
448
+ "grad_norm": 0.427734375,
449
+ "learning_rate": 0.0007,
450
+ "loss": 2.4399486541748048,
451
+ "step": 1260
452
+ },
453
+ {
454
+ "epoch": 0.08628244017526121,
455
+ "grad_norm": 0.45703125,
456
+ "learning_rate": 0.0007,
457
+ "loss": 2.4211536407470704,
458
+ "step": 1280
459
+ },
460
+ {
461
+ "epoch": 0.08763060330299967,
462
+ "grad_norm": 0.44921875,
463
+ "learning_rate": 0.0007,
464
+ "loss": 2.413456916809082,
465
+ "step": 1300
466
+ },
467
+ {
468
+ "epoch": 0.08897876643073811,
469
+ "grad_norm": 0.408203125,
470
+ "learning_rate": 0.0007,
471
+ "loss": 2.405606269836426,
472
+ "step": 1320
473
+ },
474
+ {
475
+ "epoch": 0.09032692955847657,
476
+ "grad_norm": 0.474609375,
477
+ "learning_rate": 0.0007,
478
+ "loss": 2.3934694290161134,
479
+ "step": 1340
480
+ },
481
+ {
482
+ "epoch": 0.09167509268621503,
483
+ "grad_norm": 0.443359375,
484
+ "learning_rate": 0.0007,
485
+ "loss": 2.393663024902344,
486
+ "step": 1360
487
+ },
488
+ {
489
+ "epoch": 0.09302325581395349,
490
+ "grad_norm": 0.404296875,
491
+ "learning_rate": 0.0007,
492
+ "loss": 2.3733840942382813,
493
+ "step": 1380
494
+ },
495
+ {
496
+ "epoch": 0.09437141894169195,
497
+ "grad_norm": 0.419921875,
498
+ "learning_rate": 0.0007,
499
+ "loss": 2.3658527374267577,
500
+ "step": 1400
501
+ },
502
+ {
503
+ "epoch": 0.0957195820694304,
504
+ "grad_norm": 0.451171875,
505
+ "learning_rate": 0.0007,
506
+ "loss": 2.3782094955444335,
507
+ "step": 1420
508
+ },
509
+ {
510
+ "epoch": 0.09706774519716886,
511
+ "grad_norm": 0.40234375,
512
+ "learning_rate": 0.0007,
513
+ "loss": 2.357101249694824,
514
+ "step": 1440
515
+ },
516
+ {
517
+ "epoch": 0.09841590832490732,
518
+ "grad_norm": 0.44140625,
519
+ "learning_rate": 0.0007,
520
+ "loss": 2.3440685272216797,
521
+ "step": 1460
522
+ },
523
+ {
524
+ "epoch": 0.09976407145264576,
525
+ "grad_norm": 0.40625,
526
+ "learning_rate": 0.0007,
527
+ "loss": 2.33266544342041,
528
+ "step": 1480
529
+ },
530
+ {
531
+ "epoch": 0.10111223458038422,
532
+ "grad_norm": 0.43359375,
533
+ "learning_rate": 0.0007,
534
+ "loss": 2.318921661376953,
535
+ "step": 1500
536
+ },
537
+ {
538
+ "epoch": 0.10246039770812268,
539
+ "grad_norm": 0.43359375,
540
+ "learning_rate": 0.0007,
541
+ "loss": 2.3219444274902346,
542
+ "step": 1520
543
+ },
544
+ {
545
+ "epoch": 0.10380856083586114,
546
+ "grad_norm": 0.4140625,
547
+ "learning_rate": 0.0007,
548
+ "loss": 2.312142181396484,
549
+ "step": 1540
550
+ },
551
+ {
552
+ "epoch": 0.1051567239635996,
553
+ "grad_norm": 0.400390625,
554
+ "learning_rate": 0.0007,
555
+ "loss": 2.300857162475586,
556
+ "step": 1560
557
+ },
558
+ {
559
+ "epoch": 0.10650488709133805,
560
+ "grad_norm": 0.41015625,
561
+ "learning_rate": 0.0007,
562
+ "loss": 2.3189367294311523,
563
+ "step": 1580
564
+ },
565
+ {
566
+ "epoch": 0.10785305021907651,
567
+ "grad_norm": 0.42578125,
568
+ "learning_rate": 0.0007,
569
+ "loss": 2.2867937088012695,
570
+ "step": 1600
571
+ },
572
+ {
573
+ "epoch": 0.10920121334681497,
574
+ "grad_norm": 0.392578125,
575
+ "learning_rate": 0.0007,
576
+ "loss": 2.286478614807129,
577
+ "step": 1620
578
+ },
579
+ {
580
+ "epoch": 0.11054937647455342,
581
+ "grad_norm": 0.4140625,
582
+ "learning_rate": 0.0007,
583
+ "loss": 2.299053192138672,
584
+ "step": 1640
585
+ },
586
+ {
587
+ "epoch": 0.11189753960229187,
588
+ "grad_norm": 0.404296875,
589
+ "learning_rate": 0.0007,
590
+ "loss": 2.2822343826293947,
591
+ "step": 1660
592
+ },
593
+ {
594
+ "epoch": 0.11324570273003033,
595
+ "grad_norm": 0.4140625,
596
+ "learning_rate": 0.0007,
597
+ "loss": 2.264908218383789,
598
+ "step": 1680
599
+ },
600
+ {
601
+ "epoch": 0.11459386585776879,
602
+ "grad_norm": 0.416015625,
603
+ "learning_rate": 0.0007,
604
+ "loss": 2.277639389038086,
605
+ "step": 1700
606
+ },
607
+ {
608
+ "epoch": 0.11594202898550725,
609
+ "grad_norm": 0.46484375,
610
+ "learning_rate": 0.0007,
611
+ "loss": 2.2545700073242188,
612
+ "step": 1720
613
+ },
614
+ {
615
+ "epoch": 0.1172901921132457,
616
+ "grad_norm": 0.40625,
617
+ "learning_rate": 0.0007,
618
+ "loss": 2.2448637008666994,
619
+ "step": 1740
620
+ },
621
+ {
622
+ "epoch": 0.11863835524098416,
623
+ "grad_norm": 0.4296875,
624
+ "learning_rate": 0.0007,
625
+ "loss": 2.250792694091797,
626
+ "step": 1760
627
+ },
628
+ {
629
+ "epoch": 0.11998651836872262,
630
+ "grad_norm": 0.41796875,
631
+ "learning_rate": 0.0007,
632
+ "loss": 2.264188766479492,
633
+ "step": 1780
634
+ },
635
+ {
636
+ "epoch": 0.12133468149646107,
637
+ "grad_norm": 0.4140625,
638
+ "learning_rate": 0.0007,
639
+ "loss": 2.2614953994750975,
640
+ "step": 1800
641
+ },
642
+ {
643
+ "epoch": 0.12268284462419952,
644
+ "grad_norm": 0.408203125,
645
+ "learning_rate": 0.0007,
646
+ "loss": 2.252177619934082,
647
+ "step": 1820
648
+ },
649
+ {
650
+ "epoch": 0.12403100775193798,
651
+ "grad_norm": 0.390625,
652
+ "learning_rate": 0.0007,
653
+ "loss": 2.219951057434082,
654
+ "step": 1840
655
+ },
656
+ {
657
+ "epoch": 0.12537917087967643,
658
+ "grad_norm": 0.400390625,
659
+ "learning_rate": 0.0007,
660
+ "loss": 2.219348907470703,
661
+ "step": 1860
662
+ },
663
+ {
664
+ "epoch": 0.1267273340074149,
665
+ "grad_norm": 0.4140625,
666
+ "learning_rate": 0.0007,
667
+ "loss": 2.2108036041259767,
668
+ "step": 1880
669
+ },
670
+ {
671
+ "epoch": 0.12807549713515334,
672
+ "grad_norm": 0.388671875,
673
+ "learning_rate": 0.0007,
674
+ "loss": 2.219270706176758,
675
+ "step": 1900
676
+ },
677
+ {
678
+ "epoch": 0.12942366026289182,
679
+ "grad_norm": 0.392578125,
680
+ "learning_rate": 0.0007,
681
+ "loss": 2.1969385147094727,
682
+ "step": 1920
683
+ },
684
+ {
685
+ "epoch": 0.13077182339063026,
686
+ "grad_norm": 0.42578125,
687
+ "learning_rate": 0.0007,
688
+ "loss": 2.207957077026367,
689
+ "step": 1940
690
+ },
691
+ {
692
+ "epoch": 0.13211998651836873,
693
+ "grad_norm": 0.416015625,
694
+ "learning_rate": 0.0007,
695
+ "loss": 2.1822214126586914,
696
+ "step": 1960
697
+ },
698
+ {
699
+ "epoch": 0.13346814964610718,
700
+ "grad_norm": 0.427734375,
701
+ "learning_rate": 0.0007,
702
+ "loss": 2.20617618560791,
703
+ "step": 1980
704
+ },
705
+ {
706
+ "epoch": 0.13481631277384565,
707
+ "grad_norm": 0.384765625,
708
+ "learning_rate": 0.0007,
709
+ "loss": 2.179953193664551,
710
+ "step": 2000
711
+ },
712
+ {
713
+ "epoch": 0.1361644759015841,
714
+ "grad_norm": 0.40234375,
715
+ "learning_rate": 0.0007,
716
+ "loss": 2.190639877319336,
717
+ "step": 2020
718
+ },
719
+ {
720
+ "epoch": 0.13751263902932254,
721
+ "grad_norm": 0.443359375,
722
+ "learning_rate": 0.0007,
723
+ "loss": 2.1713678359985353,
724
+ "step": 2040
725
+ },
726
+ {
727
+ "epoch": 0.138860802157061,
728
+ "grad_norm": 0.396484375,
729
+ "learning_rate": 0.0007,
730
+ "loss": 2.189349365234375,
731
+ "step": 2060
732
+ },
733
+ {
734
+ "epoch": 0.14020896528479945,
735
+ "grad_norm": 0.388671875,
736
+ "learning_rate": 0.0007,
737
+ "loss": 2.1666955947875977,
738
+ "step": 2080
739
+ },
740
+ {
741
+ "epoch": 0.14155712841253792,
742
+ "grad_norm": 0.376953125,
743
+ "learning_rate": 0.0007,
744
+ "loss": 2.1569326400756834,
745
+ "step": 2100
746
+ },
747
+ {
748
+ "epoch": 0.14290529154027637,
749
+ "grad_norm": 0.3828125,
750
+ "learning_rate": 0.0007,
751
+ "loss": 2.166208839416504,
752
+ "step": 2120
753
+ },
754
+ {
755
+ "epoch": 0.14425345466801484,
756
+ "grad_norm": 0.40234375,
757
+ "learning_rate": 0.0007,
758
+ "loss": 2.166676712036133,
759
+ "step": 2140
760
+ },
761
+ {
762
+ "epoch": 0.14560161779575329,
763
+ "grad_norm": 0.388671875,
764
+ "learning_rate": 0.0007,
765
+ "loss": 2.152173614501953,
766
+ "step": 2160
767
+ },
768
+ {
769
+ "epoch": 0.14694978092349173,
770
+ "grad_norm": 0.39453125,
771
+ "learning_rate": 0.0007,
772
+ "loss": 2.162281608581543,
773
+ "step": 2180
774
+ },
775
+ {
776
+ "epoch": 0.1482979440512302,
777
+ "grad_norm": 0.384765625,
778
+ "learning_rate": 0.0007,
779
+ "loss": 2.1356754302978516,
780
+ "step": 2200
781
+ },
782
+ {
783
+ "epoch": 0.14964610717896865,
784
+ "grad_norm": 0.40625,
785
+ "learning_rate": 0.0007,
786
+ "loss": 2.1436878204345704,
787
+ "step": 2220
788
+ },
789
+ {
790
+ "epoch": 0.15099427030670712,
791
+ "grad_norm": 0.419921875,
792
+ "learning_rate": 0.0007,
793
+ "loss": 2.1559894561767576,
794
+ "step": 2240
795
+ },
796
+ {
797
+ "epoch": 0.15234243343444556,
798
+ "grad_norm": 0.404296875,
799
+ "learning_rate": 0.0007,
800
+ "loss": 2.1330844879150392,
801
+ "step": 2260
802
+ },
803
+ {
804
+ "epoch": 0.15369059656218403,
805
+ "grad_norm": 0.37890625,
806
+ "learning_rate": 0.0007,
807
+ "loss": 2.1436931610107424,
808
+ "step": 2280
809
+ },
810
+ {
811
+ "epoch": 0.15503875968992248,
812
+ "grad_norm": 0.39453125,
813
+ "learning_rate": 0.0007,
814
+ "loss": 2.12701358795166,
815
+ "step": 2300
816
+ },
817
+ {
818
+ "epoch": 0.15638692281766095,
819
+ "grad_norm": 0.412109375,
820
+ "learning_rate": 0.0007,
821
+ "loss": 2.135152053833008,
822
+ "step": 2320
823
+ },
824
+ {
825
+ "epoch": 0.1577350859453994,
826
+ "grad_norm": 0.37109375,
827
+ "learning_rate": 0.0007,
828
+ "loss": 2.1244712829589845,
829
+ "step": 2340
830
+ },
831
+ {
832
+ "epoch": 0.15908324907313784,
833
+ "grad_norm": 0.38671875,
834
+ "learning_rate": 0.0007,
835
+ "loss": 2.127437973022461,
836
+ "step": 2360
837
+ },
838
+ {
839
+ "epoch": 0.1604314122008763,
840
+ "grad_norm": 0.388671875,
841
+ "learning_rate": 0.0007,
842
+ "loss": 2.1295385360717773,
843
+ "step": 2380
844
+ },
845
+ {
846
+ "epoch": 0.16177957532861476,
847
+ "grad_norm": 0.40625,
848
+ "learning_rate": 0.0007,
849
+ "loss": 2.1162397384643556,
850
+ "step": 2400
851
+ },
852
+ {
853
+ "epoch": 0.16312773845635323,
854
+ "grad_norm": 0.40234375,
855
+ "learning_rate": 0.0007,
856
+ "loss": 2.118353843688965,
857
+ "step": 2420
858
+ },
859
+ {
860
+ "epoch": 0.16447590158409167,
861
+ "grad_norm": 0.380859375,
862
+ "learning_rate": 0.0007,
863
+ "loss": 2.104597473144531,
864
+ "step": 2440
865
+ },
866
+ {
867
+ "epoch": 0.16582406471183014,
868
+ "grad_norm": 0.3828125,
869
+ "learning_rate": 0.0007,
870
+ "loss": 2.1171491622924803,
871
+ "step": 2460
872
+ },
873
+ {
874
+ "epoch": 0.1671722278395686,
875
+ "grad_norm": 0.392578125,
876
+ "learning_rate": 0.0007,
877
+ "loss": 2.1171087265014648,
878
+ "step": 2480
879
+ },
880
+ {
881
+ "epoch": 0.1683855746545332,
882
+ "eval_loss": 2.1098570823669434,
883
+ "eval_runtime": 15.3278,
884
+ "eval_samples_per_second": 621.551,
885
+ "eval_steps_per_second": 0.652,
886
+ "step": 2498
887
+ },
888
+ {
889
+ "epoch": 0.16852039096730703,
890
+ "grad_norm": 0.37890625,
891
+ "learning_rate": 0.0007,
892
+ "loss": 2.100436973571777,
893
+ "step": 2500
894
+ },
895
+ {
896
+ "epoch": 0.16852039096730703,
897
+ "eval_loss": 2.1097066402435303,
898
+ "eval_runtime": 15.3325,
899
+ "eval_samples_per_second": 621.361,
900
+ "eval_steps_per_second": 0.652,
901
+ "step": 2500
902
+ },
903
+ {
904
+ "epoch": 0.1698685540950455,
905
+ "grad_norm": 26607616.0,
906
+ "learning_rate": 3.4200000000000005e-05,
907
+ "loss": 2.1015687942504884,
908
+ "step": 2520
909
+ },
910
+ {
911
+ "epoch": 0.17121671722278395,
912
+ "grad_norm": 31064064.0,
913
+ "learning_rate": 7.020000000000001e-05,
914
+ "loss": 2.1284088134765624,
915
+ "step": 2540
916
+ },
917
+ {
918
+ "epoch": 0.17256488035052242,
919
+ "grad_norm": 222298112.0,
920
+ "learning_rate": 9e-05,
921
+ "loss": 4.244554901123047,
922
+ "step": 2560
923
+ },
924
+ {
925
+ "epoch": 0.17391304347826086,
926
+ "grad_norm": 488636416.0,
927
+ "learning_rate": 9e-05,
928
+ "loss": 7.165976715087891,
929
+ "step": 2580
930
+ },
931
+ {
932
+ "epoch": 0.17526120660599934,
933
+ "grad_norm": 884998144.0,
934
+ "learning_rate": 9e-05,
935
+ "loss": 7.48333740234375,
936
+ "step": 2600
937
+ }
938
+ ],
939
+ "logging_steps": 20,
940
+ "max_steps": 2700,
941
+ "num_input_tokens_seen": 0,
942
+ "num_train_epochs": 1,
943
+ "save_steps": 100,
944
+ "stateful_callbacks": {
945
+ "TrainerControl": {
946
+ "args": {
947
+ "should_epoch_stop": false,
948
+ "should_evaluate": false,
949
+ "should_log": false,
950
+ "should_save": true,
951
+ "should_training_stop": false
952
+ },
953
+ "attributes": {}
954
+ }
955
+ },
956
+ "total_flos": 8388337886822400.0,
957
+ "train_batch_size": 64,
958
+ "trial_name": null,
959
+ "trial_params": null
960
+ }
zain/Activation/out/glu-linear-100L_trash_run/checkpoint-2600/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71b2bd66d75f777a50700c6de34217c94bd1c27ce34e9a08466c71dd7e2dc626
3
+ size 4920
zain/Activation/out/glu-linear-100L_trash_run/training_log.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
zain/Activation/sweep.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sweep explicit GLU / MLP variants with identical data and hyperparameters."""
3
+
4
+ import argparse
5
+ import copy
6
+ import json
7
+ import re
8
+ import time
9
+ import os
10
+ from pathlib import Path
11
+
12
+ import yaml
13
+ import wandb
14
+ import torch
15
+ from transformers import AutoTokenizer, set_seed
16
+ from exp import (
17
+ TinyLlamaConfig,
18
+ TinyLlamaForCausalLM,
19
+ build_dataset,
20
+ create_trainer,
21
+ fetch_latest_checkpoint_from_hub,
22
+ ResumeFreezeOverrideCallback,
23
+ )
24
+
25
+
26
+ def format_param_count(total_params: int) -> str:
27
+ if total_params >= 1e9:
28
+ return f"{total_params / 1e9:.1f}B"
29
+ else:
30
+ return f"{total_params / 1e6:.1f}M"
31
+
32
+
33
+ def parse_variant(variant: str):
34
+ parts = variant.split('-')
35
+ if len(parts) < 2:
36
+ raise ValueError(f"Invalid variant format: '{variant}'. Expected: <glu|mlp>-<activation>[-<layers>L]")
37
+ prefix = parts[0]
38
+ if prefix not in ('glu', 'mlp'):
39
+ raise ValueError(f"Invalid prefix: '{prefix}'. Must be 'glu' or 'mlp'.")
40
+ last = parts[-1]
41
+ if last.endswith('L') and last[:-1].isdigit():
42
+ layers = int(last[:-1])
43
+ activation = '-'.join(parts[1:-1])
44
+ else:
45
+ layers = None
46
+ activation = '-'.join(parts[1:])
47
+ if not activation:
48
+ raise ValueError(f"Missing activation name in variant: '{variant}'")
49
+ return prefix, activation, layers
50
+
51
+
52
+ def main():
53
+ parser = argparse.ArgumentParser()
54
+ parser.add_argument("--config", required=True, help="Base YAML config")
55
+ parser.add_argument("--variants", nargs="+", required=True, help="List of variants")
56
+ parser.add_argument("--push", action="store_true")
57
+ args = parser.parse_args()
58
+
59
+ with open(args.config) as f:
60
+ base = yaml.safe_load(f)
61
+
62
+ seed = base.get("training", {}).get("seed", 42)
63
+ set_seed(seed)
64
+
65
+ wandb_project = base.get("training", {}).get("wandb_project")
66
+ if wandb_project:
67
+ os.environ["WANDB_PROJECT"] = wandb_project
68
+ print(f"[WandB] Project locked to: {wandb_project}")
69
+
70
+ tok_name = base["model"].get("tokenizer_name", "meta-llama/Llama-2-7b-hf")
71
+ tokenizer = AutoTokenizer.from_pretrained(tok_name)
72
+ if tokenizer.pad_token is None:
73
+ tokenizer.pad_token = tokenizer.eos_token
74
+
75
+ msl = base["model"].get("max_position_embeddings", 512)
76
+ train_ds = build_dataset(tokenizer, max_seq_len=msl, split="train", max_samples=None)
77
+ eval_ds = build_dataset(tokenizer, max_seq_len=msl, split="validation", max_samples=None)
78
+
79
+ results = []
80
+
81
+ for variant in args.variants:
82
+ prefix, act, layers = parse_variant(variant)
83
+
84
+ if prefix == "mlp" and act in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
85
+ raise ValueError(
86
+ f"Activation '{act}' requires GLU. Please use 'glu-{act}'."
87
+ )
88
+
89
+ cfg = copy.deepcopy(base)
90
+ cfg["model"]["mlp_type"] = prefix
91
+ cfg["model"]["activation"] = act
92
+ if layers is not None:
93
+ cfg["model"]["num_hidden_layers"] = layers
94
+
95
+ actual_layers = cfg["model"]["num_hidden_layers"]
96
+ variant_label = f"{prefix}-{act}-{actual_layers}L"
97
+
98
+ # Output directory: add _trash if override enabled
99
+ go = cfg.get("gradient_override", {})
100
+ if go.get("enabled", False):
101
+ base_out = Path(cfg["training"]["output_dir"]).parent
102
+ variant_name = variant_label + "_trash_run"
103
+ else:
104
+ base_out = Path(cfg["training"]["output_dir"]).parent
105
+ variant_name = variant_label + "_run"
106
+
107
+ out_dir = base_out / variant_name
108
+ cfg["training"]["output_dir"] = str(out_dir)
109
+
110
+ # Checkpoint fetching
111
+ checkpoint_path = None
112
+ resume_cfg = cfg.get("training", {})
113
+ if resume_cfg.get("resume_from_hub", False):
114
+ hub_cfg = cfg.get("hub", {})
115
+ repo_id = hub_cfg.get("repo_id")
116
+ subpath = hub_cfg.get("subpath", "")
117
+ if not repo_id:
118
+ raise ValueError("hub.repo_id must be set when resume_from_hub is true")
119
+ checkpoint_step = resume_cfg.get("checkpoint_step")
120
+ print(f"[Resume] Fetching {variant_label} from HF Hub: {repo_id}/{subpath}/{variant_label}_run")
121
+ checkpoint_path = fetch_latest_checkpoint_from_hub(
122
+ repo_id=repo_id,
123
+ subpath=subpath,
124
+ variant=variant_label,
125
+ checkpoint_step=checkpoint_step,
126
+ )
127
+ print(f"[Resume] Downloaded to: {checkpoint_path}")
128
+ elif resume_cfg.get("resume_from"):
129
+ print("[Warning] resume_from set to a specific path; all variants will try to use the same checkpoint.")
130
+ checkpoint_path = resume_cfg.get("resume_from")
131
+
132
+ set_seed(seed)
133
+
134
+ print(f"\n{'='*60}\n>>> Variant: {variant_label} | Out: {out_dir}\n{'='*60}")
135
+
136
+ config = TinyLlamaConfig(**cfg["model"])
137
+ model = TinyLlamaForCausalLM(config)
138
+ model = model.to(torch.bfloat16)
139
+
140
+ total_params = sum(p.numel() for p in model.parameters())
141
+ param_str = format_param_count(total_params)
142
+ timestamp = time.strftime("%Y%m%d-%H%M%S")
143
+ run_name = f"LM-{variant_label}-{param_str}-{timestamp}"
144
+ cfg["training"]["run_name"] = run_name
145
+
146
+ hub_id_base = cfg["training"].get("hub_model_id", "tiny-llama-lab")
147
+ cfg["training"]["hub_model_id"] = f"{hub_id_base}-{variant_label}"
148
+
149
+ os.environ.pop("WANDB_RUN_ID", None)
150
+
151
+ trainer = create_trainer(model, tokenizer, cfg, train_ds, eval_ds)
152
+
153
+ # ---- CRITICAL FIX: manually set trainer on the callback ----
154
+ freeze_mlp = cfg["training"].get("freeze_mlp", False)
155
+ override_enabled = go.get("enabled", False)
156
+ if freeze_mlp or override_enabled:
157
+ for cb in trainer.callback_handler.callbacks:
158
+ if isinstance(cb, ResumeFreezeOverrideCallback):
159
+ cb._trainer = trainer
160
+ break
161
+
162
+ # Also delete optimizer.pt from the checkpoint so the Trainer doesn't try to load it
163
+ if checkpoint_path is not None and os.path.isdir(checkpoint_path):
164
+ opt_path = os.path.join(checkpoint_path, "optimizer.pt")
165
+ if os.path.exists(opt_path):
166
+ os.remove(opt_path)
167
+ print("[Freeze] Removed optimizer.pt from checkpoint to avoid state mismatch.")
168
+
169
+ # ---- NOW TRAIN ----
170
+ try:
171
+ trainer.train(resume_from_checkpoint=checkpoint_path)
172
+ metrics = trainer.evaluate()
173
+ results.append({
174
+ "variant": variant_label,
175
+ "eval_loss": metrics.get("eval_loss"),
176
+ "out": str(out_dir),
177
+ "run_name": run_name,
178
+ "status": "success",
179
+ })
180
+ trainer.save_model(str(out_dir))
181
+ if args.push or cfg["training"].get("push_to_hub", False):
182
+ trainer.push_to_hub()
183
+ print(f">>> FINISHED {variant_label} successfully")
184
+
185
+ except Exception as e:
186
+ print(f"!!! VARIANT {variant_label} FAILED with: {e}")
187
+ import traceback
188
+ traceback.print_exc()
189
+ results.append({
190
+ "variant": variant_label,
191
+ "error": str(e),
192
+ "out": str(out_dir),
193
+ "status": "failed",
194
+ })
195
+ # Continue with next variant
196
+ continue
197
+
198
+ finally:
199
+ wandb.finish()
200
+ torch.cuda.empty_cache() # free memory before next variant
201
+
202
+ summary = Path(base["training"]["output_dir"]).parent / "sweep_summary.json"
203
+ summary.write_text(json.dumps(results, indent=2))
204
+ print("\nSweep complete:")
205
+ for r in results:
206
+ if r.get("status") == "success":
207
+ print(f" {r['variant']:20s} eval_loss={r['eval_loss']:.4f}")
208
+ else:
209
+ print(f" {r['variant']:20s} FAILED: {r.get('error', 'unknown')}")
210
+
211
+ # Return non-zero exit code if any variant failed
212
+ if any(r.get("status") == "failed" for r in results):
213
+ sys.exit(1)
214
+
215
+
216
+ if __name__ == "__main__":
217
+ main()
zain/Activation/train.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train one TinyLlama variant with optional resume from HF Hub."""
3
+
4
+ import argparse
5
+ import yaml
6
+ import os
7
+ import torch
8
+ from pathlib import Path
9
+
10
+ from transformers import AutoTokenizer, set_seed
11
+ from exp import (
12
+ TinyLlamaConfig,
13
+ TinyLlamaForCausalLM,
14
+ build_dataset,
15
+ create_trainer,
16
+ fetch_latest_checkpoint_from_hub,
17
+ ResumeFreezeOverrideCallback,
18
+ )
19
+
20
+
21
+ def main():
22
+ parser = argparse.ArgumentParser()
23
+ parser.add_argument("--config", required=True, help="Path to YAML config")
24
+ parser.add_argument("--variant", required=True, help="e.g., glu-silu-100L")
25
+ parser.add_argument("--resume_from", help="Local checkpoint path (overrides config)")
26
+ parser.add_argument("--push", action="store_true", help="Push final model to HF Hub")
27
+ args = parser.parse_args()
28
+
29
+ with open(args.config) as f:
30
+ cfg = yaml.safe_load(f)
31
+
32
+ seed = cfg.get("training", {}).get("seed", 42)
33
+ set_seed(seed)
34
+
35
+ wandb_project = cfg.get("training", {}).get("wandb_project")
36
+ if wandb_project:
37
+ os.environ["WANDB_PROJECT"] = wandb_project
38
+ print(f"[WandB] Project locked to: {wandb_project}")
39
+
40
+ # Determine checkpoint path
41
+ checkpoint_path = None
42
+ if args.resume_from:
43
+ checkpoint_path = args.resume_from
44
+ print(f"[Resume] Using CLI-provided local path: {checkpoint_path}")
45
+ else:
46
+ resume_config = cfg.get("training", {})
47
+ if resume_config.get("resume_from_hub", False):
48
+ hub_cfg = cfg.get("hub", {})
49
+ repo_id = hub_cfg.get("repo_id")
50
+ subpath = hub_cfg.get("subpath", "")
51
+ if not repo_id:
52
+ raise ValueError("hub.repo_id must be set when resume_from_hub is true")
53
+ checkpoint_step = resume_config.get("checkpoint_step")
54
+ print(f"[Resume] Fetching from HF Hub: {repo_id}/{subpath}/{args.variant}_run")
55
+ checkpoint_path = fetch_latest_checkpoint_from_hub(
56
+ repo_id=repo_id,
57
+ subpath=subpath,
58
+ variant=args.variant,
59
+ checkpoint_step=checkpoint_step,
60
+ )
61
+ print(f"[Resume] Downloaded to: {checkpoint_path}")
62
+ elif resume_config.get("resume_from"):
63
+ checkpoint_path = resume_config.get("resume_from")
64
+ print(f"[Resume] Using config-provided local path: {checkpoint_path}")
65
+
66
+ # Build model & tokenizer
67
+ model_cfg = cfg["model"]
68
+ train_cfg = cfg.get("training", {})
69
+
70
+ # Output dir with _trash if override enabled
71
+ go = cfg.get("gradient_override", {})
72
+ if go.get("enabled", False):
73
+ base_out = Path(train_cfg.get("output_dir", "./out"))
74
+ variant_name = args.variant + "_trash"
75
+ output_dir = base_out / variant_name
76
+ train_cfg["output_dir"] = str(output_dir)
77
+ print(f"[Override] Output directory set to: {output_dir}")
78
+
79
+ tok_name = model_cfg.pop("tokenizer_name", "meta-llama/Llama-2-7b-hf")
80
+ tokenizer = AutoTokenizer.from_pretrained(tok_name)
81
+ if tokenizer.pad_token is None:
82
+ tokenizer.pad_token = tokenizer.eos_token
83
+
84
+ tiny_config = TinyLlamaConfig(**model_cfg)
85
+ model = TinyLlamaForCausalLM(tiny_config)
86
+ model = model.to(torch.bfloat16)
87
+
88
+ n_params = sum(p.numel() for p in model.parameters()) / 1e6
89
+ print(f"Model: {n_params:.2f}M params | MLP type: {tiny_config.mlp_type} | Activation: {tiny_config.activation}")
90
+
91
+ msl = model_cfg.get("max_position_embeddings", 512)
92
+ train_ds = build_dataset(tokenizer, max_seq_len=msl, split="train", max_samples=None)
93
+ eval_ds = build_dataset(tokenizer, max_seq_len=msl, split="validation", max_samples=None)
94
+
95
+ trainer = create_trainer(model, tokenizer, cfg, train_ds, eval_ds)
96
+
97
+ # Manually set trainer on callback if freezing/override is enabled
98
+ freeze_mlp = train_cfg.get("freeze_mlp", False)
99
+ override_enabled = go.get("enabled", False)
100
+ if freeze_mlp or override_enabled:
101
+ for cb in trainer.callback_handler.callbacks:
102
+ if isinstance(cb, ResumeFreezeOverrideCallback):
103
+ cb._trainer = trainer
104
+ break
105
+ # Delete optimizer.pt to avoid state mismatch
106
+ if checkpoint_path is not None and os.path.isdir(checkpoint_path):
107
+ opt_path = os.path.join(checkpoint_path, "optimizer.pt")
108
+ if os.path.exists(opt_path):
109
+ os.remove(opt_path)
110
+ print("[Freeze] Removed optimizer.pt from checkpoint.")
111
+
112
+ trainer.train(resume_from_checkpoint=checkpoint_path)
113
+
114
+ out = train_cfg.get("output_dir", "./out")
115
+ trainer.save_model(out)
116
+ if args.push or train_cfg.get("push_to_hub", False):
117
+ trainer.push_to_hub()
118
+ print(f"Done. Artifacts in {out}")
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()
zain/Activation/wandb/debug-internal.log ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time":"2026-08-13T21:15:21.457059839Z","level":"INFO","msg":"wandb-core"}
2
+ {"time":"2026-08-13T21:15:21.457218835Z","level":"INFO","msg":"stream: starting","core version":"0.28.1"}
3
+ {"time":"2026-08-13T21:15:21.71665521Z","level":"INFO","msg":"stream: created new stream","id":"bdgno22l"}
4
+ {"time":"2026-08-13T21:15:21.716724793Z","level":"INFO","msg":"handler: started"}
5
+ {"time":"2026-08-13T21:15:21.716834966Z","level":"INFO","msg":"stream: started"}
6
+ {"time":"2026-08-13T21:15:21.716845775Z","level":"INFO","msg":"writer: started","stream_id":"bdgno22l"}
7
+ {"time":"2026-08-13T21:15:21.716864355Z","level":"INFO","msg":"sender: started"}
8
+ {"time":"2026-08-13T21:15:22.087946715Z","level":"INFO","msg":"filestream: sending request","total_files":1,"console_offset":0,"console_lines":1}
9
+ {"time":"2026-08-13T21:15:22.187941633Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
10
+ {"time":"2026-08-13T21:15:33.902773632Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2617}
11
+ {"time":"2026-08-13T21:15:33.902804288Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
12
+ {"time":"2026-08-13T21:15:33.903189126Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2650}
13
+ {"time":"2026-08-13T21:15:33.903223176Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
14
+ {"time":"2026-08-13T21:15:33.905188752Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3405}
15
+ {"time":"2026-08-13T21:15:33.905644326Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":109}
16
+ {"time":"2026-08-13T21:15:33.905737177Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3547}
17
+ {"time":"2026-08-13T21:15:33.905849936Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":11}
18
+ {"time":"2026-08-13T21:15:33.907613871Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":4244}
19
+ {"time":"2026-08-13T21:15:33.914808342Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":2917}
20
+ {"time":"2026-08-13T21:15:33.91681943Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7726}
21
+ {"time":"2026-08-13T21:15:33.917089153Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":83}
22
+ {"time":"2026-08-13T21:15:33.917182957Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7844}
23
+ {"time":"2026-08-13T21:15:33.91727044Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":13}
24
+ {"time":"2026-08-13T21:15:33.919229048Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":8663}
25
+ {"time":"2026-08-13T21:15:33.919463562Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":61}
26
+ {"time":"2026-08-13T21:15:33.92636457Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9853}
27
+ {"time":"2026-08-13T21:15:33.926563588Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":8}
28
+ {"time":"2026-08-13T21:15:33.92776116Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":10322}
29
+ {"time":"2026-08-13T21:15:33.927881025Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":18}
30
+ {"time":"2026-08-13T21:15:37.112579744Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":0,"history_lines":2,"events_offset":0,"events_lines":1,"console_offset":1,"console_lines":5,"uploaded_len":2}
31
+ {"time":"2026-08-13T21:15:37.764424515Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
32
+ {"time":"2026-08-13T21:15:52.106707323Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":2,"history_lines":3,"events_offset":1,"events_lines":2,"console_offset":3,"console_lines":1}
33
+ {"time":"2026-08-13T21:15:53.006564044Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
zain/Activation/wandb/debug.log ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_setup.py:_flush():81] Current SDK version is 0.28.1
2
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_setup.py:_flush():81] Configure stats pid to 52372
3
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_setup.py:_flush():81] Loading settings from environment variables
4
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:setup_run_log_directory():729] Logging user logs to /mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug.log
5
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:setup_run_log_directory():730] Logging internal logs to /mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug-internal.log
6
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():772] calling init triggers
7
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():777] wandb.init called with sweep_config: {}
8
+ config: {'_wandb': {}}
9
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():820] starting backend
10
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():826] Connected to an existing wandb-core service via WANDB_SERVICE
11
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():835] sending inform_init request
12
+ 2026-08-13 21:15:21,717 INFO MainThread:52372 [wandb_init.py:init():840] backend started and connected
13
+ 2026-08-13 21:15:21,720 INFO MainThread:52372 [wandb_init.py:init():910] updated telemetry
14
+ 2026-08-13 21:15:21,727 INFO MainThread:52372 [wandb_init.py:init():933] communicating run to backend with 90.0 second timeout
15
+ 2026-08-13 21:15:22,001 INFO MainThread:52372 [wandb_init.py:init():978] starting run threads in backend
16
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_console_start():2621] atexit reg
17
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_redirect():2471] redirect: wrap_raw
18
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_redirect():2540] Wrapping output streams.
19
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_redirect():2563] Redirects installed.
20
+ 2026-08-13 21:15:22,077 INFO MainThread:52372 [wandb_init.py:init():1016] run started, returning control to user process
21
+ 2026-08-13 21:15:22,078 INFO MainThread:52372 [wandb_run.py:_config_callback():1346] config_cb None None {'transformers_version': '5.16.0.dev0', 'architectures': None, 'output_hidden_states': False, 'return_dict': True, 'dtype': None, 'chunk_size_feed_forward': 0, 'is_encoder_decoder': False, 'id2label': {0: 'LABEL_0', 1: 'LABEL_1'}, 'label2id': {'LABEL_0': 0, 'LABEL_1': 1}, 'problem_type': None, 'vocab_size': 4096, 'hidden_size': 128, 'intermediate_size': 256, 'num_hidden_layers': 100, 'num_attention_heads': 4, 'num_key_value_heads': 4, 'hidden_act': 'silu', 'max_position_embeddings': 512, 'initializer_range': 0.02, 'rms_norm_eps': 1e-06, 'use_cache': False, 'pad_token_id': 0, 'bos_token_id': 1, 'eos_token_id': 2, 'pretraining_tp': 1, 'tie_word_embeddings': True, 'rope_parameters': {'rope_theta': 10000.0, 'rope_type': 'default'}, 'attention_bias': False, 'attention_dropout': 0.0, 'mlp_bias': False, 'head_dim': 32, '_name_or_path': '', 'tokenizer_name': 'w-ahmad/tiny-stories-tokenizer', 'mlp_type': 'glu', 'activation': 'linear', 'waleed_beta': 10.0, 'model_type': 'tiny_llama', 'output_attentions': False, 'output_dir': 'out/glu-linear-100L_trash_run', 'per_device_train_batch_size': 64, 'num_train_epochs': 1, 'max_steps': 2700, 'learning_rate': 9e-05, 'lr_scheduler_type': 'constant_with_warmup', 'lr_scheduler_kwargs': None, 'warmup_steps': 50, 'optim': 'adamw_torch_fused', 'optim_args': None, 'weight_decay': 0.0, 'adam_beta1': 0.9, 'adam_beta2': 0.999, 'adam_epsilon': 1e-08, 'optim_target_modules': None, 'gradient_accumulation_steps': 1, 'average_tokens_across_devices': True, 'max_grad_norm': 1.0, 'label_smoothing_factor': 0.0, 'bf16': True, 'fp16': False, 'bf16_full_eval': False, 'fp16_full_eval': False, 'tf32': None, 'gradient_checkpointing': False, 'gradient_checkpointing_kwargs': None, 'torch_compile': False, 'torch_compile_backend': None, 'torch_compile_mode': None, 'use_liger_kernel': False, 'liger_kernel_config': None, 'neftune_noise_alpha': None, 'torch_empty_cache_steps': None, 'auto_find_batch_size': False, 'logging_strategy': 'steps', 'logging_steps': 20, 'logging_first_step': False, 'log_on_each_node': True, 'logging_nan_inf_filter': True, 'include_num_input_tokens_seen': 'no', 'log_level': 'passive', 'log_level_replica': 'warning', 'disable_tqdm': False, 'report_to': ['wandb'], 'run_name': 'LM-glu-linear-100L-16.9M-20260813-211520', 'project': 'huggingface', 'trackio_space_id': None, 'trackio_bucket_id': None, 'trackio_static_space_id': None, 'eval_strategy': 'steps', 'eval_steps': 2498, 'eval_delay': 0, 'per_device_eval_batch_size': 1024, 'prediction_loss_only': False, 'eval_on_start': False, 'eval_do_concat_batches': True, 'eval_use_gather_object': False, 'eval_accumulation_steps': None, 'include_for_metrics': [], 'batch_eval_metrics': False, 'save_only_model': False, 'save_strategy': 'steps', 'save_steps': 100, 'save_on_each_node': False, 'save_total_limit': None, 'enable_jit_checkpoint': False, 'push_to_hub': False, 'hub_token': '<HUB_TOKEN>', 'hub_private_repo': None, 'hub_model_id': 'w-ahmad/6L-glu-linear-100L', 'hub_strategy': 'every_save', 'hub_always_push': False, 'hub_revision': None, 'load_best_model_at_end': False, 'metric_for_best_model': None, 'greater_is_better': None, 'ignore_data_skip': False, 'restore_callback_states_from_checkpoint': False, 'full_determinism': False, 'seed': 42, 'data_seed': 42, 'use_cpu': False, 'accelerator_config': {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}, 'parallelism_config': None, 'dataloader_drop_last': False, 'dataloader_num_workers': 0, 'dataloader_pin_memory': True, 'dataloader_persistent_workers': False, 'dataloader_prefetch_factor': None, 'dataloader_multiprocessing_context': None, 'dataloader_in_order': True, 'remove_unused_columns': False, 'label_names': None, 'train_sampling_strategy': 'random', 'length_column_name': 'length', 'ddp_find_unused_parameters': None, 'ddp_bucket_cap_mb': None, 'ddp_broadcast_buffers': None, 'ddp_static_graph': None, 'ddp_backend': None, 'ddp_timeout': 1800, 'fsdp': None, 'fsdp_config': None, 'deepspeed': None, 'debug': [], 'skip_memory_metrics': True, 'do_train': False, 'do_eval': True, 'do_predict': False, 'resume_from_checkpoint': None, 'local_rank': -1}
22
+ 2026-08-13 21:15:22,082 INFO MainThread:52372 [wandb_config.py:__setitem__():155] [no run ID] config set model/num_parameters = 16934016 - <bound method Run._config_callback of <wandb.sdk.wandb_run.Run object at 0x15235c33c510>>
23
+ 2026-08-13 21:15:22,082 INFO MainThread:52372 [wandb_run.py:_config_callback():1346] config_cb model/num_parameters 16934016 None
zain/Activation/wandb/run-20260813_211521-bdgno22l/files/output.log ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Override] Activated with value = -10.0
2
+ 0%| | 0/2700 [00:00<?, ?it/s][transformers] `use_return_dict` is deprecated! Use `return_dict` instead!
3
+ [INFO] Causal mask (float with -inf) applied to all attention layers.
4
+ 96%|█████████▋| 2600/2700 [00:27<00:00, 102.99it/s][transformers] TinyLlamaForCausalLM has generative capabilities, as `prepare_inputs_for_generation` is explicitly defined. However, it doesn't directly inherit from `GenerationMixin`. From 👉v4.50👈 onwards, `PreTrainedModel` will NOT inherit from `GenerationMixin`, and this model will lose the ability to call `generate` and other related functions.
5
+ {'loss': '2.102', 'grad_norm': '2.661e+07', 'learning_rate': '3.42e-05', 'epoch': '0.1699', 'train/total_time_seconds': '5.379', 'train/time_per_step_avg': '0.2689', 'train/epoch_time_elapsed': '6.585', 'train/estimated_remaining_minutes': '0.006403', 'train/tensor_act_model_layers_0_residual_pre_attn/norm': '187.1', 'train/tensor_act_model_layers_0_residual_pre_attn/mean': '0.001579', 'train/tensor_act_model_layers_0_residual_pre_attn/std': '0.09131', 'train/tensor_act_model_layers_0_residual_pre_attn/max_abs': '0.2734', 'train/tensor_act_model_layers_0_residual_pre_attn/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_residual_pre_attn/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_residual_pre_attn/min': '-0.2734', 'train/tensor_act_model_layers_0_residual_pre_attn/max': '0.2734', 'train/tensor_act_model_layers_0_residual_pre_attn/range': '0.5469', 'train/tensor_act_model_layers_0_residual_post_attn/norm': '188.5', 'train/tensor_act_model_layers_0_residual_post_attn/mean': '0.001442', 'train/tensor_act_model_layers_0_residual_post_attn/std': '0.09229', 'train/tensor_act_model_layers_0_residual_post_attn/max_abs': '0.3574', 'train/tensor_act_model_layers_0_residual_post_attn/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_residual_post_attn/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_residual_post_attn/min': '-0.3574', 'train/tensor_act_model_layers_0_residual_post_attn/max': '0.3418', 'train/tensor_act_model_layers_0_residual_post_attn/range': '0.6992', 'train/tensor_act_model_layers_0_mlp_gate_proj/norm': '1041', 'train/tensor_act_model_layers_0_mlp_gate_proj/mean': '0.0003281', 'train/tensor_act_model_layers_0_mlp_gate_proj/std': '0.3594', 'train/tensor_act_model_layers_0_mlp_gate_proj/max_abs': '1.828', 'train/tensor_act_model_layers_0_mlp_gate_proj/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp_gate_proj/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp_gate_proj/min': '-1.719', 'train/tensor_act_model_layers_0_mlp_gate_proj/max': '1.828', 'train/tensor_act_model_layers_0_mlp_gate_proj/range': '3.547', 'train/tensor_act_model_layers_0_mlp_up_proj/norm': '1049', 'train/tensor_act_model_layers_0_mlp_up_proj/mean': '-0.00238', 'train/tensor_act_model_layers_0_mlp_up_proj/std': '0.3613', 'train/tensor_act_model_layers_0_mlp_up_proj/max_abs': '2.125', 'train/tensor_act_model_layers_0_mlp_up_proj/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp_up_proj/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp_up_proj/min': '-1.992', 'train/tensor_act_model_layers_0_mlp_up_proj/max': '2.125', 'train/tensor_act_model_layers_0_mlp_up_proj/range': '4.117', 'train/tensor_act_model_layers_0_mlp_down_proj/norm': '200.9', 'train/tensor_act_model_layers_0_mlp_down_proj/mean': '0.0004768', 'train/tensor_act_model_layers_0_mlp_down_proj/std': '0.09814', 'train/tensor_act_model_layers_0_mlp_down_proj/max_abs': '0.5273', 'train/tensor_act_model_layers_0_mlp_down_proj/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp_down_proj/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp_down_proj/min': '-0.4902', 'train/tensor_act_model_layers_0_mlp_down_proj/max': '0.5273', 'train/tensor_act_model_layers_0_mlp_down_proj/range': '1.018', 'train/tensor_act_model_layers_0_mlp/norm': '200.9', 'train/tensor_act_model_layers_0_mlp/mean': '0.0004768', 'train/tensor_act_model_layers_0_mlp/std': '0.09814', 'train/tensor_act_model_layers_0_mlp/max_abs': '0.5273', 'train/tensor_act_model_layers_0_mlp/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp/min': '-0.4902', 'train/tensor_act_model_layers_0_mlp/max': '0.5273', 'train/tensor_act_model_layers_0_mlp/range': '1.018', 'train/tensor_act_model_layers_0_residual_post_mlp/norm': '291.2', 'train/tensor_act_model_layers_0_residual_post_mlp/mean': '0.001923', 'train/tensor_act_model_layers_0_residual_post_mlp/std': '0.1426', 'train/tensor_act_model_layers_0_residual_post_mlp/max_abs':
6
+ {'loss': '2.128', 'grad_norm': '3.106e+07', 'learning_rate': '7.02e-05', 'epoch': '0.1712', 'train/total_time_seconds': '9.549', 'train/time_per_step_avg': '0.2387', 'train/epoch_time_elapsed': '11.79', 'train/estimated_remaining_minutes': '0.01003'}
7
+ {'loss': '4.245', 'grad_norm': '2.223e+08', 'learning_rate': '9e-05', 'epoch': '0.1726', 'train/total_time_seconds': '14.12', 'train/time_per_step_avg': '0.2354', 'train/epoch_time_elapsed': '17.43', 'train/estimated_remaining_minutes': '0.01287', 'train/tensor_act_model_layers_0_residual_pre_attn/norm': '187.2', 'train/tensor_act_model_layers_0_residual_pre_attn/mean': '0.001549', 'train/tensor_act_model_layers_0_residual_pre_attn/std': '0.09131', 'train/tensor_act_model_layers_0_residual_pre_attn/max_abs': '0.2734', 'train/tensor_act_model_layers_0_residual_pre_attn/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_residual_pre_attn/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_residual_pre_attn/min': '-0.2734', 'train/tensor_act_model_layers_0_residual_pre_attn/max': '0.2734', 'train/tensor_act_model_layers_0_residual_pre_attn/range': '0.5469', 'train/tensor_act_model_layers_0_residual_post_attn/norm': '188.6', 'train/tensor_act_model_layers_0_residual_post_attn/mean': '0.001312', 'train/tensor_act_model_layers_0_residual_post_attn/std': '0.09229', 'train/tensor_act_model_layers_0_residual_post_attn/max_abs': '0.3477', 'train/tensor_act_model_layers_0_residual_post_attn/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_residual_post_attn/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_residual_post_attn/min': '-0.3477', 'train/tensor_act_model_layers_0_residual_post_attn/max': '0.3477', 'train/tensor_act_model_layers_0_residual_post_attn/range': '0.6953', 'train/tensor_act_model_layers_0_mlp_gate_proj/norm': '1087', 'train/tensor_act_model_layers_0_mlp_gate_proj/mean': '-0.000843', 'train/tensor_act_model_layers_0_mlp_gate_proj/std': '0.375', 'train/tensor_act_model_layers_0_mlp_gate_proj/max_abs': '1.867', 'train/tensor_act_model_layers_0_mlp_gate_proj/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp_gate_proj/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp_gate_proj/min': '-1.867', 'train/tensor_act_model_layers_0_mlp_gate_proj/max': '1.852', 'train/tensor_act_model_layers_0_mlp_gate_proj/range': '3.719', 'train/tensor_act_model_layers_0_mlp_up_proj/norm': '1094', 'train/tensor_act_model_layers_0_mlp_up_proj/mean': '-0.001305', 'train/tensor_act_model_layers_0_mlp_up_proj/std': '0.377', 'train/tensor_act_model_layers_0_mlp_up_proj/max_abs': '2.266', 'train/tensor_act_model_layers_0_mlp_up_proj/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp_up_proj/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp_up_proj/min': '-1.984', 'train/tensor_act_model_layers_0_mlp_up_proj/max': '2.266', 'train/tensor_act_model_layers_0_mlp_up_proj/range': '4.25', 'train/tensor_act_model_layers_0_mlp_down_proj/norm': '233.8', 'train/tensor_act_model_layers_0_mlp_down_proj/mean': '0.02856', 'train/tensor_act_model_layers_0_mlp_down_proj/std': '0.1104', 'train/tensor_act_model_layers_0_mlp_down_proj/max_abs': '0.7109', 'train/tensor_act_model_layers_0_mlp_down_proj/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp_down_proj/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp_down_proj/min': '-0.5039', 'train/tensor_act_model_layers_0_mlp_down_proj/max': '0.7109', 'train/tensor_act_model_layers_0_mlp_down_proj/range': '1.215', 'train/tensor_act_model_layers_0_mlp/norm': '233.8', 'train/tensor_act_model_layers_0_mlp/mean': '0.02856', 'train/tensor_act_model_layers_0_mlp/std': '0.1104', 'train/tensor_act_model_layers_0_mlp/max_abs': '0.7109', 'train/tensor_act_model_layers_0_mlp/frac_near_dtype_limit': '0', 'train/tensor_act_model_layers_0_mlp/frac_near_user_limit': '0', 'train/tensor_act_model_layers_0_mlp/min': '-0.5039', 'train/tensor_act_model_layers_0_mlp/max': '0.7109', 'train/tensor_act_model_layers_0_mlp/range': '1.215', 'train/tensor_act_model_layers_0_residual_post_mlp/norm': '315', 'train/tensor_act_model_layers_0_residual_post_mlp/mean': '0.02991', 'train/tensor_act_model_layers_0_residual_post_mlp/std': '0.1504', 'train/tensor_act_model_layers_0_residual_post_mlp/max_abs': '0.7734', 'tra
8
+ {'loss': '7.166', 'grad_norm': '4.886e+08', 'learning_rate': '9e-05', 'epoch': '0.1739', 'train/total_time_seconds': '18.38', 'train/time_per_step_avg': '0.2297', 'train/epoch_time_elapsed': '22.75', 'train/estimated_remaining_minutes': '0.01424'}
9
+ {'loss': '7.483', 'grad_norm': '8.85e+08', 'learning_rate': '9e-05', 'epoch': '0.1753', 'train/total_time_seconds': '22.58', 'train/time_per_step_avg': '0.2258', 'train/epoch_time_elapsed': '27.92', 'train/estimated_remaining_minutes': '0.01447'}
10
+ - If you're using `trust_remote_code=True`, you can get rid of this warning by loading the model with an auto class. See https://huggingface.co/docs/transformers/en/model_doc/auto#auto-classes
11
+ - If you are the owner of the model architecture code, please modify your model class such that it inherits from `GenerationMixin` (after `PreTrainedModel`, otherwise you'll get an exception).
12
+ - If you are not the owner of the model architecture class, please contact the model code owner to update it.
13
+ Writing model shards: 100%|██████████| 1/1 [00:00<00:00, 12.56it/s]
14
+ Writing model shards: 0%| | 0/1 [00:00<?, ?it/s]
zain/Activation/wandb/run-20260813_211521-bdgno22l/files/requirements.txt ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ asttokens==3.0.1
2
+ comm==0.2.3
3
+ debugpy==1.8.21
4
+ decorator==5.3.1
5
+ executing==2.2.1
6
+ nest-asyncio==1.6.0
7
+ parso==0.8.7
8
+ platformdirs==4.11.0
9
+ psutil==7.2.2
10
+ ptyprocess==0.7.0
11
+ pure_eval==0.2.3
12
+ Pygments==2.20.0
13
+ pyzmq==27.1.0
14
+ setuptools==83.0.0
15
+ six==1.17.0
16
+ tornado==6.5.7
17
+ traitlets==5.15.0
18
+ fsspec==2026.4.0
19
+ wcwidth==0.8.2
20
+ ipython_pygments_lexers==1.1.1
21
+ jedi==0.20.0
22
+ jupyter_core==5.9.1
23
+ matplotlib-inline==0.2.2
24
+ pexpect==4.9.0
25
+ prompt_toolkit==3.0.53
26
+ python-dateutil==2.9.0.post0
27
+ stack_data==0.6.3
28
+ wheel==0.47.0
29
+ jupyter_client==8.9.1
30
+ pip==26.1.2
31
+ ipython==9.15.0
32
+ ipykernel==7.2.0
33
+ threadpoolctl==3.6.0
34
+ pyparsing==3.3.2
35
+ typing_extensions==4.15.0
36
+ Jinja2==3.1.6
37
+ narwhals==2.24.0
38
+ kiwisolver==1.5.0
39
+ joblib==1.5.3
40
+ fonttools==4.63.0
41
+ cycler==0.12.1
42
+ scipy==1.17.1
43
+ pandas==3.0.5
44
+ contourpy==1.3.3
45
+ scikit-learn==1.9.0
46
+ matplotlib==3.11.1
47
+ urllib3==2.7.0
48
+ tqdm==4.70.0
49
+ idna==3.18
50
+ charset-normalizer==3.4.9
51
+ certifi==2026.7.22
52
+ requests==2.34.2
53
+ seaborn==0.13.2
54
+ uv==0.12.0
55
+ shellingham==1.5.4
56
+ mpmath==1.3.0
57
+ attrs==26.1.0
58
+ hf-xet==1.5.2
59
+ nvidia-nccl-cu12==2.21.5
60
+ MarkupSafe==3.0.3
61
+ regex==2026.7.19
62
+ importlib_metadata==9.0.0
63
+ httpcore==1.0.9
64
+ annotated-doc==0.0.5
65
+ multidict==6.7.1
66
+ aiohttp==3.14.3
67
+ aiosignal==1.4.0
68
+ xxhash==3.8.1
69
+ aiohappyeyeballs==2.7.1
70
+ mdurl==0.1.2
71
+ cuda-toolkit==13.0.3.0
72
+ networkx==3.6.1
73
+ PyYAML==6.0.3
74
+ nvidia-cufile==1.15.1.6
75
+ typer==0.27.0
76
+ torchaudio==2.6.0+cu124
77
+ rich==15.0.0
78
+ nvidia-cufft-cu12==11.2.1.3
79
+ h11==0.16.0
80
+ dill==0.4.1
81
+ cuda-pathfinder==1.6.0
82
+ filelock==3.29.0
83
+ nvidia-nvtx-cu12==12.4.127
84
+ httpx==0.28.1
85
+ anyio==4.14.2
86
+ numpy==2.4.4
87
+ yarl==1.24.5
88
+ click==8.4.2
89
+ triton==3.2.0
90
+ frozenlist==1.8.0
91
+ zipp==4.1.0
92
+ propcache==0.5.2
93
+ tokenizers==0.22.2
94
+ markdown-it-py==4.2.0
95
+ nvidia-cuda-runtime==13.0.96
96
+ cuda-bindings==13.3.1
97
+ nvidia-cuda-cupti==13.0.85
98
+ torch==2.6.0+cu124
99
+ multiprocess==0.70.19
100
+ pillow==12.2.0
101
+ transformers==5.16.0.dev0
102
+ wandb==0.28.1
103
+ nvidia-curand==10.4.0.35
104
+ sympy==1.13.1
105
+ nvidia-cusparse==12.6.3.3
106
+ nvidia-cuda-nvrtc==13.0.88
107
+ typing-inspection==0.4.2
108
+ nvidia-cusolver==12.0.4.66
109
+ nvidia-cufft==12.0.0.61
110
+ nvidia-cudnn-cu13==9.20.0.48
111
+ nvidia-cublas==13.1.1.3
112
+ pyarrow==25.0.0
113
+ evaluate==0.4.6
114
+ diffusers==0.39.0
115
+ pydantic==2.13.4
116
+ annotated-types==0.8.0
117
+ protobuf==7.35.1
118
+ sentry-sdk==2.66.1
119
+ einops==0.8.2
120
+ packaging==26.2
121
+ nvidia-nvjitlink-cu12==12.4.127
122
+ nvidia-curand-cu12==10.3.5.147
123
+ nvidia-cusparselt-cu12==0.6.2
124
+ nvidia-cusparse-cu12==12.3.1.170
125
+ nvidia-cuda-runtime-cu12==12.4.127
126
+ torchvision==0.21.0+cu124
127
+ nvidia-cuda-nvrtc-cu12==12.4.127
128
+ nvidia-cuda-cupti-cu12==12.4.127
129
+ nvidia-cusolver-cu12==11.6.1.9
130
+ nvidia-cublas-cu12==12.4.5.8
131
+ nvidia-cudnn-cu12==9.1.0.70
132
+ huggingface_hub==1.26.0
133
+ datasets==5.0.1
134
+ safetensors==0.8.0
135
+ accelerate==1.14.0
136
+ pydantic_core==2.46.4
137
+ ninja==1.13.0
138
+ autocommand==2.2.2
139
+ backports.tarfile==1.2.0
140
+ importlib_metadata==8.7.1
141
+ jaraco.text==4.0.0
142
+ jaraco.context==6.1.0
143
+ jaraco.functools==4.4.0
144
+ more-itertools==10.8.0
145
+ packaging==26.0
146
+ platformdirs==4.4.0
147
+ tomli==2.4.0
148
+ wheel==0.46.3
149
+ zipp==3.23.0
zain/Activation/wandb/run-20260813_211521-bdgno22l/files/wandb-metadata.json ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "os": "Linux-5.15.0-126-generic-x86_64-with-glibc2.35",
3
+ "python": "CPython 3.11.15",
4
+ "startedAt": "2026-08-13T21:15:21.454482Z",
5
+ "args": [
6
+ "--config",
7
+ "/mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/configs/baseline100L.yaml",
8
+ "--variants",
9
+ "glu-linear-100L",
10
+ "glu-silu-100L",
11
+ "glu-silu-waleed10-100L",
12
+ "glu-situglu-100L",
13
+ "glu-situglu_low-100L",
14
+ "glu-waleed-100L",
15
+ "glu-waleed10-100L",
16
+ "glu-waleedglu_low-100L"
17
+ ],
18
+ "program": "/mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/sweep.py",
19
+ "codePath": "sweep.py",
20
+ "codePathLocal": "sweep.py",
21
+ "git": {
22
+ "remote": "https://github.com/w-ahmad1a10/Activation.git",
23
+ "commit": "8381885396c6fb3cbe0304e3b3c5498dda2c7440"
24
+ },
25
+ "email": "deepnevro@gmail.com",
26
+ "root": "/mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation",
27
+ "host": "deeplens-k3s-node1",
28
+ "executable": "/mnt/data/zainulabideen/zain-exp/notebooks/my_env/bin/python",
29
+ "cpu_count": 112,
30
+ "cpu_count_logical": 224,
31
+ "gpu": "NVIDIA H100 80GB HBM3",
32
+ "gpu_count": 8,
33
+ "disk": {
34
+ "/": {
35
+ "total": "1560765693952",
36
+ "used": "710564417536"
37
+ }
38
+ },
39
+ "memory": {
40
+ "total": "2164089937920"
41
+ },
42
+ "gpu_nvidia": [
43
+ {
44
+ "name": "NVIDIA H100 80GB HBM3",
45
+ "memoryTotal": "85520809984",
46
+ "cudaCores": 16896,
47
+ "architecture": "Hopper",
48
+ "uuid": "GPU-39c684a5-fde6-83d7-1663-0859795881ae"
49
+ },
50
+ {
51
+ "name": "NVIDIA H100 80GB HBM3",
52
+ "memoryTotal": "85520809984",
53
+ "cudaCores": 16896,
54
+ "architecture": "Hopper",
55
+ "uuid": "GPU-68012e5a-38b6-b643-0ca6-62fb66720bf3"
56
+ },
57
+ {
58
+ "name": "NVIDIA H100 80GB HBM3",
59
+ "memoryTotal": "85520809984",
60
+ "cudaCores": 16896,
61
+ "architecture": "Hopper",
62
+ "uuid": "GPU-132944c4-b689-2b5f-89a4-d730401677ab"
63
+ },
64
+ {
65
+ "name": "NVIDIA H100 80GB HBM3",
66
+ "memoryTotal": "85520809984",
67
+ "cudaCores": 16896,
68
+ "architecture": "Hopper",
69
+ "uuid": "GPU-2df386cc-6d26-d0e2-7a2d-a057b0d95864"
70
+ },
71
+ {
72
+ "name": "NVIDIA H100 80GB HBM3",
73
+ "memoryTotal": "85520809984",
74
+ "cudaCores": 16896,
75
+ "architecture": "Hopper",
76
+ "uuid": "GPU-bfa16575-1d94-1aa2-4537-2c93433f42ef"
77
+ },
78
+ {
79
+ "name": "NVIDIA H100 80GB HBM3",
80
+ "memoryTotal": "85520809984",
81
+ "cudaCores": 16896,
82
+ "architecture": "Hopper",
83
+ "uuid": "GPU-bc6c3e3c-9b90-09ca-c034-774961847c54"
84
+ },
85
+ {
86
+ "name": "NVIDIA H100 80GB HBM3",
87
+ "memoryTotal": "85520809984",
88
+ "cudaCores": 16896,
89
+ "architecture": "Hopper",
90
+ "uuid": "GPU-00a441e1-7c95-e7d6-4c35-43d6b291aea9"
91
+ },
92
+ {
93
+ "name": "NVIDIA H100 80GB HBM3",
94
+ "memoryTotal": "85520809984",
95
+ "cudaCores": 16896,
96
+ "architecture": "Hopper",
97
+ "uuid": "GPU-1c4d29a2-4647-6fce-d8fc-0c5ecfbbd6ea"
98
+ }
99
+ ],
100
+ "cudaVersion": "12.4",
101
+ "writerId": "3doo1fos9k4ofmuy6vlh53x3p7tpfmqy"
102
+ }
zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug-core.log ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time":"2026-08-13T20:50:56.88837736Z","level":"INFO","msg":"main: starting server","port-filename":"/tmp/tmp_1eb1gnf/port-4013524.txt","pid":4013524,"detached":false,"idle-timeout":600000000000,"log-level":0,"disable-analytics":false,"shutdown-on-parent-exit":false,"enable-dcgm-profiling":false}
2
+ {"time":"2026-08-13T20:50:56.889974484Z","level":"INFO","msg":"server: will exit if parent process dies","ppid":4013524}
3
+ {"time":"2026-08-13T20:50:56.889954218Z","level":"INFO","msg":"server: accepting connections","addr":{"Name":"/tmp/wandb-4013524-4015748-1172316019/socket","Net":"unix"}}
4
+ {"time":"2026-08-13T20:50:57.063325317Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"1(@)"}
5
+ {"time":"2026-08-13T20:51:59.231462609Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"2(@)"}
6
+ {"time":"2026-08-13T20:51:59.35547125Z","level":"INFO","msg":"handleInformInit: received","streamId":"qudyw6my","id":"2(@)"}
7
+ {"time":"2026-08-13T20:51:59.618336359Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"qudyw6my","id":"2(@)"}
8
+ {"time":"2026-08-13T20:52:05.07357923Z","level":"INFO","msg":"connection: cancelling request","id":"2(@)","requestId":"67oxstahnbwk"}
9
+ {"time":"2026-08-13T20:53:24.810084125Z","level":"INFO","msg":"connection: cancelling request","id":"2(@)","requestId":"67oxstahnbwk"}
10
+ {"time":"2026-08-13T20:53:26.647793248Z","level":"INFO","msg":"connection: cancelling request","id":"2(@)","requestId":"67oxstahnbwk"}
11
+ {"time":"2026-08-13T20:53:26.906580178Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"qudyw6my","id":"2(@)"}
12
+ {"time":"2026-08-13T20:53:26.907531442Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"qudyw6my","id":"2(@)"}
13
+ {"time":"2026-08-13T20:53:28.4626298Z","level":"INFO","msg":"connection: closing","id":"2(@)"}
14
+ {"time":"2026-08-13T20:53:28.462723867Z","level":"INFO","msg":"connection: closed successfully","id":"2(@)"}
15
+ {"time":"2026-08-13T20:53:28.462642414Z","level":"INFO","msg":"processOutgoingData: finished","id":"2(@)"}
16
+ {"time":"2026-08-13T20:53:28.462736968Z","level":"INFO","msg":"connection: ManageConnectionData: connection closed","id":"2(@)"}
17
+ {"time":"2026-08-13T20:58:26.484371032Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"3(@)"}
18
+ {"time":"2026-08-13T20:58:26.565457961Z","level":"INFO","msg":"handleInformInit: received","streamId":"k88lj9m1","id":"3(@)"}
19
+ {"time":"2026-08-13T20:58:26.825939415Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"k88lj9m1","id":"3(@)"}
20
+ {"time":"2026-08-13T20:58:32.214683089Z","level":"INFO","msg":"connection: cancelling request","id":"3(@)","requestId":"aja3hhk7rh8b"}
21
+ {"time":"2026-08-13T20:59:51.636693819Z","level":"INFO","msg":"connection: cancelling request","id":"3(@)","requestId":"aja3hhk7rh8b"}
22
+ {"time":"2026-08-13T20:59:53.52715723Z","level":"INFO","msg":"connection: cancelling request","id":"3(@)","requestId":"aja3hhk7rh8b"}
23
+ {"time":"2026-08-13T20:59:53.844075007Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"k88lj9m1","id":"3(@)"}
24
+ {"time":"2026-08-13T20:59:53.844796525Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"k88lj9m1","id":"3(@)"}
25
+ {"time":"2026-08-13T20:59:55.642797778Z","level":"INFO","msg":"processOutgoingData: finished","id":"3(@)"}
26
+ {"time":"2026-08-13T20:59:55.6427907Z","level":"INFO","msg":"connection: closing","id":"3(@)"}
27
+ {"time":"2026-08-13T20:59:55.642884054Z","level":"INFO","msg":"connection: closed successfully","id":"3(@)"}
28
+ {"time":"2026-08-13T20:59:55.642888633Z","level":"INFO","msg":"connection: ManageConnectionData: connection closed","id":"3(@)"}
29
+ {"time":"2026-08-13T21:10:30.327897889Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"4(@)"}
30
+ {"time":"2026-08-13T21:10:30.430510211Z","level":"INFO","msg":"handleInformInit: received","streamId":"idtw6vfo","id":"4(@)"}
31
+ {"time":"2026-08-13T21:10:30.674038153Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"idtw6vfo","id":"4(@)"}
32
+ {"time":"2026-08-13T21:10:33.084198753Z","level":"INFO","msg":"connection: cancelling request","id":"4(@)","requestId":"y5arwk2qvfef"}
33
+ {"time":"2026-08-13T21:10:33.613412909Z","level":"INFO","msg":"connection: cancelling request","id":"4(@)","requestId":"y5arwk2qvfef"}
34
+ {"time":"2026-08-13T21:10:33.614423646Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"idtw6vfo","id":"4(@)"}
35
+ {"time":"2026-08-13T21:10:33.615071285Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"idtw6vfo","id":"4(@)"}
36
+ {"time":"2026-08-13T21:10:35.274863492Z","level":"INFO","msg":"connection: closing","id":"4(@)"}
37
+ {"time":"2026-08-13T21:10:35.274947383Z","level":"INFO","msg":"connection: closed successfully","id":"4(@)"}
38
+ {"time":"2026-08-13T21:10:35.274864147Z","level":"INFO","msg":"processOutgoingData: finished","id":"4(@)"}
39
+ {"time":"2026-08-13T21:10:35.274956775Z","level":"INFO","msg":"connection: ManageConnectionData: connection closed","id":"4(@)"}
40
+ {"time":"2026-08-13T21:10:59.004852712Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"5(@)"}
41
+ {"time":"2026-08-13T21:10:59.090409085Z","level":"INFO","msg":"handleInformInit: received","streamId":"cvqont09","id":"5(@)"}
42
+ {"time":"2026-08-13T21:10:59.354009138Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"cvqont09","id":"5(@)"}
43
+ {"time":"2026-08-13T21:11:04.733635221Z","level":"INFO","msg":"connection: cancelling request","id":"5(@)","requestId":"3mnjy6uk50sj"}
44
+ {"time":"2026-08-13T21:11:24.240496285Z","level":"INFO","msg":"connection: cancelling request","id":"5(@)","requestId":"3mnjy6uk50sj"}
45
+ {"time":"2026-08-13T21:11:24.943824437Z","level":"INFO","msg":"connection: cancelling request","id":"5(@)","requestId":"3mnjy6uk50sj"}
46
+ {"time":"2026-08-13T21:11:24.945036572Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"cvqont09","id":"5(@)"}
47
+ {"time":"2026-08-13T21:11:24.945565304Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"cvqont09","id":"5(@)"}
48
+ {"time":"2026-08-13T21:11:26.576272285Z","level":"INFO","msg":"connection: closing","id":"5(@)"}
49
+ {"time":"2026-08-13T21:11:26.57629102Z","level":"INFO","msg":"processOutgoingData: finished","id":"5(@)"}
50
+ {"time":"2026-08-13T21:11:26.576355678Z","level":"INFO","msg":"connection: closed successfully","id":"5(@)"}
51
+ {"time":"2026-08-13T21:11:26.576364137Z","level":"INFO","msg":"connection: ManageConnectionData: connection closed","id":"5(@)"}
52
+ {"time":"2026-08-13T21:11:43.037962092Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"6(@)"}
53
+ {"time":"2026-08-13T21:11:43.126951891Z","level":"INFO","msg":"handleInformInit: received","streamId":"olcsup4b","id":"6(@)"}
54
+ {"time":"2026-08-13T21:11:43.384950035Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"olcsup4b","id":"6(@)"}
55
+ {"time":"2026-08-13T21:11:48.74325104Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"0eevcmnde8cb"}
56
+ {"time":"2026-08-13T21:12:13.594157711Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"0eevcmnde8cb"}
57
+ {"time":"2026-08-13T21:12:14.147755589Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"0eevcmnde8cb"}
58
+ {"time":"2026-08-13T21:12:14.149406248Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"olcsup4b","id":"6(@)"}
59
+ {"time":"2026-08-13T21:12:14.150092264Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"olcsup4b","id":"6(@)"}
60
+ {"time":"2026-08-13T21:12:15.149367854Z","level":"INFO","msg":"handleInformInit: received","streamId":"o4os2eko","id":"6(@)"}
61
+ {"time":"2026-08-13T21:12:15.419403518Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"o4os2eko","id":"6(@)"}
62
+ {"time":"2026-08-13T21:12:20.903171066Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"lmwiaqx3lznd"}
63
+ {"time":"2026-08-13T21:12:31.561337484Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"lmwiaqx3lznd"}
64
+ {"time":"2026-08-13T21:12:32.158848875Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"lmwiaqx3lznd"}
65
+ {"time":"2026-08-13T21:12:32.160185701Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"o4os2eko","id":"6(@)"}
66
+ {"time":"2026-08-13T21:12:32.160843182Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"o4os2eko","id":"6(@)"}
67
+ {"time":"2026-08-13T21:12:33.26906436Z","level":"INFO","msg":"handleInformInit: received","streamId":"69zdkrji","id":"6(@)"}
68
+ {"time":"2026-08-13T21:12:33.527818889Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"69zdkrji","id":"6(@)"}
69
+ {"time":"2026-08-13T21:12:38.885554227Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"btjdkox503n3"}
70
+ {"time":"2026-08-13T21:13:03.69502194Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"btjdkox503n3"}
71
+ {"time":"2026-08-13T21:13:04.210578234Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"btjdkox503n3"}
72
+ {"time":"2026-08-13T21:13:04.211977276Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"69zdkrji","id":"6(@)"}
73
+ {"time":"2026-08-13T21:13:04.212517763Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"69zdkrji","id":"6(@)"}
74
+ {"time":"2026-08-13T21:13:05.519021818Z","level":"INFO","msg":"handleInformInit: received","streamId":"5yyvte9z","id":"6(@)"}
75
+ {"time":"2026-08-13T21:13:05.781547687Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"5yyvte9z","id":"6(@)"}
76
+ {"time":"2026-08-13T21:13:11.147370358Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"8ljb7gkyfrgm"}
77
+ {"time":"2026-08-13T21:13:38.248378546Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"8ljb7gkyfrgm"}
78
+ {"time":"2026-08-13T21:13:38.969603918Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"8ljb7gkyfrgm"}
79
+ {"time":"2026-08-13T21:13:38.970854991Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"5yyvte9z","id":"6(@)"}
80
+ {"time":"2026-08-13T21:13:38.971319805Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"5yyvte9z","id":"6(@)"}
81
+ {"time":"2026-08-13T21:13:40.112984858Z","level":"INFO","msg":"handleInformInit: received","streamId":"etbhfswt","id":"6(@)"}
82
+ {"time":"2026-08-13T21:13:40.374066248Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"etbhfswt","id":"6(@)"}
83
+ {"time":"2026-08-13T21:13:45.77023074Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"y1z3ogdatulo"}
84
+ {"time":"2026-08-13T21:14:12.750151439Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"y1z3ogdatulo"}
85
+ {"time":"2026-08-13T21:14:13.738994621Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"y1z3ogdatulo"}
86
+ {"time":"2026-08-13T21:14:13.739800429Z","level":"INFO","msg":"handleInformFinish: finish message received","streamId":"etbhfswt","id":"6(@)"}
87
+ {"time":"2026-08-13T21:14:13.74128316Z","level":"INFO","msg":"handleInformFinish: stream closed","streamId":"etbhfswt","id":"6(@)"}
88
+ {"time":"2026-08-13T21:14:33.07143742Z","level":"INFO","msg":"handleInformInit: received","streamId":"vouvkqbm","id":"6(@)"}
89
+ {"time":"2026-08-13T21:14:33.432731087Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"vouvkqbm","id":"6(@)"}
90
+ {"time":"2026-08-13T21:14:38.883290826Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"m1t6sbtmcgac"}
91
+ {"time":"2026-08-13T21:15:04.878189732Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"m1t6sbtmcgac"}
92
+ {"time":"2026-08-13T21:15:05.414751942Z","level":"INFO","msg":"connection: cancelling request","id":"6(@)","requestId":"m1t6sbtmcgac"}
93
+ {"time":"2026-08-13T21:15:07.242042844Z","level":"INFO","msg":"connection: closing","id":"6(@)"}
94
+ {"time":"2026-08-13T21:15:07.24213917Z","level":"INFO","msg":"connection: closed successfully","id":"6(@)"}
95
+ {"time":"2026-08-13T21:15:07.242050444Z","level":"INFO","msg":"processOutgoingData: finished","id":"6(@)"}
96
+ {"time":"2026-08-13T21:15:07.242164062Z","level":"INFO","msg":"connection: ManageConnectionData: connection closed","id":"6(@)"}
97
+ {"time":"2026-08-13T21:15:21.224912597Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"7(@)"}
98
+ {"time":"2026-08-13T21:15:21.456878232Z","level":"INFO","msg":"handleInformInit: received","streamId":"bdgno22l","id":"7(@)"}
99
+ {"time":"2026-08-13T21:15:21.716846245Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"bdgno22l","id":"7(@)"}
100
+ {"time":"2026-08-13T21:15:27.078470483Z","level":"INFO","msg":"connection: cancelling request","id":"7(@)","requestId":"7nz3jdwc0fg3"}
zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug-internal.log ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"time":"2026-08-13T21:15:21.457059839Z","level":"INFO","msg":"wandb-core"}
2
+ {"time":"2026-08-13T21:15:21.457218835Z","level":"INFO","msg":"stream: starting","core version":"0.28.1"}
3
+ {"time":"2026-08-13T21:15:21.71665521Z","level":"INFO","msg":"stream: created new stream","id":"bdgno22l"}
4
+ {"time":"2026-08-13T21:15:21.716724793Z","level":"INFO","msg":"handler: started"}
5
+ {"time":"2026-08-13T21:15:21.716834966Z","level":"INFO","msg":"stream: started"}
6
+ {"time":"2026-08-13T21:15:21.716845775Z","level":"INFO","msg":"writer: started","stream_id":"bdgno22l"}
7
+ {"time":"2026-08-13T21:15:21.716864355Z","level":"INFO","msg":"sender: started"}
8
+ {"time":"2026-08-13T21:15:22.087946715Z","level":"INFO","msg":"filestream: sending request","total_files":1,"console_offset":0,"console_lines":1}
9
+ {"time":"2026-08-13T21:15:22.187941633Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
10
+ {"time":"2026-08-13T21:15:33.902773632Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2617}
11
+ {"time":"2026-08-13T21:15:33.902804288Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
12
+ {"time":"2026-08-13T21:15:33.903189126Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":2650}
13
+ {"time":"2026-08-13T21:15:33.903223176Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":1}
14
+ {"time":"2026-08-13T21:15:33.905188752Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3405}
15
+ {"time":"2026-08-13T21:15:33.905644326Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":109}
16
+ {"time":"2026-08-13T21:15:33.905737177Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":3547}
17
+ {"time":"2026-08-13T21:15:33.905849936Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":11}
18
+ {"time":"2026-08-13T21:15:33.907613871Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":4244}
19
+ {"time":"2026-08-13T21:15:33.914808342Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":2917}
20
+ {"time":"2026-08-13T21:15:33.91681943Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7726}
21
+ {"time":"2026-08-13T21:15:33.917089153Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":83}
22
+ {"time":"2026-08-13T21:15:33.917182957Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":7844}
23
+ {"time":"2026-08-13T21:15:33.91727044Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":13}
24
+ {"time":"2026-08-13T21:15:33.919229048Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":8663}
25
+ {"time":"2026-08-13T21:15:33.919463562Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":61}
26
+ {"time":"2026-08-13T21:15:33.92636457Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":9853}
27
+ {"time":"2026-08-13T21:15:33.926563588Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":8}
28
+ {"time":"2026-08-13T21:15:33.92776116Z","level":"INFO","msg":"flowcontrol: backed up, offloading to disk","recordNumber":10322}
29
+ {"time":"2026-08-13T21:15:33.927881025Z","level":"INFO","msg":"flowcontrol: unblocked","totalOffloaded":18}
30
+ {"time":"2026-08-13T21:15:37.112579744Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":0,"history_lines":2,"events_offset":0,"events_lines":1,"console_offset":1,"console_lines":5,"uploaded_len":2}
31
+ {"time":"2026-08-13T21:15:37.764424515Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
32
+ {"time":"2026-08-13T21:15:52.106707323Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":2,"history_lines":3,"events_offset":1,"events_lines":2,"console_offset":3,"console_lines":1}
33
+ {"time":"2026-08-13T21:15:53.006564044Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug.log ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_setup.py:_flush():81] Current SDK version is 0.28.1
2
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_setup.py:_flush():81] Configure stats pid to 52372
3
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_setup.py:_flush():81] Loading settings from environment variables
4
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:setup_run_log_directory():729] Logging user logs to /mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug.log
5
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:setup_run_log_directory():730] Logging internal logs to /mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/wandb/run-20260813_211521-bdgno22l/logs/debug-internal.log
6
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():772] calling init triggers
7
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():777] wandb.init called with sweep_config: {}
8
+ config: {'_wandb': {}}
9
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():820] starting backend
10
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():826] Connected to an existing wandb-core service via WANDB_SERVICE
11
+ 2026-08-13 21:15:21,455 INFO MainThread:52372 [wandb_init.py:init():835] sending inform_init request
12
+ 2026-08-13 21:15:21,717 INFO MainThread:52372 [wandb_init.py:init():840] backend started and connected
13
+ 2026-08-13 21:15:21,720 INFO MainThread:52372 [wandb_init.py:init():910] updated telemetry
14
+ 2026-08-13 21:15:21,727 INFO MainThread:52372 [wandb_init.py:init():933] communicating run to backend with 90.0 second timeout
15
+ 2026-08-13 21:15:22,001 INFO MainThread:52372 [wandb_init.py:init():978] starting run threads in backend
16
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_console_start():2621] atexit reg
17
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_redirect():2471] redirect: wrap_raw
18
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_redirect():2540] Wrapping output streams.
19
+ 2026-08-13 21:15:22,074 INFO MainThread:52372 [wandb_run.py:_redirect():2563] Redirects installed.
20
+ 2026-08-13 21:15:22,077 INFO MainThread:52372 [wandb_init.py:init():1016] run started, returning control to user process
21
+ 2026-08-13 21:15:22,078 INFO MainThread:52372 [wandb_run.py:_config_callback():1346] config_cb None None {'transformers_version': '5.16.0.dev0', 'architectures': None, 'output_hidden_states': False, 'return_dict': True, 'dtype': None, 'chunk_size_feed_forward': 0, 'is_encoder_decoder': False, 'id2label': {0: 'LABEL_0', 1: 'LABEL_1'}, 'label2id': {'LABEL_0': 0, 'LABEL_1': 1}, 'problem_type': None, 'vocab_size': 4096, 'hidden_size': 128, 'intermediate_size': 256, 'num_hidden_layers': 100, 'num_attention_heads': 4, 'num_key_value_heads': 4, 'hidden_act': 'silu', 'max_position_embeddings': 512, 'initializer_range': 0.02, 'rms_norm_eps': 1e-06, 'use_cache': False, 'pad_token_id': 0, 'bos_token_id': 1, 'eos_token_id': 2, 'pretraining_tp': 1, 'tie_word_embeddings': True, 'rope_parameters': {'rope_theta': 10000.0, 'rope_type': 'default'}, 'attention_bias': False, 'attention_dropout': 0.0, 'mlp_bias': False, 'head_dim': 32, '_name_or_path': '', 'tokenizer_name': 'w-ahmad/tiny-stories-tokenizer', 'mlp_type': 'glu', 'activation': 'linear', 'waleed_beta': 10.0, 'model_type': 'tiny_llama', 'output_attentions': False, 'output_dir': 'out/glu-linear-100L_trash_run', 'per_device_train_batch_size': 64, 'num_train_epochs': 1, 'max_steps': 2700, 'learning_rate': 9e-05, 'lr_scheduler_type': 'constant_with_warmup', 'lr_scheduler_kwargs': None, 'warmup_steps': 50, 'optim': 'adamw_torch_fused', 'optim_args': None, 'weight_decay': 0.0, 'adam_beta1': 0.9, 'adam_beta2': 0.999, 'adam_epsilon': 1e-08, 'optim_target_modules': None, 'gradient_accumulation_steps': 1, 'average_tokens_across_devices': True, 'max_grad_norm': 1.0, 'label_smoothing_factor': 0.0, 'bf16': True, 'fp16': False, 'bf16_full_eval': False, 'fp16_full_eval': False, 'tf32': None, 'gradient_checkpointing': False, 'gradient_checkpointing_kwargs': None, 'torch_compile': False, 'torch_compile_backend': None, 'torch_compile_mode': None, 'use_liger_kernel': False, 'liger_kernel_config': None, 'neftune_noise_alpha': None, 'torch_empty_cache_steps': None, 'auto_find_batch_size': False, 'logging_strategy': 'steps', 'logging_steps': 20, 'logging_first_step': False, 'log_on_each_node': True, 'logging_nan_inf_filter': True, 'include_num_input_tokens_seen': 'no', 'log_level': 'passive', 'log_level_replica': 'warning', 'disable_tqdm': False, 'report_to': ['wandb'], 'run_name': 'LM-glu-linear-100L-16.9M-20260813-211520', 'project': 'huggingface', 'trackio_space_id': None, 'trackio_bucket_id': None, 'trackio_static_space_id': None, 'eval_strategy': 'steps', 'eval_steps': 2498, 'eval_delay': 0, 'per_device_eval_batch_size': 1024, 'prediction_loss_only': False, 'eval_on_start': False, 'eval_do_concat_batches': True, 'eval_use_gather_object': False, 'eval_accumulation_steps': None, 'include_for_metrics': [], 'batch_eval_metrics': False, 'save_only_model': False, 'save_strategy': 'steps', 'save_steps': 100, 'save_on_each_node': False, 'save_total_limit': None, 'enable_jit_checkpoint': False, 'push_to_hub': False, 'hub_token': '<HUB_TOKEN>', 'hub_private_repo': None, 'hub_model_id': 'w-ahmad/6L-glu-linear-100L', 'hub_strategy': 'every_save', 'hub_always_push': False, 'hub_revision': None, 'load_best_model_at_end': False, 'metric_for_best_model': None, 'greater_is_better': None, 'ignore_data_skip': False, 'restore_callback_states_from_checkpoint': False, 'full_determinism': False, 'seed': 42, 'data_seed': 42, 'use_cpu': False, 'accelerator_config': {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}, 'parallelism_config': None, 'dataloader_drop_last': False, 'dataloader_num_workers': 0, 'dataloader_pin_memory': True, 'dataloader_persistent_workers': False, 'dataloader_prefetch_factor': None, 'dataloader_multiprocessing_context': None, 'dataloader_in_order': True, 'remove_unused_columns': False, 'label_names': None, 'train_sampling_strategy': 'random', 'length_column_name': 'length', 'ddp_find_unused_parameters': None, 'ddp_bucket_cap_mb': None, 'ddp_broadcast_buffers': None, 'ddp_static_graph': None, 'ddp_backend': None, 'ddp_timeout': 1800, 'fsdp': None, 'fsdp_config': None, 'deepspeed': None, 'debug': [], 'skip_memory_metrics': True, 'do_train': False, 'do_eval': True, 'do_predict': False, 'resume_from_checkpoint': None, 'local_rank': -1}
22
+ 2026-08-13 21:15:22,082 INFO MainThread:52372 [wandb_config.py:__setitem__():155] [no run ID] config set model/num_parameters = 16934016 - <bound method Run._config_callback of <wandb.sdk.wandb_run.Run object at 0x15235c33c510>>
23
+ 2026-08-13 21:15:22,082 INFO MainThread:52372 [wandb_run.py:_config_callback():1346] config_cb model/num_parameters 16934016 None
zain/Activation/wandb/run-20260813_211521-bdgno22l/run-bdgno22l.wandb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ece0f55ea9c52b047f9cd363b24f56e42f5a3adb5fc7b623a2089361224a2ed9
3
+ size 6356992