Auto upload zain 2026-08-18T17:31:44.052752
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- zain/Activation/README.md +1 -0
- zain/Activation/__pycache__/exp.cpython-311.pyc +0 -0
- zain/Activation/exp.py +953 -0
- zain/Activation/grad.py +571 -0
- zain/Activation/llm_analyzer_wandb.py +1307 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/config.json +37 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/model.safetensors +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/optimizer.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/rng_state.pth +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/scheduler.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/tokenizer.json +0 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/tokenizer_config.json +13 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/trainer_state.json +77 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-100/training_args.bin +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/config.json +37 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/model.safetensors +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/optimizer.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/rng_state.pth +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/scheduler.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/tokenizer.json +0 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/tokenizer_config.json +13 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/trainer_state.json +120 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-200/training_args.bin +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/config.json +37 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/model.safetensors +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/optimizer.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/rng_state.pth +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/scheduler.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/tokenizer.json +0 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/tokenizer_config.json +13 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/trainer_state.json +163 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-300/training_args.bin +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/config.json +37 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/model.safetensors +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/optimizer.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/rng_state.pth +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/scheduler.pt +3 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/tokenizer.json +0 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/tokenizer_config.json +13 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/trainer_state.json +206 -0
- zain/Activation/out/mlp-linear-3L_run/checkpoint-400/training_args.bin +3 -0
- zain/Activation/out/mlp-linear-3L_run/training_log.jsonl +29 -0
- zain/Activation/sweep.py +217 -0
- zain/Activation/train.py +122 -0
- zain/Activation/wandb/debug-internal.log +15 -0
- zain/Activation/wandb/debug.log +23 -0
- zain/Activation/wandb/run-20260818_173055-ojtyk5jg/files/output.log +42 -0
- zain/Activation/wandb/run-20260818_173055-ojtyk5jg/files/requirements.txt +149 -0
- zain/Activation/wandb/run-20260818_173055-ojtyk5jg/files/wandb-metadata.json +169 -0
- zain/Activation/wandb/run-20260818_173055-ojtyk5jg/logs/debug-core.log +8 -0
zain/Activation/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =====================================================================
|
| 2 |
+
# exp.py
|
| 3 |
+
# =====================================================================
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
import json
|
| 9 |
+
import re
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from itertools import chain
|
| 12 |
+
from typing import Dict, Callable, Optional, List, Any, Tuple
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
from transformers import (
|
| 17 |
+
LlamaConfig,
|
| 18 |
+
LlamaPreTrainedModel,
|
| 19 |
+
Trainer,
|
| 20 |
+
TrainerCallback,
|
| 21 |
+
TrainingArguments,
|
| 22 |
+
DataCollatorForLanguageModeling,
|
| 23 |
+
AutoTokenizer,
|
| 24 |
+
set_seed,
|
| 25 |
+
)
|
| 26 |
+
from transformers.models.llama.modeling_llama import (
|
| 27 |
+
LlamaAttention,
|
| 28 |
+
LlamaRMSNorm,
|
| 29 |
+
LlamaRotaryEmbedding,
|
| 30 |
+
)
|
| 31 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 32 |
+
from datasets import load_dataset
|
| 33 |
+
from huggingface_hub import snapshot_download
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# =============================================================================
|
| 37 |
+
# 1. ACTIVATION REGISTRY
|
| 38 |
+
# =============================================================================
|
| 39 |
+
|
| 40 |
+
class GLUActivationRegistry:
|
| 41 |
+
_registry: Dict[str, Callable[[torch.Tensor], torch.Tensor]] = {}
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def register(cls, name: str, fn: Callable[[torch.Tensor], torch.Tensor]) -> None:
|
| 45 |
+
cls._registry[name] = fn
|
| 46 |
+
|
| 47 |
+
@classmethod
|
| 48 |
+
def get(cls, name: str) -> Callable[[torch.Tensor], torch.Tensor]:
|
| 49 |
+
if name not in cls._registry:
|
| 50 |
+
raise KeyError(
|
| 51 |
+
f"Activation '{name}' not found. Available: {list(cls._registry.keys())}"
|
| 52 |
+
)
|
| 53 |
+
return cls._registry[name]
|
| 54 |
+
|
| 55 |
+
# Built-ins
|
| 56 |
+
GLUActivationRegistry.register("silu", nn.functional.silu)
|
| 57 |
+
GLUActivationRegistry.register("swish", nn.functional.silu)
|
| 58 |
+
GLUActivationRegistry.register("relu", nn.functional.relu)
|
| 59 |
+
GLUActivationRegistry.register("gelu", nn.functional.gelu)
|
| 60 |
+
GLUActivationRegistry.register("sigmoid", torch.sigmoid)
|
| 61 |
+
GLUActivationRegistry.register("tanh", torch.tanh)
|
| 62 |
+
GLUActivationRegistry.register("softplus", nn.functional.softplus)
|
| 63 |
+
GLUActivationRegistry.register("linear", lambda x: x)
|
| 64 |
+
GLUActivationRegistry.register("s10", lambda x: x * x * torch.sigmoid(x))
|
| 65 |
+
GLUActivationRegistry.register("w1a", lambda x: x * torch.tanh(x))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# =============================================================================
|
| 69 |
+
# 2. CONFIG
|
| 70 |
+
# =============================================================================
|
| 71 |
+
|
| 72 |
+
class TinyLlamaConfig(LlamaConfig):
|
| 73 |
+
model_type = "tiny_llama"
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
mlp_type: str = "glu",
|
| 78 |
+
activation: str = "silu",
|
| 79 |
+
waleed_beta: float = 10.0,
|
| 80 |
+
powlu_m: float = 3.0, # <-- NEW: PowLU hyperparameter
|
| 81 |
+
**kwargs
|
| 82 |
+
):
|
| 83 |
+
super().__init__(**kwargs)
|
| 84 |
+
self.mlp_type = mlp_type
|
| 85 |
+
self.activation = activation
|
| 86 |
+
self.waleed_beta = waleed_beta
|
| 87 |
+
self.powlu_m = powlu_m # <-- store it
|
| 88 |
+
if self.num_key_value_heads != self.num_attention_heads:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
f"Pure MHA required: num_key_value_heads ({self.num_key_value_heads}) "
|
| 91 |
+
f"must equal num_attention_heads ({self.num_attention_heads})."
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# =============================================================================
|
| 96 |
+
# 3. MODEL (with PowLU)
|
| 97 |
+
# =============================================================================
|
| 98 |
+
|
| 99 |
+
class TinyLlamaMLP(nn.Module):
|
| 100 |
+
override_active = False
|
| 101 |
+
override_value = -100.0
|
| 102 |
+
|
| 103 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.hidden_size = config.hidden_size
|
| 106 |
+
self.intermediate_size = config.intermediate_size
|
| 107 |
+
self.mlp_type = config.mlp_type
|
| 108 |
+
self.activation_name = config.activation
|
| 109 |
+
self.waleed_beta = getattr(config, "waleed_beta", 10.0)
|
| 110 |
+
self.powlu_m = getattr(config, "powlu_m", 3.0) # <-- store m
|
| 111 |
+
|
| 112 |
+
if self.mlp_type == "glu":
|
| 113 |
+
effective_intermediate = self.intermediate_size
|
| 114 |
+
elif self.mlp_type == "mlp":
|
| 115 |
+
effective_intermediate = int(self.intermediate_size * 1.5)
|
| 116 |
+
print(f"[MLP] Auto‑scaled intermediate_size from {self.intermediate_size} to {effective_intermediate}")
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"Unknown mlp_type: {self.mlp_type}")
|
| 119 |
+
|
| 120 |
+
self.effective_intermediate = effective_intermediate
|
| 121 |
+
|
| 122 |
+
if self.mlp_type == "glu":
|
| 123 |
+
self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 124 |
+
self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 125 |
+
else:
|
| 126 |
+
self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 127 |
+
|
| 128 |
+
self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
|
| 129 |
+
|
| 130 |
+
# ---- Activation flags ----
|
| 131 |
+
self.is_powlu = (self.activation_name == "powlu") # <-- NEW
|
| 132 |
+
self.is_situglu = self.activation_name in ("situglu", "situglu_low")
|
| 133 |
+
self.is_waleed = self.activation_name in ("waleed", "waleedglu_low")
|
| 134 |
+
self.is_waleed10 = self.activation_name in ("waleed10", "silu-waleed10")
|
| 135 |
+
self.has_sigmoid_gate = self.activation_name.startswith("situglu")
|
| 136 |
+
|
| 137 |
+
# ---- Activation function (for non-PowLU) ----
|
| 138 |
+
if self.mlp_type == "glu":
|
| 139 |
+
if self.is_powlu:
|
| 140 |
+
# PowLU handled in forward, no act_fn needed
|
| 141 |
+
self.act_fn = None
|
| 142 |
+
elif self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
|
| 143 |
+
self.act_fn = None # custom handling
|
| 144 |
+
elif self.activation_name == "waleed10":
|
| 145 |
+
self.act_fn = GLUActivationRegistry.get("linear")
|
| 146 |
+
elif self.activation_name == "silu-waleed10":
|
| 147 |
+
self.act_fn = GLUActivationRegistry.get("silu")
|
| 148 |
+
else:
|
| 149 |
+
self.act_fn = GLUActivationRegistry.get(self.activation_name)
|
| 150 |
+
else: # mlp
|
| 151 |
+
if self.is_powlu:
|
| 152 |
+
raise ValueError("PowLU is only supported with mlp_type='glu'")
|
| 153 |
+
if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
|
| 154 |
+
raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
|
| 155 |
+
elif self.activation_name == "waleed10":
|
| 156 |
+
self.act_fn = GLUActivationRegistry.get("linear")
|
| 157 |
+
elif self.activation_name == "silu-waleed10":
|
| 158 |
+
self.act_fn = GLUActivationRegistry.get("silu")
|
| 159 |
+
else:
|
| 160 |
+
self.act_fn = GLUActivationRegistry.get(self.activation_name)
|
| 161 |
+
|
| 162 |
+
# beta values for situglu/waleed
|
| 163 |
+
if self.activation_name in ("situglu_low", "waleedglu_low"):
|
| 164 |
+
self.beta1 = 2.5
|
| 165 |
+
self.beta2 = 4.0
|
| 166 |
+
else:
|
| 167 |
+
self.beta1 = 4.0
|
| 168 |
+
self.beta2 = 25.0
|
| 169 |
+
|
| 170 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 171 |
+
if self.mlp_type == "glu":
|
| 172 |
+
gate = self.gate_proj(x)
|
| 173 |
+
up = self.up_proj(x)
|
| 174 |
+
|
| 175 |
+
# ----- PowLU branch (FIXED: safe sqrt/pow to avoid NaN-gradient leak) -----
|
| 176 |
+
if self.is_powlu:
|
| 177 |
+
m = self.powlu_m
|
| 178 |
+
sig_gate = torch.sigmoid(gate)
|
| 179 |
+
pos_mask = gate > 0
|
| 180 |
+
|
| 181 |
+
# Clamp ONLY for the pow/sqrt computation so negative values never
|
| 182 |
+
# reach sqrt(); the real `gate` tensor is left untouched everywhere else.
|
| 183 |
+
safe_gate = torch.clamp(gate, min=1e-6)
|
| 184 |
+
|
| 185 |
+
# For positive: gate^(m/(sqrt(gate)+1)) * sigmoid(gate)
|
| 186 |
+
powlu_pos = safe_gate ** (m / (torch.sqrt(safe_gate) + 1)) * sig_gate
|
| 187 |
+
# For non-positive: gate * sigmoid(gate) (= SiLU)
|
| 188 |
+
powlu_neg = gate * sig_gate
|
| 189 |
+
activated_gate = torch.where(pos_mask, powlu_pos, powlu_neg)
|
| 190 |
+
hidden = activated_gate * up
|
| 191 |
+
|
| 192 |
+
# ----- situglu / waleed branches (unchanged) -----
|
| 193 |
+
elif self.is_situglu or self.is_waleed:
|
| 194 |
+
if self.has_sigmoid_gate:
|
| 195 |
+
gate = self.beta1 * torch.tanh(gate / self.beta1) * torch.sigmoid(gate)
|
| 196 |
+
else:
|
| 197 |
+
gate = self.beta1 * torch.tanh(gate / self.beta1)
|
| 198 |
+
up = self.beta2 * torch.tanh(up / self.beta2)
|
| 199 |
+
hidden = gate * up
|
| 200 |
+
|
| 201 |
+
# ----- Standard GLU (ReLU, GELU, SiLU, etc.) -----
|
| 202 |
+
else:
|
| 203 |
+
hidden = self.act_fn(gate) * up
|
| 204 |
+
|
| 205 |
+
out = self.down_proj(hidden)
|
| 206 |
+
|
| 207 |
+
else: # mlp
|
| 208 |
+
hidden = self.act_fn(self.up_proj(x))
|
| 209 |
+
out = self.down_proj(hidden)
|
| 210 |
+
|
| 211 |
+
# Optional Waleed clipping after down projection
|
| 212 |
+
if self.is_waleed10:
|
| 213 |
+
out = self.waleed_beta * torch.tanh(out / self.waleed_beta)
|
| 214 |
+
|
| 215 |
+
# Override hook (unchanged)
|
| 216 |
+
if TinyLlamaMLP.override_active and out.requires_grad:
|
| 217 |
+
out.register_hook(lambda grad: TinyLlamaMLP.override_value * torch.ones_like(grad))
|
| 218 |
+
|
| 219 |
+
return out
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ----------------------------------------------------------------------------
|
| 223 |
+
# DECODER LAYER, ATTENTION MASK, MODEL (unchanged)
|
| 224 |
+
# ----------------------------------------------------------------------------
|
| 225 |
+
|
| 226 |
+
class TinyLlamaDecoderLayer(nn.Module):
|
| 227 |
+
def __init__(self, config: TinyLlamaConfig, layer_idx: int):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.hidden_size = config.hidden_size
|
| 230 |
+
self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
|
| 231 |
+
self.mlp = TinyLlamaMLP(config)
|
| 232 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 233 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 234 |
+
self.residual_pre_attn = nn.Identity()
|
| 235 |
+
self.residual_post_attn = nn.Identity()
|
| 236 |
+
self.residual_post_mlp = nn.Identity()
|
| 237 |
+
|
| 238 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None, position_embeddings=None, **kwargs):
|
| 239 |
+
residual = hidden_states
|
| 240 |
+
hidden_states = self.residual_pre_attn(hidden_states)
|
| 241 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 242 |
+
attn_out = self.self_attn(
|
| 243 |
+
hidden_states=hidden_states,
|
| 244 |
+
attention_mask=attention_mask,
|
| 245 |
+
position_ids=position_ids,
|
| 246 |
+
position_embeddings=position_embeddings,
|
| 247 |
+
)[0]
|
| 248 |
+
hidden_states = residual + attn_out
|
| 249 |
+
hidden_states = self.residual_post_attn(hidden_states)
|
| 250 |
+
|
| 251 |
+
residual = hidden_states
|
| 252 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 253 |
+
hidden_states = self.mlp(hidden_states)
|
| 254 |
+
hidden_states = residual + hidden_states
|
| 255 |
+
hidden_states = self.residual_post_mlp(hidden_states)
|
| 256 |
+
return (hidden_states,)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _build_causal_mask(attention_mask, seq_len, dtype, device):
|
| 260 |
+
min_value = torch.finfo(dtype).min
|
| 261 |
+
causal = torch.full((seq_len, seq_len), fill_value=min_value, dtype=dtype, device=device)
|
| 262 |
+
causal = torch.triu(causal, diagonal=1)
|
| 263 |
+
causal = causal[None, None, :, :]
|
| 264 |
+
if attention_mask is None:
|
| 265 |
+
batch_size = 1
|
| 266 |
+
return causal.expand(batch_size, 1, seq_len, seq_len)
|
| 267 |
+
batch_size = attention_mask.shape[0]
|
| 268 |
+
causal = causal.expand(batch_size, 1, seq_len, seq_len).clone()
|
| 269 |
+
padding = attention_mask[:, None, None, :].to(device) == 0
|
| 270 |
+
causal = causal.masked_fill(padding, min_value)
|
| 271 |
+
return causal
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
_MASK_PRINTED = False
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class TinyLlamaModel(LlamaPreTrainedModel):
|
| 278 |
+
config_class = TinyLlamaConfig
|
| 279 |
+
|
| 280 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 281 |
+
super().__init__(config)
|
| 282 |
+
self.padding_idx = config.pad_token_id
|
| 283 |
+
self.vocab_size = config.vocab_size
|
| 284 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 285 |
+
self.layers = nn.ModuleList([TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 286 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 287 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 288 |
+
self.post_init()
|
| 289 |
+
|
| 290 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None, return_dict=None, **kwargs):
|
| 291 |
+
global _MASK_PRINTED
|
| 292 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 293 |
+
if inputs_embeds is None:
|
| 294 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 295 |
+
if position_ids is None:
|
| 296 |
+
seq_len = inputs_embeds.shape[1]
|
| 297 |
+
position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0).expand(inputs_embeds.shape[0], -1)
|
| 298 |
+
hidden_states = inputs_embeds
|
| 299 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 300 |
+
seq_len = hidden_states.shape[1]
|
| 301 |
+
causal_mask = _build_causal_mask(attention_mask, seq_len, hidden_states.dtype, hidden_states.device)
|
| 302 |
+
if not _MASK_PRINTED:
|
| 303 |
+
print("[INFO] Causal mask (float with -inf) applied to all attention layers.")
|
| 304 |
+
_MASK_PRINTED = True
|
| 305 |
+
for decoder_layer in self.layers:
|
| 306 |
+
layer_outputs = decoder_layer(
|
| 307 |
+
hidden_states,
|
| 308 |
+
attention_mask=causal_mask,
|
| 309 |
+
position_ids=position_ids,
|
| 310 |
+
position_embeddings=position_embeddings,
|
| 311 |
+
)
|
| 312 |
+
hidden_states = layer_outputs[0]
|
| 313 |
+
hidden_states = self.norm(hidden_states)
|
| 314 |
+
if not return_dict:
|
| 315 |
+
return (hidden_states,)
|
| 316 |
+
return {"last_hidden_state": hidden_states, "hidden_states": None, "attentions": None}
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class TinyLlamaForCausalLM(LlamaPreTrainedModel):
|
| 320 |
+
config_class = TinyLlamaConfig
|
| 321 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 322 |
+
|
| 323 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 324 |
+
super().__init__(config)
|
| 325 |
+
self.model = TinyLlamaModel(config)
|
| 326 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 327 |
+
if config.tie_word_embeddings:
|
| 328 |
+
self.lm_head.weight = self.model.embed_tokens.weight
|
| 329 |
+
self.post_init()
|
| 330 |
+
|
| 331 |
+
def get_input_embeddings(self):
|
| 332 |
+
return self.model.embed_tokens
|
| 333 |
+
|
| 334 |
+
def set_input_embeddings(self, value):
|
| 335 |
+
self.model.embed_tokens = value
|
| 336 |
+
|
| 337 |
+
def get_output_embeddings(self):
|
| 338 |
+
return self.lm_head
|
| 339 |
+
|
| 340 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
|
| 341 |
+
labels=None, return_dict=None, **kwargs):
|
| 342 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 343 |
+
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids,
|
| 344 |
+
inputs_embeds=inputs_embeds, return_dict=return_dict)
|
| 345 |
+
hidden_states = outputs["last_hidden_state"] if return_dict else outputs[0]
|
| 346 |
+
logits = self.lm_head(hidden_states)
|
| 347 |
+
loss = None
|
| 348 |
+
if labels is not None:
|
| 349 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 350 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 351 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 352 |
+
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
|
| 353 |
+
if not return_dict:
|
| 354 |
+
output = (logits,) + outputs[1:]
|
| 355 |
+
return (loss,) + output if loss is not None else output
|
| 356 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None, hidden_states=None, attentions=None)
|
| 357 |
+
|
| 358 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
|
| 359 |
+
if past_key_values:
|
| 360 |
+
input_ids = input_ids[:, -1:]
|
| 361 |
+
position_ids = kwargs.get("position_ids")
|
| 362 |
+
if attention_mask is not None and position_ids is None:
|
| 363 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 364 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 365 |
+
if past_key_values:
|
| 366 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
| 367 |
+
return {
|
| 368 |
+
"input_ids": input_ids,
|
| 369 |
+
"position_ids": position_ids,
|
| 370 |
+
"past_key_values": past_key_values,
|
| 371 |
+
"attention_mask": attention_mask,
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# =============================================================================
|
| 376 |
+
# 4. HF CHECKPOINT FETCHER (unchanged)
|
| 377 |
+
# =============================================================================
|
| 378 |
+
|
| 379 |
+
def fetch_latest_checkpoint_from_hub(
|
| 380 |
+
repo_id: str,
|
| 381 |
+
subpath: str,
|
| 382 |
+
variant: str,
|
| 383 |
+
checkpoint_step: Optional[int] = None
|
| 384 |
+
) -> str:
|
| 385 |
+
remote_prefix = f"{subpath}/{variant}_run" if subpath else f"{variant}_run"
|
| 386 |
+
if checkpoint_step is not None:
|
| 387 |
+
full_remote_path = f"{remote_prefix}/checkpoint-{checkpoint_step}"
|
| 388 |
+
print(f"[Hub] Fetching specific checkpoint: {repo_id}/{full_remote_path}")
|
| 389 |
+
local_root = snapshot_download(
|
| 390 |
+
repo_id=repo_id,
|
| 391 |
+
allow_patterns=[f"{full_remote_path}/*"],
|
| 392 |
+
local_dir_use_symlinks=False,
|
| 393 |
+
)
|
| 394 |
+
checkpoint_local_path = os.path.join(local_root, full_remote_path)
|
| 395 |
+
if not os.path.exists(checkpoint_local_path):
|
| 396 |
+
raise RuntimeError(f"Downloaded checkpoint not found at {checkpoint_local_path}")
|
| 397 |
+
return checkpoint_local_path
|
| 398 |
+
|
| 399 |
+
print(f"[Hub] Downloading entire run folder: {repo_id}/{remote_prefix}")
|
| 400 |
+
local_root = snapshot_download(
|
| 401 |
+
repo_id=repo_id,
|
| 402 |
+
allow_patterns=[f"{remote_prefix}/*"],
|
| 403 |
+
local_dir_use_symlinks=False,
|
| 404 |
+
)
|
| 405 |
+
run_local_path = os.path.join(local_root, remote_prefix)
|
| 406 |
+
if not os.path.exists(run_local_path):
|
| 407 |
+
raise RuntimeError(f"Run folder not found at {run_local_path}")
|
| 408 |
+
|
| 409 |
+
checkpoints = []
|
| 410 |
+
for item in os.listdir(run_local_path):
|
| 411 |
+
if item.startswith("checkpoint-") and os.path.isdir(os.path.join(run_local_path, item)):
|
| 412 |
+
match = re.match(r"checkpoint-(\d+)", item)
|
| 413 |
+
if match:
|
| 414 |
+
step = int(match.group(1))
|
| 415 |
+
checkpoints.append((step, item))
|
| 416 |
+
|
| 417 |
+
if not checkpoints:
|
| 418 |
+
raise RuntimeError(f"No checkpoint folders found in {run_local_path}")
|
| 419 |
+
|
| 420 |
+
latest_step, latest_name = max(checkpoints, key=lambda x: x[0])
|
| 421 |
+
print(f"[Hub] Latest checkpoint found: step {latest_step}")
|
| 422 |
+
return os.path.join(run_local_path, latest_name)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
# =============================================================================
|
| 426 |
+
# 5. RESUME + FREEZE + OVERRIDE CALLBACK (unchanged)
|
| 427 |
+
# =============================================================================
|
| 428 |
+
|
| 429 |
+
class ResumeFreezeOverrideCallback(TrainerCallback):
|
| 430 |
+
def __init__(self, override_value: Optional[float] = None):
|
| 431 |
+
self.override_value = override_value
|
| 432 |
+
self._trainer = None # Will be set manually
|
| 433 |
+
|
| 434 |
+
def on_train_begin(self, args, state, control, **kwargs):
|
| 435 |
+
# Try multiple ways to get the trainer
|
| 436 |
+
trainer = kwargs.get('trainer')
|
| 437 |
+
if trainer is None:
|
| 438 |
+
trainer = getattr(self, '_trainer', None)
|
| 439 |
+
if trainer is None:
|
| 440 |
+
trainer = getattr(self, 'trainer', None)
|
| 441 |
+
if trainer is None:
|
| 442 |
+
raise ValueError("Trainer not accessible in callback")
|
| 443 |
+
|
| 444 |
+
model = trainer.model
|
| 445 |
+
|
| 446 |
+
# ----- FREEZE ALL EXCEPT MLP PROJECTIONS -----
|
| 447 |
+
for name, param in model.named_parameters():
|
| 448 |
+
if any(x in name for x in ["gate_proj", "up_proj", "down_proj"]):
|
| 449 |
+
param.requires_grad = True
|
| 450 |
+
else:
|
| 451 |
+
param.requires_grad = False
|
| 452 |
+
|
| 453 |
+
trainable_params = [p for p in model.parameters() if p.requires_grad]
|
| 454 |
+
|
| 455 |
+
# ----- REBUILD OPTIMIZER -----
|
| 456 |
+
from torch.optim import AdamW
|
| 457 |
+
new_optimizer = AdamW(
|
| 458 |
+
trainable_params,
|
| 459 |
+
lr=args.learning_rate,
|
| 460 |
+
weight_decay=args.weight_decay,
|
| 461 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 462 |
+
eps=args.adam_epsilon,
|
| 463 |
+
)
|
| 464 |
+
trainer.optimizer = new_optimizer
|
| 465 |
+
|
| 466 |
+
# ----- KEEP EXISTING SCHEDULER (re‑attach) -----
|
| 467 |
+
if trainer.lr_scheduler is not None:
|
| 468 |
+
trainer.lr_scheduler.optimizer = new_optimizer
|
| 469 |
+
|
| 470 |
+
# ----- ACTIVATE OVERRIDE -----
|
| 471 |
+
if self.override_value is not None:
|
| 472 |
+
TinyLlamaMLP.override_active = True
|
| 473 |
+
TinyLlamaMLP.override_value = self.override_value
|
| 474 |
+
print(f"[Override] Activated with value = {self.override_value}")
|
| 475 |
+
else:
|
| 476 |
+
print("[Freeze] MLP projections frozen; no gradient override.")
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
# =============================================================================
|
| 480 |
+
# 6. MONITORING (unchanged)
|
| 481 |
+
# =============================================================================
|
| 482 |
+
|
| 483 |
+
class StatsEngine:
|
| 484 |
+
@staticmethod
|
| 485 |
+
def compute(tensor: torch.Tensor, user_limit: float, dtype_ratio: float) -> Dict[str, float]:
|
| 486 |
+
with torch.no_grad():
|
| 487 |
+
abs_t = tensor.abs()
|
| 488 |
+
dtype_info = torch.finfo(tensor.dtype)
|
| 489 |
+
dtype_limit = dtype_ratio * dtype_info.max if not torch.isinf(torch.tensor(dtype_info.max)) else float("inf")
|
| 490 |
+
return {
|
| 491 |
+
"norm": tensor.norm(2).item(),
|
| 492 |
+
"mean": tensor.mean().item(),
|
| 493 |
+
"std": tensor.std().item(),
|
| 494 |
+
"max_abs": abs_t.max().item(),
|
| 495 |
+
"frac_near_dtype_limit": (abs_t > dtype_limit).float().mean().item() if not math.isinf(dtype_limit) else 0.0,
|
| 496 |
+
"frac_near_user_limit": (abs_t > user_limit).float().mean().item(),
|
| 497 |
+
"min": tensor.min().item(),
|
| 498 |
+
"max": tensor.max().item(),
|
| 499 |
+
"range": tensor.max().item() - tensor.min().item(),
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class StepAccumulator:
|
| 504 |
+
def __init__(self):
|
| 505 |
+
self.tensors: Dict[str, Dict[str, float]] = {}
|
| 506 |
+
|
| 507 |
+
def add(self, name: str, numel: int, stats: Dict[str, float]):
|
| 508 |
+
new_entry = {"numel": numel, **stats}
|
| 509 |
+
existing = self.tensors.get(name)
|
| 510 |
+
self.tensors[name] = new_entry if existing is None else self._merge_entry(existing, new_entry)
|
| 511 |
+
|
| 512 |
+
@staticmethod
|
| 513 |
+
def _merge_entry(a: Dict[str, float], b: Dict[str, float]) -> Dict[str, float]:
|
| 514 |
+
total_n = a["numel"] + b["numel"]
|
| 515 |
+
if total_n == 0:
|
| 516 |
+
return a
|
| 517 |
+
norm = math.sqrt(a["norm"] ** 2 + b["norm"] ** 2)
|
| 518 |
+
max_abs = max(a["max_abs"], b["max_abs"])
|
| 519 |
+
mean = (a["mean"] * a["numel"] + b["mean"] * b["numel"]) / total_n
|
| 520 |
+
ex2 = (a["numel"] * (a["std"] ** 2 + a["mean"] ** 2) + b["numel"] * (b["std"] ** 2 + b["mean"] ** 2)) / total_n
|
| 521 |
+
std = math.sqrt(max(0.0, ex2 - mean ** 2))
|
| 522 |
+
frac_dtype = (a["frac_near_dtype_limit"] * a["numel"] + b["frac_near_dtype_limit"] * b["numel"]) / total_n
|
| 523 |
+
frac_user = (a["frac_near_user_limit"] * a["numel"] + b["frac_near_user_limit"] * b["numel"]) / total_n
|
| 524 |
+
t_min = min(a.get("min", float("inf")), b.get("min", float("inf")))
|
| 525 |
+
t_max = max(a.get("max", float("-inf")), b.get("max", float("-inf")))
|
| 526 |
+
return {
|
| 527 |
+
"numel": total_n,
|
| 528 |
+
"norm": norm,
|
| 529 |
+
"mean": mean,
|
| 530 |
+
"std": std,
|
| 531 |
+
"max_abs": max_abs,
|
| 532 |
+
"frac_near_dtype_limit": frac_dtype,
|
| 533 |
+
"frac_near_user_limit": frac_user,
|
| 534 |
+
"min": t_min,
|
| 535 |
+
"max": t_max,
|
| 536 |
+
"range": t_max - t_min,
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
def clear(self):
|
| 540 |
+
self.tensors.clear()
|
| 541 |
+
|
| 542 |
+
def _aggregate(self, entries: Dict[str, Dict[str, float]]) -> Dict[str, float]:
|
| 543 |
+
if not entries:
|
| 544 |
+
return {}
|
| 545 |
+
numels = [e["numel"] for e in entries.values()]
|
| 546 |
+
total_n = sum(numels)
|
| 547 |
+
norm = math.sqrt(sum(e["norm"] ** 2 for e in entries.values()))
|
| 548 |
+
max_abs = max(e["max_abs"] for e in entries.values())
|
| 549 |
+
mean = sum(e["mean"] * e["numel"] for e in entries.values()) / total_n
|
| 550 |
+
ex2 = sum(e["numel"] * (e["std"] ** 2 + e["mean"] ** 2) for e in entries.values()) / total_n
|
| 551 |
+
std = math.sqrt(max(0.0, ex2 - mean ** 2))
|
| 552 |
+
frac_dtype = sum(e["frac_near_dtype_limit"] * e["numel"] for e in entries.values()) / total_n
|
| 553 |
+
frac_user = sum(e["frac_near_user_limit"] * e["numel"] for e in entries.values()) / total_n
|
| 554 |
+
t_min = min(e.get("min", float("inf")) for e in entries.values())
|
| 555 |
+
t_max = max(e.get("max", float("-inf")) for e in entries.values())
|
| 556 |
+
return {
|
| 557 |
+
"norm": norm,
|
| 558 |
+
"mean": mean,
|
| 559 |
+
"std": std,
|
| 560 |
+
"max_abs": max_abs,
|
| 561 |
+
"frac_near_dtype_limit": frac_dtype,
|
| 562 |
+
"frac_near_user_limit": frac_user,
|
| 563 |
+
"min": t_min,
|
| 564 |
+
"max": t_max,
|
| 565 |
+
"range": t_max - t_min,
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
def get_global_stats(self) -> Dict[str, float]:
|
| 569 |
+
return self._aggregate(self.tensors)
|
| 570 |
+
|
| 571 |
+
def get_layer_stats(self, layer_prefix: str) -> Dict[str, float]:
|
| 572 |
+
entries = {k: v for k, v in self.tensors.items() if k.startswith(layer_prefix + ".")}
|
| 573 |
+
return self._aggregate(entries)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
class HookRegistry:
|
| 577 |
+
def __init__(self, model: nn.Module):
|
| 578 |
+
self.model = model
|
| 579 |
+
self.handles = []
|
| 580 |
+
self.active = False
|
| 581 |
+
|
| 582 |
+
def attach_forward(self, module_patterns, accumulator, user_limit, dtype_ratio):
|
| 583 |
+
for name, module in self.model.named_modules():
|
| 584 |
+
if any(re.search(p, name) for p in module_patterns):
|
| 585 |
+
h = module.register_forward_hook(
|
| 586 |
+
self._make_forward_hook(name, accumulator, user_limit, dtype_ratio)
|
| 587 |
+
)
|
| 588 |
+
self.handles.append(h)
|
| 589 |
+
|
| 590 |
+
def attach_backward(self, param_patterns, accumulator, user_limit, dtype_ratio):
|
| 591 |
+
for name, param in self.model.named_parameters():
|
| 592 |
+
if not param.requires_grad:
|
| 593 |
+
continue
|
| 594 |
+
if param_patterns and not any(re.search(p, name) for p in param_patterns):
|
| 595 |
+
continue
|
| 596 |
+
h = param.register_hook(
|
| 597 |
+
self._make_backward_hook(f"grad.{name}", accumulator, user_limit, dtype_ratio)
|
| 598 |
+
)
|
| 599 |
+
self.handles.append(h)
|
| 600 |
+
|
| 601 |
+
def _make_forward_hook(self, module_name, accumulator, user_limit, dtype_ratio):
|
| 602 |
+
def hook(module, inp, out):
|
| 603 |
+
if not self.active:
|
| 604 |
+
return
|
| 605 |
+
if isinstance(out, dict):
|
| 606 |
+
out = out.get("last_hidden_state")
|
| 607 |
+
if not torch.is_tensor(out):
|
| 608 |
+
return
|
| 609 |
+
stats = StatsEngine.compute(out.detach(), user_limit, dtype_ratio)
|
| 610 |
+
accumulator.add(f"act.{module_name}", out.numel(), stats)
|
| 611 |
+
return hook
|
| 612 |
+
|
| 613 |
+
def _make_backward_hook(self, param_name, accumulator, user_limit, dtype_ratio):
|
| 614 |
+
def hook(grad):
|
| 615 |
+
if not self.active:
|
| 616 |
+
return
|
| 617 |
+
stats = StatsEngine.compute(grad.detach(), user_limit, dtype_ratio)
|
| 618 |
+
accumulator.add(param_name, grad.numel(), stats)
|
| 619 |
+
return hook
|
| 620 |
+
|
| 621 |
+
def set_active(self, active: bool):
|
| 622 |
+
self.active = active
|
| 623 |
+
|
| 624 |
+
def clear(self):
|
| 625 |
+
for h in self.handles:
|
| 626 |
+
h.remove()
|
| 627 |
+
self.handles.clear()
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class StabilityMonitorCallback(TrainerCallback):
|
| 631 |
+
def __init__(
|
| 632 |
+
self,
|
| 633 |
+
model: nn.Module,
|
| 634 |
+
monitor_every_n_steps: int = 10,
|
| 635 |
+
module_patterns: Optional[List[str]] = None,
|
| 636 |
+
param_patterns: Optional[List[str]] = None,
|
| 637 |
+
user_limits: Optional[Dict[str, float]] = None,
|
| 638 |
+
dtype_proximity_ratio: float = 0.9,
|
| 639 |
+
log_scope: Optional[Dict[str, bool]] = None,
|
| 640 |
+
monitor_during_eval: bool = False,
|
| 641 |
+
):
|
| 642 |
+
self.model = model
|
| 643 |
+
self.monitor_every_n_steps = monitor_every_n_steps
|
| 644 |
+
self.module_patterns = module_patterns or [".*mlp.*", ".*residual.*"]
|
| 645 |
+
self.param_patterns = param_patterns or self.module_patterns
|
| 646 |
+
self.user_limits = user_limits or {"grad": 1.0, "param": 100.0, "act": 50.0}
|
| 647 |
+
self.dtype_ratio = dtype_proximity_ratio
|
| 648 |
+
self.log_scope = log_scope or {"global": True, "per_layer": True, "per_tensor": False}
|
| 649 |
+
self.monitor_during_eval = monitor_during_eval
|
| 650 |
+
|
| 651 |
+
self.accumulator = StepAccumulator()
|
| 652 |
+
self.hooks = HookRegistry(model)
|
| 653 |
+
self.hooks.attach_forward(
|
| 654 |
+
self.module_patterns,
|
| 655 |
+
self.accumulator,
|
| 656 |
+
self.user_limits["act"],
|
| 657 |
+
self.dtype_ratio,
|
| 658 |
+
)
|
| 659 |
+
self.hooks.attach_backward(
|
| 660 |
+
self.param_patterns,
|
| 661 |
+
self.accumulator,
|
| 662 |
+
self.user_limits["grad"],
|
| 663 |
+
self.dtype_ratio,
|
| 664 |
+
)
|
| 665 |
+
self.pending_metrics = None
|
| 666 |
+
|
| 667 |
+
def _should_monitor(self, state):
|
| 668 |
+
return state.global_step % self.monitor_every_n_steps == 0
|
| 669 |
+
|
| 670 |
+
def on_step_begin(self, args, state, control, **kwargs):
|
| 671 |
+
if self._should_monitor(state):
|
| 672 |
+
self.accumulator.clear()
|
| 673 |
+
self.hooks.set_active(True)
|
| 674 |
+
|
| 675 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 676 |
+
if not self.hooks.active:
|
| 677 |
+
return
|
| 678 |
+
for name, param in self.model.named_parameters():
|
| 679 |
+
if self.param_patterns and not any(re.search(p, name) for p in self.param_patterns):
|
| 680 |
+
continue
|
| 681 |
+
stats = StatsEngine.compute(param.data, self.user_limits["param"], self.dtype_ratio)
|
| 682 |
+
self.accumulator.add(f"param.{name}", param.numel(), stats)
|
| 683 |
+
self.hooks.set_active(False)
|
| 684 |
+
self.pending_metrics = self._build_metrics()
|
| 685 |
+
|
| 686 |
+
def _kind_of(self, name: str) -> str:
|
| 687 |
+
if name.startswith("act."):
|
| 688 |
+
return "act"
|
| 689 |
+
if name.startswith("grad."):
|
| 690 |
+
return "grad"
|
| 691 |
+
if name.startswith("param."):
|
| 692 |
+
return "param"
|
| 693 |
+
return "other"
|
| 694 |
+
|
| 695 |
+
def _strip_kind(self, name: str) -> str:
|
| 696 |
+
if name.startswith("act."):
|
| 697 |
+
return name[4:]
|
| 698 |
+
if name.startswith(("grad.", "param.")):
|
| 699 |
+
return name[5:]
|
| 700 |
+
return name
|
| 701 |
+
|
| 702 |
+
def _build_metrics(self, scope: str = "train") -> Dict[str, float]:
|
| 703 |
+
metrics = {}
|
| 704 |
+
if self.log_scope.get("global", True):
|
| 705 |
+
by_kind = {}
|
| 706 |
+
for k, v in self.accumulator.tensors.items():
|
| 707 |
+
by_kind.setdefault(self._kind_of(k), {})[k] = v
|
| 708 |
+
for kind, entries in by_kind.items():
|
| 709 |
+
stats = self.accumulator._aggregate(entries)
|
| 710 |
+
for kk, vv in stats.items():
|
| 711 |
+
metrics[f"{scope}/global/{kind}/{kk}"] = vv
|
| 712 |
+
|
| 713 |
+
if self.log_scope.get("per_layer", True):
|
| 714 |
+
layer_prefixes = set()
|
| 715 |
+
for name in self.accumulator.tensors:
|
| 716 |
+
clean = self._strip_kind(name)
|
| 717 |
+
parts = clean.split(".")
|
| 718 |
+
for i, p in enumerate(parts):
|
| 719 |
+
if p == "layers" and i + 1 < len(parts):
|
| 720 |
+
prefix = ".".join(parts[: i + 2])
|
| 721 |
+
layer_prefixes.add(prefix)
|
| 722 |
+
for prefix in layer_prefixes:
|
| 723 |
+
by_kind = {}
|
| 724 |
+
for k, v in self.accumulator.tensors.items():
|
| 725 |
+
clean = self._strip_kind(k)
|
| 726 |
+
if clean.startswith(prefix + ".") or clean == prefix:
|
| 727 |
+
by_kind.setdefault(self._kind_of(k), {})[k] = v
|
| 728 |
+
safe = prefix.replace(".", "_")
|
| 729 |
+
for kind, entries in by_kind.items():
|
| 730 |
+
if not entries:
|
| 731 |
+
continue
|
| 732 |
+
stats = self.accumulator._aggregate(entries)
|
| 733 |
+
for kk, vv in stats.items():
|
| 734 |
+
metrics[f"{scope}/layer_{safe}/{kind}/{kk}"] = vv
|
| 735 |
+
|
| 736 |
+
if self.log_scope.get("per_tensor", False):
|
| 737 |
+
for name, stats in self.accumulator.tensors.items():
|
| 738 |
+
safe = name.replace(".", "_")
|
| 739 |
+
for kk, vv in stats.items():
|
| 740 |
+
if kk == "numel":
|
| 741 |
+
continue
|
| 742 |
+
metrics[f"{scope}/tensor_{safe}/{kk}"] = vv
|
| 743 |
+
return metrics
|
| 744 |
+
|
| 745 |
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
| 746 |
+
if logs is not None and self.pending_metrics is not None:
|
| 747 |
+
logs.update(self.pending_metrics)
|
| 748 |
+
try:
|
| 749 |
+
import wandb
|
| 750 |
+
if wandb.run is not None:
|
| 751 |
+
wandb.log(self.pending_metrics, step=state.global_step)
|
| 752 |
+
except ImportError:
|
| 753 |
+
pass
|
| 754 |
+
self.pending_metrics = None
|
| 755 |
+
|
| 756 |
+
def on_prediction_step(self, args, state, control, **kwargs):
|
| 757 |
+
if not self.monitor_during_eval:
|
| 758 |
+
return
|
| 759 |
+
if not self.hooks.active:
|
| 760 |
+
self.accumulator.clear()
|
| 761 |
+
self.hooks.set_active(True)
|
| 762 |
+
for name, param in self.model.named_parameters():
|
| 763 |
+
if self.param_patterns and not any(re.search(p, name) for p in self.param_patterns):
|
| 764 |
+
continue
|
| 765 |
+
stats = StatsEngine.compute(param.data, self.user_limits["param"], self.dtype_ratio)
|
| 766 |
+
self.accumulator.add(f"param.{name}", param.numel(), stats)
|
| 767 |
+
self.pending_metrics = self._build_metrics(scope="eval")
|
| 768 |
+
|
| 769 |
+
def on_evaluate(self, args, state, control, metrics=None, **kwargs):
|
| 770 |
+
self.hooks.set_active(False)
|
| 771 |
+
self.accumulator.clear()
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
# =============================================================================
|
| 775 |
+
# 7. TIME TRACKER (unchanged)
|
| 776 |
+
# =============================================================================
|
| 777 |
+
|
| 778 |
+
class TimeTrackerCallback(TrainerCallback):
|
| 779 |
+
def __init__(self):
|
| 780 |
+
self.step_start = None
|
| 781 |
+
self.epoch_start = None
|
| 782 |
+
self.total_train_time = 0.0
|
| 783 |
+
self.step_times = []
|
| 784 |
+
|
| 785 |
+
def on_epoch_begin(self, args, state, control, **kwargs):
|
| 786 |
+
self.epoch_start = time.perf_counter()
|
| 787 |
+
|
| 788 |
+
def on_step_begin(self, args, state, control, **kwargs):
|
| 789 |
+
self.step_start = time.perf_counter()
|
| 790 |
+
|
| 791 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 792 |
+
if self.step_start is not None:
|
| 793 |
+
dt = time.perf_counter() - self.step_start
|
| 794 |
+
self.step_times.append(dt)
|
| 795 |
+
self.total_train_time += dt
|
| 796 |
+
self.step_start = None
|
| 797 |
+
|
| 798 |
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
| 799 |
+
if logs is None:
|
| 800 |
+
return
|
| 801 |
+
logs["train/total_time_seconds"] = self.total_train_time
|
| 802 |
+
if self.step_times:
|
| 803 |
+
recent = self.step_times[-100:]
|
| 804 |
+
logs["train/time_per_step_avg"] = sum(recent) / len(recent)
|
| 805 |
+
if self.epoch_start is not None:
|
| 806 |
+
logs["train/epoch_time_elapsed"] = time.perf_counter() - self.epoch_start
|
| 807 |
+
if state.max_steps and state.global_step > 0:
|
| 808 |
+
avg = self.total_train_time / state.global_step
|
| 809 |
+
remaining = (state.max_steps - state.global_step) * avg
|
| 810 |
+
logs["train/estimated_remaining_minutes"] = remaining / 60.0
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
# =============================================================================
|
| 814 |
+
# 8. METRICS LOGGER (unchanged)
|
| 815 |
+
# =============================================================================
|
| 816 |
+
|
| 817 |
+
class MetricsLoggerCallback(TrainerCallback):
|
| 818 |
+
def __init__(self, output_dir: str):
|
| 819 |
+
self.output_dir = Path(output_dir)
|
| 820 |
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
| 821 |
+
self.log_file = self.output_dir / "training_log.jsonl"
|
| 822 |
+
|
| 823 |
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
| 824 |
+
if logs is None:
|
| 825 |
+
return
|
| 826 |
+
entry = {"step": state.global_step, "epoch": state.epoch, "timestamp": time.time(), **logs}
|
| 827 |
+
with open(self.log_file, "a") as f:
|
| 828 |
+
f.write(json.dumps(entry, default=str) + "\n")
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
# =============================================================================
|
| 832 |
+
# 9. DATA & TRAINER FACTORY (unchanged)
|
| 833 |
+
# =============================================================================
|
| 834 |
+
|
| 835 |
+
def build_dataset(
|
| 836 |
+
tokenizer,
|
| 837 |
+
max_seq_len: int = 512,
|
| 838 |
+
split: str = "train",
|
| 839 |
+
dataset_name: str = "roneneldan/TinyStories",
|
| 840 |
+
max_samples: Optional[int] = None,
|
| 841 |
+
):
|
| 842 |
+
ds = load_dataset(dataset_name, split=split)
|
| 843 |
+
if max_samples is not None and split == "train":
|
| 844 |
+
ds = ds.select(range(min(max_samples, len(ds))))
|
| 845 |
+
|
| 846 |
+
def tokenize(examples):
|
| 847 |
+
out = tokenizer(examples["text"], add_special_tokens=False)
|
| 848 |
+
eos_id = tokenizer.eos_token_id
|
| 849 |
+
out["input_ids"] = [ids + [eos_id] for ids in out["input_ids"]]
|
| 850 |
+
if "attention_mask" in out:
|
| 851 |
+
out["attention_mask"] = [mask + [1] for mask in out["attention_mask"]]
|
| 852 |
+
return out
|
| 853 |
+
|
| 854 |
+
tokenized = ds.map(tokenize, batched=True, num_proc=4, remove_columns=ds.column_names)
|
| 855 |
+
|
| 856 |
+
def group_texts(examples):
|
| 857 |
+
concatenated = {k: list(chain.from_iterable(examples[k])) for k in examples.keys()}
|
| 858 |
+
total_length = len(concatenated[list(examples.keys())[0]])
|
| 859 |
+
total_length = (total_length // max_seq_len) * max_seq_len
|
| 860 |
+
result = {
|
| 861 |
+
k: [t[i:i + max_seq_len] for i in range(0, total_length, max_seq_len)]
|
| 862 |
+
for k, t in concatenated.items()
|
| 863 |
+
}
|
| 864 |
+
result["labels"] = result["input_ids"].copy()
|
| 865 |
+
return result
|
| 866 |
+
|
| 867 |
+
return tokenized.map(group_texts, batched=True, batch_size=10000, num_proc=4)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def create_trainer(
|
| 871 |
+
model,
|
| 872 |
+
tokenizer,
|
| 873 |
+
config: Dict[str, Any],
|
| 874 |
+
train_dataset,
|
| 875 |
+
eval_dataset=None,
|
| 876 |
+
):
|
| 877 |
+
tc = config.get("training", {})
|
| 878 |
+
mc = config.get("monitor", {})
|
| 879 |
+
go = config.get("gradient_override", {})
|
| 880 |
+
|
| 881 |
+
wandb_project = tc.get("wandb_project")
|
| 882 |
+
if wandb_project:
|
| 883 |
+
os.environ["WANDB_PROJECT"] = wandb_project
|
| 884 |
+
|
| 885 |
+
args = TrainingArguments(
|
| 886 |
+
output_dir=tc.get("output_dir", "./out"),
|
| 887 |
+
run_name=tc.get("run_name", None),
|
| 888 |
+
num_train_epochs=tc.get("num_train_epochs", 3),
|
| 889 |
+
per_device_train_batch_size=tc.get("per_device_train_batch_size", 16),
|
| 890 |
+
per_device_eval_batch_size=tc.get("per_device_eval_batch_size", 16),
|
| 891 |
+
gradient_accumulation_steps=tc.get("gradient_accumulation_steps", 4),
|
| 892 |
+
learning_rate=tc.get("learning_rate", 3e-4),
|
| 893 |
+
weight_decay=tc.get("weight_decay", 0.0),
|
| 894 |
+
max_grad_norm=tc.get("max_grad_norm", 1.0),
|
| 895 |
+
optim=tc.get("optim", "adamw_torch"),
|
| 896 |
+
warmup_steps=tc.get("warmup_steps", 0),
|
| 897 |
+
lr_scheduler_type=tc.get("lr_scheduler_type", "cosine"),
|
| 898 |
+
bf16=tc.get("bf16", True),
|
| 899 |
+
logging_steps=tc.get("logging_steps", 10),
|
| 900 |
+
eval_strategy=tc.get("eval_strategy", "steps"),
|
| 901 |
+
eval_steps=tc.get("eval_steps", 500),
|
| 902 |
+
save_strategy=tc.get("save_strategy", "steps"),
|
| 903 |
+
save_steps=tc.get("save_steps", 1000),
|
| 904 |
+
load_best_model_at_end=tc.get("load_best_model_at_end", False),
|
| 905 |
+
report_to=tc.get("report_to", "tensorboard"),
|
| 906 |
+
push_to_hub=tc.get("push_to_hub", False),
|
| 907 |
+
hub_model_id=tc.get("hub_model_id", None),
|
| 908 |
+
hub_token=tc.get("hub_token") or os.environ.get("HF_TOKEN"),
|
| 909 |
+
max_steps=tc.get("max_steps", -1),
|
| 910 |
+
seed=tc.get("seed", 42),
|
| 911 |
+
data_seed=tc.get("data_seed", 42),
|
| 912 |
+
remove_unused_columns=False,
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
callbacks = [TimeTrackerCallback()]
|
| 916 |
+
|
| 917 |
+
# ---- FREEZE + OVERRIDE CALLBACK ----
|
| 918 |
+
freeze_mlp = tc.get("freeze_mlp", False)
|
| 919 |
+
override_enabled = go.get("enabled", False)
|
| 920 |
+
if freeze_mlp or override_enabled:
|
| 921 |
+
override_value = go.get("value", -100.0) if override_enabled else None
|
| 922 |
+
callbacks.append(ResumeFreezeOverrideCallback(override_value=override_value))
|
| 923 |
+
|
| 924 |
+
# ---- MONITORING ----
|
| 925 |
+
if mc.get("enabled", True):
|
| 926 |
+
module_patterns = mc.get("module_patterns", [".*mlp.*", ".*residual.*"])
|
| 927 |
+
callbacks.append(
|
| 928 |
+
StabilityMonitorCallback(
|
| 929 |
+
model=model,
|
| 930 |
+
monitor_every_n_steps=mc.get("monitor_every_n_steps", 10),
|
| 931 |
+
module_patterns=module_patterns,
|
| 932 |
+
param_patterns=module_patterns,
|
| 933 |
+
user_limits=mc.get("user_limits", {"grad": 1.0, "param": 100.0, "act": 50.0}),
|
| 934 |
+
dtype_proximity_ratio=mc.get("dtype_proximity_ratio", 0.9),
|
| 935 |
+
log_scope=mc.get("log_scope", {"global": True, "per_layer": True, "per_tensor": False}),
|
| 936 |
+
monitor_during_eval=mc.get("monitor_during_eval", False),
|
| 937 |
+
)
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
callbacks.append(MetricsLoggerCallback(args.output_dir))
|
| 941 |
+
|
| 942 |
+
collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
| 943 |
+
|
| 944 |
+
trainer = Trainer(
|
| 945 |
+
model=model,
|
| 946 |
+
args=args,
|
| 947 |
+
train_dataset=train_dataset,
|
| 948 |
+
eval_dataset=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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Standalone script to extract Adam RMS and SNR from HF Hub checkpoints.
|
| 4 |
+
Uses exact model definitions from the activation analyzer (exp.py).
|
| 5 |
+
Normalizes names to match the analyzer's naming (gate_proj, up_proj, etc.).
|
| 6 |
+
Configured for: w-ahmad/STRESS-TEST2 / zain/Activation/out
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import json
|
| 12 |
+
import tempfile
|
| 13 |
+
import shutil
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Dict, List, Optional, Tuple, Any
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import wandb
|
| 20 |
+
from huggingface_hub import HfApi, hf_hub_download, list_repo_tree
|
| 21 |
+
from transformers import LlamaConfig, LlamaPreTrainedModel
|
| 22 |
+
from transformers.models.llama.modeling_llama import (
|
| 23 |
+
LlamaAttention, LlamaRMSNorm, LlamaRotaryEmbedding,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# ============================================================================
|
| 27 |
+
# EXACT MODEL DEFINITIONS (copied from the activation analyzer)
|
| 28 |
+
# ============================================================================
|
| 29 |
+
|
| 30 |
+
class GLUActivationRegistry:
|
| 31 |
+
_registry: Dict[str, callable] = {}
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def register(cls, name: str, fn: callable) -> None:
|
| 35 |
+
cls._registry[name] = fn
|
| 36 |
+
|
| 37 |
+
@classmethod
|
| 38 |
+
def get(cls, name: str) -> callable:
|
| 39 |
+
if name not in cls._registry:
|
| 40 |
+
raise KeyError(f"Activation '{name}' not found")
|
| 41 |
+
return cls._registry[name]
|
| 42 |
+
|
| 43 |
+
# Register all activations used in the analyzer
|
| 44 |
+
GLUActivationRegistry.register("silu", nn.functional.silu)
|
| 45 |
+
GLUActivationRegistry.register("swish", nn.functional.silu)
|
| 46 |
+
GLUActivationRegistry.register("relu", nn.functional.relu)
|
| 47 |
+
GLUActivationRegistry.register("gelu", nn.functional.gelu)
|
| 48 |
+
GLUActivationRegistry.register("mish", nn.functional.mish)
|
| 49 |
+
GLUActivationRegistry.register("sigmoid", torch.sigmoid)
|
| 50 |
+
GLUActivationRegistry.register("tanh", torch.tanh)
|
| 51 |
+
GLUActivationRegistry.register("elu", nn.functional.elu)
|
| 52 |
+
GLUActivationRegistry.register("softplus", nn.functional.softplus)
|
| 53 |
+
GLUActivationRegistry.register("linear", lambda x: x)
|
| 54 |
+
GLUActivationRegistry.register("s10", lambda x: x * x * torch.sigmoid(x))
|
| 55 |
+
GLUActivationRegistry.register("w1a", lambda x: x * torch.tanh(x))
|
| 56 |
+
GLUActivationRegistry.register("powlu", lambda x: x) # dummy for param extraction
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class TinyLlamaConfig(LlamaConfig):
|
| 60 |
+
model_type = "tiny_llama"
|
| 61 |
+
|
| 62 |
+
def __init__(
|
| 63 |
+
self,
|
| 64 |
+
mlp_type: str = "glu",
|
| 65 |
+
activation: str = "silu",
|
| 66 |
+
waleed_beta: float = 10.0,
|
| 67 |
+
powlu_m: float = 3.0,
|
| 68 |
+
**kwargs
|
| 69 |
+
):
|
| 70 |
+
super().__init__(**kwargs)
|
| 71 |
+
self.mlp_type = mlp_type
|
| 72 |
+
self.activation = activation
|
| 73 |
+
self.waleed_beta = waleed_beta
|
| 74 |
+
self.powlu_m = powlu_m
|
| 75 |
+
if self.num_key_value_heads != self.num_attention_heads:
|
| 76 |
+
raise ValueError("Pure MHA required.")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class SiTUGLU(nn.Module):
|
| 80 |
+
def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.beta1 = beta1
|
| 83 |
+
self.beta2 = beta2
|
| 84 |
+
self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 85 |
+
self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 86 |
+
|
| 87 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 88 |
+
g = self.W_g(x)
|
| 89 |
+
gate = self.beta1 * torch.tanh(g / self.beta1) * torch.sigmoid(g)
|
| 90 |
+
up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
|
| 91 |
+
return gate * up
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class WaleedGLU(nn.Module):
|
| 95 |
+
def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.beta1 = beta1
|
| 98 |
+
self.beta2 = beta2
|
| 99 |
+
self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 100 |
+
self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 101 |
+
|
| 102 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 103 |
+
g = self.W_g(x)
|
| 104 |
+
gate = self.beta1 * torch.tanh(g / self.beta1)
|
| 105 |
+
up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
|
| 106 |
+
return gate * up
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class TinyLlamaMLP(nn.Module):
|
| 110 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.hidden_size = config.hidden_size
|
| 113 |
+
self.intermediate_size = config.intermediate_size
|
| 114 |
+
self.mlp_type = config.mlp_type
|
| 115 |
+
self.activation_name = config.activation
|
| 116 |
+
|
| 117 |
+
if self.mlp_type == "glu":
|
| 118 |
+
effective_intermediate = self.intermediate_size
|
| 119 |
+
else:
|
| 120 |
+
effective_intermediate = int(self.intermediate_size * 1.5)
|
| 121 |
+
|
| 122 |
+
self.effective_intermediate = effective_intermediate
|
| 123 |
+
self.situglu = None
|
| 124 |
+
self.waleed = None
|
| 125 |
+
self.gate_proj = None
|
| 126 |
+
self.up_proj = None
|
| 127 |
+
self.act_fn = None
|
| 128 |
+
|
| 129 |
+
if self.mlp_type == "glu":
|
| 130 |
+
if self.activation_name == "situglu":
|
| 131 |
+
self.situglu = SiTUGLU(self.hidden_size, effective_intermediate)
|
| 132 |
+
elif self.activation_name == "waleed":
|
| 133 |
+
self.waleed = WaleedGLU(self.hidden_size, effective_intermediate)
|
| 134 |
+
else:
|
| 135 |
+
# Standard GLU (including waleed10, silu-waleed10, powlu, situglu_low, waleedglu_low)
|
| 136 |
+
self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 137 |
+
self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 138 |
+
# Activation handling (not needed for param extraction, but avoid errors)
|
| 139 |
+
if self.activation_name == "waleed10":
|
| 140 |
+
self.act_fn = GLUActivationRegistry.get("linear")
|
| 141 |
+
elif self.activation_name == "silu-waleed10":
|
| 142 |
+
self.act_fn = GLUActivationRegistry.get("silu")
|
| 143 |
+
elif self.activation_name in ("situglu_low", "waleedglu_low"):
|
| 144 |
+
self.act_fn = None
|
| 145 |
+
else:
|
| 146 |
+
self.act_fn = GLUActivationRegistry.get(self.activation_name)
|
| 147 |
+
else:
|
| 148 |
+
# MLP (non-GLU) – not used in your runs, but kept for completeness
|
| 149 |
+
if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
|
| 150 |
+
raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
|
| 151 |
+
self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 152 |
+
if self.activation_name == "waleed10":
|
| 153 |
+
self.act_fn = GLUActivationRegistry.get("linear")
|
| 154 |
+
elif self.activation_name == "silu-waleed10":
|
| 155 |
+
self.act_fn = GLUActivationRegistry.get("silu")
|
| 156 |
+
else:
|
| 157 |
+
self.act_fn = GLUActivationRegistry.get(self.activation_name)
|
| 158 |
+
|
| 159 |
+
self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
|
| 160 |
+
|
| 161 |
+
def forward(self, x):
|
| 162 |
+
raise NotImplementedError
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class TinyLlamaDecoderLayer(nn.Module):
|
| 166 |
+
def __init__(self, config: TinyLlamaConfig, layer_idx: int):
|
| 167 |
+
super().__init__()
|
| 168 |
+
self.hidden_size = config.hidden_size
|
| 169 |
+
self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
|
| 170 |
+
self.mlp = TinyLlamaMLP(config)
|
| 171 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 172 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 173 |
+
|
| 174 |
+
def forward(self, *args, **kwargs):
|
| 175 |
+
raise NotImplementedError
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TinyLlamaModel(LlamaPreTrainedModel):
|
| 179 |
+
config_class = TinyLlamaConfig
|
| 180 |
+
|
| 181 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 182 |
+
super().__init__(config)
|
| 183 |
+
self.padding_idx = config.pad_token_id
|
| 184 |
+
self.vocab_size = config.vocab_size
|
| 185 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 186 |
+
self.layers = nn.ModuleList(
|
| 187 |
+
[TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 188 |
+
)
|
| 189 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 190 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 191 |
+
self.post_init()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class TinyLlamaForCausalLM(LlamaPreTrainedModel):
|
| 195 |
+
config_class = TinyLlamaConfig
|
| 196 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 197 |
+
|
| 198 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 199 |
+
super().__init__(config)
|
| 200 |
+
self.model = TinyLlamaModel(config)
|
| 201 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 202 |
+
if config.tie_word_embeddings:
|
| 203 |
+
self.lm_head.weight = self.model.embed_tokens.weight
|
| 204 |
+
self.post_init()
|
| 205 |
+
|
| 206 |
+
def get_input_embeddings(self):
|
| 207 |
+
return self.model.embed_tokens
|
| 208 |
+
|
| 209 |
+
def set_input_embeddings(self, value):
|
| 210 |
+
self.model.embed_tokens = value
|
| 211 |
+
|
| 212 |
+
def get_output_embeddings(self):
|
| 213 |
+
return self.lm_head
|
| 214 |
+
|
| 215 |
+
def forward(self, **kwargs):
|
| 216 |
+
raise NotImplementedError
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# ============================================================================
|
| 220 |
+
# NAME NORMALIZATION – matches activation analyzer exactly
|
| 221 |
+
# ============================================================================
|
| 222 |
+
|
| 223 |
+
def canonical_param_name(name: str) -> str:
|
| 224 |
+
"""
|
| 225 |
+
Normalize parameter names to match the activation analyzer's naming.
|
| 226 |
+
- W_g -> gate_proj, W_u -> up_proj (for situglu/waleed)
|
| 227 |
+
- Keep gate_proj and up_proj unchanged (they already are canonical)
|
| 228 |
+
- Leave all other names as-is.
|
| 229 |
+
This allows direct overlays between RMS/SNR and activation stats.
|
| 230 |
+
"""
|
| 231 |
+
# WaleedGLU → use gate_proj/up_proj
|
| 232 |
+
if "mlp.waleed.W_g" in name:
|
| 233 |
+
return name.replace("mlp.waleed.W_g", "mlp.waleed.gate_proj")
|
| 234 |
+
if "mlp.waleed.W_u" in name:
|
| 235 |
+
return name.replace("mlp.waleed.W_u", "mlp.waleed.up_proj")
|
| 236 |
+
|
| 237 |
+
# SiTUGLU → use gate_proj/up_proj
|
| 238 |
+
if "mlp.situglu.W_g" in name:
|
| 239 |
+
return name.replace("mlp.situglu.W_g", "mlp.situglu.gate_proj")
|
| 240 |
+
if "mlp.situglu.W_u" in name:
|
| 241 |
+
return name.replace("mlp.situglu.W_u", "mlp.situglu.up_proj")
|
| 242 |
+
|
| 243 |
+
# For standard GLU, names already have gate_proj/up_proj – keep them.
|
| 244 |
+
# Everything else (attention, norms, embeddings, lm_head) stays as-is.
|
| 245 |
+
return name
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# ============================================================================
|
| 249 |
+
# Stats helpers
|
| 250 |
+
# ============================================================================
|
| 251 |
+
|
| 252 |
+
def tensor_stats(tensor: torch.Tensor) -> Dict[str, float]:
|
| 253 |
+
with torch.no_grad():
|
| 254 |
+
return {
|
| 255 |
+
"numel": tensor.numel(),
|
| 256 |
+
"mean": tensor.mean().item(),
|
| 257 |
+
"std": tensor.std().item(),
|
| 258 |
+
"max_abs": tensor.abs().max().item(),
|
| 259 |
+
"norm": tensor.norm().item(),
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def aggregate_stats(stats_list: List[Dict[str, float]]) -> Dict[str, float]:
|
| 264 |
+
if not stats_list:
|
| 265 |
+
return {"numel": 0, "mean": 0.0, "std": 0.0, "max_abs": 0.0, "norm": 0.0}
|
| 266 |
+
|
| 267 |
+
total_numel = sum(s["numel"] for s in stats_list)
|
| 268 |
+
if total_numel == 0:
|
| 269 |
+
return {"numel": 0, "mean": 0.0, "std": 0.0, "max_abs": 0.0, "norm": 0.0}
|
| 270 |
+
|
| 271 |
+
mean = sum(s["mean"] * s["numel"] for s in stats_list) / total_numel
|
| 272 |
+
ex2 = sum(s["numel"] * (s["std"]**2 + s["mean"]**2) for s in stats_list) / total_numel
|
| 273 |
+
std = math.sqrt(max(0.0, ex2 - mean**2))
|
| 274 |
+
norm = math.sqrt(sum(s["norm"]**2 for s in stats_list))
|
| 275 |
+
max_abs = max(s["max_abs"] for s in stats_list)
|
| 276 |
+
|
| 277 |
+
return {"numel": total_numel, "mean": mean, "std": std, "max_abs": max_abs, "norm": norm}
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def get_param_names_from_model(config: TinyLlamaConfig) -> List[str]:
|
| 281 |
+
model = TinyLlamaForCausalLM(config)
|
| 282 |
+
return [name for name, _ in model.named_parameters()]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ============================================================================
|
| 286 |
+
# HF Hub helpers – configured for your repo
|
| 287 |
+
# ============================================================================
|
| 288 |
+
|
| 289 |
+
REPO_ID = "w-ahmad/art"
|
| 290 |
+
BASE_PATH = "out"
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def list_run_directories() -> List[str]:
|
| 294 |
+
api = HfApi()
|
| 295 |
+
items = list_repo_tree(repo_id=REPO_ID, path_in_repo=BASE_PATH, recursive=False)
|
| 296 |
+
return [item.path for item in items if item.path.endswith("_run")]
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def list_checkpoints_for_run(run_path: str) -> List[str]:
|
| 300 |
+
api = HfApi()
|
| 301 |
+
items = list_repo_tree(repo_id=REPO_ID, path_in_repo=run_path, recursive=False)
|
| 302 |
+
ckpts = [item.path for item in items if item.path.split("/")[-1].startswith("checkpoint-")]
|
| 303 |
+
ckpts.sort(key=lambda x: int(x.split("-")[-1]))
|
| 304 |
+
return ckpts
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def download_file_from_hub(file_path: str, local_dir: str) -> str:
|
| 308 |
+
return hf_hub_download(
|
| 309 |
+
repo_id=REPO_ID,
|
| 310 |
+
filename=file_path,
|
| 311 |
+
local_dir=local_dir,
|
| 312 |
+
local_dir_use_symlinks=False,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# ============================================================================
|
| 317 |
+
# Core analysis
|
| 318 |
+
# ============================================================================
|
| 319 |
+
|
| 320 |
+
def analyze_checkpoint_from_hub(
|
| 321 |
+
ckpt_path: str,
|
| 322 |
+
config: TinyLlamaConfig,
|
| 323 |
+
param_names: List[str],
|
| 324 |
+
temp_dir: str,
|
| 325 |
+
) -> Dict[str, Any]:
|
| 326 |
+
opt_file = download_file_from_hub(f"{ckpt_path}/optimizer.pt", temp_dir)
|
| 327 |
+
opt_state = torch.load(opt_file, map_location="cpu")
|
| 328 |
+
state = opt_state["state"]
|
| 329 |
+
param_groups = opt_state["param_groups"]
|
| 330 |
+
|
| 331 |
+
param_ids = []
|
| 332 |
+
for group in param_groups:
|
| 333 |
+
param_ids.extend(group["params"])
|
| 334 |
+
|
| 335 |
+
if len(param_ids) != len(param_names):
|
| 336 |
+
raise ValueError(
|
| 337 |
+
f"Param ID mismatch: {len(param_ids)} vs {len(param_names)}"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
id_to_name = {pid: param_names[i] for i, pid in enumerate(param_ids)}
|
| 341 |
+
|
| 342 |
+
# Per-tensor RMS + SNR (canonical names)
|
| 343 |
+
per_tensor_rms: Dict[str, Dict[str, float]] = {}
|
| 344 |
+
per_tensor_snr: Dict[str, Dict[str, float]] = {}
|
| 345 |
+
|
| 346 |
+
for pid, raw_name in id_to_name.items():
|
| 347 |
+
if pid not in state:
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
name = canonical_param_name(raw_name)
|
| 351 |
+
|
| 352 |
+
# RMS
|
| 353 |
+
v_t = state[pid]["exp_avg_sq"]
|
| 354 |
+
rms = torch.sqrt(v_t + 1e-8)
|
| 355 |
+
per_tensor_rms[name] = tensor_stats(rms)
|
| 356 |
+
|
| 357 |
+
# SNR = |m_t| / (rms + eps)
|
| 358 |
+
m_t = state[pid]["exp_avg"]
|
| 359 |
+
snr = m_t.abs() / (rms + 1e-8)
|
| 360 |
+
snr = snr.clamp(max=1e4)
|
| 361 |
+
per_tensor_snr[name] = tensor_stats(snr)
|
| 362 |
+
|
| 363 |
+
# Layer aggregation
|
| 364 |
+
def build_layer_stats(per_tensor_dict: Dict[str, Dict[str, float]]) -> Dict[str, Dict[str, float]]:
|
| 365 |
+
layers: Dict[str, List[Dict[str, float]]] = {}
|
| 366 |
+
for name, stats in per_tensor_dict.items():
|
| 367 |
+
parts = name.split(".")
|
| 368 |
+
layer_key = None
|
| 369 |
+
for i, p in enumerate(parts):
|
| 370 |
+
if p == "layers" and i + 1 < len(parts):
|
| 371 |
+
layer_key = f"layers.{parts[i+1]}"
|
| 372 |
+
break
|
| 373 |
+
if layer_key is None:
|
| 374 |
+
layer_key = "root"
|
| 375 |
+
layers.setdefault(layer_key, []).append(stats)
|
| 376 |
+
return {k: aggregate_stats(v) for k, v in layers.items()}
|
| 377 |
+
|
| 378 |
+
layer_rms = build_layer_stats(per_tensor_rms)
|
| 379 |
+
layer_snr = build_layer_stats(per_tensor_snr)
|
| 380 |
+
|
| 381 |
+
global_rms = aggregate_stats(list(per_tensor_rms.values()))
|
| 382 |
+
global_snr = aggregate_stats(list(per_tensor_snr.values()))
|
| 383 |
+
|
| 384 |
+
return {
|
| 385 |
+
"step": int(ckpt_path.split("-")[-1]),
|
| 386 |
+
"per_tensor_rms": per_tensor_rms,
|
| 387 |
+
"per_tensor_snr": per_tensor_snr,
|
| 388 |
+
"per_layer_rms": layer_rms,
|
| 389 |
+
"per_layer_snr": layer_snr,
|
| 390 |
+
"global_rms": global_rms,
|
| 391 |
+
"global_snr": global_snr,
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ============================================================================
|
| 396 |
+
# Main
|
| 397 |
+
# ============================================================================
|
| 398 |
+
|
| 399 |
+
def main():
|
| 400 |
+
import argparse
|
| 401 |
+
parser = argparse.ArgumentParser()
|
| 402 |
+
parser.add_argument("--wandb_project", type=str, default="llm-gradient-rms-analysis")
|
| 403 |
+
parser.add_argument("--wandb_entity", type=str, default=None)
|
| 404 |
+
parser.add_argument("--limit_runs", type=str, nargs="+", default=None)
|
| 405 |
+
parser.add_argument("--limit_checkpoints", type=str, nargs="+", default=None)
|
| 406 |
+
parser.add_argument("--cache_dir", type=str, default=None)
|
| 407 |
+
parser.add_argument("--log_all_tensors", action="store_true", default=False,
|
| 408 |
+
help="Log every tensor's RMS/SNR (may hit WandB limits).")
|
| 409 |
+
args = parser.parse_args()
|
| 410 |
+
|
| 411 |
+
print(f"Listing run directories in {REPO_ID}/{BASE_PATH} ...")
|
| 412 |
+
run_paths = list_run_directories()
|
| 413 |
+
print(f"Found {len(run_paths)} run directories.")
|
| 414 |
+
|
| 415 |
+
if args.limit_runs:
|
| 416 |
+
run_paths = [r for r in run_paths if r.split("/")[-1] in args.limit_runs]
|
| 417 |
+
print(f"Filtered to {len(run_paths)} runs.")
|
| 418 |
+
|
| 419 |
+
if args.cache_dir:
|
| 420 |
+
cache_dir = Path(args.cache_dir)
|
| 421 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 422 |
+
use_temp = False
|
| 423 |
+
else:
|
| 424 |
+
cache_dir = Path(tempfile.mkdtemp(prefix="hf_cache_"))
|
| 425 |
+
use_temp = True
|
| 426 |
+
|
| 427 |
+
try:
|
| 428 |
+
for run_path in run_paths:
|
| 429 |
+
run_name = run_path.split("/")[-1]
|
| 430 |
+
print(f"\nProcessing run: {run_name}")
|
| 431 |
+
|
| 432 |
+
ckpt_paths = list_checkpoints_for_run(run_path)
|
| 433 |
+
if not ckpt_paths:
|
| 434 |
+
print(f" No checkpoints found, skipping.")
|
| 435 |
+
continue
|
| 436 |
+
|
| 437 |
+
first_ckpt = ckpt_paths[0]
|
| 438 |
+
config_file = download_file_from_hub(f"{first_ckpt}/config.json", str(cache_dir))
|
| 439 |
+
config = TinyLlamaConfig.from_pretrained(config_file)
|
| 440 |
+
param_names = get_param_names_from_model(config)
|
| 441 |
+
print(f" Model: {len(param_names)} params, {config.num_hidden_layers} layers.")
|
| 442 |
+
print(f" waleed_beta: {config.waleed_beta}, powlu_m: {config.powlu_m}")
|
| 443 |
+
|
| 444 |
+
if args.log_all_tensors and len(param_names) > 200:
|
| 445 |
+
print(f" ⚠️ {len(param_names)} tensors — may hit WandB limits.")
|
| 446 |
+
|
| 447 |
+
wandb.init(
|
| 448 |
+
project=args.wandb_project,
|
| 449 |
+
entity=args.wandb_entity,
|
| 450 |
+
name=run_name,
|
| 451 |
+
config={
|
| 452 |
+
"run_name": run_name,
|
| 453 |
+
"mlp_type": config.mlp_type,
|
| 454 |
+
"activation": config.activation,
|
| 455 |
+
"num_layers": config.num_hidden_layers,
|
| 456 |
+
"hidden_size": config.hidden_size,
|
| 457 |
+
"waleed_beta": config.waleed_beta,
|
| 458 |
+
"powlu_m": config.powlu_m,
|
| 459 |
+
},
|
| 460 |
+
reinit=True,
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
for ckpt in ckpt_paths:
|
| 464 |
+
step = int(ckpt.split("-")[-1])
|
| 465 |
+
if args.limit_checkpoints and str(step) not in args.limit_checkpoints:
|
| 466 |
+
continue
|
| 467 |
+
print(f" Analyzing {ckpt} ...")
|
| 468 |
+
try:
|
| 469 |
+
result = analyze_checkpoint_from_hub(ckpt, config, param_names, str(cache_dir))
|
| 470 |
+
except Exception as e:
|
| 471 |
+
print(f" Error: {e}, skipping.")
|
| 472 |
+
continue
|
| 473 |
+
|
| 474 |
+
log_dict: Dict[str, Any] = {}
|
| 475 |
+
|
| 476 |
+
# GLOBAL (RMS + SNR)
|
| 477 |
+
gr = result["global_rms"]
|
| 478 |
+
gs = result["global_snr"]
|
| 479 |
+
|
| 480 |
+
log_dict["global/rms_norm"] = gr["norm"]
|
| 481 |
+
log_dict["global/rms_mean"] = gr["mean"]
|
| 482 |
+
log_dict["global/rms_std"] = gr["std"]
|
| 483 |
+
log_dict["global/rms_max_abs"] = gr["max_abs"]
|
| 484 |
+
|
| 485 |
+
log_dict["global/snr_mean"] = gs["mean"]
|
| 486 |
+
log_dict["global/snr_std"] = gs["std"]
|
| 487 |
+
log_dict["global/snr_max_abs"] = gs["max_abs"]
|
| 488 |
+
log_dict["global/snr_norm"] = gs["norm"]
|
| 489 |
+
|
| 490 |
+
# PER-LAYER
|
| 491 |
+
for layer_name, stats in result["per_layer_rms"].items():
|
| 492 |
+
safe = layer_name.replace(".", "_")
|
| 493 |
+
log_dict[f"layers/{safe}/rms_norm"] = stats["norm"]
|
| 494 |
+
|
| 495 |
+
for layer_name, stats in result["per_layer_snr"].items():
|
| 496 |
+
safe = layer_name.replace(".", "_")
|
| 497 |
+
log_dict[f"layers/{safe}/snr_mean"] = stats["mean"]
|
| 498 |
+
|
| 499 |
+
# PER-TENSOR (canonical names → all variants overlay)
|
| 500 |
+
if args.log_all_tensors:
|
| 501 |
+
# RMS
|
| 502 |
+
for name, stats in result["per_tensor_rms"].items():
|
| 503 |
+
safe = name.replace(".", "_")
|
| 504 |
+
log_dict[f"tensors/{safe}/rms_norm"] = stats["norm"]
|
| 505 |
+
log_dict[f"tensors/{safe}/rms_mean"] = stats["mean"]
|
| 506 |
+
log_dict[f"tensors/{safe}/rms_std"] = stats["std"]
|
| 507 |
+
log_dict[f"tensors/{safe}/rms_max_abs"] = stats["max_abs"]
|
| 508 |
+
|
| 509 |
+
# SNR
|
| 510 |
+
for name, stats in result["per_tensor_snr"].items():
|
| 511 |
+
safe = name.replace(".", "_")
|
| 512 |
+
log_dict[f"tensors/{safe}/snr_mean"] = stats["mean"]
|
| 513 |
+
log_dict[f"tensors/{safe}/snr_std"] = stats["std"]
|
| 514 |
+
log_dict[f"tensors/{safe}/snr_max_abs"] = stats["max_abs"]
|
| 515 |
+
log_dict[f"tensors/{safe}/snr_norm"] = stats["norm"]
|
| 516 |
+
else:
|
| 517 |
+
# Top/bottom 5 by RMS norm
|
| 518 |
+
sorted_tensors = sorted(
|
| 519 |
+
result["per_tensor_rms"].items(),
|
| 520 |
+
key=lambda x: x[1]["norm"],
|
| 521 |
+
reverse=True,
|
| 522 |
+
)
|
| 523 |
+
top5 = sorted_tensors[:5]
|
| 524 |
+
bottom5 = sorted_tensors[-5:] if len(sorted_tensors) >= 5 else sorted_tensors
|
| 525 |
+
|
| 526 |
+
for i, (name, stats) in enumerate(top5):
|
| 527 |
+
log_dict[f"top_{i+1}/name"] = name
|
| 528 |
+
log_dict[f"top_{i+1}/rms_norm"] = stats["norm"]
|
| 529 |
+
log_dict[f"top_{i+1}/rms_mean"] = stats["mean"]
|
| 530 |
+
for i, (name, stats) in enumerate(bottom5):
|
| 531 |
+
log_dict[f"bottom_{i+1}/name"] = name
|
| 532 |
+
log_dict[f"bottom_{i+1}/rms_norm"] = stats["norm"]
|
| 533 |
+
|
| 534 |
+
# TABLES
|
| 535 |
+
rms_table_data = []
|
| 536 |
+
for name, stats in result["per_tensor_rms"].items():
|
| 537 |
+
rms_table_data.append([
|
| 538 |
+
name, stats["mean"], stats["std"],
|
| 539 |
+
stats["max_abs"], stats["norm"], stats["numel"],
|
| 540 |
+
])
|
| 541 |
+
if rms_table_data:
|
| 542 |
+
log_dict["rms_table"] = wandb.Table(
|
| 543 |
+
columns=["param_name", "mean", "std", "max_abs", "norm", "numel"],
|
| 544 |
+
data=rms_table_data,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
snr_table_data = []
|
| 548 |
+
for name, stats in result["per_tensor_snr"].items():
|
| 549 |
+
snr_table_data.append([
|
| 550 |
+
name, stats["mean"], stats["std"],
|
| 551 |
+
stats["max_abs"], stats["norm"], stats["numel"],
|
| 552 |
+
])
|
| 553 |
+
if snr_table_data:
|
| 554 |
+
log_dict["snr_table"] = wandb.Table(
|
| 555 |
+
columns=["param_name", "mean", "std", "max_abs", "norm", "numel"],
|
| 556 |
+
data=snr_table_data,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
wandb.log(log_dict, step=step)
|
| 560 |
+
|
| 561 |
+
wandb.finish()
|
| 562 |
+
|
| 563 |
+
finally:
|
| 564 |
+
if use_temp and cache_dir.exists():
|
| 565 |
+
shutil.rmtree(cache_dir, ignore_errors=True)
|
| 566 |
+
|
| 567 |
+
print("\nAll done.")
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
if __name__ == "__main__":
|
| 571 |
+
main()
|
zain/Activation/llm_analyzer_wandb.py
ADDED
|
@@ -0,0 +1,1307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Multi-LLM Activation & Loss Analyzer with WandB Logging
|
| 3 |
+
GPU-only, FP32, exact training‑style tokenization (concatenate + chunk).
|
| 4 |
+
Supports PowLU, custom name normalization, full‑dataset evaluation,
|
| 5 |
+
and now captures pre‑down_proj inputs & layer outputs.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
import tempfile
|
| 11 |
+
import shutil
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
from transformers import (
|
| 16 |
+
LlamaConfig,
|
| 17 |
+
LlamaPreTrainedModel,
|
| 18 |
+
AutoTokenizer,
|
| 19 |
+
AutoConfig,
|
| 20 |
+
AutoModelForCausalLM,
|
| 21 |
+
)
|
| 22 |
+
from transformers.models.llama.modeling_llama import (
|
| 23 |
+
LlamaAttention,
|
| 24 |
+
LlamaRMSNorm,
|
| 25 |
+
LlamaRotaryEmbedding,
|
| 26 |
+
)
|
| 27 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 28 |
+
from datasets import load_dataset as hf_load_dataset
|
| 29 |
+
from typing import List, Dict, Optional, Tuple
|
| 30 |
+
from dataclasses import dataclass, asdict
|
| 31 |
+
from collections import defaultdict
|
| 32 |
+
import json
|
| 33 |
+
import warnings
|
| 34 |
+
import os
|
| 35 |
+
from tqdm import tqdm
|
| 36 |
+
import wandb
|
| 37 |
+
|
| 38 |
+
warnings.filterwarnings("ignore")
|
| 39 |
+
|
| 40 |
+
# ============================================================================
|
| 41 |
+
# REPO CONFIGURATION
|
| 42 |
+
# ============================================================================
|
| 43 |
+
|
| 44 |
+
REPO_ID = "w-ahmad/STRESS-TEST3"
|
| 45 |
+
BASE_PATH = "zain/Activation/out" # <-- NO trailing slash
|
| 46 |
+
|
| 47 |
+
# ============================================================================
|
| 48 |
+
# 1. ACTIVATION REGISTRY (exact copy from exp.py)
|
| 49 |
+
# ============================================================================
|
| 50 |
+
|
| 51 |
+
class GLUActivationRegistry:
|
| 52 |
+
_registry: Dict[str, callable] = {}
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def register(cls, name: str, fn: callable) -> None:
|
| 56 |
+
cls._registry[name] = fn
|
| 57 |
+
|
| 58 |
+
@classmethod
|
| 59 |
+
def get(cls, name: str) -> callable:
|
| 60 |
+
if name not in cls._registry:
|
| 61 |
+
raise KeyError(f"Activation '{name}' not found.")
|
| 62 |
+
return cls._registry[name]
|
| 63 |
+
|
| 64 |
+
# Register built-ins
|
| 65 |
+
GLUActivationRegistry.register("silu", nn.functional.silu)
|
| 66 |
+
GLUActivationRegistry.register("swish", nn.functional.silu)
|
| 67 |
+
GLUActivationRegistry.register("relu", nn.functional.relu)
|
| 68 |
+
GLUActivationRegistry.register("gelu", nn.functional.gelu)
|
| 69 |
+
GLUActivationRegistry.register("sigmoid", torch.sigmoid)
|
| 70 |
+
GLUActivationRegistry.register("tanh", torch.tanh)
|
| 71 |
+
GLUActivationRegistry.register("softplus", nn.functional.softplus)
|
| 72 |
+
GLUActivationRegistry.register("linear", lambda x: x)
|
| 73 |
+
GLUActivationRegistry.register("s10", lambda x: x * x * torch.sigmoid(x))
|
| 74 |
+
GLUActivationRegistry.register("w1a", lambda x: x * torch.tanh(x))
|
| 75 |
+
|
| 76 |
+
# ============================================================================
|
| 77 |
+
# 2. CUSTOM CONFIG & MODEL (with PowLU)
|
| 78 |
+
# ============================================================================
|
| 79 |
+
|
| 80 |
+
class TinyLlamaConfig(LlamaConfig):
|
| 81 |
+
model_type = "tiny_llama"
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
mlp_type: str = "glu",
|
| 86 |
+
activation: str = "silu",
|
| 87 |
+
waleed_beta: float = 10.0,
|
| 88 |
+
powlu_m: float = 3.0,
|
| 89 |
+
**kwargs
|
| 90 |
+
):
|
| 91 |
+
super().__init__(**kwargs)
|
| 92 |
+
self.mlp_type = mlp_type
|
| 93 |
+
self.activation = activation
|
| 94 |
+
self.waleed_beta = waleed_beta
|
| 95 |
+
self.powlu_m = powlu_m
|
| 96 |
+
if self.num_key_value_heads != self.num_attention_heads:
|
| 97 |
+
raise ValueError("Pure MHA required.")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class SiTUGLU(nn.Module):
|
| 101 |
+
def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.beta1 = beta1
|
| 104 |
+
self.beta2 = beta2
|
| 105 |
+
self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 106 |
+
self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 107 |
+
|
| 108 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
g = self.W_g(x)
|
| 110 |
+
gate = self.beta1 * torch.tanh(g / self.beta1) * torch.sigmoid(g)
|
| 111 |
+
up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
|
| 112 |
+
return gate * up
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class WaleedGLU(nn.Module):
|
| 116 |
+
def __init__(self, input_dim: int, hidden_dim: int, beta1: float = 4.0, beta2: float = 25.0):
|
| 117 |
+
super().__init__()
|
| 118 |
+
self.beta1 = beta1
|
| 119 |
+
self.beta2 = beta2
|
| 120 |
+
self.W_g = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 121 |
+
self.W_u = nn.Linear(input_dim, hidden_dim, bias=False)
|
| 122 |
+
|
| 123 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 124 |
+
g = self.W_g(x)
|
| 125 |
+
gate = self.beta1 * torch.tanh(g / self.beta1)
|
| 126 |
+
up = self.beta2 * torch.tanh(self.W_u(x) / self.beta2)
|
| 127 |
+
return gate * up
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class TinyLlamaMLP(nn.Module):
|
| 131 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.hidden_size = config.hidden_size
|
| 134 |
+
self.intermediate_size = config.intermediate_size
|
| 135 |
+
self.mlp_type = config.mlp_type
|
| 136 |
+
self.activation_name = config.activation
|
| 137 |
+
self.waleed_beta = getattr(config, "waleed_beta", 10.0)
|
| 138 |
+
self.powlu_m = getattr(config, "powlu_m", 3.0)
|
| 139 |
+
|
| 140 |
+
if self.mlp_type == "glu":
|
| 141 |
+
effective_intermediate = self.intermediate_size
|
| 142 |
+
elif self.mlp_type == "mlp":
|
| 143 |
+
effective_intermediate = int(self.intermediate_size * 1.5)
|
| 144 |
+
else:
|
| 145 |
+
raise ValueError(f"Unknown mlp_type: {self.mlp_type}")
|
| 146 |
+
|
| 147 |
+
self.effective_intermediate = effective_intermediate
|
| 148 |
+
|
| 149 |
+
if self.mlp_type == "glu":
|
| 150 |
+
self.gate_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 151 |
+
self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 152 |
+
else:
|
| 153 |
+
self.up_proj = nn.Linear(self.hidden_size, effective_intermediate, bias=False)
|
| 154 |
+
self.down_proj = nn.Linear(effective_intermediate, self.hidden_size, bias=False)
|
| 155 |
+
|
| 156 |
+
# ---- Activation flags ----
|
| 157 |
+
self.is_powlu = (self.activation_name == "powlu")
|
| 158 |
+
self.is_situglu = self.activation_name in ("situglu", "situglu_low")
|
| 159 |
+
self.is_waleed = self.activation_name in ("waleed", "waleedglu_low")
|
| 160 |
+
self.is_waleed10 = self.activation_name in ("waleed10", "silu-waleed10")
|
| 161 |
+
self.has_sigmoid_gate = self.activation_name.startswith("situglu")
|
| 162 |
+
|
| 163 |
+
# ---- Activation function (for non-PowLU) ----
|
| 164 |
+
if self.mlp_type == "glu":
|
| 165 |
+
if self.is_powlu:
|
| 166 |
+
self.act_fn = None
|
| 167 |
+
elif self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
|
| 168 |
+
self.act_fn = None
|
| 169 |
+
elif self.activation_name == "waleed10":
|
| 170 |
+
self.act_fn = GLUActivationRegistry.get("linear")
|
| 171 |
+
elif self.activation_name == "silu-waleed10":
|
| 172 |
+
self.act_fn = GLUActivationRegistry.get("silu")
|
| 173 |
+
else:
|
| 174 |
+
self.act_fn = GLUActivationRegistry.get(self.activation_name)
|
| 175 |
+
else: # mlp
|
| 176 |
+
if self.is_powlu:
|
| 177 |
+
raise ValueError("PowLU is only supported with mlp_type='glu'")
|
| 178 |
+
if self.activation_name in ("situglu", "waleed", "situglu_low", "waleedglu_low"):
|
| 179 |
+
raise ValueError(f"Activation '{self.activation_name}' requires GLU.")
|
| 180 |
+
elif self.activation_name == "waleed10":
|
| 181 |
+
self.act_fn = GLUActivationRegistry.get("linear")
|
| 182 |
+
elif self.activation_name == "silu-waleed10":
|
| 183 |
+
self.act_fn = GLUActivationRegistry.get("silu")
|
| 184 |
+
else:
|
| 185 |
+
self.act_fn = GLUActivationRegistry.get(self.activation_name)
|
| 186 |
+
|
| 187 |
+
# beta values for situglu/waleed
|
| 188 |
+
if self.activation_name in ("situglu_low", "waleedglu_low"):
|
| 189 |
+
self.beta1 = 2.5
|
| 190 |
+
self.beta2 = 4.0
|
| 191 |
+
else:
|
| 192 |
+
self.beta1 = 4.0
|
| 193 |
+
self.beta2 = 25.0
|
| 194 |
+
|
| 195 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 196 |
+
if self.mlp_type == "glu":
|
| 197 |
+
gate = self.gate_proj(x)
|
| 198 |
+
up = self.up_proj(x)
|
| 199 |
+
|
| 200 |
+
# ----- PowLU branch -----
|
| 201 |
+
if self.is_powlu:
|
| 202 |
+
m = self.powlu_m
|
| 203 |
+
sig_gate = torch.sigmoid(gate)
|
| 204 |
+
pos_mask = gate > 0
|
| 205 |
+
powlu_pos = gate ** (m / (torch.sqrt(gate) + 1)) * sig_gate
|
| 206 |
+
powlu_neg = gate * sig_gate
|
| 207 |
+
activated_gate = torch.where(pos_mask, powlu_pos, powlu_neg)
|
| 208 |
+
hidden = activated_gate * up
|
| 209 |
+
|
| 210 |
+
# ----- situglu / waleed branches -----
|
| 211 |
+
elif self.is_situglu or self.is_waleed:
|
| 212 |
+
if self.has_sigmoid_gate:
|
| 213 |
+
gate = self.beta1 * torch.tanh(gate / self.beta1) * torch.sigmoid(gate)
|
| 214 |
+
else:
|
| 215 |
+
gate = self.beta1 * torch.tanh(gate / self.beta1)
|
| 216 |
+
up = self.beta2 * torch.tanh(up / self.beta2)
|
| 217 |
+
hidden = gate * up
|
| 218 |
+
|
| 219 |
+
# ----- Standard GLU -----
|
| 220 |
+
else:
|
| 221 |
+
hidden = self.act_fn(gate) * up
|
| 222 |
+
|
| 223 |
+
out = self.down_proj(hidden)
|
| 224 |
+
|
| 225 |
+
else: # mlp
|
| 226 |
+
hidden = self.act_fn(self.up_proj(x))
|
| 227 |
+
out = self.down_proj(hidden)
|
| 228 |
+
|
| 229 |
+
# Optional Waleed clipping
|
| 230 |
+
if self.is_waleed10:
|
| 231 |
+
out = self.waleed_beta * torch.tanh(out / self.waleed_beta)
|
| 232 |
+
|
| 233 |
+
return out
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class TinyLlamaDecoderLayer(nn.Module):
|
| 237 |
+
def __init__(self, config: TinyLlamaConfig, layer_idx: int):
|
| 238 |
+
super().__init__()
|
| 239 |
+
self.hidden_size = config.hidden_size
|
| 240 |
+
self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
|
| 241 |
+
self.mlp = TinyLlamaMLP(config)
|
| 242 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 243 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 244 |
+
|
| 245 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None,
|
| 246 |
+
position_embeddings=None, **kwargs):
|
| 247 |
+
residual = hidden_states
|
| 248 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 249 |
+
attn_out = self.self_attn(
|
| 250 |
+
hidden_states=hidden_states,
|
| 251 |
+
attention_mask=attention_mask,
|
| 252 |
+
position_ids=position_ids,
|
| 253 |
+
position_embeddings=position_embeddings,
|
| 254 |
+
)[0]
|
| 255 |
+
hidden_states = residual + attn_out
|
| 256 |
+
|
| 257 |
+
residual = hidden_states
|
| 258 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 259 |
+
hidden_states = self.mlp(hidden_states)
|
| 260 |
+
hidden_states = residual + hidden_states
|
| 261 |
+
return (hidden_states,)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _build_causal_mask(attention_mask, seq_len, dtype, device):
|
| 265 |
+
min_value = torch.finfo(dtype).min
|
| 266 |
+
causal = torch.full((seq_len, seq_len), min_value, dtype=dtype, device=device)
|
| 267 |
+
causal = torch.triu(causal, diagonal=1)
|
| 268 |
+
causal = causal[None, None, :, :]
|
| 269 |
+
if attention_mask is None:
|
| 270 |
+
return causal
|
| 271 |
+
batch_size = attention_mask.shape[0]
|
| 272 |
+
causal = causal.expand(batch_size, 1, seq_len, seq_len).clone()
|
| 273 |
+
padding = attention_mask[:, None, None, :].to(device) == 0
|
| 274 |
+
causal = causal.masked_fill(padding, min_value)
|
| 275 |
+
return causal
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class TinyLlamaModel(LlamaPreTrainedModel):
|
| 279 |
+
config_class = TinyLlamaConfig
|
| 280 |
+
|
| 281 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 282 |
+
super().__init__(config)
|
| 283 |
+
self.padding_idx = config.pad_token_id
|
| 284 |
+
self.vocab_size = config.vocab_size
|
| 285 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 286 |
+
self.layers = nn.ModuleList(
|
| 287 |
+
[TinyLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 288 |
+
)
|
| 289 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 290 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 291 |
+
self.post_init()
|
| 292 |
+
|
| 293 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 294 |
+
inputs_embeds=None, return_dict=None, **kwargs):
|
| 295 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 296 |
+
if inputs_embeds is None:
|
| 297 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 298 |
+
if position_ids is None:
|
| 299 |
+
seq_len = inputs_embeds.shape[1]
|
| 300 |
+
position_ids = torch.arange(seq_len, device=inputs_embeds.device).unsqueeze(0).expand(
|
| 301 |
+
inputs_embeds.shape[0], -1
|
| 302 |
+
)
|
| 303 |
+
hidden_states = inputs_embeds
|
| 304 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 305 |
+
|
| 306 |
+
seq_len = hidden_states.shape[1]
|
| 307 |
+
causal_mask = _build_causal_mask(
|
| 308 |
+
attention_mask, seq_len, hidden_states.dtype, hidden_states.device
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
for decoder_layer in self.layers:
|
| 312 |
+
layer_outputs = decoder_layer(
|
| 313 |
+
hidden_states,
|
| 314 |
+
attention_mask=causal_mask,
|
| 315 |
+
position_ids=position_ids,
|
| 316 |
+
position_embeddings=position_embeddings,
|
| 317 |
+
)
|
| 318 |
+
hidden_states = layer_outputs[0]
|
| 319 |
+
|
| 320 |
+
hidden_states = self.norm(hidden_states)
|
| 321 |
+
if not return_dict:
|
| 322 |
+
return (hidden_states,)
|
| 323 |
+
return {"last_hidden_state": hidden_states, "hidden_states": None, "attentions": None}
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class TinyLlamaForCausalLM(LlamaPreTrainedModel):
|
| 327 |
+
config_class = TinyLlamaConfig
|
| 328 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 329 |
+
|
| 330 |
+
def __init__(self, config: TinyLlamaConfig):
|
| 331 |
+
super().__init__(config)
|
| 332 |
+
self.model = TinyLlamaModel(config)
|
| 333 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 334 |
+
if config.tie_word_embeddings:
|
| 335 |
+
self.lm_head.weight = self.model.embed_tokens.weight
|
| 336 |
+
self.post_init()
|
| 337 |
+
|
| 338 |
+
def get_input_embeddings(self):
|
| 339 |
+
return self.model.embed_tokens
|
| 340 |
+
|
| 341 |
+
def set_input_embeddings(self, value):
|
| 342 |
+
self.model.embed_tokens = value
|
| 343 |
+
|
| 344 |
+
def get_output_embeddings(self):
|
| 345 |
+
return self.lm_head
|
| 346 |
+
|
| 347 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 348 |
+
inputs_embeds=None, labels=None, return_dict=None, **kwargs):
|
| 349 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 350 |
+
outputs = self.model(
|
| 351 |
+
input_ids=input_ids,
|
| 352 |
+
attention_mask=attention_mask,
|
| 353 |
+
position_ids=position_ids,
|
| 354 |
+
inputs_embeds=inputs_embeds,
|
| 355 |
+
return_dict=return_dict,
|
| 356 |
+
)
|
| 357 |
+
hidden_states = outputs["last_hidden_state"] if return_dict else outputs[0]
|
| 358 |
+
logits = self.lm_head(hidden_states)
|
| 359 |
+
|
| 360 |
+
loss = None
|
| 361 |
+
if labels is not None:
|
| 362 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 363 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 364 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 365 |
+
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
|
| 366 |
+
|
| 367 |
+
if not return_dict:
|
| 368 |
+
output = (logits,) + outputs[1:]
|
| 369 |
+
return (loss,) + output if loss is not None else output
|
| 370 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None,
|
| 371 |
+
hidden_states=None, attentions=None)
|
| 372 |
+
|
| 373 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 374 |
+
attention_mask=None, **kwargs):
|
| 375 |
+
if past_key_values:
|
| 376 |
+
input_ids = input_ids[:, -1:]
|
| 377 |
+
position_ids = kwargs.get("position_ids")
|
| 378 |
+
if attention_mask is not None and position_ids is None:
|
| 379 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 380 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 381 |
+
if past_key_values:
|
| 382 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
| 383 |
+
return {
|
| 384 |
+
"input_ids": input_ids,
|
| 385 |
+
"position_ids": position_ids,
|
| 386 |
+
"past_key_values": past_key_values,
|
| 387 |
+
"attention_mask": attention_mask,
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
# ============================================================================
|
| 391 |
+
# END OF MODEL DEFINITIONS
|
| 392 |
+
# ============================================================================
|
| 393 |
+
|
| 394 |
+
# Percentiles we report everywhere
|
| 395 |
+
PERCENTILES = [25.0, 50.0, 90.0, 99.0, 99.9]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
@dataclass
|
| 399 |
+
class TensorStats:
|
| 400 |
+
mean: float
|
| 401 |
+
max_abs: float
|
| 402 |
+
std: float
|
| 403 |
+
norm: float
|
| 404 |
+
numel: int
|
| 405 |
+
min_val: float
|
| 406 |
+
max_val: float
|
| 407 |
+
range_val: float
|
| 408 |
+
p25: float
|
| 409 |
+
p50: float
|
| 410 |
+
p90: float
|
| 411 |
+
p99: float
|
| 412 |
+
p999: float
|
| 413 |
+
|
| 414 |
+
@staticmethod
|
| 415 |
+
def zero() -> "TensorStats":
|
| 416 |
+
return TensorStats(
|
| 417 |
+
mean=0.0, max_abs=0.0, std=0.0, norm=0.0, numel=0,
|
| 418 |
+
min_val=0.0, max_val=0.0, range_val=0.0,
|
| 419 |
+
p25=0.0, p50=0.0, p90=0.0, p99=0.0, p999=0.0,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
@dataclass
|
| 424 |
+
class ModelResult:
|
| 425 |
+
model_name: str
|
| 426 |
+
dataset_name: str
|
| 427 |
+
loss: float
|
| 428 |
+
perplexity: float
|
| 429 |
+
global_act: TensorStats
|
| 430 |
+
layer_acts: Dict[str, TensorStats]
|
| 431 |
+
num_tokens: int
|
| 432 |
+
num_layers: int
|
| 433 |
+
hidden_size: int
|
| 434 |
+
num_params: int
|
| 435 |
+
checkpoint_step: int = 0
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
# ============================================================================
|
| 439 |
+
# ACTIVATION HOOK MANAGER — with name normalization & extra hooks
|
| 440 |
+
# ============================================================================
|
| 441 |
+
|
| 442 |
+
class ActivationHookManager:
|
| 443 |
+
def __init__(
|
| 444 |
+
self,
|
| 445 |
+
store_dtype: torch.dtype = torch.float16,
|
| 446 |
+
exclude_substrings: Optional[List[str]] = None,
|
| 447 |
+
max_elements_per_tensor: Optional[int] = 500_000,
|
| 448 |
+
disk_offload: bool = False,
|
| 449 |
+
disk_dir: Optional[str] = None,
|
| 450 |
+
capture_pre_down: bool = True,
|
| 451 |
+
capture_layer_output: bool = True,
|
| 452 |
+
):
|
| 453 |
+
self.raw_values: Dict[str, List[torch.Tensor]] = defaultdict(list)
|
| 454 |
+
self.hooks = []
|
| 455 |
+
self._attention_mask: Optional[torch.Tensor] = None
|
| 456 |
+
self.store_dtype = store_dtype
|
| 457 |
+
self.exclude_substrings = exclude_substrings if exclude_substrings is not None else ["lm_head"]
|
| 458 |
+
self.max_elements_per_tensor = max_elements_per_tensor
|
| 459 |
+
self._per_batch_quota: Optional[int] = None
|
| 460 |
+
self._counts: Dict[str, int] = defaultdict(int)
|
| 461 |
+
self.disk_offload = disk_offload
|
| 462 |
+
self.disk_dir = disk_dir
|
| 463 |
+
self._file_handles: Dict[str, "object"] = {}
|
| 464 |
+
self.capture_pre_down = capture_pre_down
|
| 465 |
+
self.capture_layer_output = capture_layer_output
|
| 466 |
+
if self.disk_offload:
|
| 467 |
+
self.disk_dir = disk_dir or tempfile.mkdtemp(prefix="act_cache_")
|
| 468 |
+
os.makedirs(self.disk_dir, exist_ok=True)
|
| 469 |
+
|
| 470 |
+
@staticmethod
|
| 471 |
+
def _safe_filename(name: str) -> str:
|
| 472 |
+
return name.replace("/", "__").replace(".", "_") + ".bin"
|
| 473 |
+
|
| 474 |
+
def set_expected_batches(self, num_batches: int):
|
| 475 |
+
if self.max_elements_per_tensor is not None:
|
| 476 |
+
self._per_batch_quota = max(1, self.max_elements_per_tensor // max(1, num_batches))
|
| 477 |
+
else:
|
| 478 |
+
self._per_batch_quota = None
|
| 479 |
+
|
| 480 |
+
def set_attention_mask(self, attention_mask: Optional[torch.Tensor]):
|
| 481 |
+
self._attention_mask = attention_mask
|
| 482 |
+
|
| 483 |
+
def _make_hook(self, name: str, is_pre: bool = False):
|
| 484 |
+
"""Factory for hook functions. If is_pre, captures input; otherwise output."""
|
| 485 |
+
def hook(module, input_or_output, output=None):
|
| 486 |
+
# For pre_hook: input_or_output is the input tuple, output is None.
|
| 487 |
+
# For post_hook: input_or_output is the input tuple (ignored), output is the module output.
|
| 488 |
+
if is_pre:
|
| 489 |
+
# Capture the first input tensor (usually the only one)
|
| 490 |
+
tensor = input_or_output[0] if isinstance(input_or_output, tuple) else input_or_output
|
| 491 |
+
else:
|
| 492 |
+
# For post hook, we capture output
|
| 493 |
+
if isinstance(output, torch.Tensor):
|
| 494 |
+
tensor = output
|
| 495 |
+
elif isinstance(output, tuple) and len(output) > 0 and isinstance(output[0], torch.Tensor):
|
| 496 |
+
tensor = output[0]
|
| 497 |
+
else:
|
| 498 |
+
return
|
| 499 |
+
|
| 500 |
+
if not torch.is_tensor(tensor):
|
| 501 |
+
return
|
| 502 |
+
|
| 503 |
+
# Apply attention mask if available (only for post hooks that have matching shape)
|
| 504 |
+
mask = self._attention_mask
|
| 505 |
+
if not is_pre and mask is not None and tensor.dim() >= 2 and tensor.shape[0] == mask.shape[0] and tensor.shape[1] == mask.shape[1]:
|
| 506 |
+
flat = tensor[mask.bool()].reshape(-1)
|
| 507 |
+
else:
|
| 508 |
+
flat = tensor.reshape(-1)
|
| 509 |
+
|
| 510 |
+
if flat.numel() == 0:
|
| 511 |
+
return
|
| 512 |
+
|
| 513 |
+
if self._per_batch_quota is not None and flat.numel() > self._per_batch_quota:
|
| 514 |
+
idx = torch.randperm(flat.numel(), device=flat.device)[:self._per_batch_quota]
|
| 515 |
+
sampled = flat[idx]
|
| 516 |
+
else:
|
| 517 |
+
sampled = flat
|
| 518 |
+
|
| 519 |
+
if self.disk_offload:
|
| 520 |
+
self._write_to_disk(name, sampled)
|
| 521 |
+
else:
|
| 522 |
+
self.raw_values[name].append(sampled.detach().to(self.store_dtype))
|
| 523 |
+
self._counts[name] += sampled.numel()
|
| 524 |
+
return hook
|
| 525 |
+
|
| 526 |
+
def _write_to_disk(self, name: str, flat: torch.Tensor):
|
| 527 |
+
arr = flat.detach().to(self.store_dtype).cpu().numpy()
|
| 528 |
+
fh = self._file_handles.get(name)
|
| 529 |
+
if fh is None:
|
| 530 |
+
path = os.path.join(self.disk_dir, self._safe_filename(name))
|
| 531 |
+
fh = open(path, "ab")
|
| 532 |
+
self._file_handles[name] = fh
|
| 533 |
+
arr.tofile(fh)
|
| 534 |
+
|
| 535 |
+
def register_hooks(self, model: torch.nn.Module):
|
| 536 |
+
"""Register hooks for MLP activations, pre-down, and layer outputs."""
|
| 537 |
+
# 1. Standard hooks on gate_proj, up_proj, down_proj (post-activation)
|
| 538 |
+
for name, module in model.named_modules():
|
| 539 |
+
if any(x in name for x in ["gate_proj", "up_proj", "down_proj"]):
|
| 540 |
+
# Normalize: W_g/W_u already handled in canonical names; for down_proj keep as is
|
| 541 |
+
# For down_proj we also want a pre-hook separately
|
| 542 |
+
# For post-hook we use the original name (already canonical for gate/up)
|
| 543 |
+
norm_name = name.replace("W_g", "gate_proj").replace("W_u", "up_proj")
|
| 544 |
+
hook = module.register_forward_hook(self._make_hook(norm_name, is_pre=False))
|
| 545 |
+
self.hooks.append(hook)
|
| 546 |
+
|
| 547 |
+
# 2. Pre-down_proj hook (captures input to down_proj)
|
| 548 |
+
if self.capture_pre_down:
|
| 549 |
+
for name, module in model.named_modules():
|
| 550 |
+
if "down_proj" in name:
|
| 551 |
+
# Name: replace "down_proj" with "pre_down"
|
| 552 |
+
pre_name = name.replace("down_proj", "pre_down")
|
| 553 |
+
hook = module.register_forward_pre_hook(self._make_hook(pre_name, is_pre=True))
|
| 554 |
+
self.hooks.append(hook)
|
| 555 |
+
|
| 556 |
+
# 3. Layer output hook (captures final hidden_states from each decoder layer)
|
| 557 |
+
if self.capture_layer_output:
|
| 558 |
+
for name, module in model.named_modules():
|
| 559 |
+
if isinstance(module, TinyLlamaDecoderLayer):
|
| 560 |
+
# Use the module's full name, e.g., model.layers.0
|
| 561 |
+
out_name = f"{name}.output"
|
| 562 |
+
hook = module.register_forward_hook(self._make_hook(out_name, is_pre=False))
|
| 563 |
+
self.hooks.append(hook)
|
| 564 |
+
|
| 565 |
+
def clear(self):
|
| 566 |
+
self.raw_values.clear()
|
| 567 |
+
self._counts.clear()
|
| 568 |
+
for fh in self._file_handles.values():
|
| 569 |
+
try:
|
| 570 |
+
fh.close()
|
| 571 |
+
except Exception:
|
| 572 |
+
pass
|
| 573 |
+
self._file_handles.clear()
|
| 574 |
+
if self.disk_offload and self.disk_dir:
|
| 575 |
+
shutil.rmtree(self.disk_dir, ignore_errors=True)
|
| 576 |
+
|
| 577 |
+
def remove_hooks(self):
|
| 578 |
+
for hook in self.hooks:
|
| 579 |
+
hook.remove()
|
| 580 |
+
self.hooks.clear()
|
| 581 |
+
|
| 582 |
+
@staticmethod
|
| 583 |
+
def _compute_stats_from_tensor(flat: torch.Tensor) -> TensorStats:
|
| 584 |
+
flat32 = flat.to(torch.float32)
|
| 585 |
+
numel = flat32.numel()
|
| 586 |
+
mean = flat32.mean().item()
|
| 587 |
+
std = flat32.std(unbiased=False).item()
|
| 588 |
+
norm = flat32.norm().item()
|
| 589 |
+
min_val = flat32.min().item()
|
| 590 |
+
max_val = flat32.max().item()
|
| 591 |
+
max_abs = max(abs(min_val), abs(max_val))
|
| 592 |
+
|
| 593 |
+
q = torch.tensor([p / 100.0 for p in PERCENTILES], device=flat32.device, dtype=torch.float32)
|
| 594 |
+
try:
|
| 595 |
+
quantiles = torch.quantile(flat32, q).tolist()
|
| 596 |
+
except RuntimeError:
|
| 597 |
+
import numpy as np
|
| 598 |
+
arr = flat32.cpu().numpy()
|
| 599 |
+
quantiles = np.percentile(arr, PERCENTILES).tolist()
|
| 600 |
+
|
| 601 |
+
p25, p50, p90, p99, p999 = quantiles
|
| 602 |
+
|
| 603 |
+
return TensorStats(
|
| 604 |
+
mean=mean, max_abs=max_abs, std=std, norm=norm, numel=numel,
|
| 605 |
+
min_val=min_val, max_val=max_val, range_val=max_val - min_val,
|
| 606 |
+
p25=p25, p50=p50, p90=p90, p99=p99, p999=p999,
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
def get_all_stats(self) -> Tuple[Dict[str, "TensorStats"], "TensorStats"]:
|
| 610 |
+
if self.disk_offload:
|
| 611 |
+
return self._get_all_stats_from_disk()
|
| 612 |
+
|
| 613 |
+
layer_stats: Dict[str, TensorStats] = {}
|
| 614 |
+
for name, chunks in self.raw_values.items():
|
| 615 |
+
if not chunks:
|
| 616 |
+
continue
|
| 617 |
+
flat = torch.cat(chunks)
|
| 618 |
+
layer_stats[name] = self._compute_stats_from_tensor(flat)
|
| 619 |
+
del chunks, flat
|
| 620 |
+
self.raw_values[name] = []
|
| 621 |
+
|
| 622 |
+
global_stats = TensorStats.zero()
|
| 623 |
+
return layer_stats, global_stats
|
| 624 |
+
|
| 625 |
+
def _get_all_stats_from_disk(self) -> Tuple[Dict[str, "TensorStats"], "TensorStats"]:
|
| 626 |
+
for fh in self._file_handles.values():
|
| 627 |
+
try:
|
| 628 |
+
fh.close()
|
| 629 |
+
except Exception:
|
| 630 |
+
pass
|
| 631 |
+
self._file_handles.clear()
|
| 632 |
+
|
| 633 |
+
np_dtype = np.float16 if self.store_dtype == torch.float16 else np.float32
|
| 634 |
+
layer_stats: Dict[str, TensorStats] = {}
|
| 635 |
+
|
| 636 |
+
for name in list(self._counts.keys()):
|
| 637 |
+
path = os.path.join(self.disk_dir, self._safe_filename(name))
|
| 638 |
+
if not os.path.exists(path):
|
| 639 |
+
continue
|
| 640 |
+
arr = np.fromfile(path, dtype=np_dtype)
|
| 641 |
+
os.remove(path)
|
| 642 |
+
if arr.size == 0:
|
| 643 |
+
continue
|
| 644 |
+
t = torch.from_numpy(arr.astype(np.float32))
|
| 645 |
+
layer_stats[name] = self._compute_stats_from_tensor(t)
|
| 646 |
+
del t, arr
|
| 647 |
+
|
| 648 |
+
shutil.rmtree(self.disk_dir, ignore_errors=True)
|
| 649 |
+
global_stats = TensorStats.zero()
|
| 650 |
+
return layer_stats, global_stats
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
# ============================================================================
|
| 654 |
+
# LLM ANALYZER — TRAINING‑STYLE TOKENIZATION, FULL DATASET SUPPORT
|
| 655 |
+
# ============================================================================
|
| 656 |
+
|
| 657 |
+
class LLMAnalyzer:
|
| 658 |
+
def __init__(
|
| 659 |
+
self,
|
| 660 |
+
max_length: int = 512,
|
| 661 |
+
max_samples: Optional[int] = 1000,
|
| 662 |
+
batch_size: int = 4,
|
| 663 |
+
wandb_project: Optional[str] = None,
|
| 664 |
+
cbt_simple_max_chars: int = 120,
|
| 665 |
+
min_line_chars: int = 20,
|
| 666 |
+
activation_store_dtype: torch.dtype = torch.float16,
|
| 667 |
+
track_activations: bool = True,
|
| 668 |
+
activation_hook_exclude: Optional[List[str]] = None,
|
| 669 |
+
max_elements_per_tensor: Optional[int] = 500_000,
|
| 670 |
+
activation_disk_offload: bool = False,
|
| 671 |
+
activation_disk_dir: Optional[str] = None,
|
| 672 |
+
capture_pre_down: bool = True,
|
| 673 |
+
capture_layer_output: bool = True,
|
| 674 |
+
):
|
| 675 |
+
if not torch.cuda.is_available():
|
| 676 |
+
raise RuntimeError("This script requires a GPU. CUDA is not available.")
|
| 677 |
+
self.device = "cuda"
|
| 678 |
+
self.dtype = torch.float32
|
| 679 |
+
|
| 680 |
+
self.max_length = max_length
|
| 681 |
+
self.max_samples = max_samples
|
| 682 |
+
self.batch_size = batch_size
|
| 683 |
+
self.wandb_project = wandb_project or os.environ.get("WANDB_PROJECT", "llm-activation-analysis")
|
| 684 |
+
self.cbt_simple_max_chars = cbt_simple_max_chars
|
| 685 |
+
self.min_line_chars = min_line_chars
|
| 686 |
+
self.activation_store_dtype = activation_store_dtype
|
| 687 |
+
self.track_activations = track_activations
|
| 688 |
+
self.activation_hook_exclude = activation_hook_exclude if activation_hook_exclude is not None else ["lm_head"]
|
| 689 |
+
self.max_elements_per_tensor = max_elements_per_tensor
|
| 690 |
+
self.activation_disk_offload = activation_disk_offload
|
| 691 |
+
self.activation_disk_dir = activation_disk_dir
|
| 692 |
+
self.capture_pre_down = capture_pre_down
|
| 693 |
+
self.capture_layer_output = capture_layer_output
|
| 694 |
+
self._cache = {}
|
| 695 |
+
self._dataset_cache: Dict[str, List[str]] = {}
|
| 696 |
+
|
| 697 |
+
# ------------------------------------------------------------------
|
| 698 |
+
# Dataset loaders – now respect max_samples=None (load all)
|
| 699 |
+
# ------------------------------------------------------------------
|
| 700 |
+
|
| 701 |
+
def _load_tinystories(self, split: str = "validation") -> List[str]:
|
| 702 |
+
print(f"[Dataset] Loading TinyStories (split='{split}')...")
|
| 703 |
+
ds = hf_load_dataset("roneneldan/TinyStories", split=split)
|
| 704 |
+
lines = []
|
| 705 |
+
for example in ds:
|
| 706 |
+
text = (example.get("text") or "").strip()
|
| 707 |
+
if len(text) >= self.min_line_chars:
|
| 708 |
+
lines.append(text)
|
| 709 |
+
if self.max_samples is not None and len(lines) >= self.max_samples:
|
| 710 |
+
break
|
| 711 |
+
print(f"[Dataset] Loaded {len(lines)} TinyStories examples")
|
| 712 |
+
return lines
|
| 713 |
+
|
| 714 |
+
def _load_simplestories(self, split: str = "test") -> List[str]:
|
| 715 |
+
print(f"[Dataset] Loading SimpleStories (split='{split}')...")
|
| 716 |
+
ds = hf_load_dataset("SimpleStories/SimpleStories", split=split)
|
| 717 |
+
lines = []
|
| 718 |
+
for example in ds:
|
| 719 |
+
text = (example.get("story") or "").strip()
|
| 720 |
+
if len(text) >= self.min_line_chars:
|
| 721 |
+
lines.append(text)
|
| 722 |
+
if self.max_samples is not None and len(lines) >= self.max_samples:
|
| 723 |
+
break
|
| 724 |
+
print(f"[Dataset] Loaded {len(lines)} SimpleStories examples")
|
| 725 |
+
return lines
|
| 726 |
+
|
| 727 |
+
def _load_cbt_simple(self, split: str = "test") -> List[str]:
|
| 728 |
+
print(f"[Dataset] Loading CBT-simple (cam-cst/cbt, raw, split='{split}', "
|
| 729 |
+
f"max_chars={self.cbt_simple_max_chars})...")
|
| 730 |
+
ds = hf_load_dataset("cam-cst/cbt", "raw", split=split)
|
| 731 |
+
lines = []
|
| 732 |
+
for example in ds:
|
| 733 |
+
content = example.get("content", "")
|
| 734 |
+
if not content:
|
| 735 |
+
continue
|
| 736 |
+
for chunk in content.replace("\r\n", "\n").split("\n"):
|
| 737 |
+
chunk = chunk.strip()
|
| 738 |
+
if self.min_line_chars <= len(chunk) <= self.cbt_simple_max_chars:
|
| 739 |
+
lines.append(chunk)
|
| 740 |
+
if self.max_samples is not None and len(lines) >= self.max_samples:
|
| 741 |
+
break
|
| 742 |
+
print(f"[Dataset] Loaded {len(lines)} simple CBT sentences")
|
| 743 |
+
return lines[:self.max_samples] if self.max_samples is not None else lines
|
| 744 |
+
|
| 745 |
+
DATASET_LOADERS = {
|
| 746 |
+
"tinystories": lambda self, split: self._load_tinystories(split or "validation"),
|
| 747 |
+
"simplestories": lambda self, split: self._load_simplestories(split or "test"),
|
| 748 |
+
"cbt_simple": lambda self, split: self._load_cbt_simple(split or "test"),
|
| 749 |
+
}
|
| 750 |
+
|
| 751 |
+
def load_dataset(self, dataset_name: str, split: Optional[str] = None) -> List[str]:
|
| 752 |
+
cache_key = f"{dataset_name}:{split}"
|
| 753 |
+
if cache_key in self._dataset_cache:
|
| 754 |
+
return self._dataset_cache[cache_key]
|
| 755 |
+
if dataset_name not in self.DATASET_LOADERS:
|
| 756 |
+
raise ValueError(f"Unknown dataset '{dataset_name}'. Options: {list(self.DATASET_LOADERS)}")
|
| 757 |
+
texts = self.DATASET_LOADERS[dataset_name](self, split)
|
| 758 |
+
self._dataset_cache[cache_key] = texts
|
| 759 |
+
return texts
|
| 760 |
+
|
| 761 |
+
# ------------------------------------------------------------------
|
| 762 |
+
# Training‑style block preparation (no padding, no BOS)
|
| 763 |
+
# ------------------------------------------------------------------
|
| 764 |
+
|
| 765 |
+
def _prepare_blocks(self, texts: List[str], tokenizer, max_seq_len: int) -> List[List[int]]:
|
| 766 |
+
"""
|
| 767 |
+
Tokenize texts exactly as in training:
|
| 768 |
+
- add_special_tokens=False
|
| 769 |
+
- append EOS token (tokenizer.eos_token_id)
|
| 770 |
+
- concatenate all stories into one flat list
|
| 771 |
+
- split into blocks of size max_seq_len, discarding any remainder
|
| 772 |
+
Returns a list of token ID lists, each exactly max_seq_len long.
|
| 773 |
+
"""
|
| 774 |
+
eos_id = tokenizer.eos_token_id # should be 0 for this tokenizer
|
| 775 |
+
flat_tokens = []
|
| 776 |
+
for text in texts:
|
| 777 |
+
ids = tokenizer.encode(text, add_special_tokens=False)
|
| 778 |
+
ids.append(eos_id)
|
| 779 |
+
flat_tokens.extend(ids)
|
| 780 |
+
|
| 781 |
+
num_blocks = len(flat_tokens) // max_seq_len
|
| 782 |
+
blocks = []
|
| 783 |
+
for i in range(num_blocks):
|
| 784 |
+
start = i * max_seq_len
|
| 785 |
+
end = start + max_seq_len
|
| 786 |
+
blocks.append(flat_tokens[start:end])
|
| 787 |
+
return blocks
|
| 788 |
+
|
| 789 |
+
# ------------------------------------------------------------------
|
| 790 |
+
# Model loading – reads waleed_beta and powlu_m from config
|
| 791 |
+
# ------------------------------------------------------------------
|
| 792 |
+
|
| 793 |
+
def load_model(self, model_name: str):
|
| 794 |
+
if model_name in self._cache:
|
| 795 |
+
return self._cache[model_name]
|
| 796 |
+
|
| 797 |
+
print(f"[Loading] {model_name} ...")
|
| 798 |
+
parts = model_name.split("/")
|
| 799 |
+
if len(parts) > 2:
|
| 800 |
+
repo_id = "/".join(parts[:2])
|
| 801 |
+
subfolder = "/".join(parts[2:])
|
| 802 |
+
else:
|
| 803 |
+
repo_id = model_name
|
| 804 |
+
subfolder = None
|
| 805 |
+
|
| 806 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 807 |
+
"w-ahmad/tiny-stories-tokenizer",
|
| 808 |
+
trust_remote_code=True,
|
| 809 |
+
padding_side="left"
|
| 810 |
+
)
|
| 811 |
+
if tokenizer.pad_token is None:
|
| 812 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 813 |
+
|
| 814 |
+
config = TinyLlamaConfig.from_pretrained(
|
| 815 |
+
repo_id, subfolder=subfolder, trust_remote_code=True
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
model = TinyLlamaForCausalLM.from_pretrained(
|
| 819 |
+
repo_id,
|
| 820 |
+
config=config,
|
| 821 |
+
subfolder=subfolder,
|
| 822 |
+
torch_dtype=self.dtype,
|
| 823 |
+
trust_remote_code=True,
|
| 824 |
+
)
|
| 825 |
+
model = model.to(self.device)
|
| 826 |
+
model.eval()
|
| 827 |
+
num_params = sum(p.numel() for p in model.parameters())
|
| 828 |
+
|
| 829 |
+
self._cache[model_name] = (tokenizer, model, config, num_params)
|
| 830 |
+
print(f"[Loaded] {model_name} | Params: {num_params/1e6:.1f}M | Layers: {config.num_hidden_layers} | Hidden: {config.hidden_size} | waleed_beta: {config.waleed_beta} | powlu_m: {config.powlu_m}")
|
| 831 |
+
return tokenizer, model, config, num_params
|
| 832 |
+
|
| 833 |
+
# ------------------------------------------------------------------
|
| 834 |
+
# Discover checkpoints (unchanged)
|
| 835 |
+
# ------------------------------------------------------------------
|
| 836 |
+
|
| 837 |
+
def discover_checkpoints(self) -> Dict[str, List[Tuple[int, str]]]:
|
| 838 |
+
from huggingface_hub import list_repo_files
|
| 839 |
+
print(f"🔍 Scanning Hugging Face repo: {REPO_ID}/{BASE_PATH} ...")
|
| 840 |
+
try:
|
| 841 |
+
all_files = list_repo_files(REPO_ID)
|
| 842 |
+
except Exception as e:
|
| 843 |
+
print(f"❌ Failed to fetch from Hugging Face Hub: {e}")
|
| 844 |
+
print("💡 Falling back to manual list.")
|
| 845 |
+
return {
|
| 846 |
+
"glu-silu-waleed10_run": [(100, "checkpoint-100")],
|
| 847 |
+
}
|
| 848 |
+
|
| 849 |
+
run_checkpoints = defaultdict(list)
|
| 850 |
+
prefix = BASE_PATH + "/"
|
| 851 |
+
for file_path in all_files:
|
| 852 |
+
if not file_path.startswith(prefix):
|
| 853 |
+
continue
|
| 854 |
+
rel_path = file_path[len(prefix):]
|
| 855 |
+
parts = rel_path.split("/")
|
| 856 |
+
if len(parts) < 2:
|
| 857 |
+
continue
|
| 858 |
+
run_folder = parts[0]
|
| 859 |
+
ckpt_folder = parts[1]
|
| 860 |
+
if not ckpt_folder.startswith("checkpoint-"):
|
| 861 |
+
continue
|
| 862 |
+
if not (file_path.endswith("config.json") or file_path.endswith("model.safetensors")):
|
| 863 |
+
continue
|
| 864 |
+
try:
|
| 865 |
+
ckpt_num = int(ckpt_folder.replace("checkpoint-", ""))
|
| 866 |
+
except ValueError:
|
| 867 |
+
continue
|
| 868 |
+
run_checkpoints[run_folder].append((ckpt_num, ckpt_folder))
|
| 869 |
+
|
| 870 |
+
result = {}
|
| 871 |
+
for run_folder, ckpts in run_checkpoints.items():
|
| 872 |
+
seen = set()
|
| 873 |
+
unique = []
|
| 874 |
+
for ckpt_num, ckpt_folder in sorted(ckpts, key=lambda x: x[0]):
|
| 875 |
+
if ckpt_num not in seen:
|
| 876 |
+
seen.add(ckpt_num)
|
| 877 |
+
unique.append((ckpt_num, ckpt_folder))
|
| 878 |
+
result[run_folder] = unique
|
| 879 |
+
|
| 880 |
+
print(f"✅ Found {len(result)} run folders:")
|
| 881 |
+
for run_folder, ckpts in sorted(result.items()):
|
| 882 |
+
print(f" - {run_folder}: {len(ckpts)} checkpoints ({ckpts[0][0]}...{ckpts[-1][0]})")
|
| 883 |
+
return result
|
| 884 |
+
|
| 885 |
+
# ------------------------------------------------------------------
|
| 886 |
+
# Single checkpoint evaluation
|
| 887 |
+
# ------------------------------------------------------------------
|
| 888 |
+
|
| 889 |
+
def _evaluate_checkpoint(
|
| 890 |
+
self,
|
| 891 |
+
model_name: str,
|
| 892 |
+
dataset_name: str,
|
| 893 |
+
blocks: List[List[int]],
|
| 894 |
+
) -> ModelResult:
|
| 895 |
+
tokenizer, model, config, num_params = self.load_model(model_name)
|
| 896 |
+
|
| 897 |
+
total_loss = 0.0
|
| 898 |
+
total_tokens = 0
|
| 899 |
+
num_batches = (len(blocks) + self.batch_size - 1) // self.batch_size
|
| 900 |
+
|
| 901 |
+
hook_mgr = None
|
| 902 |
+
if self.track_activations:
|
| 903 |
+
hook_mgr = ActivationHookManager(
|
| 904 |
+
store_dtype=self.activation_store_dtype,
|
| 905 |
+
exclude_substrings=self.activation_hook_exclude,
|
| 906 |
+
max_elements_per_tensor=self.max_elements_per_tensor,
|
| 907 |
+
disk_offload=self.activation_disk_offload,
|
| 908 |
+
disk_dir=self.activation_disk_dir,
|
| 909 |
+
capture_pre_down=self.capture_pre_down,
|
| 910 |
+
capture_layer_output=self.capture_layer_output,
|
| 911 |
+
)
|
| 912 |
+
hook_mgr.register_hooks(model)
|
| 913 |
+
hook_mgr.set_expected_batches(num_batches)
|
| 914 |
+
|
| 915 |
+
if hook_mgr is not None:
|
| 916 |
+
n_hooks = len(hook_mgr.hooks)
|
| 917 |
+
mode = "disk" if self.activation_disk_offload else "in-memory"
|
| 918 |
+
if self.max_elements_per_tensor is None:
|
| 919 |
+
print(f"[Memory] ⚠️ {n_hooks} modules hooked ({mode}) with NO cap.")
|
| 920 |
+
else:
|
| 921 |
+
est_mb = (n_hooks * self.max_elements_per_tensor * 2) / (1024 ** 2)
|
| 922 |
+
where = f"on disk at {hook_mgr.disk_dir}" if self.activation_disk_offload else "in RAM/VRAM"
|
| 923 |
+
print(f"[Memory] {n_hooks} modules hooked, capped at {self.max_elements_per_tensor:,} elements/tensor (~{est_mb:.0f} MB ceiling, stored {where}).")
|
| 924 |
+
|
| 925 |
+
try:
|
| 926 |
+
desc = f"Eval {model_name.split('/')[-2]}/{model_name.split('/')[-1]}"
|
| 927 |
+
for batch_idx, i in enumerate(tqdm(range(0, len(blocks), self.batch_size), desc=desc, total=num_batches)):
|
| 928 |
+
batch_blocks = blocks[i:i+self.batch_size]
|
| 929 |
+
input_ids = torch.tensor(batch_blocks, dtype=torch.long, device=self.device)
|
| 930 |
+
attention_mask = None
|
| 931 |
+
labels = input_ids.clone()
|
| 932 |
+
|
| 933 |
+
if hook_mgr is not None:
|
| 934 |
+
hook_mgr.set_attention_mask(None)
|
| 935 |
+
|
| 936 |
+
with torch.no_grad():
|
| 937 |
+
outputs = model(
|
| 938 |
+
input_ids=input_ids,
|
| 939 |
+
attention_mask=attention_mask,
|
| 940 |
+
labels=labels,
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
logits = outputs.logits
|
| 944 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 945 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 946 |
+
loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
|
| 947 |
+
token_losses = loss_fct(
|
| 948 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 949 |
+
shift_labels.view(-1)
|
| 950 |
+
)
|
| 951 |
+
num_valid_tokens = token_losses.numel()
|
| 952 |
+
batch_loss = token_losses.sum().item()
|
| 953 |
+
total_loss += batch_loss
|
| 954 |
+
total_tokens += num_valid_tokens
|
| 955 |
+
|
| 956 |
+
if batch_idx % 20 == 19:
|
| 957 |
+
torch.cuda.empty_cache()
|
| 958 |
+
|
| 959 |
+
if hook_mgr is not None:
|
| 960 |
+
hook_mgr.remove_hooks()
|
| 961 |
+
final_layer_stats, global_stats = hook_mgr.get_all_stats()
|
| 962 |
+
else:
|
| 963 |
+
final_layer_stats, global_stats = {}, TensorStats.zero()
|
| 964 |
+
except Exception:
|
| 965 |
+
if hook_mgr is not None:
|
| 966 |
+
hook_mgr.remove_hooks()
|
| 967 |
+
hook_mgr.clear()
|
| 968 |
+
raise
|
| 969 |
+
|
| 970 |
+
avg_loss = total_loss / max(total_tokens, 1)
|
| 971 |
+
perplexity = torch.exp(torch.tensor(avg_loss)).item()
|
| 972 |
+
|
| 973 |
+
checkpoint_step = 0
|
| 974 |
+
for part in model_name.split("/"):
|
| 975 |
+
if part.startswith("checkpoint-"):
|
| 976 |
+
try:
|
| 977 |
+
checkpoint_step = int(part.replace("checkpoint-", ""))
|
| 978 |
+
except ValueError:
|
| 979 |
+
pass
|
| 980 |
+
|
| 981 |
+
result = ModelResult(
|
| 982 |
+
model_name=model_name,
|
| 983 |
+
dataset_name=dataset_name,
|
| 984 |
+
loss=avg_loss,
|
| 985 |
+
perplexity=perplexity,
|
| 986 |
+
global_act=global_stats,
|
| 987 |
+
layer_acts=final_layer_stats,
|
| 988 |
+
num_tokens=total_tokens,
|
| 989 |
+
num_layers=config.num_hidden_layers,
|
| 990 |
+
hidden_size=config.hidden_size,
|
| 991 |
+
num_params=num_params,
|
| 992 |
+
checkpoint_step=checkpoint_step,
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
self._cache.pop(model_name, None)
|
| 996 |
+
del model
|
| 997 |
+
torch.cuda.empty_cache()
|
| 998 |
+
|
| 999 |
+
return result
|
| 1000 |
+
|
| 1001 |
+
# ------------------------------------------------------------------
|
| 1002 |
+
# Logging (updated to include new stats)
|
| 1003 |
+
# ------------------------------------------------------------------
|
| 1004 |
+
|
| 1005 |
+
def _log_checkpoint_to_wandb(self, result: ModelResult, step: int):
|
| 1006 |
+
wandb.log({
|
| 1007 |
+
"final/loss": result.loss,
|
| 1008 |
+
"final/perplexity": result.perplexity,
|
| 1009 |
+
"final/num_tokens": result.num_tokens,
|
| 1010 |
+
}, step=step)
|
| 1011 |
+
|
| 1012 |
+
if not self.track_activations:
|
| 1013 |
+
return
|
| 1014 |
+
|
| 1015 |
+
# Log per-tensor stats
|
| 1016 |
+
for tensor_name, stats in result.layer_acts.items():
|
| 1017 |
+
clean_name = tensor_name.replace(".", "/")
|
| 1018 |
+
# Determine the kind from the name: pre_down, output, or others (gate/up/down)
|
| 1019 |
+
if "pre_down" in tensor_name:
|
| 1020 |
+
prefix = f"train/{clean_name}/pre_down"
|
| 1021 |
+
elif "output" in tensor_name and "layers" in tensor_name:
|
| 1022 |
+
prefix = f"train/{clean_name}/output"
|
| 1023 |
+
else:
|
| 1024 |
+
prefix = f"train/{clean_name}/act" # existing activation stats
|
| 1025 |
+
|
| 1026 |
+
wandb.log({
|
| 1027 |
+
f"{prefix}/mean": stats.mean,
|
| 1028 |
+
f"{prefix}/max_abs": stats.max_abs,
|
| 1029 |
+
f"{prefix}/std": stats.std,
|
| 1030 |
+
f"{prefix}/norm": stats.norm,
|
| 1031 |
+
f"{prefix}/min": stats.min_val,
|
| 1032 |
+
f"{prefix}/max": stats.max_val,
|
| 1033 |
+
f"{prefix}/range": stats.range_val,
|
| 1034 |
+
f"{prefix}/p25": stats.p25,
|
| 1035 |
+
f"{prefix}/p50": stats.p50,
|
| 1036 |
+
f"{prefix}/p90": stats.p90,
|
| 1037 |
+
f"{prefix}/p99": stats.p99,
|
| 1038 |
+
f"{prefix}/p999": stats.p999,
|
| 1039 |
+
}, step=step)
|
| 1040 |
+
|
| 1041 |
+
# Tables: include all tensors with a column indicating the type
|
| 1042 |
+
table_data = []
|
| 1043 |
+
for tensor_name, stats in sorted(result.layer_acts.items()):
|
| 1044 |
+
# Determine type for table
|
| 1045 |
+
if "pre_down" in tensor_name:
|
| 1046 |
+
ttype = "pre_down"
|
| 1047 |
+
elif "output" in tensor_name and "layers" in tensor_name:
|
| 1048 |
+
ttype = "output"
|
| 1049 |
+
else:
|
| 1050 |
+
ttype = "activation"
|
| 1051 |
+
table_data.append([
|
| 1052 |
+
tensor_name,
|
| 1053 |
+
ttype,
|
| 1054 |
+
stats.mean,
|
| 1055 |
+
stats.max_abs,
|
| 1056 |
+
stats.std,
|
| 1057 |
+
stats.norm,
|
| 1058 |
+
stats.min_val,
|
| 1059 |
+
stats.max_val,
|
| 1060 |
+
stats.range_val,
|
| 1061 |
+
stats.p25,
|
| 1062 |
+
stats.p50,
|
| 1063 |
+
stats.p90,
|
| 1064 |
+
stats.p99,
|
| 1065 |
+
stats.p999,
|
| 1066 |
+
stats.numel,
|
| 1067 |
+
])
|
| 1068 |
+
|
| 1069 |
+
if table_data:
|
| 1070 |
+
table = wandb.Table(
|
| 1071 |
+
columns=["tensor_name", "type", "mean", "max_abs", "std", "norm",
|
| 1072 |
+
"min", "max", "range", "p25", "p50", "p90", "p99", "p999", "numel"],
|
| 1073 |
+
data=table_data
|
| 1074 |
+
)
|
| 1075 |
+
wandb.log({"activation_table": table}, step=step)
|
| 1076 |
+
|
| 1077 |
+
# ------------------------------------------------------------------
|
| 1078 |
+
# Run‑folder evaluation – includes waleed_beta and powlu_m in name
|
| 1079 |
+
# ------------------------------------------------------------------
|
| 1080 |
+
|
| 1081 |
+
def _evaluate_run_folder(
|
| 1082 |
+
self,
|
| 1083 |
+
run_folder: str,
|
| 1084 |
+
dataset_name: str,
|
| 1085 |
+
blocks: List[List[int]],
|
| 1086 |
+
checkpoints: List[Tuple[int, str]],
|
| 1087 |
+
) -> List[ModelResult]:
|
| 1088 |
+
first_model_name = f"{REPO_ID}/{BASE_PATH}/{run_folder}/{checkpoints[0][1]}"
|
| 1089 |
+
_, _, first_config, first_num_params = self.load_model(first_model_name)
|
| 1090 |
+
|
| 1091 |
+
effective_beta = first_config.waleed_beta
|
| 1092 |
+
powlu_m = first_config.powlu_m
|
| 1093 |
+
beta_str = f"_beta{effective_beta}" if effective_beta is not None else ""
|
| 1094 |
+
powlu_str = f"_powlu{powlu_m}" if powlu_m is not None else ""
|
| 1095 |
+
|
| 1096 |
+
run_name = f"{run_folder}__{dataset_name}{beta_str}{powlu_str}"
|
| 1097 |
+
|
| 1098 |
+
wandb.init(
|
| 1099 |
+
project=self.wandb_project,
|
| 1100 |
+
name=run_name,
|
| 1101 |
+
config={
|
| 1102 |
+
"run_folder": run_folder,
|
| 1103 |
+
"dataset": dataset_name,
|
| 1104 |
+
"max_length": self.max_length,
|
| 1105 |
+
"max_samples": self.max_samples,
|
| 1106 |
+
"batch_size": self.batch_size,
|
| 1107 |
+
"dtype": "float32",
|
| 1108 |
+
"num_params": first_num_params,
|
| 1109 |
+
"num_layers": first_config.num_hidden_layers,
|
| 1110 |
+
"hidden_size": first_config.hidden_size,
|
| 1111 |
+
"waleed_beta": effective_beta,
|
| 1112 |
+
"powlu_m": powlu_m,
|
| 1113 |
+
"checkpoints": [c[0] for c in checkpoints],
|
| 1114 |
+
"capture_pre_down": self.capture_pre_down,
|
| 1115 |
+
"capture_layer_output": self.capture_layer_output,
|
| 1116 |
+
},
|
| 1117 |
+
reinit=True
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
self._cache.pop(first_model_name, None)
|
| 1121 |
+
torch.cuda.empty_cache()
|
| 1122 |
+
|
| 1123 |
+
results = []
|
| 1124 |
+
for ckpt_num, ckpt_folder in checkpoints:
|
| 1125 |
+
model_name = f"{REPO_ID}/{BASE_PATH}/{run_folder}/{ckpt_folder}"
|
| 1126 |
+
try:
|
| 1127 |
+
result = self._evaluate_checkpoint(model_name, dataset_name, blocks)
|
| 1128 |
+
self._log_checkpoint_to_wandb(result, step=ckpt_num)
|
| 1129 |
+
results.append(result)
|
| 1130 |
+
print(f" ✅ checkpoint-{ckpt_num}: loss={result.loss:.4f} ppl={result.perplexity:.2f}")
|
| 1131 |
+
except Exception as e:
|
| 1132 |
+
print(f" ❌ checkpoint-{ckpt_num} failed: {e}")
|
| 1133 |
+
import traceback
|
| 1134 |
+
traceback.print_exc()
|
| 1135 |
+
continue
|
| 1136 |
+
|
| 1137 |
+
wandb.finish()
|
| 1138 |
+
return results
|
| 1139 |
+
|
| 1140 |
+
# ------------------------------------------------------------------
|
| 1141 |
+
# Main compute – prepares training‑style blocks once per dataset
|
| 1142 |
+
# ------------------------------------------------------------------
|
| 1143 |
+
|
| 1144 |
+
def compute(
|
| 1145 |
+
self,
|
| 1146 |
+
dataset_names: List[str],
|
| 1147 |
+
run_folders: Optional[List[str]] = None,
|
| 1148 |
+
) -> Dict[str, Dict[str, List[ModelResult]]]:
|
| 1149 |
+
all_run_folders = self.discover_checkpoints()
|
| 1150 |
+
|
| 1151 |
+
if run_folders is not None:
|
| 1152 |
+
filtered = {}
|
| 1153 |
+
for name in run_folders:
|
| 1154 |
+
if name in all_run_folders:
|
| 1155 |
+
filtered[name] = all_run_folders[name]
|
| 1156 |
+
else:
|
| 1157 |
+
print(f"⚠️ Run folder '{name}' not found. Skipping.")
|
| 1158 |
+
all_run_folders = filtered
|
| 1159 |
+
if not all_run_folders:
|
| 1160 |
+
print("❌ No valid run folders to evaluate. Exiting.")
|
| 1161 |
+
return {}
|
| 1162 |
+
|
| 1163 |
+
# Load tokenizer once (same for all datasets)
|
| 1164 |
+
tokenizer = AutoTokenizer.from_pretrained("w-ahmad/tiny-stories-tokenizer", trust_remote_code=True)
|
| 1165 |
+
if tokenizer.pad_token is None:
|
| 1166 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 1167 |
+
|
| 1168 |
+
blocks_by_dataset = {}
|
| 1169 |
+
for dataset_name in dataset_names:
|
| 1170 |
+
texts = self.load_dataset(dataset_name)
|
| 1171 |
+
blocks = self._prepare_blocks(texts, tokenizer, self.max_length)
|
| 1172 |
+
blocks_by_dataset[dataset_name] = blocks
|
| 1173 |
+
print(f"[Dataset] {dataset_name} → {len(blocks)} blocks of length {self.max_length}")
|
| 1174 |
+
|
| 1175 |
+
results_by_dataset: Dict[str, Dict[str, List[ModelResult]]] = {
|
| 1176 |
+
name: {} for name in dataset_names
|
| 1177 |
+
}
|
| 1178 |
+
|
| 1179 |
+
for dataset_name in dataset_names:
|
| 1180 |
+
blocks = blocks_by_dataset[dataset_name]
|
| 1181 |
+
for run_folder, checkpoints in sorted(all_run_folders.items()):
|
| 1182 |
+
print(f"\n🚀 Evaluating {run_folder} on {dataset_name} ({len(checkpoints)} checkpoints)...")
|
| 1183 |
+
results = self._evaluate_run_folder(run_folder, dataset_name, blocks, checkpoints)
|
| 1184 |
+
results_by_dataset[dataset_name][run_folder] = results
|
| 1185 |
+
|
| 1186 |
+
return results_by_dataset
|
| 1187 |
+
|
| 1188 |
+
# ------------------------------------------------------------------
|
| 1189 |
+
# Reporting (updated to include new stats in the top‑5 summary)
|
| 1190 |
+
# ------------------------------------------------------------------
|
| 1191 |
+
|
| 1192 |
+
def print_report(self, results_by_dataset: Dict[str, Dict[str, List[ModelResult]]]):
|
| 1193 |
+
for dataset_name, run_results in results_by_dataset.items():
|
| 1194 |
+
print("\n" + "=" * 150)
|
| 1195 |
+
print(f" Dataset: {dataset_name}")
|
| 1196 |
+
print("=" * 150)
|
| 1197 |
+
|
| 1198 |
+
print(f"{'Run Folder':<38} {'Ckpt':>7} {'Loss':>9} {'PPL':>9} {'Tokens':>8} {'Num Layers':>10}")
|
| 1199 |
+
print("-" * 90)
|
| 1200 |
+
|
| 1201 |
+
for run_folder, results in sorted(run_results.items()):
|
| 1202 |
+
if not results:
|
| 1203 |
+
continue
|
| 1204 |
+
latest = max(results, key=lambda r: r.checkpoint_step)
|
| 1205 |
+
name = run_folder[:36]
|
| 1206 |
+
print(
|
| 1207 |
+
f"{name:<38} "
|
| 1208 |
+
f"{latest.checkpoint_step:>7} "
|
| 1209 |
+
f"{latest.loss:>9.4f} "
|
| 1210 |
+
f"{latest.perplexity:>9.2f} "
|
| 1211 |
+
f"{latest.num_tokens:>8} "
|
| 1212 |
+
f"{latest.num_layers:>10}"
|
| 1213 |
+
)
|
| 1214 |
+
|
| 1215 |
+
# Show top‑5 per tensor type for the latest checkpoint
|
| 1216 |
+
print("\n[Per-Tensor Max Abs Top 5 (latest checkpoint per run)]")
|
| 1217 |
+
for dataset_name, run_results in results_by_dataset.items():
|
| 1218 |
+
for run_folder, results in sorted(run_results.items()):
|
| 1219 |
+
if not results:
|
| 1220 |
+
continue
|
| 1221 |
+
latest = max(results, key=lambda r: r.checkpoint_step)
|
| 1222 |
+
name = f"{run_folder} [{dataset_name}]"
|
| 1223 |
+
# Group by type
|
| 1224 |
+
activations = []
|
| 1225 |
+
pre_downs = []
|
| 1226 |
+
outputs = []
|
| 1227 |
+
for tensor_name, stats in latest.layer_acts.items():
|
| 1228 |
+
if "pre_down" in tensor_name:
|
| 1229 |
+
pre_downs.append((tensor_name, stats))
|
| 1230 |
+
elif "output" in tensor_name and "layers" in tensor_name:
|
| 1231 |
+
outputs.append((tensor_name, stats))
|
| 1232 |
+
else:
|
| 1233 |
+
activations.append((tensor_name, stats))
|
| 1234 |
+
|
| 1235 |
+
# Top 5 for each type
|
| 1236 |
+
for group_name, group_list in [
|
| 1237 |
+
("Activations", activations),
|
| 1238 |
+
("Pre-down", pre_downs),
|
| 1239 |
+
("Layer outputs", outputs)
|
| 1240 |
+
]:
|
| 1241 |
+
if not group_list:
|
| 1242 |
+
continue
|
| 1243 |
+
sorted_group = sorted(group_list, key=lambda x: x[1].max_abs, reverse=True)[:5]
|
| 1244 |
+
print(f"\n {name} (ckpt-{latest.checkpoint_step}) – {group_name}:")
|
| 1245 |
+
for tensor_name, stats in sorted_group:
|
| 1246 |
+
print(
|
| 1247 |
+
f" {tensor_name:<50} max_abs={stats.max_abs:>9.4f} "
|
| 1248 |
+
f"mean={stats.mean:>9.4f} std={stats.std:>9.4f} norm={stats.norm:>9.4f}"
|
| 1249 |
+
)
|
| 1250 |
+
|
| 1251 |
+
def export_json(self, results_by_dataset: Dict[str, Dict[str, List[ModelResult]]], path: str):
|
| 1252 |
+
data = []
|
| 1253 |
+
for dataset_name, run_results in results_by_dataset.items():
|
| 1254 |
+
for run_folder, results in run_results.items():
|
| 1255 |
+
for r in results:
|
| 1256 |
+
entry = {
|
| 1257 |
+
"run_folder": run_folder,
|
| 1258 |
+
"model": r.model_name,
|
| 1259 |
+
"dataset": r.dataset_name,
|
| 1260 |
+
"checkpoint_step": r.checkpoint_step,
|
| 1261 |
+
"loss": r.loss,
|
| 1262 |
+
"perplexity": r.perplexity,
|
| 1263 |
+
"num_tokens": r.num_tokens,
|
| 1264 |
+
"num_layers": r.num_layers,
|
| 1265 |
+
"hidden_size": r.hidden_size,
|
| 1266 |
+
"num_params": r.num_params,
|
| 1267 |
+
"global_act": asdict(r.global_act),
|
| 1268 |
+
"layer_acts": {k: asdict(v) for k, v in r.layer_acts.items()}
|
| 1269 |
+
}
|
| 1270 |
+
data.append(entry)
|
| 1271 |
+
|
| 1272 |
+
with open(path, "w") as f:
|
| 1273 |
+
json.dump(data, f, indent=2)
|
| 1274 |
+
print(f"[Exported] Results saved to {path}")
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
# ============================================================================
|
| 1278 |
+
# DRIVER CODE
|
| 1279 |
+
# ============================================================================
|
| 1280 |
+
if __name__ == "__main__":
|
| 1281 |
+
# --- HARDCODE WANDB LOGIN (optional, replace with your key) ---
|
| 1282 |
+
# wandb.login(key="wandb_v1_...")
|
| 1283 |
+
# -------------------------------------------------------------
|
| 1284 |
+
|
| 1285 |
+
analyzer = LLMAnalyzer(
|
| 1286 |
+
max_length=512,
|
| 1287 |
+
max_samples=100, # use None for all samples
|
| 1288 |
+
batch_size=50,
|
| 1289 |
+
wandb_project="RESEARCH-10",
|
| 1290 |
+
activation_disk_offload=False,
|
| 1291 |
+
max_elements_per_tensor=None,
|
| 1292 |
+
activation_hook_exclude=[],
|
| 1293 |
+
track_activations=True, # set to False to skip all activation collection
|
| 1294 |
+
capture_pre_down=True, # enable pre-down capture
|
| 1295 |
+
capture_layer_output=True, # enable layer output capture
|
| 1296 |
+
)
|
| 1297 |
+
|
| 1298 |
+
DATASETS = ["tinystories"]
|
| 1299 |
+
# RUN_FOLDERS = ["glu-powlu-100L_run"] # uncomment to limit runs
|
| 1300 |
+
|
| 1301 |
+
print(f"\n🚀 Starting evaluation across datasets: {DATASETS}...")
|
| 1302 |
+
results_by_dataset = analyzer.compute(dataset_names=DATASETS) # add run_folders if needed
|
| 1303 |
+
|
| 1304 |
+
analyzer.print_report(results_by_dataset)
|
| 1305 |
+
analyzer.export_json(results_by_dataset, "evaluation_results_powlu.json")
|
| 1306 |
+
|
| 1307 |
+
print("\n✅ Done! Pre-down and layer output stats are now captured.")
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": "mlp",
|
| 19 |
+
"model_type": "tiny_llama",
|
| 20 |
+
"num_attention_heads": 4,
|
| 21 |
+
"num_hidden_layers": 3,
|
| 22 |
+
"num_key_value_heads": 4,
|
| 23 |
+
"pad_token_id": 0,
|
| 24 |
+
"powlu_m": 3.0,
|
| 25 |
+
"pretraining_tp": 1,
|
| 26 |
+
"rms_norm_eps": 1e-06,
|
| 27 |
+
"rope_parameters": {
|
| 28 |
+
"rope_theta": 10000.0,
|
| 29 |
+
"rope_type": "default"
|
| 30 |
+
},
|
| 31 |
+
"tie_word_embeddings": true,
|
| 32 |
+
"tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
|
| 33 |
+
"transformers_version": "5.16.0.dev0",
|
| 34 |
+
"use_cache": false,
|
| 35 |
+
"vocab_size": 4096,
|
| 36 |
+
"waleed_beta": 10.0
|
| 37 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2862c815aeffd1d2f67bb37e4e2369bdccbdf9aa375ed38a3abe35db750ffbd7
|
| 3 |
+
size 2036216
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/optimizer.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:927d5b938ca9b6d3f934e3f289c5c0a325fec6ff4496a1913ca7ae414ea3e8db
|
| 3 |
+
size 4089360
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/rng_state.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b66e3cc7c452b707ddac5caf0aa17618afb9bc1a0333600a22c4afb353f3165
|
| 3 |
+
size 14244
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/scheduler.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb46541d572e87fb0d4fda911efea60cde9a6c4b2c0ba1e6a6c081af0a9ab78c
|
| 3 |
+
size 1064
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": "<|endoftext|>",
|
| 5 |
+
"eos_token": "<|endoftext|>",
|
| 6 |
+
"errors": "replace",
|
| 7 |
+
"is_local": false,
|
| 8 |
+
"local_files_only": false,
|
| 9 |
+
"model_max_length": 1024,
|
| 10 |
+
"pad_token": "<|endoftext|>",
|
| 11 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 12 |
+
"unk_token": "<|endoftext|>"
|
| 13 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/trainer_state.json
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_global_step": null,
|
| 3 |
+
"best_metric": null,
|
| 4 |
+
"best_model_checkpoint": null,
|
| 5 |
+
"epoch": 0.003370407819346141,
|
| 6 |
+
"eval_steps": 100,
|
| 7 |
+
"global_step": 100,
|
| 8 |
+
"is_hyper_param_search": false,
|
| 9 |
+
"is_local_process_zero": true,
|
| 10 |
+
"is_world_process_zero": true,
|
| 11 |
+
"log_history": [
|
| 12 |
+
{
|
| 13 |
+
"epoch": 0.0006740815638692282,
|
| 14 |
+
"grad_norm": 1.4921875,
|
| 15 |
+
"learning_rate": 1.14e-05,
|
| 16 |
+
"loss": 8.323189544677735,
|
| 17 |
+
"step": 20
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"epoch": 0.0013481631277384564,
|
| 21 |
+
"grad_norm": 1.609375,
|
| 22 |
+
"learning_rate": 2.34e-05,
|
| 23 |
+
"loss": 8.292604064941406,
|
| 24 |
+
"step": 40
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"epoch": 0.0020222446916076846,
|
| 28 |
+
"grad_norm": 1.5234375,
|
| 29 |
+
"learning_rate": 3.539999999999999e-05,
|
| 30 |
+
"loss": 8.182575988769532,
|
| 31 |
+
"step": 60
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"epoch": 0.002696326255476913,
|
| 35 |
+
"grad_norm": 1.296875,
|
| 36 |
+
"learning_rate": 4.7399999999999993e-05,
|
| 37 |
+
"loss": 7.984093475341797,
|
| 38 |
+
"step": 80
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"epoch": 0.003370407819346141,
|
| 42 |
+
"grad_norm": 1.265625,
|
| 43 |
+
"learning_rate": 5.94e-05,
|
| 44 |
+
"loss": 7.79156265258789,
|
| 45 |
+
"step": 100
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"epoch": 0.003370407819346141,
|
| 49 |
+
"eval_loss": 7.687253952026367,
|
| 50 |
+
"eval_runtime": 8.0233,
|
| 51 |
+
"eval_samples_per_second": 1187.42,
|
| 52 |
+
"eval_steps_per_second": 1.246,
|
| 53 |
+
"step": 100
|
| 54 |
+
}
|
| 55 |
+
],
|
| 56 |
+
"logging_steps": 20,
|
| 57 |
+
"max_steps": 2500,
|
| 58 |
+
"num_input_tokens_seen": 0,
|
| 59 |
+
"num_train_epochs": 1,
|
| 60 |
+
"save_steps": 100,
|
| 61 |
+
"stateful_callbacks": {
|
| 62 |
+
"TrainerControl": {
|
| 63 |
+
"args": {
|
| 64 |
+
"should_epoch_stop": false,
|
| 65 |
+
"should_evaluate": false,
|
| 66 |
+
"should_log": false,
|
| 67 |
+
"should_save": true,
|
| 68 |
+
"should_training_stop": false
|
| 69 |
+
},
|
| 70 |
+
"attributes": {}
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"total_flos": 4840646246400.0,
|
| 74 |
+
"train_batch_size": 32,
|
| 75 |
+
"trial_name": null,
|
| 76 |
+
"trial_params": null
|
| 77 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-100/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ce805d43d77f09e6d5ef2d9de1dd1e463729e5281bb7884e3d95d10f06b2e69
|
| 3 |
+
size 4920
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": "mlp",
|
| 19 |
+
"model_type": "tiny_llama",
|
| 20 |
+
"num_attention_heads": 4,
|
| 21 |
+
"num_hidden_layers": 3,
|
| 22 |
+
"num_key_value_heads": 4,
|
| 23 |
+
"pad_token_id": 0,
|
| 24 |
+
"powlu_m": 3.0,
|
| 25 |
+
"pretraining_tp": 1,
|
| 26 |
+
"rms_norm_eps": 1e-06,
|
| 27 |
+
"rope_parameters": {
|
| 28 |
+
"rope_theta": 10000.0,
|
| 29 |
+
"rope_type": "default"
|
| 30 |
+
},
|
| 31 |
+
"tie_word_embeddings": true,
|
| 32 |
+
"tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
|
| 33 |
+
"transformers_version": "5.16.0.dev0",
|
| 34 |
+
"use_cache": false,
|
| 35 |
+
"vocab_size": 4096,
|
| 36 |
+
"waleed_beta": 10.0
|
| 37 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0b06dc845bd604f9412d26749d35987e48e46a889e8809dc73ed3e442750679c
|
| 3 |
+
size 2036216
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/optimizer.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:071c5b0c32076eab074231bdca3e22ded5f2c2c6bbec7b1f4f6c048c64494094
|
| 3 |
+
size 4089360
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/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/mlp-linear-3L_run/checkpoint-200/scheduler.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b8135ef28e3a46ab54526e011bfc69abed48145f3d54b2d14293e0383798411e
|
| 3 |
+
size 1064
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/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/mlp-linear-3L_run/checkpoint-200/trainer_state.json
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_global_step": null,
|
| 3 |
+
"best_metric": null,
|
| 4 |
+
"best_model_checkpoint": null,
|
| 5 |
+
"epoch": 0.006740815638692282,
|
| 6 |
+
"eval_steps": 100,
|
| 7 |
+
"global_step": 200,
|
| 8 |
+
"is_hyper_param_search": false,
|
| 9 |
+
"is_local_process_zero": true,
|
| 10 |
+
"is_world_process_zero": true,
|
| 11 |
+
"log_history": [
|
| 12 |
+
{
|
| 13 |
+
"epoch": 0.0006740815638692282,
|
| 14 |
+
"grad_norm": 1.4921875,
|
| 15 |
+
"learning_rate": 1.14e-05,
|
| 16 |
+
"loss": 8.323189544677735,
|
| 17 |
+
"step": 20
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"epoch": 0.0013481631277384564,
|
| 21 |
+
"grad_norm": 1.609375,
|
| 22 |
+
"learning_rate": 2.34e-05,
|
| 23 |
+
"loss": 8.292604064941406,
|
| 24 |
+
"step": 40
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"epoch": 0.0020222446916076846,
|
| 28 |
+
"grad_norm": 1.5234375,
|
| 29 |
+
"learning_rate": 3.539999999999999e-05,
|
| 30 |
+
"loss": 8.182575988769532,
|
| 31 |
+
"step": 60
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"epoch": 0.002696326255476913,
|
| 35 |
+
"grad_norm": 1.296875,
|
| 36 |
+
"learning_rate": 4.7399999999999993e-05,
|
| 37 |
+
"loss": 7.984093475341797,
|
| 38 |
+
"step": 80
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"epoch": 0.003370407819346141,
|
| 42 |
+
"grad_norm": 1.265625,
|
| 43 |
+
"learning_rate": 5.94e-05,
|
| 44 |
+
"loss": 7.79156265258789,
|
| 45 |
+
"step": 100
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"epoch": 0.003370407819346141,
|
| 49 |
+
"eval_loss": 7.687253952026367,
|
| 50 |
+
"eval_runtime": 8.0233,
|
| 51 |
+
"eval_samples_per_second": 1187.42,
|
| 52 |
+
"eval_steps_per_second": 1.246,
|
| 53 |
+
"step": 100
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"epoch": 0.004044489383215369,
|
| 57 |
+
"grad_norm": 1.25,
|
| 58 |
+
"learning_rate": 7.139999999999999e-05,
|
| 59 |
+
"loss": 7.586382293701172,
|
| 60 |
+
"step": 120
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"epoch": 0.0047185709470845974,
|
| 64 |
+
"grad_norm": 1.25,
|
| 65 |
+
"learning_rate": 8.34e-05,
|
| 66 |
+
"loss": 7.356954193115234,
|
| 67 |
+
"step": 140
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"epoch": 0.005392652510953826,
|
| 71 |
+
"grad_norm": 1.21875,
|
| 72 |
+
"learning_rate": 9.539999999999999e-05,
|
| 73 |
+
"loss": 7.125580596923828,
|
| 74 |
+
"step": 160
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"epoch": 0.006066734074823054,
|
| 78 |
+
"grad_norm": 1.1953125,
|
| 79 |
+
"learning_rate": 0.00010739999999999998,
|
| 80 |
+
"loss": 6.8821556091308596,
|
| 81 |
+
"step": 180
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"epoch": 0.006740815638692282,
|
| 85 |
+
"grad_norm": 1.125,
|
| 86 |
+
"learning_rate": 0.0001194,
|
| 87 |
+
"loss": 6.638446807861328,
|
| 88 |
+
"step": 200
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"epoch": 0.006740815638692282,
|
| 92 |
+
"eval_loss": 6.517788887023926,
|
| 93 |
+
"eval_runtime": 7.4667,
|
| 94 |
+
"eval_samples_per_second": 1275.933,
|
| 95 |
+
"eval_steps_per_second": 1.339,
|
| 96 |
+
"step": 200
|
| 97 |
+
}
|
| 98 |
+
],
|
| 99 |
+
"logging_steps": 20,
|
| 100 |
+
"max_steps": 2500,
|
| 101 |
+
"num_input_tokens_seen": 0,
|
| 102 |
+
"num_train_epochs": 1,
|
| 103 |
+
"save_steps": 100,
|
| 104 |
+
"stateful_callbacks": {
|
| 105 |
+
"TrainerControl": {
|
| 106 |
+
"args": {
|
| 107 |
+
"should_epoch_stop": false,
|
| 108 |
+
"should_evaluate": false,
|
| 109 |
+
"should_log": false,
|
| 110 |
+
"should_save": true,
|
| 111 |
+
"should_training_stop": false
|
| 112 |
+
},
|
| 113 |
+
"attributes": {}
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
"total_flos": 9681292492800.0,
|
| 117 |
+
"train_batch_size": 32,
|
| 118 |
+
"trial_name": null,
|
| 119 |
+
"trial_params": null
|
| 120 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-200/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ce805d43d77f09e6d5ef2d9de1dd1e463729e5281bb7884e3d95d10f06b2e69
|
| 3 |
+
size 4920
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": "mlp",
|
| 19 |
+
"model_type": "tiny_llama",
|
| 20 |
+
"num_attention_heads": 4,
|
| 21 |
+
"num_hidden_layers": 3,
|
| 22 |
+
"num_key_value_heads": 4,
|
| 23 |
+
"pad_token_id": 0,
|
| 24 |
+
"powlu_m": 3.0,
|
| 25 |
+
"pretraining_tp": 1,
|
| 26 |
+
"rms_norm_eps": 1e-06,
|
| 27 |
+
"rope_parameters": {
|
| 28 |
+
"rope_theta": 10000.0,
|
| 29 |
+
"rope_type": "default"
|
| 30 |
+
},
|
| 31 |
+
"tie_word_embeddings": true,
|
| 32 |
+
"tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
|
| 33 |
+
"transformers_version": "5.16.0.dev0",
|
| 34 |
+
"use_cache": false,
|
| 35 |
+
"vocab_size": 4096,
|
| 36 |
+
"waleed_beta": 10.0
|
| 37 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41772288a7df8f4bb7c033f1405f6b03fdc2bcaccf71dc5f1294870515bc0849
|
| 3 |
+
size 2036216
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/optimizer.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7fec19f35549b1a62d88675fffc36724d97a6638eec0a94bca78ba3e2b773d53
|
| 3 |
+
size 4089360
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/rng_state.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f37c40ce327861a7ca13b719d3aa37510a143368b6e74358bdb14becb3899e1e
|
| 3 |
+
size 14244
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/scheduler.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:58882af6bc66e44afb6aa7c1675e12212a966de0b9a2fc23de850f993cbc78d3
|
| 3 |
+
size 1064
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/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/mlp-linear-3L_run/checkpoint-300/trainer_state.json
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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": null,
|
| 5 |
+
"epoch": 0.010111223458038422,
|
| 6 |
+
"eval_steps": 100,
|
| 7 |
+
"global_step": 300,
|
| 8 |
+
"is_hyper_param_search": false,
|
| 9 |
+
"is_local_process_zero": true,
|
| 10 |
+
"is_world_process_zero": true,
|
| 11 |
+
"log_history": [
|
| 12 |
+
{
|
| 13 |
+
"epoch": 0.0006740815638692282,
|
| 14 |
+
"grad_norm": 1.4921875,
|
| 15 |
+
"learning_rate": 1.14e-05,
|
| 16 |
+
"loss": 8.323189544677735,
|
| 17 |
+
"step": 20
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"epoch": 0.0013481631277384564,
|
| 21 |
+
"grad_norm": 1.609375,
|
| 22 |
+
"learning_rate": 2.34e-05,
|
| 23 |
+
"loss": 8.292604064941406,
|
| 24 |
+
"step": 40
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"epoch": 0.0020222446916076846,
|
| 28 |
+
"grad_norm": 1.5234375,
|
| 29 |
+
"learning_rate": 3.539999999999999e-05,
|
| 30 |
+
"loss": 8.182575988769532,
|
| 31 |
+
"step": 60
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"epoch": 0.002696326255476913,
|
| 35 |
+
"grad_norm": 1.296875,
|
| 36 |
+
"learning_rate": 4.7399999999999993e-05,
|
| 37 |
+
"loss": 7.984093475341797,
|
| 38 |
+
"step": 80
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"epoch": 0.003370407819346141,
|
| 42 |
+
"grad_norm": 1.265625,
|
| 43 |
+
"learning_rate": 5.94e-05,
|
| 44 |
+
"loss": 7.79156265258789,
|
| 45 |
+
"step": 100
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"epoch": 0.003370407819346141,
|
| 49 |
+
"eval_loss": 7.687253952026367,
|
| 50 |
+
"eval_runtime": 8.0233,
|
| 51 |
+
"eval_samples_per_second": 1187.42,
|
| 52 |
+
"eval_steps_per_second": 1.246,
|
| 53 |
+
"step": 100
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"epoch": 0.004044489383215369,
|
| 57 |
+
"grad_norm": 1.25,
|
| 58 |
+
"learning_rate": 7.139999999999999e-05,
|
| 59 |
+
"loss": 7.586382293701172,
|
| 60 |
+
"step": 120
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"epoch": 0.0047185709470845974,
|
| 64 |
+
"grad_norm": 1.25,
|
| 65 |
+
"learning_rate": 8.34e-05,
|
| 66 |
+
"loss": 7.356954193115234,
|
| 67 |
+
"step": 140
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"epoch": 0.005392652510953826,
|
| 71 |
+
"grad_norm": 1.21875,
|
| 72 |
+
"learning_rate": 9.539999999999999e-05,
|
| 73 |
+
"loss": 7.125580596923828,
|
| 74 |
+
"step": 160
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"epoch": 0.006066734074823054,
|
| 78 |
+
"grad_norm": 1.1953125,
|
| 79 |
+
"learning_rate": 0.00010739999999999998,
|
| 80 |
+
"loss": 6.8821556091308596,
|
| 81 |
+
"step": 180
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"epoch": 0.006740815638692282,
|
| 85 |
+
"grad_norm": 1.125,
|
| 86 |
+
"learning_rate": 0.0001194,
|
| 87 |
+
"loss": 6.638446807861328,
|
| 88 |
+
"step": 200
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"epoch": 0.006740815638692282,
|
| 92 |
+
"eval_loss": 6.517788887023926,
|
| 93 |
+
"eval_runtime": 7.4667,
|
| 94 |
+
"eval_samples_per_second": 1275.933,
|
| 95 |
+
"eval_steps_per_second": 1.339,
|
| 96 |
+
"step": 200
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"epoch": 0.00741489720256151,
|
| 100 |
+
"grad_norm": 1.1171875,
|
| 101 |
+
"learning_rate": 0.0001314,
|
| 102 |
+
"loss": 6.419033813476562,
|
| 103 |
+
"step": 220
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"epoch": 0.008088978766430738,
|
| 107 |
+
"grad_norm": 0.99609375,
|
| 108 |
+
"learning_rate": 0.0001434,
|
| 109 |
+
"loss": 6.19798698425293,
|
| 110 |
+
"step": 240
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"epoch": 0.008763060330299966,
|
| 114 |
+
"grad_norm": 0.85546875,
|
| 115 |
+
"learning_rate": 0.00015539999999999998,
|
| 116 |
+
"loss": 6.01253662109375,
|
| 117 |
+
"step": 260
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"epoch": 0.009437141894169195,
|
| 121 |
+
"grad_norm": 2.4375,
|
| 122 |
+
"learning_rate": 0.0001674,
|
| 123 |
+
"loss": 5.827148818969727,
|
| 124 |
+
"step": 280
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"epoch": 0.010111223458038422,
|
| 128 |
+
"grad_norm": 1.1171875,
|
| 129 |
+
"learning_rate": 0.00017939999999999997,
|
| 130 |
+
"loss": 5.6793663024902346,
|
| 131 |
+
"step": 300
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"epoch": 0.010111223458038422,
|
| 135 |
+
"eval_loss": 5.609452724456787,
|
| 136 |
+
"eval_runtime": 7.5288,
|
| 137 |
+
"eval_samples_per_second": 1265.404,
|
| 138 |
+
"eval_steps_per_second": 1.328,
|
| 139 |
+
"step": 300
|
| 140 |
+
}
|
| 141 |
+
],
|
| 142 |
+
"logging_steps": 20,
|
| 143 |
+
"max_steps": 2500,
|
| 144 |
+
"num_input_tokens_seen": 0,
|
| 145 |
+
"num_train_epochs": 1,
|
| 146 |
+
"save_steps": 100,
|
| 147 |
+
"stateful_callbacks": {
|
| 148 |
+
"TrainerControl": {
|
| 149 |
+
"args": {
|
| 150 |
+
"should_epoch_stop": false,
|
| 151 |
+
"should_evaluate": false,
|
| 152 |
+
"should_log": false,
|
| 153 |
+
"should_save": true,
|
| 154 |
+
"should_training_stop": false
|
| 155 |
+
},
|
| 156 |
+
"attributes": {}
|
| 157 |
+
}
|
| 158 |
+
},
|
| 159 |
+
"total_flos": 14521938739200.0,
|
| 160 |
+
"train_batch_size": 32,
|
| 161 |
+
"trial_name": null,
|
| 162 |
+
"trial_params": null
|
| 163 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-300/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ce805d43d77f09e6d5ef2d9de1dd1e463729e5281bb7884e3d95d10f06b2e69
|
| 3 |
+
size 4920
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": "mlp",
|
| 19 |
+
"model_type": "tiny_llama",
|
| 20 |
+
"num_attention_heads": 4,
|
| 21 |
+
"num_hidden_layers": 3,
|
| 22 |
+
"num_key_value_heads": 4,
|
| 23 |
+
"pad_token_id": 0,
|
| 24 |
+
"powlu_m": 3.0,
|
| 25 |
+
"pretraining_tp": 1,
|
| 26 |
+
"rms_norm_eps": 1e-06,
|
| 27 |
+
"rope_parameters": {
|
| 28 |
+
"rope_theta": 10000.0,
|
| 29 |
+
"rope_type": "default"
|
| 30 |
+
},
|
| 31 |
+
"tie_word_embeddings": true,
|
| 32 |
+
"tokenizer_name": "w-ahmad/tiny-stories-tokenizer",
|
| 33 |
+
"transformers_version": "5.16.0.dev0",
|
| 34 |
+
"use_cache": false,
|
| 35 |
+
"vocab_size": 4096,
|
| 36 |
+
"waleed_beta": 10.0
|
| 37 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d0b9caf5aef6a40ddfc8b439193dcdf1f09e366ea4a9d962e91615e5601beacc
|
| 3 |
+
size 2036216
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/optimizer.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ff081781d005f5468b429863b16218d3d6c579e354919efcd3aff94c2d14c009
|
| 3 |
+
size 4089360
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/rng_state.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ecefbb3f17bb76b6655eb0157c98b5287c17fa4b4c72a6b9068b0823ce9fd18d
|
| 3 |
+
size 14244
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/scheduler.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f768f3dc231ac5aded23c6f019b283714352126180577c2c811e2d205bc7704f
|
| 3 |
+
size 1064
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/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/mlp-linear-3L_run/checkpoint-400/trainer_state.json
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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5 |
+
"epoch": 0.013481631277384564,
|
| 6 |
+
"eval_steps": 100,
|
| 7 |
+
"global_step": 400,
|
| 8 |
+
"is_hyper_param_search": false,
|
| 9 |
+
"is_local_process_zero": true,
|
| 10 |
+
"is_world_process_zero": true,
|
| 11 |
+
"log_history": [
|
| 12 |
+
{
|
| 13 |
+
"epoch": 0.0006740815638692282,
|
| 14 |
+
"grad_norm": 1.4921875,
|
| 15 |
+
"learning_rate": 1.14e-05,
|
| 16 |
+
"loss": 8.323189544677735,
|
| 17 |
+
"step": 20
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"epoch": 0.0013481631277384564,
|
| 21 |
+
"grad_norm": 1.609375,
|
| 22 |
+
"learning_rate": 2.34e-05,
|
| 23 |
+
"loss": 8.292604064941406,
|
| 24 |
+
"step": 40
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"epoch": 0.0020222446916076846,
|
| 28 |
+
"grad_norm": 1.5234375,
|
| 29 |
+
"learning_rate": 3.539999999999999e-05,
|
| 30 |
+
"loss": 8.182575988769532,
|
| 31 |
+
"step": 60
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"epoch": 0.002696326255476913,
|
| 35 |
+
"grad_norm": 1.296875,
|
| 36 |
+
"learning_rate": 4.7399999999999993e-05,
|
| 37 |
+
"loss": 7.984093475341797,
|
| 38 |
+
"step": 80
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"epoch": 0.003370407819346141,
|
| 42 |
+
"grad_norm": 1.265625,
|
| 43 |
+
"learning_rate": 5.94e-05,
|
| 44 |
+
"loss": 7.79156265258789,
|
| 45 |
+
"step": 100
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"epoch": 0.003370407819346141,
|
| 49 |
+
"eval_loss": 7.687253952026367,
|
| 50 |
+
"eval_runtime": 8.0233,
|
| 51 |
+
"eval_samples_per_second": 1187.42,
|
| 52 |
+
"eval_steps_per_second": 1.246,
|
| 53 |
+
"step": 100
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"epoch": 0.004044489383215369,
|
| 57 |
+
"grad_norm": 1.25,
|
| 58 |
+
"learning_rate": 7.139999999999999e-05,
|
| 59 |
+
"loss": 7.586382293701172,
|
| 60 |
+
"step": 120
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"epoch": 0.0047185709470845974,
|
| 64 |
+
"grad_norm": 1.25,
|
| 65 |
+
"learning_rate": 8.34e-05,
|
| 66 |
+
"loss": 7.356954193115234,
|
| 67 |
+
"step": 140
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"epoch": 0.005392652510953826,
|
| 71 |
+
"grad_norm": 1.21875,
|
| 72 |
+
"learning_rate": 9.539999999999999e-05,
|
| 73 |
+
"loss": 7.125580596923828,
|
| 74 |
+
"step": 160
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"epoch": 0.006066734074823054,
|
| 78 |
+
"grad_norm": 1.1953125,
|
| 79 |
+
"learning_rate": 0.00010739999999999998,
|
| 80 |
+
"loss": 6.8821556091308596,
|
| 81 |
+
"step": 180
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"epoch": 0.006740815638692282,
|
| 85 |
+
"grad_norm": 1.125,
|
| 86 |
+
"learning_rate": 0.0001194,
|
| 87 |
+
"loss": 6.638446807861328,
|
| 88 |
+
"step": 200
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"epoch": 0.006740815638692282,
|
| 92 |
+
"eval_loss": 6.517788887023926,
|
| 93 |
+
"eval_runtime": 7.4667,
|
| 94 |
+
"eval_samples_per_second": 1275.933,
|
| 95 |
+
"eval_steps_per_second": 1.339,
|
| 96 |
+
"step": 200
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"epoch": 0.00741489720256151,
|
| 100 |
+
"grad_norm": 1.1171875,
|
| 101 |
+
"learning_rate": 0.0001314,
|
| 102 |
+
"loss": 6.419033813476562,
|
| 103 |
+
"step": 220
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"epoch": 0.008088978766430738,
|
| 107 |
+
"grad_norm": 0.99609375,
|
| 108 |
+
"learning_rate": 0.0001434,
|
| 109 |
+
"loss": 6.19798698425293,
|
| 110 |
+
"step": 240
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"epoch": 0.008763060330299966,
|
| 114 |
+
"grad_norm": 0.85546875,
|
| 115 |
+
"learning_rate": 0.00015539999999999998,
|
| 116 |
+
"loss": 6.01253662109375,
|
| 117 |
+
"step": 260
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"epoch": 0.009437141894169195,
|
| 121 |
+
"grad_norm": 2.4375,
|
| 122 |
+
"learning_rate": 0.0001674,
|
| 123 |
+
"loss": 5.827148818969727,
|
| 124 |
+
"step": 280
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"epoch": 0.010111223458038422,
|
| 128 |
+
"grad_norm": 1.1171875,
|
| 129 |
+
"learning_rate": 0.00017939999999999997,
|
| 130 |
+
"loss": 5.6793663024902346,
|
| 131 |
+
"step": 300
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"epoch": 0.010111223458038422,
|
| 135 |
+
"eval_loss": 5.609452724456787,
|
| 136 |
+
"eval_runtime": 7.5288,
|
| 137 |
+
"eval_samples_per_second": 1265.404,
|
| 138 |
+
"eval_steps_per_second": 1.328,
|
| 139 |
+
"step": 300
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"epoch": 0.010785305021907651,
|
| 143 |
+
"grad_norm": 0.9375,
|
| 144 |
+
"learning_rate": 0.0001914,
|
| 145 |
+
"loss": 5.544954299926758,
|
| 146 |
+
"step": 320
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"epoch": 0.011459386585776879,
|
| 150 |
+
"grad_norm": 1.2734375,
|
| 151 |
+
"learning_rate": 0.00020339999999999998,
|
| 152 |
+
"loss": 5.418224334716797,
|
| 153 |
+
"step": 340
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"epoch": 0.012133468149646108,
|
| 157 |
+
"grad_norm": 1.890625,
|
| 158 |
+
"learning_rate": 0.00021539999999999998,
|
| 159 |
+
"loss": 5.2604835510253904,
|
| 160 |
+
"step": 360
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"epoch": 0.012807549713515335,
|
| 164 |
+
"grad_norm": 1.265625,
|
| 165 |
+
"learning_rate": 0.00022739999999999997,
|
| 166 |
+
"loss": 5.145714187622071,
|
| 167 |
+
"step": 380
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"epoch": 0.013481631277384564,
|
| 171 |
+
"grad_norm": 1.6328125,
|
| 172 |
+
"learning_rate": 0.0002394,
|
| 173 |
+
"loss": 5.026620101928711,
|
| 174 |
+
"step": 400
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"epoch": 0.013481631277384564,
|
| 178 |
+
"eval_loss": 4.965352535247803,
|
| 179 |
+
"eval_runtime": 7.5776,
|
| 180 |
+
"eval_samples_per_second": 1257.265,
|
| 181 |
+
"eval_steps_per_second": 1.32,
|
| 182 |
+
"step": 400
|
| 183 |
+
}
|
| 184 |
+
],
|
| 185 |
+
"logging_steps": 20,
|
| 186 |
+
"max_steps": 2500,
|
| 187 |
+
"num_input_tokens_seen": 0,
|
| 188 |
+
"num_train_epochs": 1,
|
| 189 |
+
"save_steps": 100,
|
| 190 |
+
"stateful_callbacks": {
|
| 191 |
+
"TrainerControl": {
|
| 192 |
+
"args": {
|
| 193 |
+
"should_epoch_stop": false,
|
| 194 |
+
"should_evaluate": false,
|
| 195 |
+
"should_log": false,
|
| 196 |
+
"should_save": true,
|
| 197 |
+
"should_training_stop": false
|
| 198 |
+
},
|
| 199 |
+
"attributes": {}
|
| 200 |
+
}
|
| 201 |
+
},
|
| 202 |
+
"total_flos": 19362584985600.0,
|
| 203 |
+
"train_batch_size": 32,
|
| 204 |
+
"trial_name": null,
|
| 205 |
+
"trial_params": null
|
| 206 |
+
}
|
zain/Activation/out/mlp-linear-3L_run/checkpoint-400/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ce805d43d77f09e6d5ef2d9de1dd1e463729e5281bb7884e3d95d10f06b2e69
|
| 3 |
+
size 4920
|
zain/Activation/out/mlp-linear-3L_run/training_log.jsonl
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"step": 20, "epoch": 0.0006740815638692282, "timestamp": 1787074257.4930282, "loss": 8.323189544677735, "grad_norm": 1.4921875, "learning_rate": 1.14e-05, "train/total_time_seconds": 0.7460830584168434, "train/time_per_step_avg": 0.037304152920842173, "train/epoch_time_elapsed": 1.3678817190229893, "train/estimated_remaining_minutes": 1.5419049873948096}
|
| 2 |
+
{"step": 40, "epoch": 0.0013481631277384564, "timestamp": 1787074258.1952043, "loss": 8.292604064941406, "grad_norm": 1.609375, "learning_rate": 2.34e-05, "train/total_time_seconds": 0.9485452510416508, "train/time_per_step_avg": 0.02371363127604127, "train/epoch_time_elapsed": 2.070059809833765, "train/estimated_remaining_minutes": 0.9722588823176921}
|
| 3 |
+
{"step": 60, "epoch": 0.0020222446916076846, "timestamp": 1787074258.9123142, "loss": 8.182575988769532, "grad_norm": 1.5234375, "learning_rate": 3.539999999999999e-05, "train/total_time_seconds": 1.1520088501274586, "train/time_per_step_avg": 0.019200147502124308, "train/epoch_time_elapsed": 2.7871683575212955, "train/estimated_remaining_minutes": 0.7808059984197219}
|
| 4 |
+
{"step": 80, "epoch": 0.002696326255476913, "timestamp": 1787074259.6286278, "loss": 7.984093475341797, "grad_norm": 1.296875, "learning_rate": 4.7399999999999993e-05, "train/total_time_seconds": 1.3568183742463589, "train/time_per_step_avg": 0.016960229678079485, "train/epoch_time_elapsed": 3.503482311964035, "train/estimated_remaining_minutes": 0.6840625970158726}
|
| 5 |
+
{"step": 100, "epoch": 0.003370407819346141, "timestamp": 1787074260.3504589, "loss": 7.79156265258789, "grad_norm": 1.265625, "learning_rate": 5.94e-05, "train/total_time_seconds": 1.5590789467096329, "train/time_per_step_avg": 0.01559078946709633, "train/epoch_time_elapsed": 4.225313637405634, "train/estimated_remaining_minutes": 0.6236315786838531}
|
| 6 |
+
{"step": 100, "epoch": 0.003370407819346141, "timestamp": 1787074268.3756442, "eval_loss": 7.687253952026367, "eval_runtime": 8.0233, "eval_samples_per_second": 1187.42, "eval_steps_per_second": 1.246, "train/total_time_seconds": 1.5590789467096329, "train/time_per_step_avg": 0.01559078946709633, "train/epoch_time_elapsed": 12.250497162342072, "train/estimated_remaining_minutes": 0.6236315786838531}
|
| 7 |
+
{"step": 120, "epoch": 0.004044489383215369, "timestamp": 1787074269.2032769, "loss": 7.586382293701172, "grad_norm": 1.25, "learning_rate": 7.139999999999999e-05, "train/total_time_seconds": 1.7841728813946247, "train/time_per_step_avg": 0.010380898229777813, "train/epoch_time_elapsed": 13.078132025897503, "train/estimated_remaining_minutes": 0.5897682580165565}
|
| 8 |
+
{"step": 140, "epoch": 0.0047185709470845974, "timestamp": 1787074269.9116251, "loss": 7.356954193115234, "grad_norm": 1.25, "learning_rate": 8.34e-05, "train/total_time_seconds": 1.994844526052475, "train/time_per_step_avg": 0.010462992750108242, "train/epoch_time_elapsed": 13.786480002105236, "train/estimated_remaining_minutes": 0.5604563192242668}
|
| 9 |
+
{"step": 160, "epoch": 0.005392652510953826, "timestamp": 1787074270.6187358, "loss": 7.125580596923828, "grad_norm": 1.21875, "learning_rate": 9.539999999999999e-05, "train/total_time_seconds": 2.202128253877163, "train/time_per_step_avg": 0.010501194037497044, "train/epoch_time_elapsed": 14.49359218403697, "train/estimated_remaining_minutes": 0.5367687618825585}
|
| 10 |
+
{"step": 180, "epoch": 0.006066734074823054, "timestamp": 1787074271.329272, "loss": 6.8821556091308596, "grad_norm": 1.1953125, "learning_rate": 0.00010739999999999998, "train/total_time_seconds": 2.4119039587676525, "train/time_per_step_avg": 0.010550855845212936, "train/epoch_time_elapsed": 15.204128384590149, "train/estimated_remaining_minutes": 0.518112702253792}
|
| 11 |
+
{"step": 200, "epoch": 0.006740815638692282, "timestamp": 1787074272.0278583, "loss": 6.638446807861328, "grad_norm": 1.125, "learning_rate": 0.0001194, "train/total_time_seconds": 2.6177961491048336, "train/time_per_step_avg": 0.010587172023952008, "train/epoch_time_elapsed": 15.902714412659407, "train/estimated_remaining_minutes": 0.5017442619117598}
|
| 12 |
+
{"step": 200, "epoch": 0.006740815638692282, "timestamp": 1787074279.4963796, "eval_loss": 6.517788887023926, "eval_runtime": 7.4667, "eval_samples_per_second": 1275.933, "eval_steps_per_second": 1.339, "train/total_time_seconds": 2.6177961491048336, "train/time_per_step_avg": 0.010587172023952008, "train/epoch_time_elapsed": 23.371235564351082, "train/estimated_remaining_minutes": 0.5017442619117598}
|
| 13 |
+
{"step": 220, "epoch": 0.00741489720256151, "timestamp": 1787074280.228166, "loss": 6.419033813476562, "grad_norm": 1.1171875, "learning_rate": 0.0001314, "train/total_time_seconds": 2.8245462253689766, "train/time_per_step_avg": 0.01040373343974352, "train/epoch_time_elapsed": 24.103022642433643, "train/estimated_remaining_minutes": 0.48787616620009594}
|
| 14 |
+
{"step": 240, "epoch": 0.008088978766430738, "timestamp": 1787074280.9735563, "loss": 6.19798698425293, "grad_norm": 0.99609375, "learning_rate": 0.0001434, "train/total_time_seconds": 3.0400132834911346, "train/time_per_step_avg": 0.010451687574386597, "train/epoch_time_elapsed": 24.84841227531433, "train/estimated_remaining_minutes": 0.4771131958812475}
|
| 15 |
+
{"step": 260, "epoch": 0.008763060330299966, "timestamp": 1787074281.6759663, "loss": 6.01253662109375, "grad_norm": 0.85546875, "learning_rate": 0.00015539999999999998, "train/total_time_seconds": 3.248403426259756, "train/time_per_step_avg": 0.01046275172382593, "train/epoch_time_elapsed": 25.550822518765926, "train/estimated_remaining_minutes": 0.46643741505268294}
|
| 16 |
+
{"step": 280, "epoch": 0.009437141894169195, "timestamp": 1787074282.37463, "loss": 5.827148818969727, "grad_norm": 2.4375, "learning_rate": 0.0001674, "train/total_time_seconds": 3.4553334414958954, "train/time_per_step_avg": 0.010434294827282429, "train/epoch_time_elapsed": 26.249484304338694, "train/estimated_remaining_minutes": 0.45659763334052905}
|
| 17 |
+
{"step": 300, "epoch": 0.010111223458038422, "timestamp": 1787074283.0718303, "loss": 5.6793663024902346, "grad_norm": 1.1171875, "learning_rate": 0.00017939999999999997, "train/total_time_seconds": 3.6605737172067165, "train/time_per_step_avg": 0.01042777568101883, "train/epoch_time_elapsed": 26.94668624177575, "train/estimated_remaining_minutes": 0.4474034543252653}
|
| 18 |
+
{"step": 300, "epoch": 0.010111223458038422, "timestamp": 1787074290.6024668, "eval_loss": 5.609452724456787, "eval_runtime": 7.5288, "eval_samples_per_second": 1265.404, "eval_steps_per_second": 1.328, "train/total_time_seconds": 3.6605737172067165, "train/time_per_step_avg": 0.01042777568101883, "train/epoch_time_elapsed": 34.47732298821211, "train/estimated_remaining_minutes": 0.4474034543252653}
|
| 19 |
+
{"step": 320, "epoch": 0.010785305021907651, "timestamp": 1787074291.3248556, "loss": 5.544954299926758, "grad_norm": 0.9375, "learning_rate": 0.0001914, "train/total_time_seconds": 3.865416429936886, "train/time_per_step_avg": 0.010408702045679093, "train/epoch_time_elapsed": 35.199711341410875, "train/estimated_remaining_minutes": 0.4388858238157506}
|
| 20 |
+
{"step": 340, "epoch": 0.011459386585776879, "timestamp": 1787074292.0202703, "loss": 5.418224334716797, "grad_norm": 1.2734375, "learning_rate": 0.00020339999999999998, "train/total_time_seconds": 4.069368842989206, "train/time_per_step_avg": 0.010293555594980717, "train/epoch_time_elapsed": 35.895126920193434, "train/estimated_remaining_minutes": 0.43087434808121006}
|
| 21 |
+
{"step": 360, "epoch": 0.012133468149646108, "timestamp": 1787074292.7171614, "loss": 5.2604835510253904, "grad_norm": 1.890625, "learning_rate": 0.00021539999999999998, "train/total_time_seconds": 4.273556467145681, "train/time_per_step_avg": 0.010251530408859254, "train/epoch_time_elapsed": 36.59201791137457, "train/estimated_remaining_minutes": 0.42339864998572957}
|
| 22 |
+
{"step": 380, "epoch": 0.012807549713515335, "timestamp": 1787074293.4187381, "loss": 5.145714187622071, "grad_norm": 1.265625, "learning_rate": 0.00022739999999999997, "train/total_time_seconds": 4.481581345200539, "train/time_per_step_avg": 0.010262479037046433, "train/epoch_time_elapsed": 37.29359433054924, "train/estimated_remaining_minutes": 0.41670844086952374}
|
| 23 |
+
{"step": 400, "epoch": 0.013481631277384564, "timestamp": 1787074294.1157317, "loss": 5.026620101928711, "grad_norm": 1.6328125, "learning_rate": 0.0002394, "train/total_time_seconds": 4.685721717774868, "train/time_per_step_avg": 0.010251480005681515, "train/epoch_time_elapsed": 37.99058823287487, "train/estimated_remaining_minutes": 0.410000650305301}
|
| 24 |
+
{"step": 400, "epoch": 0.013481631277384564, "timestamp": 1787074301.6949267, "eval_loss": 4.965352535247803, "eval_runtime": 7.5776, "eval_samples_per_second": 1257.265, "eval_steps_per_second": 1.32, "train/total_time_seconds": 4.685721717774868, "train/time_per_step_avg": 0.010251480005681515, "train/epoch_time_elapsed": 45.56978277862072, "train/estimated_remaining_minutes": 0.410000650305301}
|
| 25 |
+
{"step": 420, "epoch": 0.014155712841253791, "timestamp": 1787074302.4310777, "loss": 4.905144500732422, "grad_norm": 0.96484375, "learning_rate": 0.0002514, "train/total_time_seconds": 4.892613511532545, "train/time_per_step_avg": 0.010271970815956592, "train/epoch_time_elapsed": 46.30593340098858, "train/estimated_remaining_minutes": 0.40383476603125773}
|
| 26 |
+
{"step": 440, "epoch": 0.01482979440512302, "timestamp": 1787074303.133277, "loss": 4.836254501342774, "grad_norm": 1.953125, "learning_rate": 0.00026339999999999995, "train/total_time_seconds": 5.098997637629509, "train/time_per_step_avg": 0.010296287946403027, "train/epoch_time_elapsed": 47.008133206516504, "train/estimated_remaining_minutes": 0.3978763308150298}
|
| 27 |
+
{"step": 460, "epoch": 0.015503875968992248, "timestamp": 1787074303.8344178, "loss": 4.767382431030273, "grad_norm": 1.90625, "learning_rate": 0.00027539999999999997, "train/total_time_seconds": 5.303807999938726, "train/time_per_step_avg": 0.01030251532793045, "train/epoch_time_elapsed": 47.70927469432354, "train/estimated_remaining_minutes": 0.39202059129981887}
|
| 28 |
+
{"step": 480, "epoch": 0.016177957532861477, "timestamp": 1787074304.541217, "loss": 4.681509017944336, "grad_norm": 1.6875, "learning_rate": 0.00028739999999999994, "train/total_time_seconds": 5.510302223265171, "train/time_per_step_avg": 0.010287208780646324, "train/epoch_time_elapsed": 48.41607332974672, "train/estimated_remaining_minutes": 0.3864864753817932}
|
| 29 |
+
{"step": 500, "epoch": 0.016852039096730706, "timestamp": 1787074305.2466145, "loss": 4.624195098876953, "grad_norm": 1.609375, "learning_rate": 0.00029939999999999996, "train/total_time_seconds": 5.717924311757088, "train/time_per_step_avg": 0.010322025939822198, "train/epoch_time_elapsed": 49.12147046625614, "train/estimated_remaining_minutes": 0.38119495411713916}
|
zain/Activation/sweep.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
#!/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,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"time":"2026-08-18T17:30:55.133920805Z","level":"INFO","msg":"wandb-core"}
|
| 2 |
+
{"time":"2026-08-18T17:30:55.134243482Z","level":"INFO","msg":"stream: starting","core version":"0.28.1"}
|
| 3 |
+
{"time":"2026-08-18T17:30:55.396770377Z","level":"INFO","msg":"stream: created new stream","id":"ojtyk5jg"}
|
| 4 |
+
{"time":"2026-08-18T17:30:55.396878883Z","level":"INFO","msg":"handler: started"}
|
| 5 |
+
{"time":"2026-08-18T17:30:55.396967225Z","level":"INFO","msg":"stream: started"}
|
| 6 |
+
{"time":"2026-08-18T17:30:55.396993134Z","level":"INFO","msg":"sender: started"}
|
| 7 |
+
{"time":"2026-08-18T17:30:55.396992373Z","level":"INFO","msg":"writer: started","stream_id":"ojtyk5jg"}
|
| 8 |
+
{"time":"2026-08-18T17:30:56.125634159Z","level":"INFO","msg":"filestream: sending request","total_files":1,"console_offset":0,"console_lines":1}
|
| 9 |
+
{"time":"2026-08-18T17:30:56.224956848Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
|
| 10 |
+
{"time":"2026-08-18T17:31:11.125786142Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":0,"history_lines":9,"events_offset":0,"events_lines":1,"console_offset":0,"console_lines":17,"uploaded_len":2}
|
| 11 |
+
{"time":"2026-08-18T17:31:11.265222192Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
|
| 12 |
+
{"time":"2026-08-18T17:31:26.125882709Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":9,"history_lines":8,"events_offset":1,"events_lines":2,"console_offset":13,"console_lines":1}
|
| 13 |
+
{"time":"2026-08-18T17:31:26.260200947Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
|
| 14 |
+
{"time":"2026-08-18T17:31:41.126654882Z","level":"INFO","msg":"filestream: sending request","total_files":4,"history_offset":17,"history_lines":6,"events_offset":3,"events_lines":2,"console_offset":17,"console_lines":25}
|
| 15 |
+
{"time":"2026-08-18T17:31:41.255752433Z","level":"INFO","msg":"filestream: request sent","status":"200 OK"}
|
zain/Activation/wandb/debug.log
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_setup.py:_flush():81] Current SDK version is 0.28.1
|
| 2 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_setup.py:_flush():81] Configure stats pid to 2958647
|
| 3 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_setup.py:_flush():81] Loading settings from environment variables
|
| 4 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:setup_run_log_directory():729] Logging user logs to /mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/wandb/run-20260818_173055-ojtyk5jg/logs/debug.log
|
| 5 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:setup_run_log_directory():730] Logging internal logs to /mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/wandb/run-20260818_173055-ojtyk5jg/logs/debug-internal.log
|
| 6 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:init():772] calling init triggers
|
| 7 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:init():777] wandb.init called with sweep_config: {}
|
| 8 |
+
config: {'_wandb': {}}
|
| 9 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:init():820] starting backend
|
| 10 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:init():826] Connected to an existing wandb-core service via WANDB_SERVICE
|
| 11 |
+
2026-08-18 17:30:55,132 INFO MainThread:2958647 [wandb_init.py:init():835] sending inform_init request
|
| 12 |
+
2026-08-18 17:30:55,397 INFO MainThread:2958647 [wandb_init.py:init():840] backend started and connected
|
| 13 |
+
2026-08-18 17:30:55,400 INFO MainThread:2958647 [wandb_init.py:init():910] updated telemetry
|
| 14 |
+
2026-08-18 17:30:55,407 INFO MainThread:2958647 [wandb_init.py:init():933] communicating run to backend with 90.0 second timeout
|
| 15 |
+
2026-08-18 17:30:56,041 INFO MainThread:2958647 [wandb_init.py:init():978] starting run threads in backend
|
| 16 |
+
2026-08-18 17:30:56,118 INFO MainThread:2958647 [wandb_run.py:_console_start():2621] atexit reg
|
| 17 |
+
2026-08-18 17:30:56,119 INFO MainThread:2958647 [wandb_run.py:_redirect():2471] redirect: wrap_raw
|
| 18 |
+
2026-08-18 17:30:56,119 INFO MainThread:2958647 [wandb_run.py:_redirect():2540] Wrapping output streams.
|
| 19 |
+
2026-08-18 17:30:56,119 INFO MainThread:2958647 [wandb_run.py:_redirect():2563] Redirects installed.
|
| 20 |
+
2026-08-18 17:30:56,121 INFO MainThread:2958647 [wandb_init.py:init():1016] run started, returning control to user process
|
| 21 |
+
2026-08-18 17:30:56,122 INFO MainThread:2958647 [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': 3, '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': 'mlp', 'activation': 'linear', 'waleed_beta': 10.0, 'powlu_m': 3.0, 'model_type': 'tiny_llama', 'output_attentions': False, 'output_dir': 'out/mlp-linear-3L_run', 'per_device_train_batch_size': 32, 'num_train_epochs': 1, 'max_steps': 2500, 'learning_rate': 0.0003, 'lr_scheduler_type': 'constant_with_warmup', 'lr_scheduler_kwargs': None, 'warmup_steps': 500, '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-mlp-linear-3L-1.0M-20260818-173054', 'project': 'huggingface', 'trackio_space_id': None, 'trackio_bucket_id': None, 'trackio_static_space_id': None, 'eval_strategy': 'steps', 'eval_steps': 100, '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-mlp-linear-3L', '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-18 17:30:56,124 INFO MainThread:2958647 [wandb_config.py:__setitem__():155] [no run ID] config set model/num_parameters = 1016704 - <bound method Run._config_callback of <wandb.sdk.wandb_run.Run object at 0x14a3d44c0550>>
|
| 23 |
+
2026-08-18 17:30:56,124 INFO MainThread:2958647 [wandb_run.py:_config_callback():1346] config_cb model/num_parameters 1016704 None
|
zain/Activation/wandb/run-20260818_173055-ojtyk5jg/files/output.log
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
0%| | 0/2500 [00:00<?, ?it/s][transformers] `use_return_dict` is deprecated! Use `return_dict` instead!
|
| 2 |
+
[INFO] Causal mask (float with -inf) applied to all attention layers.
|
| 3 |
+
4%|▍ | 100/2500 [00:12<01:26, 27.81it[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.
|
| 4 |
+
{'loss': '8.323', 'grad_norm': '1.492', 'learning_rate': '1.14e-05', 'epoch': '0.0006741', 'train/total_time_seconds': '0.7461', 'train/time_per_step_avg': '0.0373', 'train/epoch_time_elapsed': '1.368', 'train/estimated_remaining_minutes': '1.542'}
|
| 5 |
+
{'loss': '8.293', 'grad_norm': '1.609', 'learning_rate': '2.34e-05', 'epoch': '0.001348', 'train/total_time_seconds': '0.9485', 'train/time_per_step_avg': '0.02371', 'train/epoch_time_elapsed': '2.07', 'train/estimated_remaining_minutes': '0.9723'}
|
| 6 |
+
{'loss': '8.183', 'grad_norm': '1.523', 'learning_rate': '3.54e-05', 'epoch': '0.002022', 'train/total_time_seconds': '1.152', 'train/time_per_step_avg': '0.0192', 'train/epoch_time_elapsed': '2.787', 'train/estimated_remaining_minutes': '0.7808'}
|
| 7 |
+
{'loss': '7.984', 'grad_norm': '1.297', 'learning_rate': '4.74e-05', 'epoch': '0.002696', 'train/total_time_seconds': '1.357', 'train/time_per_step_avg': '0.01696', 'train/epoch_time_elapsed': '3.503', 'train/estimated_remaining_minutes': '0.6841'}
|
| 8 |
+
{'loss': '7.792', 'grad_norm': '1.266', 'learning_rate': '5.94e-05', 'epoch': '0.00337', 'train/total_time_seconds': '1.559', 'train/time_per_step_avg': '0.01559', 'train/epoch_time_elapsed': '4.225', 'train/estimated_remaining_minutes': '0.6236'}
|
| 9 |
+
- 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
|
| 10 |
+
{'eval_loss': '7.687', 'eval_runtime': '8.023', 'eval_samples_per_second': '1187', 'eval_steps_per_second': '1.246', 'epoch': '0.00337', 'train/total_time_seconds': '1.559', 'train/time_per_step_avg': '0.01559', 'train/epoch_time_elapsed': '12.25', 'train/estimated_remaining_minutes': '0.6236'}
|
| 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, 209.69it/s]
|
| 14 |
+
8%|▊ | 200/2500 [00:23<01:20, 28.66it[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.
|
| 15 |
+
{'loss': '7.586', 'grad_norm': '1.25', 'learning_rate': '7.14e-05', 'epoch': '0.004044', 'train/total_time_seconds': '1.784', 'train/time_per_step_avg': '0.01038', 'train/epoch_time_elapsed': '13.08', 'train/estimated_remaining_minutes': '0.5898'}
|
| 16 |
+
{'loss': '7.357', 'grad_norm': '1.25', 'learning_rate': '8.34e-05', 'epoch': '0.004719', 'train/total_time_seconds': '1.995', 'train/time_per_step_avg': '0.01046', 'train/epoch_time_elapsed': '13.79', 'train/estimated_remaining_minutes': '0.5605'}
|
| 17 |
+
{'loss': '7.126', 'grad_norm': '1.219', 'learning_rate': '9.54e-05', 'epoch': '0.005393', 'train/total_time_seconds': '2.202', 'train/time_per_step_avg': '0.0105', 'train/epoch_time_elapsed': '14.49', 'train/estimated_remaining_minutes': '0.5368'}
|
| 18 |
+
{'loss': '6.882', 'grad_norm': '1.195', 'learning_rate': '0.0001074', 'epoch': '0.006067', 'train/total_time_seconds': '2.412', 'train/time_per_step_avg': '0.01055', 'train/epoch_time_elapsed': '15.2', 'train/estimated_remaining_minutes': '0.5181'}
|
| 19 |
+
{'loss': '6.638', 'grad_norm': '1.125', 'learning_rate': '0.0001194', 'epoch': '0.006741', 'train/total_time_seconds': '2.618', 'train/time_per_step_avg': '0.01059', 'train/epoch_time_elapsed': '15.9', 'train/estimated_remaining_minutes': '0.5017'}
|
| 20 |
+
- 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
|
| 21 |
+
{'eval_loss': '6.518', 'eval_runtime': '7.467', 'eval_samples_per_second': '1276', 'eval_steps_per_second': '1.339', 'epoch': '0.006741', 'train/total_time_seconds': '2.618', 'train/time_per_step_avg': '0.01059', 'train/epoch_time_elapsed': '23.37', 'train/estimated_remaining_minutes': '0.5017'}
|
| 22 |
+
- 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).
|
| 23 |
+
- If you are not the owner of the model architecture class, please contact the model code owner to update it.
|
| 24 |
+
Writing model shards: 100%|██████████| 1/1 [00:00<00:00, 313.66it/s]
|
| 25 |
+
12%|█▏ | 300/2500 [00:34<01:16, 28.69it[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.
|
| 26 |
+
{'loss': '6.419', 'grad_norm': '1.117', 'learning_rate': '0.0001314', 'epoch': '0.007415', 'train/total_time_seconds': '2.825', 'train/time_per_step_avg': '0.0104', 'train/epoch_time_elapsed': '24.1', 'train/estimated_remaining_minutes': '0.4879'}
|
| 27 |
+
{'loss': '6.198', 'grad_norm': '0.9961', 'learning_rate': '0.0001434', 'epoch': '0.008089', 'train/total_time_seconds': '3.04', 'train/time_per_step_avg': '0.01045', 'train/epoch_time_elapsed': '24.85', 'train/estimated_remaining_minutes': '0.4771'}
|
| 28 |
+
{'loss': '6.013', 'grad_norm': '0.8555', 'learning_rate': '0.0001554', 'epoch': '0.008763', 'train/total_time_seconds': '3.248', 'train/time_per_step_avg': '0.01046', 'train/epoch_time_elapsed': '25.55', 'train/estimated_remaining_minutes': '0.4664'}
|
| 29 |
+
{'loss': '5.827', 'grad_norm': '2.438', 'learning_rate': '0.0001674', 'epoch': '0.009437', 'train/total_time_seconds': '3.455', 'train/time_per_step_avg': '0.01043', 'train/epoch_time_elapsed': '26.25', 'train/estimated_remaining_minutes': '0.4566'}
|
| 30 |
+
{'loss': '5.679', 'grad_norm': '1.117', 'learning_rate': '0.0001794', 'epoch': '0.01011', 'train/total_time_seconds': '3.661', 'train/time_per_step_avg': '0.01043', 'train/epoch_time_elapsed': '26.95', 'train/estimated_remaining_minutes': '0.4474'}
|
| 31 |
+
- 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
|
| 32 |
+
{'eval_loss': '5.609', 'eval_runtime': '7.529', 'eval_samples_per_second': '1265', 'eval_steps_per_second': '1.328', 'epoch': '0.01011', 'train/total_time_seconds': '3.661', 'train/time_per_step_avg': '0.01043', 'train/epoch_time_elapsed': '34.48', 'train/estimated_remaining_minutes': '0.4474'}
|
| 33 |
+
- 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).
|
| 34 |
+
- If you are not the owner of the model architecture class, please contact the model code owner to update it.
|
| 35 |
+
Writing model shards: 100%|██████████| 1/1 [00:00<00:00, 334.87it/s]
|
| 36 |
+
16%|█▌ | 400/2500 [00:37<01:13, 28.72it/s]?, ?it/s]
|
| 37 |
+
{'loss': '5.545', 'grad_norm': '0.9375', 'learning_rate': '0.0001914', 'epoch': '0.01079', 'train/total_time_seconds': '3.865', 'train/time_per_step_avg': '0.01041', 'train/epoch_time_elapsed': '35.2', 'train/estimated_remaining_minutes': '0.4389'}
|
| 38 |
+
{'loss': '5.418', 'grad_norm': '1.273', 'learning_rate': '0.0002034', 'epoch': '0.01146', 'train/total_time_seconds': '4.069', 'train/time_per_step_avg': '0.01029', 'train/epoch_time_elapsed': '35.9', 'train/estimated_remaining_minutes': '0.4309'}
|
| 39 |
+
{'loss': '5.26', 'grad_norm': '1.891', 'learning_rate': '0.0002154', 'epoch': '0.01213', 'train/total_time_seconds': '4.274', 'train/time_per_step_avg': '0.01025', 'train/epoch_time_elapsed': '36.59', 'train/estimated_remaining_minutes': '0.4234'}
|
| 40 |
+
{'loss': '5.146', 'grad_norm': '1.266', 'learning_rate': '0.0002274', 'epoch': '0.01281', 'train/total_time_seconds': '4.482', 'train/time_per_step_avg': '0.01026', 'train/epoch_time_elapsed': '37.29', 'train/estimated_remaining_minutes': '0.4167'}
|
| 41 |
+
{'loss': '5.027', 'grad_norm': '1.633', 'learning_rate': '0.0002394', 'epoch': '0.01348', 'train/total_time_seconds': '4.686', 'train/time_per_step_avg': '0.01025', 'train/epoch_time_elapsed': '37.99', 'train/estimated_remaining_minutes': '0.41'}
|
| 42 |
+
70%|███████ | 7/10 [00:04<00:02, 1.29it/s]
|
zain/Activation/wandb/run-20260818_173055-ojtyk5jg/files/requirements.txt
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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yzmq==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 |
+
markdown-it-py==4.2.0
|
| 94 |
+
nvidia-cuda-runtime==13.0.96
|
| 95 |
+
cuda-bindings==13.3.1
|
| 96 |
+
nvidia-cuda-cupti==13.0.85
|
| 97 |
+
torch==2.6.0+cu124
|
| 98 |
+
multiprocess==0.70.19
|
| 99 |
+
pillow==12.2.0
|
| 100 |
+
transformers==5.16.0.dev0
|
| 101 |
+
wandb==0.28.1
|
| 102 |
+
nvidia-curand==10.4.0.35
|
| 103 |
+
sympy==1.13.1
|
| 104 |
+
nvidia-cusparse==12.6.3.3
|
| 105 |
+
nvidia-cuda-nvrtc==13.0.88
|
| 106 |
+
typing-inspection==0.4.2
|
| 107 |
+
nvidia-cusolver==12.0.4.66
|
| 108 |
+
nvidia-cufft==12.0.0.61
|
| 109 |
+
nvidia-cudnn-cu13==9.20.0.48
|
| 110 |
+
nvidia-cublas==13.1.1.3
|
| 111 |
+
pyarrow==25.0.0
|
| 112 |
+
evaluate==0.4.6
|
| 113 |
+
diffusers==0.39.0
|
| 114 |
+
pydantic==2.13.4
|
| 115 |
+
annotated-types==0.8.0
|
| 116 |
+
protobuf==7.35.1
|
| 117 |
+
sentry-sdk==2.66.1
|
| 118 |
+
einops==0.8.2
|
| 119 |
+
packaging==26.2
|
| 120 |
+
nvidia-nvjitlink-cu12==12.4.127
|
| 121 |
+
nvidia-curand-cu12==10.3.5.147
|
| 122 |
+
nvidia-cusparselt-cu12==0.6.2
|
| 123 |
+
nvidia-cusparse-cu12==12.3.1.170
|
| 124 |
+
nvidia-cuda-runtime-cu12==12.4.127
|
| 125 |
+
torchvision==0.21.0+cu124
|
| 126 |
+
nvidia-cuda-nvrtc-cu12==12.4.127
|
| 127 |
+
nvidia-cuda-cupti-cu12==12.4.127
|
| 128 |
+
nvidia-cusolver-cu12==11.6.1.9
|
| 129 |
+
nvidia-cublas-cu12==12.4.5.8
|
| 130 |
+
nvidia-cudnn-cu12==9.1.0.70
|
| 131 |
+
huggingface_hub==1.26.0
|
| 132 |
+
datasets==5.0.1
|
| 133 |
+
safetensors==0.8.0
|
| 134 |
+
accelerate==1.14.0
|
| 135 |
+
pydantic_core==2.46.4
|
| 136 |
+
ninja==1.13.0
|
| 137 |
+
tokenizers==0.23.1
|
| 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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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"os": "Linux-5.15.0-126-generic-x86_64-with-glibc2.35",
|
| 3 |
+
"python": "CPython 3.11.15",
|
| 4 |
+
"startedAt": "2026-08-18T17:30:55.131243Z",
|
| 5 |
+
"args": [
|
| 6 |
+
"--config",
|
| 7 |
+
"/mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/configs/baseline100L.yaml",
|
| 8 |
+
"--variants",
|
| 9 |
+
"mlp-linear-3L",
|
| 10 |
+
"mlp-gelu-3L",
|
| 11 |
+
"mlp-relu-3L",
|
| 12 |
+
"mlp-silu-waleed10-3L",
|
| 13 |
+
"mlp-waleed10-3L",
|
| 14 |
+
"mlp-s10-3L",
|
| 15 |
+
"mlp-w1a-3L",
|
| 16 |
+
"mlp-silu-3L",
|
| 17 |
+
"mlp-sigmoid-3L",
|
| 18 |
+
"mlp-tanh-3L",
|
| 19 |
+
"mlp-powlu-3L",
|
| 20 |
+
"glu-linear-3L",
|
| 21 |
+
"glu-gelu-3L",
|
| 22 |
+
"glu-relu-3L",
|
| 23 |
+
"glu-powlu-3L",
|
| 24 |
+
"glu-situglu-3L",
|
| 25 |
+
"glu-waleed-3L",
|
| 26 |
+
"glu-waleedglu_low-3L",
|
| 27 |
+
"glu-situglu_low-3L",
|
| 28 |
+
"glu-silu-waleed10-3L",
|
| 29 |
+
"glu-waleed10-3L",
|
| 30 |
+
"glu-w1a-3L",
|
| 31 |
+
"glu-silu-3L",
|
| 32 |
+
"glu-sigmoid-3L",
|
| 33 |
+
"glu-tanh-3L",
|
| 34 |
+
"mlp-linear-6L",
|
| 35 |
+
"mlp-gelu-6L",
|
| 36 |
+
"mlp-relu-6L",
|
| 37 |
+
"mlp-silu-waleed10-6L",
|
| 38 |
+
"mlp-waleed10-6L",
|
| 39 |
+
"mlp-s10-6L",
|
| 40 |
+
"mlp-w1a-6L",
|
| 41 |
+
"mlp-silu-6L",
|
| 42 |
+
"mlp-sigmoid-6L",
|
| 43 |
+
"mlp-tanh-6L",
|
| 44 |
+
"mlp-powlu-6L",
|
| 45 |
+
"glu-linear-6L",
|
| 46 |
+
"glu-gelu-6L",
|
| 47 |
+
"glu-relu-6L",
|
| 48 |
+
"glu-powlu-6L",
|
| 49 |
+
"glu-situglu-6L",
|
| 50 |
+
"glu-waleed-6L",
|
| 51 |
+
"glu-waleedglu_low-6L",
|
| 52 |
+
"glu-situglu_low-6L",
|
| 53 |
+
"glu-silu-waleed10-6L",
|
| 54 |
+
"glu-waleed10-6L",
|
| 55 |
+
"glu-w1a-6L",
|
| 56 |
+
"glu-silu-6L",
|
| 57 |
+
"glu-sigmoid-6L",
|
| 58 |
+
"glu-tanh-6L",
|
| 59 |
+
"mlp-linear-9L",
|
| 60 |
+
"mlp-gelu-9L",
|
| 61 |
+
"mlp-relu-9L",
|
| 62 |
+
"mlp-silu-waleed10-9L",
|
| 63 |
+
"mlp-waleed10-9L",
|
| 64 |
+
"mlp-s10-9L",
|
| 65 |
+
"mlp-w1a-9L",
|
| 66 |
+
"mlp-silu-9L",
|
| 67 |
+
"mlp-sigmoid-9L",
|
| 68 |
+
"mlp-tanh-9L",
|
| 69 |
+
"mlp-powlu-9L",
|
| 70 |
+
"glu-linear-9L",
|
| 71 |
+
"glu-gelu-9L",
|
| 72 |
+
"glu-relu-9L",
|
| 73 |
+
"glu-powlu-9L",
|
| 74 |
+
"glu-situglu-9L",
|
| 75 |
+
"glu-waleed-9L",
|
| 76 |
+
"glu-waleedglu_low-9L",
|
| 77 |
+
"glu-situglu_low-9L",
|
| 78 |
+
"glu-silu-waleed10-9L",
|
| 79 |
+
"glu-waleed10-9L",
|
| 80 |
+
"glu-w1a-9L",
|
| 81 |
+
"glu-silu-9L",
|
| 82 |
+
"glu-sigmoid-9L",
|
| 83 |
+
"glu-tanh-9L"
|
| 84 |
+
],
|
| 85 |
+
"program": "/mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation/sweep.py",
|
| 86 |
+
"codePath": "sweep.py",
|
| 87 |
+
"codePathLocal": "sweep.py",
|
| 88 |
+
"git": {
|
| 89 |
+
"remote": "https://github.com/w-ahmad1a10/Activation.git",
|
| 90 |
+
"commit": "463c9961366755fc55f02df9a0d471b3cbcb025e"
|
| 91 |
+
},
|
| 92 |
+
"email": "deepnevro@gmail.com",
|
| 93 |
+
"root": "/mnt/data/zainulabideen/zain-exp/notebooks/zain/Activation",
|
| 94 |
+
"host": "deeplens-k3s-node1",
|
| 95 |
+
"executable": "/mnt/data/zainulabideen/zain-exp/notebooks/my_env/bin/python",
|
| 96 |
+
"cpu_count": 112,
|
| 97 |
+
"cpu_count_logical": 224,
|
| 98 |
+
"gpu": "NVIDIA H100 80GB HBM3",
|
| 99 |
+
"gpu_count": 8,
|
| 100 |
+
"disk": {
|
| 101 |
+
"/": {
|
| 102 |
+
"total": "1560765693952",
|
| 103 |
+
"used": "705143742464"
|
| 104 |
+
}
|
| 105 |
+
},
|
| 106 |
+
"memory": {
|
| 107 |
+
"total": "2164089937920"
|
| 108 |
+
},
|
| 109 |
+
"gpu_nvidia": [
|
| 110 |
+
{
|
| 111 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 112 |
+
"memoryTotal": "85520809984",
|
| 113 |
+
"cudaCores": 16896,
|
| 114 |
+
"architecture": "Hopper",
|
| 115 |
+
"uuid": "GPU-39c684a5-fde6-83d7-1663-0859795881ae"
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 119 |
+
"memoryTotal": "85520809984",
|
| 120 |
+
"cudaCores": 16896,
|
| 121 |
+
"architecture": "Hopper",
|
| 122 |
+
"uuid": "GPU-68012e5a-38b6-b643-0ca6-62fb66720bf3"
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 126 |
+
"memoryTotal": "85520809984",
|
| 127 |
+
"cudaCores": 16896,
|
| 128 |
+
"architecture": "Hopper",
|
| 129 |
+
"uuid": "GPU-132944c4-b689-2b5f-89a4-d730401677ab"
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 133 |
+
"memoryTotal": "85520809984",
|
| 134 |
+
"cudaCores": 16896,
|
| 135 |
+
"architecture": "Hopper",
|
| 136 |
+
"uuid": "GPU-2df386cc-6d26-d0e2-7a2d-a057b0d95864"
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 140 |
+
"memoryTotal": "85520809984",
|
| 141 |
+
"cudaCores": 16896,
|
| 142 |
+
"architecture": "Hopper",
|
| 143 |
+
"uuid": "GPU-bfa16575-1d94-1aa2-4537-2c93433f42ef"
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 147 |
+
"memoryTotal": "85520809984",
|
| 148 |
+
"cudaCores": 16896,
|
| 149 |
+
"architecture": "Hopper",
|
| 150 |
+
"uuid": "GPU-bc6c3e3c-9b90-09ca-c034-774961847c54"
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 154 |
+
"memoryTotal": "85520809984",
|
| 155 |
+
"cudaCores": 16896,
|
| 156 |
+
"architecture": "Hopper",
|
| 157 |
+
"uuid": "GPU-00a441e1-7c95-e7d6-4c35-43d6b291aea9"
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"name": "NVIDIA H100 80GB HBM3",
|
| 161 |
+
"memoryTotal": "85520809984",
|
| 162 |
+
"cudaCores": 16896,
|
| 163 |
+
"architecture": "Hopper",
|
| 164 |
+
"uuid": "GPU-1c4d29a2-4647-6fce-d8fc-0c5ecfbbd6ea"
|
| 165 |
+
}
|
| 166 |
+
],
|
| 167 |
+
"cudaVersion": "12.4",
|
| 168 |
+
"writerId": "tubesu4fsqao8mgfr6qv79ajcykzur8u"
|
| 169 |
+
}
|
zain/Activation/wandb/run-20260818_173055-ojtyk5jg/logs/debug-core.log
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"time":"2026-08-18T17:28:42.000027215Z","level":"INFO","msg":"main: starting server","port-filename":"/tmp/tmpptgl1iw7/port-2936361.txt","pid":2936361,"detached":false,"idle-timeout":600000000000,"log-level":0,"disable-analytics":false,"shutdown-on-parent-exit":false,"enable-dcgm-profiling":false}
|
| 2 |
+
{"time":"2026-08-18T17:28:42.009724961Z","level":"INFO","msg":"server: will exit if parent process dies","ppid":2936361}
|
| 3 |
+
{"time":"2026-08-18T17:28:42.00971545Z","level":"INFO","msg":"server: accepting connections","addr":{"Name":"/tmp/wandb-2936361-2939112-1622088723/socket","Net":"unix"}}
|
| 4 |
+
{"time":"2026-08-18T17:28:42.177351153Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"1(@)"}
|
| 5 |
+
{"time":"2026-08-18T17:30:54.990566831Z","level":"INFO","msg":"connection: ManageConnectionData: new connection created","id":"2(@)"}
|
| 6 |
+
{"time":"2026-08-18T17:30:55.133755029Z","level":"INFO","msg":"handleInformInit: received","streamId":"ojtyk5jg","id":"2(@)"}
|
| 7 |
+
{"time":"2026-08-18T17:30:55.396973873Z","level":"INFO","msg":"handleInformInit: stream started","streamId":"ojtyk5jg","id":"2(@)"}
|
| 8 |
+
{"time":"2026-08-18T17:31:01.125148608Z","level":"INFO","msg":"connection: cancelling request","id":"2(@)","requestId":"rb4y2wpbltr8"}
|