File size: 6,270 Bytes
6d5c79f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | """Medium-sized Zenex MoE training using a real BPE tokenizer.
Loads SentencePiece tokenizer, encodes corpus once (cached as .npy),
trains a larger MoE config for many more steps. Still CPU-friendly.
"""
from __future__ import annotations
import argparse
import logging
import math
import time
from pathlib import Path
import numpy as np
import sentencepiece as spm
import torch
from architecture.config import ModelConfig
from architecture.model import ZenexMoEDecoder
LOGGER = logging.getLogger(__name__)
def build_medium_config(vocab_size: int) -> ModelConfig:
"""Bigger MoE that still trains on a laptop CPU in a few hours."""
return ModelConfig(
num_layers=6,
hidden_size=384,
num_attention_heads_q=8,
num_attention_heads_kv=8,
head_dim=48,
vocab_size=vocab_size,
ffn_intermediate_size=1024,
num_routed_experts=8,
num_shared_experts=1,
top_k_experts=2,
mla_kv_latent_dim=192,
mla_q_latent_dim=192,
mtp_predict_steps=1,
)
def encode_corpus(sp: spm.SentencePieceProcessor, corpus: Path, cache: Path) -> np.ndarray:
"""Tokenize corpus once and cache as .npy on disk."""
if cache.exists():
LOGGER.info("Loading cached token array: %s", cache)
return np.load(cache)
LOGGER.info("Encoding corpus with BPE: %s", corpus)
tokens: list[int] = []
eos = sp.eos_id() if sp.eos_id() >= 0 else 3
chunk_size = 0
with corpus.open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
ids = sp.encode(line, out_type=int)
tokens.extend(ids)
tokens.append(eos)
chunk_size += 1
if chunk_size % 50_000 == 0:
LOGGER.info("Encoded %d lines, %d tokens", chunk_size, len(tokens))
arr = np.asarray(tokens, dtype=np.int32)
cache.parent.mkdir(parents=True, exist_ok=True)
np.save(cache, arr)
LOGGER.info("Saved %d tokens to %s", len(arr), cache)
return arr
def get_batch(data: np.ndarray, seq_len: int, batch_size: int, device: torch.device):
"""Sample random contiguous chunks."""
ix = np.random.randint(0, len(data) - seq_len - 1, size=batch_size)
x = np.stack([data[i : i + seq_len].astype(np.int64) for i in ix])
y = np.stack([data[i + 1 : i + seq_len + 1].astype(np.int64) for i in ix])
return torch.from_numpy(x).to(device), torch.from_numpy(y).to(device)
def cosine_lr(step: int, total: int, warmup: int, peak: float, min_lr: float) -> float:
if step < warmup:
return peak * (step + 1) / max(1, warmup)
progress = (step - warmup) / max(1, total - warmup)
return min_lr + 0.5 * (peak - min_lr) * (1 + math.cos(math.pi * progress))
def pick_device() -> torch.device:
"""Pick best available device: CUDA > Apple MPS > CPU."""
if torch.cuda.is_available():
return torch.device("cuda")
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def train(args: argparse.Namespace) -> None:
"""Main training loop."""
device = pick_device()
LOGGER.info("Training on device: %s", device)
sp = spm.SentencePieceProcessor(model_file=str(args.tokenizer))
LOGGER.info("Tokenizer loaded: vocab=%d", sp.vocab_size())
data = encode_corpus(sp, args.corpus, args.cache)
LOGGER.info("Corpus tokens: %d", len(data))
cfg = build_medium_config(vocab_size=sp.vocab_size())
model = ZenexMoEDecoder(cfg).to(device)
n_params = sum(p.numel() for p in model.parameters())
LOGGER.info("Model size: %.2fM params", n_params / 1e6)
optimizer = torch.optim.AdamW(
model.parameters(), lr=args.peak_lr, betas=(0.9, 0.95),
eps=1e-8, weight_decay=0.1,
)
model.train()
args.output.parent.mkdir(parents=True, exist_ok=True)
start = time.time()
for step in range(1, args.steps + 1):
lr = cosine_lr(step, args.steps, warmup=max(50, args.steps // 50),
peak=args.peak_lr, min_lr=args.peak_lr * 0.1)
for g in optimizer.param_groups:
g["lr"] = lr
x, y = get_batch(data, args.seq_len, args.batch_size, device)
optimizer.zero_grad(set_to_none=True)
out = model(x)
logits = out.logits
loss = torch.nn.functional.cross_entropy(
logits.reshape(-1, logits.size(-1)), y.reshape(-1)
)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
if step % args.log_every == 0 or step == 1:
elapsed = time.time() - start
tps = step * args.batch_size * args.seq_len / max(1e-6, elapsed)
LOGGER.info(
"step=%d loss=%.4f lr=%.2e tok/s=%.0f elapsed=%.1fs",
step, float(loss.item()), lr, tps, elapsed,
)
if step % args.save_every == 0 or step == args.steps:
torch.save(model.state_dict(), args.output)
LOGGER.info("Checkpoint saved -> %s", args.output)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Medium MoE training with BPE tokenizer")
parser.add_argument("--corpus", type=Path, default=Path("/mnt/nas/data/corpus.txt"))
parser.add_argument("--cache", type=Path, default=Path("/mnt/nas/data/corpus.tokens.npy"))
parser.add_argument("--tokenizer", type=Path, default=Path("/mnt/nas/tokenizer/tokenizer.model"))
parser.add_argument("--output", type=Path, default=Path("/mnt/nas/checkpoints/medium.pt"))
parser.add_argument("--steps", type=int, default=3000)
parser.add_argument("--seq-len", type=int, default=256)
parser.add_argument("--batch-size", type=int, default=8)
parser.add_argument("--peak-lr", type=float, default=3e-4)
parser.add_argument("--log-every", type=int, default=20)
parser.add_argument("--save-every", type=int, default=500)
return parser.parse_args()
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
args = parse_args()
train(args)
if __name__ == "__main__":
main()
|