Delete v5/.ipynb_checkpoints
Browse files
v5/.ipynb_checkpoints/eval_inverter_v5-checkpoint.py
DELETED
|
@@ -1,137 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python
|
| 2 |
-
import argparse
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
from transformers import AutoTokenizer
|
| 8 |
-
|
| 9 |
-
from train_inverter_v5 import EncoderOnlyModel, ExpertStream, TrainState
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def _load_state_dict(path: str):
|
| 13 |
-
ckpt = torch.load(path, map_location="cpu")
|
| 14 |
-
state = ckpt.get("model", ckpt)
|
| 15 |
-
if any(k.startswith("_orig_mod.") for k in state.keys()):
|
| 16 |
-
state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
|
| 17 |
-
return state
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def main():
|
| 21 |
-
parser = argparse.ArgumentParser(
|
| 22 |
-
description="Evaluate V5 multihot inverter (per-layer MLP)."
|
| 23 |
-
)
|
| 24 |
-
parser.add_argument("--idx", required=True)
|
| 25 |
-
parser.add_argument("--dataset", default="vietgpt/openwebtext_en")
|
| 26 |
-
parser.add_argument("--dataset-revision", default=None)
|
| 27 |
-
parser.add_argument("--model", default="openai/gpt-oss-20b")
|
| 28 |
-
parser.add_argument("--model-revision", default=None)
|
| 29 |
-
parser.add_argument("--seq-len", type=int, default=32)
|
| 30 |
-
parser.add_argument("--layers", type=int, default=24)
|
| 31 |
-
parser.add_argument("--max-tokens", type=int, default=200000000)
|
| 32 |
-
parser.add_argument("--sample-tokens", type=int, default=200000)
|
| 33 |
-
parser.add_argument("--batch-size", type=int, default=8)
|
| 34 |
-
parser.add_argument("--topk", default="1,5,10")
|
| 35 |
-
parser.add_argument("--checkpoint", required=True)
|
| 36 |
-
parser.add_argument("--d-model", type=int, default=768)
|
| 37 |
-
parser.add_argument("--n-head", type=int, default=12)
|
| 38 |
-
parser.add_argument("--d-ff", type=int, default=2048)
|
| 39 |
-
parser.add_argument("--n-layer", type=int, default=6)
|
| 40 |
-
parser.add_argument("--layer-hidden", type=int, default=64)
|
| 41 |
-
parser.add_argument("--layer-proj", type=int, default=64)
|
| 42 |
-
parser.add_argument("--dropout", type=float, default=0.1)
|
| 43 |
-
parser.add_argument("--logit-softcap", type=float, default=0.0)
|
| 44 |
-
parser.add_argument("--layer-gating", action="store_true")
|
| 45 |
-
parser.add_argument("--attn-impl", choices=["auto", "flash", "mem_efficient", "math"], default="auto")
|
| 46 |
-
parser.add_argument("--hard-exit", action="store_true")
|
| 47 |
-
args = parser.parse_args()
|
| 48 |
-
|
| 49 |
-
if torch.cuda.is_available():
|
| 50 |
-
if args.attn_impl != "auto":
|
| 51 |
-
try:
|
| 52 |
-
torch.backends.cuda.enable_flash_sdp(args.attn_impl == "flash")
|
| 53 |
-
torch.backends.cuda.enable_mem_efficient_sdp(
|
| 54 |
-
args.attn_impl == "mem_efficient"
|
| 55 |
-
)
|
| 56 |
-
torch.backends.cuda.enable_math_sdp(args.attn_impl == "math")
|
| 57 |
-
except AttributeError:
|
| 58 |
-
pass
|
| 59 |
-
|
| 60 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 61 |
-
args.model,
|
| 62 |
-
revision=args.model_revision,
|
| 63 |
-
)
|
| 64 |
-
if tokenizer.pad_token_id is None:
|
| 65 |
-
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 66 |
-
|
| 67 |
-
state = TrainState()
|
| 68 |
-
stream = ExpertStream(
|
| 69 |
-
idx_path=args.idx,
|
| 70 |
-
dataset_name=args.dataset,
|
| 71 |
-
dataset_revision=args.dataset_revision,
|
| 72 |
-
tokenizer=tokenizer,
|
| 73 |
-
seq_len=args.seq_len,
|
| 74 |
-
max_tokens=args.max_tokens,
|
| 75 |
-
batch_size=args.batch_size,
|
| 76 |
-
state=state,
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 80 |
-
model = EncoderOnlyModel(
|
| 81 |
-
vocab_size=len(tokenizer),
|
| 82 |
-
num_experts=32,
|
| 83 |
-
num_layers=args.layers,
|
| 84 |
-
topk=4,
|
| 85 |
-
d_model=args.d_model,
|
| 86 |
-
n_head=args.n_head,
|
| 87 |
-
d_ff=args.d_ff,
|
| 88 |
-
n_layer=args.n_layer,
|
| 89 |
-
dropout=args.dropout,
|
| 90 |
-
max_len=args.seq_len,
|
| 91 |
-
layer_gating=args.layer_gating,
|
| 92 |
-
logit_softcap=args.logit_softcap,
|
| 93 |
-
layer_hidden=args.layer_hidden,
|
| 94 |
-
layer_proj=args.layer_proj,
|
| 95 |
-
).to(device)
|
| 96 |
-
|
| 97 |
-
model.load_state_dict(_load_state_dict(args.checkpoint), strict=True)
|
| 98 |
-
model.eval()
|
| 99 |
-
|
| 100 |
-
eval_topk = [int(k.strip()) for k in args.topk.split(",") if k.strip()]
|
| 101 |
-
eval_topk = sorted({k for k in eval_topk if k > 0})
|
| 102 |
-
correct = {k: 0 for k in eval_topk}
|
| 103 |
-
total = 0
|
| 104 |
-
|
| 105 |
-
for batch in stream:
|
| 106 |
-
if total >= args.sample_tokens:
|
| 107 |
-
break
|
| 108 |
-
|
| 109 |
-
input_ids = batch["input_ids"].to(device, non_blocking=True)
|
| 110 |
-
expert_idx = batch["expert_idx"][:, :, :args.layers].to(device, non_blocking=True)
|
| 111 |
-
attention_mask = batch["attention_mask"].to(device, non_blocking=True)
|
| 112 |
-
|
| 113 |
-
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 114 |
-
logits = model(expert_idx, attention_mask)
|
| 115 |
-
|
| 116 |
-
for k in eval_topk:
|
| 117 |
-
topk_pred = torch.topk(logits, k=k, dim=-1).indices
|
| 118 |
-
match = (topk_pred == input_ids.unsqueeze(-1)).any(dim=-1)
|
| 119 |
-
match = match & attention_mask
|
| 120 |
-
correct[k] += int(match.sum().item())
|
| 121 |
-
|
| 122 |
-
total += int(attention_mask.sum().item())
|
| 123 |
-
if total >= args.sample_tokens:
|
| 124 |
-
break
|
| 125 |
-
|
| 126 |
-
result = {
|
| 127 |
-
"tokens": total,
|
| 128 |
-
"accuracy": {str(k): correct[k] / total for k in eval_topk},
|
| 129 |
-
}
|
| 130 |
-
print(json.dumps(result, indent=2))
|
| 131 |
-
|
| 132 |
-
if args.hard_exit:
|
| 133 |
-
os._exit(0)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
if __name__ == "__main__":
|
| 137 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
v5/.ipynb_checkpoints/train_inverter_v5-checkpoint.py
DELETED
|
@@ -1,570 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python
|
| 2 |
-
import argparse
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
import time
|
| 6 |
-
from dataclasses import dataclass
|
| 7 |
-
|
| 8 |
-
import numpy as np
|
| 9 |
-
import torch
|
| 10 |
-
import torch.nn as nn
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
-
from datasets import load_dataset
|
| 13 |
-
from transformers import AutoTokenizer
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
@dataclass
|
| 17 |
-
class TrainState:
|
| 18 |
-
tokens_seen: int = 0
|
| 19 |
-
example_index: int = 0
|
| 20 |
-
example_token_offset: int = 0
|
| 21 |
-
step: int = 0
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
def _write_json_atomic(path, payload):
|
| 25 |
-
tmp = f"{path}.tmp"
|
| 26 |
-
with open(tmp, "w") as f:
|
| 27 |
-
json.dump(payload, f, indent=2, sort_keys=True)
|
| 28 |
-
os.replace(tmp, path)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class ExpertStream:
|
| 32 |
-
def __init__(
|
| 33 |
-
self,
|
| 34 |
-
idx_path,
|
| 35 |
-
dataset_name,
|
| 36 |
-
dataset_revision,
|
| 37 |
-
tokenizer,
|
| 38 |
-
seq_len,
|
| 39 |
-
max_tokens,
|
| 40 |
-
batch_size,
|
| 41 |
-
state: TrainState,
|
| 42 |
-
):
|
| 43 |
-
self.idx_path = idx_path
|
| 44 |
-
self.dataset_name = dataset_name
|
| 45 |
-
self.dataset_revision = dataset_revision
|
| 46 |
-
self.tokenizer = tokenizer
|
| 47 |
-
self.seq_len = seq_len
|
| 48 |
-
self.max_tokens = max_tokens
|
| 49 |
-
self.batch_size = batch_size
|
| 50 |
-
self.state = state
|
| 51 |
-
|
| 52 |
-
self.idx_mmap = np.load(self.idx_path, mmap_mode="r")
|
| 53 |
-
if self.idx_mmap.shape != (self.max_tokens, 24, 4):
|
| 54 |
-
raise ValueError(f"Unexpected idx shape {self.idx_mmap.shape}.")
|
| 55 |
-
|
| 56 |
-
def __iter__(self):
|
| 57 |
-
ds = load_dataset(
|
| 58 |
-
self.dataset_name,
|
| 59 |
-
split="train",
|
| 60 |
-
streaming=True,
|
| 61 |
-
revision=self.dataset_revision,
|
| 62 |
-
)
|
| 63 |
-
tokens_seen = self.state.tokens_seen
|
| 64 |
-
example_index = self.state.example_index
|
| 65 |
-
example_token_offset = self.state.example_token_offset
|
| 66 |
-
|
| 67 |
-
batch_tokens = []
|
| 68 |
-
batch_idx = []
|
| 69 |
-
batch_mask = []
|
| 70 |
-
|
| 71 |
-
for idx, example in enumerate(ds):
|
| 72 |
-
if idx < example_index:
|
| 73 |
-
continue
|
| 74 |
-
if tokens_seen >= self.max_tokens:
|
| 75 |
-
break
|
| 76 |
-
|
| 77 |
-
token_ids = self.tokenizer.encode(
|
| 78 |
-
example["text"], add_special_tokens=False
|
| 79 |
-
)
|
| 80 |
-
if idx == example_index and example_token_offset > 0:
|
| 81 |
-
token_ids = token_ids[example_token_offset:]
|
| 82 |
-
|
| 83 |
-
if not token_ids:
|
| 84 |
-
example_index = idx + 1
|
| 85 |
-
example_token_offset = 0
|
| 86 |
-
continue
|
| 87 |
-
|
| 88 |
-
pos = 0
|
| 89 |
-
while pos < len(token_ids) and tokens_seen < self.max_tokens:
|
| 90 |
-
remaining = self.max_tokens - tokens_seen
|
| 91 |
-
current_len = min(self.seq_len, len(token_ids) - pos, remaining)
|
| 92 |
-
if current_len <= 0:
|
| 93 |
-
break
|
| 94 |
-
|
| 95 |
-
chunk = token_ids[pos:pos + current_len]
|
| 96 |
-
idx_chunk = self.idx_mmap[tokens_seen:tokens_seen + current_len]
|
| 97 |
-
|
| 98 |
-
tokens_seen += current_len
|
| 99 |
-
pos += current_len
|
| 100 |
-
example_token_offset += current_len
|
| 101 |
-
|
| 102 |
-
pad_len = self.seq_len - current_len
|
| 103 |
-
if pad_len:
|
| 104 |
-
chunk = chunk + [self.tokenizer.pad_token_id] * pad_len
|
| 105 |
-
idx_chunk = np.pad(
|
| 106 |
-
idx_chunk,
|
| 107 |
-
((0, pad_len), (0, 0), (0, 0)),
|
| 108 |
-
mode="edge",
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
mask = [1] * current_len + [0] * pad_len
|
| 112 |
-
|
| 113 |
-
batch_tokens.append(chunk)
|
| 114 |
-
batch_idx.append(idx_chunk)
|
| 115 |
-
batch_mask.append(mask)
|
| 116 |
-
|
| 117 |
-
if len(batch_tokens) >= self.batch_size:
|
| 118 |
-
yield {
|
| 119 |
-
"input_ids": torch.tensor(
|
| 120 |
-
np.asarray(batch_tokens, dtype=np.int64)
|
| 121 |
-
),
|
| 122 |
-
"expert_idx": torch.tensor(
|
| 123 |
-
np.asarray(batch_idx, dtype=np.int64)
|
| 124 |
-
),
|
| 125 |
-
"attention_mask": torch.tensor(
|
| 126 |
-
np.asarray(batch_mask, dtype=np.bool_)
|
| 127 |
-
),
|
| 128 |
-
"state": TrainState(
|
| 129 |
-
tokens_seen=tokens_seen,
|
| 130 |
-
example_index=idx,
|
| 131 |
-
example_token_offset=example_token_offset,
|
| 132 |
-
),
|
| 133 |
-
}
|
| 134 |
-
batch_tokens, batch_idx, batch_mask = [], [], []
|
| 135 |
-
|
| 136 |
-
example_index = idx + 1
|
| 137 |
-
example_token_offset = 0
|
| 138 |
-
|
| 139 |
-
if batch_tokens:
|
| 140 |
-
yield {
|
| 141 |
-
"input_ids": torch.tensor(np.asarray(batch_tokens, dtype=np.int64)),
|
| 142 |
-
"expert_idx": torch.tensor(np.asarray(batch_idx, dtype=np.int64)),
|
| 143 |
-
"attention_mask": torch.tensor(
|
| 144 |
-
np.asarray(batch_mask, dtype=np.bool_)
|
| 145 |
-
),
|
| 146 |
-
"state": TrainState(
|
| 147 |
-
tokens_seen=tokens_seen,
|
| 148 |
-
example_index=example_index,
|
| 149 |
-
example_token_offset=example_token_offset,
|
| 150 |
-
),
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
class RMSNorm(nn.Module):
|
| 155 |
-
def __init__(self, dim, eps=1e-5):
|
| 156 |
-
super().__init__()
|
| 157 |
-
self.eps = eps
|
| 158 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 159 |
-
|
| 160 |
-
def forward(self, x):
|
| 161 |
-
norm = x.norm(dim=-1, keepdim=True) * (1.0 / (x.size(-1) ** 0.5))
|
| 162 |
-
return self.weight * x / (norm + self.eps)
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
class ExpertEncoderMultiHot(nn.Module):
|
| 166 |
-
def __init__(
|
| 167 |
-
self,
|
| 168 |
-
num_experts,
|
| 169 |
-
num_layers,
|
| 170 |
-
d_model,
|
| 171 |
-
layer_hidden,
|
| 172 |
-
layer_proj,
|
| 173 |
-
dropout,
|
| 174 |
-
layer_gating,
|
| 175 |
-
):
|
| 176 |
-
super().__init__()
|
| 177 |
-
self.num_experts = num_experts
|
| 178 |
-
self.num_layers = num_layers
|
| 179 |
-
self.layer_gating = layer_gating
|
| 180 |
-
if layer_gating:
|
| 181 |
-
self.layer_gate = nn.Parameter(torch.zeros(num_layers))
|
| 182 |
-
self.layer_norm = nn.LayerNorm(num_experts)
|
| 183 |
-
self.layer_mlp = nn.Sequential(
|
| 184 |
-
nn.Linear(num_experts, layer_hidden),
|
| 185 |
-
nn.ReLU(),
|
| 186 |
-
nn.Linear(layer_hidden, layer_proj),
|
| 187 |
-
)
|
| 188 |
-
self.proj = nn.Linear(num_layers * layer_proj, d_model)
|
| 189 |
-
self.dropout = nn.Dropout(dropout)
|
| 190 |
-
|
| 191 |
-
def forward(self, expert_idx):
|
| 192 |
-
# expert_idx: [B, S, L, K]
|
| 193 |
-
bsz, seq_len, num_layers, _topk = expert_idx.shape
|
| 194 |
-
multihot = torch.zeros(
|
| 195 |
-
(bsz, seq_len, num_layers, self.num_experts),
|
| 196 |
-
device=expert_idx.device,
|
| 197 |
-
dtype=torch.float32,
|
| 198 |
-
)
|
| 199 |
-
multihot.scatter_(-1, expert_idx, 1.0)
|
| 200 |
-
if self.layer_gating:
|
| 201 |
-
gate = torch.sigmoid(self.layer_gate).view(1, 1, num_layers, 1)
|
| 202 |
-
multihot = multihot * gate
|
| 203 |
-
multihot = self.layer_norm(multihot)
|
| 204 |
-
layer_repr = self.layer_mlp(multihot) # [B,S,L,P]
|
| 205 |
-
flat = layer_repr.reshape(bsz, seq_len, num_layers * layer_repr.size(-1))
|
| 206 |
-
return self.dropout(self.proj(flat))
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
class EncoderBlock(nn.Module):
|
| 210 |
-
def __init__(self, d_model, n_head, d_ff, dropout):
|
| 211 |
-
super().__init__()
|
| 212 |
-
self.n_head = n_head
|
| 213 |
-
self.d_model = d_model
|
| 214 |
-
self.attn_norm = RMSNorm(d_model)
|
| 215 |
-
self.mlp_norm = RMSNorm(d_model)
|
| 216 |
-
self.attn = nn.Linear(d_model, 3 * d_model)
|
| 217 |
-
self.proj = nn.Linear(d_model, d_model)
|
| 218 |
-
self.dropout = nn.Dropout(dropout)
|
| 219 |
-
self.fc = nn.Linear(d_model, d_ff)
|
| 220 |
-
self.fc_out = nn.Linear(d_ff, d_model)
|
| 221 |
-
|
| 222 |
-
def forward(self, x, attention_mask):
|
| 223 |
-
bsz, seq_len, d_model = x.shape
|
| 224 |
-
qkv = self.attn(self.attn_norm(x))
|
| 225 |
-
q, k, v = qkv.split(d_model, dim=-1)
|
| 226 |
-
d_head = d_model // self.n_head
|
| 227 |
-
q = q.view(bsz, seq_len, self.n_head, d_head).transpose(1, 2)
|
| 228 |
-
k = k.view(bsz, seq_len, self.n_head, d_head).transpose(1, 2)
|
| 229 |
-
v = v.view(bsz, seq_len, self.n_head, d_head).transpose(1, 2)
|
| 230 |
-
attn = torch.nn.functional.scaled_dot_product_attention(
|
| 231 |
-
q,
|
| 232 |
-
k,
|
| 233 |
-
v,
|
| 234 |
-
attn_mask=None,
|
| 235 |
-
dropout_p=0.0,
|
| 236 |
-
is_causal=False,
|
| 237 |
-
)
|
| 238 |
-
attn = attn.transpose(1, 2).contiguous().view(bsz, seq_len, d_model)
|
| 239 |
-
x = x + self.dropout(self.proj(attn))
|
| 240 |
-
mlp = self.fc(self.mlp_norm(x))
|
| 241 |
-
mlp = torch.relu(mlp).pow(2)
|
| 242 |
-
x = x + self.dropout(self.fc_out(mlp))
|
| 243 |
-
if attention_mask is not None:
|
| 244 |
-
x = x * attention_mask.unsqueeze(-1)
|
| 245 |
-
return x
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
class EncoderOnlyModel(nn.Module):
|
| 249 |
-
def __init__(
|
| 250 |
-
self,
|
| 251 |
-
vocab_size,
|
| 252 |
-
num_experts,
|
| 253 |
-
num_layers,
|
| 254 |
-
topk,
|
| 255 |
-
d_model,
|
| 256 |
-
n_head,
|
| 257 |
-
d_ff,
|
| 258 |
-
n_layer,
|
| 259 |
-
dropout,
|
| 260 |
-
max_len,
|
| 261 |
-
layer_gating,
|
| 262 |
-
logit_softcap,
|
| 263 |
-
layer_hidden,
|
| 264 |
-
layer_proj,
|
| 265 |
-
):
|
| 266 |
-
super().__init__()
|
| 267 |
-
self.encoder_in = ExpertEncoderMultiHot(
|
| 268 |
-
num_experts,
|
| 269 |
-
num_layers,
|
| 270 |
-
d_model,
|
| 271 |
-
layer_hidden,
|
| 272 |
-
layer_proj,
|
| 273 |
-
dropout,
|
| 274 |
-
layer_gating,
|
| 275 |
-
)
|
| 276 |
-
self.pos_emb = nn.Embedding(max_len, d_model)
|
| 277 |
-
self.blocks = nn.ModuleList(
|
| 278 |
-
[EncoderBlock(d_model, n_head, d_ff, dropout) for _ in range(n_layer)]
|
| 279 |
-
)
|
| 280 |
-
self.norm = RMSNorm(d_model)
|
| 281 |
-
self.head = nn.Linear(d_model, vocab_size, bias=False)
|
| 282 |
-
self.logit_softcap = logit_softcap
|
| 283 |
-
|
| 284 |
-
def forward(self, expert_idx, attention_mask):
|
| 285 |
-
bsz, seq_len = expert_idx.shape[:2]
|
| 286 |
-
x = self.encoder_in(expert_idx)
|
| 287 |
-
pos_ids = torch.arange(seq_len, device=expert_idx.device)
|
| 288 |
-
pos_ids = pos_ids.unsqueeze(0).expand(bsz, -1)
|
| 289 |
-
x = x + self.pos_emb(pos_ids)
|
| 290 |
-
for block in self.blocks:
|
| 291 |
-
x = block(x, attention_mask)
|
| 292 |
-
x = self.norm(x)
|
| 293 |
-
logits = self.head(x)
|
| 294 |
-
if self.logit_softcap and self.logit_softcap > 0:
|
| 295 |
-
logits = self.logit_softcap * torch.tanh(logits / self.logit_softcap)
|
| 296 |
-
return logits
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
def split_muon_params(model):
|
| 300 |
-
muon_params = []
|
| 301 |
-
adam_params = []
|
| 302 |
-
for name, p in model.named_parameters():
|
| 303 |
-
if not p.requires_grad:
|
| 304 |
-
continue
|
| 305 |
-
is_matrix = p.ndim == 2
|
| 306 |
-
is_embedding_or_head = (
|
| 307 |
-
name.endswith("head.weight") or name.endswith("pos_emb.weight")
|
| 308 |
-
)
|
| 309 |
-
if is_matrix and not is_embedding_or_head:
|
| 310 |
-
muon_params.append(p)
|
| 311 |
-
else:
|
| 312 |
-
adam_params.append(p)
|
| 313 |
-
return muon_params, adam_params
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
def make_trapezoidal_lr(step_idx, max_steps, warmup_ratio, warmdown_ratio):
|
| 317 |
-
warmup_steps = max(1, int(warmup_ratio * max_steps)) if warmup_ratio > 0 else 0
|
| 318 |
-
warmdown_steps = max(1, int(warmdown_ratio * max_steps)) if warmdown_ratio > 0 else 0
|
| 319 |
-
if warmup_steps > 0 and step_idx < warmup_steps:
|
| 320 |
-
return float(step_idx + 1) / float(warmup_steps)
|
| 321 |
-
warmdown_start = max_steps - warmdown_steps
|
| 322 |
-
if step_idx < warmdown_start:
|
| 323 |
-
return 1.0
|
| 324 |
-
if warmdown_steps > 0 and step_idx < max_steps:
|
| 325 |
-
remaining = max_steps - step_idx
|
| 326 |
-
return max(0.0, float(remaining) / float(warmdown_steps))
|
| 327 |
-
return 0.0
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
def main():
|
| 331 |
-
parser = argparse.ArgumentParser(
|
| 332 |
-
description="V5 encoder-only inverter (multihot + per-layer MLP)."
|
| 333 |
-
)
|
| 334 |
-
parser.add_argument("--idx", required=True)
|
| 335 |
-
parser.add_argument("--dataset", default="vietgpt/openwebtext_en")
|
| 336 |
-
parser.add_argument("--dataset-revision", default=None)
|
| 337 |
-
parser.add_argument("--model", default="openai/gpt-oss-20b")
|
| 338 |
-
parser.add_argument("--model-revision", default=None)
|
| 339 |
-
parser.add_argument("--seq-len", type=int, default=32)
|
| 340 |
-
parser.add_argument("--layers", type=int, default=24)
|
| 341 |
-
parser.add_argument("--max-tokens", type=int, default=200000000)
|
| 342 |
-
parser.add_argument("--batch-size", type=int, default=32)
|
| 343 |
-
parser.add_argument("--grad-accum", type=int, default=1)
|
| 344 |
-
parser.add_argument("--steps", type=int, default=10000)
|
| 345 |
-
parser.add_argument("--save-every", type=int, default=1000)
|
| 346 |
-
parser.add_argument("--out", default="inverter_v5.pt")
|
| 347 |
-
parser.add_argument("--state-path", default="train_state_v5.json")
|
| 348 |
-
parser.add_argument("--resume", action="store_true")
|
| 349 |
-
parser.add_argument("--compile", action="store_true")
|
| 350 |
-
parser.add_argument(
|
| 351 |
-
"--attn-impl",
|
| 352 |
-
choices=["auto", "flash", "mem_efficient", "math"],
|
| 353 |
-
default="auto",
|
| 354 |
-
)
|
| 355 |
-
parser.add_argument("--logit-softcap", type=float, default=0.0)
|
| 356 |
-
parser.add_argument("--layer-gating", action="store_true")
|
| 357 |
-
parser.add_argument("--d-model", type=int, default=768)
|
| 358 |
-
parser.add_argument("--n-head", type=int, default=12)
|
| 359 |
-
parser.add_argument("--d-ff", type=int, default=2048)
|
| 360 |
-
parser.add_argument("--n-layer", type=int, default=6)
|
| 361 |
-
parser.add_argument("--layer-hidden", type=int, default=64)
|
| 362 |
-
parser.add_argument("--layer-proj", type=int, default=64)
|
| 363 |
-
parser.add_argument("--dropout", type=float, default=0.1)
|
| 364 |
-
parser.add_argument("--adam-lr", type=float, default=3e-4)
|
| 365 |
-
parser.add_argument("--muon-lr-factor", type=float, default=4.0)
|
| 366 |
-
parser.add_argument("--weight-decay", type=float, default=0.1)
|
| 367 |
-
parser.add_argument("--warmup-ratio", type=float, default=0.01)
|
| 368 |
-
parser.add_argument("--warmdown-ratio", type=float, default=0.20)
|
| 369 |
-
parser.add_argument("--wandb", action="store_true")
|
| 370 |
-
parser.add_argument("--wandb-project", default="expert-inversion")
|
| 371 |
-
parser.add_argument("--wandb-entity", default=None)
|
| 372 |
-
parser.add_argument("--wandb-run-name", default=None)
|
| 373 |
-
args = parser.parse_args()
|
| 374 |
-
|
| 375 |
-
if torch.cuda.is_available():
|
| 376 |
-
torch.backends.cuda.matmul.allow_tf32 = True
|
| 377 |
-
torch.set_float32_matmul_precision("high")
|
| 378 |
-
if args.attn_impl != "auto":
|
| 379 |
-
try:
|
| 380 |
-
torch.backends.cuda.enable_flash_sdp(args.attn_impl == "flash")
|
| 381 |
-
torch.backends.cuda.enable_mem_efficient_sdp(
|
| 382 |
-
args.attn_impl == "mem_efficient"
|
| 383 |
-
)
|
| 384 |
-
torch.backends.cuda.enable_math_sdp(args.attn_impl == "math")
|
| 385 |
-
except AttributeError:
|
| 386 |
-
pass
|
| 387 |
-
|
| 388 |
-
wandb_run = None
|
| 389 |
-
if args.wandb:
|
| 390 |
-
import wandb
|
| 391 |
-
|
| 392 |
-
wandb_run = wandb.init(
|
| 393 |
-
project=args.wandb_project,
|
| 394 |
-
entity=args.wandb_entity,
|
| 395 |
-
name=args.wandb_run_name,
|
| 396 |
-
config=vars(args),
|
| 397 |
-
)
|
| 398 |
-
|
| 399 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 400 |
-
args.model,
|
| 401 |
-
revision=args.model_revision,
|
| 402 |
-
)
|
| 403 |
-
if tokenizer.pad_token_id is None:
|
| 404 |
-
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 405 |
-
|
| 406 |
-
state = TrainState()
|
| 407 |
-
if args.resume and os.path.exists(args.state_path):
|
| 408 |
-
with open(args.state_path, "r") as f:
|
| 409 |
-
payload = json.load(f)
|
| 410 |
-
state = TrainState(
|
| 411 |
-
tokens_seen=payload.get("tokens_seen", 0),
|
| 412 |
-
example_index=payload.get("example_index", 0),
|
| 413 |
-
example_token_offset=payload.get("example_token_offset", 0),
|
| 414 |
-
step=payload.get("step", 0),
|
| 415 |
-
)
|
| 416 |
-
|
| 417 |
-
stream = ExpertStream(
|
| 418 |
-
idx_path=args.idx,
|
| 419 |
-
dataset_name=args.dataset,
|
| 420 |
-
dataset_revision=args.dataset_revision,
|
| 421 |
-
tokenizer=tokenizer,
|
| 422 |
-
seq_len=args.seq_len,
|
| 423 |
-
max_tokens=args.max_tokens,
|
| 424 |
-
batch_size=args.batch_size,
|
| 425 |
-
state=state,
|
| 426 |
-
)
|
| 427 |
-
|
| 428 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 429 |
-
model = EncoderOnlyModel(
|
| 430 |
-
vocab_size=len(tokenizer),
|
| 431 |
-
num_experts=32,
|
| 432 |
-
num_layers=args.layers,
|
| 433 |
-
topk=4,
|
| 434 |
-
d_model=args.d_model,
|
| 435 |
-
n_head=args.n_head,
|
| 436 |
-
d_ff=args.d_ff,
|
| 437 |
-
n_layer=args.n_layer,
|
| 438 |
-
dropout=args.dropout,
|
| 439 |
-
max_len=args.seq_len,
|
| 440 |
-
layer_gating=args.layer_gating,
|
| 441 |
-
logit_softcap=args.logit_softcap,
|
| 442 |
-
layer_hidden=args.layer_hidden,
|
| 443 |
-
layer_proj=args.layer_proj,
|
| 444 |
-
).to(device)
|
| 445 |
-
|
| 446 |
-
if args.compile and device.type == "cuda":
|
| 447 |
-
model = torch.compile(model, dynamic=False)
|
| 448 |
-
|
| 449 |
-
muon_params, adam_params = split_muon_params(model)
|
| 450 |
-
if not muon_params:
|
| 451 |
-
raise RuntimeError("No Muon parameters found; check parameter names.")
|
| 452 |
-
|
| 453 |
-
if not hasattr(torch.optim, "Muon"):
|
| 454 |
-
raise RuntimeError("torch.optim.Muon not available in this environment.")
|
| 455 |
-
|
| 456 |
-
optimizer_adam = torch.optim.AdamW(
|
| 457 |
-
adam_params,
|
| 458 |
-
lr=args.adam_lr,
|
| 459 |
-
betas=(0.9, 0.95),
|
| 460 |
-
weight_decay=args.weight_decay,
|
| 461 |
-
)
|
| 462 |
-
optimizer_muon = torch.optim.Muon(
|
| 463 |
-
muon_params,
|
| 464 |
-
lr=args.adam_lr * args.muon_lr_factor,
|
| 465 |
-
weight_decay=args.weight_decay,
|
| 466 |
-
momentum=0.95,
|
| 467 |
-
nesterov=True,
|
| 468 |
-
adjust_lr_fn="match_rms_adamw",
|
| 469 |
-
)
|
| 470 |
-
optimizers = [optimizer_adam, optimizer_muon]
|
| 471 |
-
|
| 472 |
-
def lr_lambda(step_idx):
|
| 473 |
-
return make_trapezoidal_lr(
|
| 474 |
-
step_idx, args.steps, args.warmup_ratio, args.warmdown_ratio
|
| 475 |
-
)
|
| 476 |
-
|
| 477 |
-
schedulers = [
|
| 478 |
-
torch.optim.lr_scheduler.LambdaLR(optimizer_adam, lr_lambda=lr_lambda),
|
| 479 |
-
torch.optim.lr_scheduler.LambdaLR(optimizer_muon, lr_lambda=lr_lambda),
|
| 480 |
-
]
|
| 481 |
-
|
| 482 |
-
scaler = torch.amp.GradScaler("cuda", enabled=device.type == "cuda")
|
| 483 |
-
model.train()
|
| 484 |
-
step = state.step
|
| 485 |
-
micro_step = 0
|
| 486 |
-
start_time = time.time()
|
| 487 |
-
for opt in optimizers:
|
| 488 |
-
opt.zero_grad(set_to_none=True)
|
| 489 |
-
|
| 490 |
-
for batch in stream:
|
| 491 |
-
if step >= args.steps:
|
| 492 |
-
break
|
| 493 |
-
|
| 494 |
-
micro_step += 1
|
| 495 |
-
input_ids = batch["input_ids"].to(device, non_blocking=True)
|
| 496 |
-
expert_idx = batch["expert_idx"][:, :, :args.layers].to(device, non_blocking=True)
|
| 497 |
-
attention_mask = batch["attention_mask"].to(device, non_blocking=True)
|
| 498 |
-
|
| 499 |
-
labels = input_ids.clone()
|
| 500 |
-
labels[~attention_mask] = -100
|
| 501 |
-
|
| 502 |
-
with torch.autocast(device_type=device.type, dtype=torch.bfloat16):
|
| 503 |
-
logits = model(expert_idx, attention_mask)
|
| 504 |
-
loss = F.cross_entropy(
|
| 505 |
-
logits.view(-1, logits.size(-1)),
|
| 506 |
-
labels.view(-1),
|
| 507 |
-
ignore_index=-100,
|
| 508 |
-
)
|
| 509 |
-
loss = loss / args.grad_accum
|
| 510 |
-
|
| 511 |
-
scaler.scale(loss).backward()
|
| 512 |
-
|
| 513 |
-
if micro_step % args.grad_accum != 0:
|
| 514 |
-
continue
|
| 515 |
-
|
| 516 |
-
for opt in optimizers:
|
| 517 |
-
scaler.step(opt)
|
| 518 |
-
scaler.update()
|
| 519 |
-
for opt in optimizers:
|
| 520 |
-
opt.zero_grad(set_to_none=True)
|
| 521 |
-
for sched in schedulers:
|
| 522 |
-
sched.step()
|
| 523 |
-
|
| 524 |
-
step += 1
|
| 525 |
-
state = batch["state"]
|
| 526 |
-
state.step = step
|
| 527 |
-
micro_step = 0
|
| 528 |
-
|
| 529 |
-
if step % 10 == 0:
|
| 530 |
-
elapsed = time.time() - start_time
|
| 531 |
-
lr_adam = schedulers[0].get_last_lr()[0]
|
| 532 |
-
lr_muon = schedulers[1].get_last_lr()[0]
|
| 533 |
-
print(
|
| 534 |
-
f\"step {step} loss {loss.item():.4f} lr_adam {lr_adam:.6e} lr_muon {lr_muon:.6e}\"
|
| 535 |
-
)
|
| 536 |
-
if wandb_run:
|
| 537 |
-
wandb_run.log(
|
| 538 |
-
{
|
| 539 |
-
\"train/loss\": loss.item() * args.grad_accum,
|
| 540 |
-
\"train/lr_adam\": lr_adam,
|
| 541 |
-
\"train/lr_muon\": lr_muon,
|
| 542 |
-
\"train/step\": step,
|
| 543 |
-
\"train/time_elapsed_s\": elapsed,
|
| 544 |
-
},
|
| 545 |
-
step=step,
|
| 546 |
-
)
|
| 547 |
-
|
| 548 |
-
if step % args.save_every == 0:
|
| 549 |
-
payload = {
|
| 550 |
-
\"model\": model.state_dict(),
|
| 551 |
-
\"config\": vars(args),
|
| 552 |
-
\"step\": step,
|
| 553 |
-
}
|
| 554 |
-
torch.save(payload, args.out)
|
| 555 |
-
_write_json_atomic(args.state_path, state.__dict__)
|
| 556 |
-
|
| 557 |
-
payload = {
|
| 558 |
-
\"model\": model.state_dict(),
|
| 559 |
-
\"config\": vars(args),
|
| 560 |
-
\"step\": step,
|
| 561 |
-
}
|
| 562 |
-
torch.save(payload, args.out)
|
| 563 |
-
_write_json_atomic(args.state_path, state.__dict__)
|
| 564 |
-
|
| 565 |
-
if wandb_run:
|
| 566 |
-
wandb_run.finish()
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
if __name__ == \"__main__\":
|
| 570 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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