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|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
# 5L_joint_sft.py β Joint AR+SAT Trainer with SFT Phase
|
| 4 |
+
# Merges 5L.py (Joint Model + Adaptive OOM) with 5apg.py (Robust Stream + SFT Phases)
|
| 5 |
+
# Features:
|
| 6 |
+
# - Joint AR + SAT training objective
|
| 7 |
+
# - Phase 1: Pretrain -> Phase 2: SFT (Chat/Instruction Tuning)
|
| 8 |
+
# - Adaptive OOM: Reduces Batch Size, then Block Size
|
| 9 |
+
# - Robust Data: Retries, JSONL, Chat Templates, Source Mixing
|
| 10 |
+
# - Chinchilla Scaling, Checkpoint Pruning, FP8/AMP support
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
import argparse, json, math, pathlib, random, time, os, sys
|
| 14 |
+
from contextlib import nullcontext
|
| 15 |
+
from typing import Dict, Any, List, Optional, Tuple
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from datasets import load_dataset, DownloadConfig
|
| 20 |
+
from transformers import AutoTokenizer, logging as hf_log
|
| 21 |
+
from tqdm.auto import tqdm
|
| 22 |
+
|
| 23 |
+
# βββββββββββββββββββββββββ Terminal Colors βββββββββββββββββββββββββ
|
| 24 |
+
class Colors:
|
| 25 |
+
RESET = "\033[0m"
|
| 26 |
+
BOLD = "\033[1m"
|
| 27 |
+
DIM = "\033[2m"
|
| 28 |
+
# Foreground
|
| 29 |
+
RED = "\033[31m"
|
| 30 |
+
GREEN = "\033[32m"
|
| 31 |
+
YELLOW = "\033[33m"
|
| 32 |
+
BLUE = "\033[34m"
|
| 33 |
+
MAGENTA = "\033[35m"
|
| 34 |
+
CYAN = "\033[36m"
|
| 35 |
+
WHITE = "\033[37m"
|
| 36 |
+
# Bright
|
| 37 |
+
BRIGHT_GREEN = "\033[92m"
|
| 38 |
+
BRIGHT_CYAN = "\033[96m"
|
| 39 |
+
BRIGHT_YELLOW = "\033[93m"
|
| 40 |
+
# Prompt color
|
| 41 |
+
PROMPT = "\033[36m" # Cyan for prompt
|
| 42 |
+
GENERATED = "\033[0m" # Default for generated
|
| 43 |
+
|
| 44 |
+
# βββββββββββββββββββββββββ Globals βββββββββββββββββββββββββ
|
| 45 |
+
hf_log.set_verbosity_error()
|
| 46 |
+
DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 47 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 48 |
+
try:
|
| 49 |
+
torch.set_float32_matmul_precision("high")
|
| 50 |
+
except Exception:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
# Tokenizer
|
| 54 |
+
TOKENIZER_ID = os.environ.get("TOKENIZER_ID", "deepseek-ai/DeepSeek-V3.2-Exp")
|
| 55 |
+
tok = AutoTokenizer.from_pretrained(TOKENIZER_ID, use_fast=True, trust_remote_code=True)
|
| 56 |
+
if tok.pad_token is None:
|
| 57 |
+
tok.add_special_tokens({"pad_token": "<|pad|>"})
|
| 58 |
+
|
| 59 |
+
VOCAB, EOS = (
|
| 60 |
+
max(tok.get_vocab().values()) + 1,
|
| 61 |
+
tok.eos_token_id if tok.eos_token_id is not None else tok.sep_token_id
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
PRESETS: Dict[str, Dict[str, int]] = {
|
| 65 |
+
"small": dict(d=512, layers=8, heads=16, rank=64),
|
| 66 |
+
"smallx2": dict(d=512, layers=16, heads=16, rank=64),
|
| 67 |
+
"base": dict(d=768, layers=12, heads=24, rank=96),
|
| 68 |
+
"base18": dict(d=768, layers=18, heads=24, rank=96),
|
| 69 |
+
"large": dict(d=1024, layers=24, heads=16, rank=128),
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
# Configuration
|
| 73 |
+
DEFAULT_BLOCK = 1122
|
| 74 |
+
DEFAULT_BATCH = 4
|
| 75 |
+
SAT_BLOCK = 2
|
| 76 |
+
LR_CORE, LR_HEAD = 5e-5, 2e-4
|
| 77 |
+
EMIT_LAMBDA = 0.1
|
| 78 |
+
DEFAULT_SAVE_SEC = 24 * 3600
|
| 79 |
+
CKDIR = pathlib.Path("ckpts_joint")
|
| 80 |
+
|
| 81 |
+
# Defaults for SFT
|
| 82 |
+
DEFAULT_PRETRAIN_SOURCES = "cerebras/SlimPajama-627B"
|
| 83 |
+
DEFAULT_AFTER_SFT_SOURCES = "mlabonne/opc-sft-stage2-chat,HuggingFaceH4/ultrachat_200k"
|
| 84 |
+
DEFAULT_AFTER_SFT_BLOCK = 1122
|
| 85 |
+
|
| 86 |
+
# βββββββββββββββββββββββββ Utilities βββββββββββββββββββββββββ
|
| 87 |
+
def rng_state():
|
| 88 |
+
if DEV.type == "cuda":
|
| 89 |
+
try:
|
| 90 |
+
return torch.cuda.get_rng_state(DEV)
|
| 91 |
+
except TypeError:
|
| 92 |
+
return torch.cuda.get_rng_state()
|
| 93 |
+
return torch.get_rng_state()
|
| 94 |
+
|
| 95 |
+
def _is_probably_ckpt(path: pathlib.Path) -> bool:
|
| 96 |
+
try:
|
| 97 |
+
return path.is_file() and path.suffix == ".pt" and not path.name.endswith(".pt.tmp") and path.stat().st_size > (1<<20)
|
| 98 |
+
except Exception:
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
def _resolve_ckpt(path: pathlib.Path) -> pathlib.Path | None:
|
| 102 |
+
try:
|
| 103 |
+
if path.is_dir():
|
| 104 |
+
cands = sorted([p for p in path.glob("*.pt") if _is_probably_ckpt(p)],
|
| 105 |
+
key=lambda p: p.stat().st_mtime, reverse=True)
|
| 106 |
+
return cands[0] if cands else None
|
| 107 |
+
if path.suffix == ".tmp":
|
| 108 |
+
solid = path.with_suffix("")
|
| 109 |
+
return solid if _is_probably_ckpt(solid) else _resolve_ckpt(path.parent)
|
| 110 |
+
return path if _is_probably_ckpt(path) else _resolve_ckpt(path.parent)
|
| 111 |
+
except Exception:
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
def _try_load(path: pathlib.Path, map_location="cpu"):
|
| 115 |
+
try:
|
| 116 |
+
return torch.load(path, map_location="cpu")
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"[ckpt-skip] {path} not usable: {e}")
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
def _prune_checkpoints(save_dir: pathlib.Path, phase_name: str, max_ckpts: int):
|
| 122 |
+
"""Prune old checkpoints for a specific phase."""
|
| 123 |
+
if max_ckpts is None or max_ckpts <= 0:
|
| 124 |
+
return
|
| 125 |
+
try:
|
| 126 |
+
pattern = f"{phase_name}_step*.pt"
|
| 127 |
+
ckpts = sorted(
|
| 128 |
+
[p for p in save_dir.glob(pattern) if _is_probably_ckpt(p)],
|
| 129 |
+
key=lambda p: p.stat().st_mtime
|
| 130 |
+
)
|
| 131 |
+
excess = len(ckpts) - max_ckpts
|
| 132 |
+
if excess > 0:
|
| 133 |
+
for p in ckpts[:excess]:
|
| 134 |
+
try:
|
| 135 |
+
p.unlink()
|
| 136 |
+
print(f" [prune] deleted old {p.name}")
|
| 137 |
+
except Exception:
|
| 138 |
+
pass
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(f"[ckpt-prune] error: {e}")
|
| 141 |
+
|
| 142 |
+
# βββββββββββββββββββββββββ AMP helper βββββββββββββββββββββββββ
|
| 143 |
+
try:
|
| 144 |
+
from torch.amp import autocast as _ac, GradScaler
|
| 145 |
+
except ImportError:
|
| 146 |
+
from torch.cuda.amp import autocast as _ac, GradScaler
|
| 147 |
+
|
| 148 |
+
def _auto_amp_dtype():
|
| 149 |
+
if DEV.type == "cuda":
|
| 150 |
+
try:
|
| 151 |
+
if torch.cuda.is_bf16_supported(): return torch.bfloat16
|
| 152 |
+
return torch.float16
|
| 153 |
+
except Exception: return torch.float16
|
| 154 |
+
return torch.float32
|
| 155 |
+
|
| 156 |
+
def amp(enabled: bool):
|
| 157 |
+
return nullcontext() if not (enabled and DEV.type == "cuda") else _ac(device_type="cuda", dtype=_auto_amp_dtype())
|
| 158 |
+
|
| 159 |
+
# βββββββββββββββββββββββββ Chat & Data Stream βββββββββββββββββββββββββ
|
| 160 |
+
def _coerce_role(r: str) -> str:
|
| 161 |
+
r = (r or "").lower()
|
| 162 |
+
if r in {"user", "human", "customer"}: return "user"
|
| 163 |
+
if r in {"assistant", "gpt", "bot"}: return "assistant"
|
| 164 |
+
if r in {"system", "context"}: return "system"
|
| 165 |
+
return r or "user"
|
| 166 |
+
|
| 167 |
+
def _render_chat_text_from_ex(ex: dict, messages_key: str, add_generation_prompt: bool) -> Optional[str]:
|
| 168 |
+
msgs = ex.get(messages_key)
|
| 169 |
+
if msgs is None:
|
| 170 |
+
for alt in ("conversations", "dialog", "turns"):
|
| 171 |
+
if isinstance(ex.get(alt), list):
|
| 172 |
+
msgs = ex[alt]; break
|
| 173 |
+
if isinstance(msgs, list) and msgs and isinstance(msgs[0], dict):
|
| 174 |
+
try:
|
| 175 |
+
norm = []
|
| 176 |
+
for m in msgs:
|
| 177 |
+
role = _coerce_role(m.get("role", "")); content = m.get("content", m.get("text", ""))
|
| 178 |
+
if not isinstance(content, str): continue
|
| 179 |
+
norm.append({"role": role, "content": content})
|
| 180 |
+
if not norm: return None
|
| 181 |
+
return tok.apply_chat_template(norm, tokenize=False, add_generation_prompt=add_generation_prompt)
|
| 182 |
+
except Exception: return None
|
| 183 |
+
# Fallback for prompt/response pairs
|
| 184 |
+
for a, b in (("prompt", "response"), ("instruction", "output"), ("question", "answer")):
|
| 185 |
+
if isinstance(ex.get(a), str) and isinstance(ex.get(b), str):
|
| 186 |
+
return f"User: {ex[a]}\nAssistant: {ex[b]}"
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
def _open_stream_one(ds_name: str, seed: int):
|
| 190 |
+
dc = DownloadConfig(max_retries=5, use_etag=True, resume_download=True)
|
| 191 |
+
if ":" in ds_name: base, config = ds_name.split(":", 1)
|
| 192 |
+
else: base, config = ds_name, None
|
| 193 |
+
|
| 194 |
+
if base == "json":
|
| 195 |
+
data_files = {"train": config}
|
| 196 |
+
ds = load_dataset("json", data_files=data_files, split="train", streaming=True, download_config=dc)
|
| 197 |
+
else:
|
| 198 |
+
ds = load_dataset(base, config, split="train", streaming=True, download_config=dc) if config else \
|
| 199 |
+
load_dataset(base, split="train", streaming=True, download_config=dc)
|
| 200 |
+
return iter(ds.shuffle(buffer_size=10_000, seed=seed))
|
| 201 |
+
|
| 202 |
+
def token_stream(ds_names: str, target: int, seed: int = 42,
|
| 203 |
+
chat: bool = False, chat_messages_key: str = "messages",
|
| 204 |
+
sft_add_generation_prompt: bool = False, dataset_field_text: str = "text"):
|
| 205 |
+
sources = [s.strip() for s in ds_names.split(",") if s.strip()]
|
| 206 |
+
if not sources: return
|
| 207 |
+
|
| 208 |
+
src_idx = 0; emitted = 0; it = None; attempts = 0; backoff_base = 2.0
|
| 209 |
+
|
| 210 |
+
while emitted < target:
|
| 211 |
+
try:
|
| 212 |
+
if it is None: it = _open_stream_one(sources[src_idx], seed)
|
| 213 |
+
ex = next(it)
|
| 214 |
+
text = None
|
| 215 |
+
if isinstance(ex, dict):
|
| 216 |
+
if chat:
|
| 217 |
+
text = _render_chat_text_from_ex(ex, chat_messages_key, sft_add_generation_prompt)
|
| 218 |
+
if text is None:
|
| 219 |
+
if dataset_field_text and isinstance(ex.get(dataset_field_text), str):
|
| 220 |
+
text = ex[dataset_field_text]
|
| 221 |
+
elif isinstance(ex.get("text"), str):
|
| 222 |
+
text = ex["text"]
|
| 223 |
+
|
| 224 |
+
if not isinstance(text, str):
|
| 225 |
+
attempts = 0; continue
|
| 226 |
+
|
| 227 |
+
enc = tok.encode(text)
|
| 228 |
+
if EOS is not None and (len(enc) == 0 or enc[-1] != EOS):
|
| 229 |
+
enc = enc + [EOS]
|
| 230 |
+
|
| 231 |
+
for t in enc:
|
| 232 |
+
yield t
|
| 233 |
+
emitted += 1
|
| 234 |
+
if emitted >= target: return
|
| 235 |
+
attempts = 0
|
| 236 |
+
except StopIteration:
|
| 237 |
+
it = None; src_idx = (src_idx + 1) % len(sources)
|
| 238 |
+
except Exception as e:
|
| 239 |
+
attempts += 1
|
| 240 |
+
sleep_s = min(60.0, backoff_base ** min(attempts, 6))
|
| 241 |
+
print(f"[stream-retry] {sources[src_idx]} error: {type(e).__name__}, sleeping {sleep_s:.1f}s")
|
| 242 |
+
time.sleep(sleep_s); it = None
|
| 243 |
+
if attempts % 5 == 0 and len(sources) > 1:
|
| 244 |
+
src_idx = (src_idx + 1) % len(sources)
|
| 245 |
+
|
| 246 |
+
# βββββββββββββββββββββββββ Relative positional bias (ALiBi) βββββββββββββββββββββββββ
|
| 247 |
+
def _alibi_slopes(n_heads: int):
|
| 248 |
+
import math
|
| 249 |
+
def pow2slopes(n):
|
| 250 |
+
start = 2 ** (-2 ** -(math.log2(n) - 3))
|
| 251 |
+
ratio = start
|
| 252 |
+
return [start * (ratio ** i) for i in range(n)]
|
| 253 |
+
if math.log2(n_heads).is_integer(): vals = pow2slopes(n_heads)
|
| 254 |
+
else:
|
| 255 |
+
closest = 2 ** math.floor(math.log2(n_heads))
|
| 256 |
+
vals = pow2slopes(closest)
|
| 257 |
+
extra = pow2slopes(2 * closest)
|
| 258 |
+
vals += extra[0::2][: n_heads - closest]
|
| 259 |
+
return torch.tensor(vals, device=DEV).view(1, n_heads, 1, 1)
|
| 260 |
+
|
| 261 |
+
def alibi_bias(n_heads: int, n_tokens: int):
|
| 262 |
+
i = torch.arange(n_tokens, device=DEV).view(1, 1, n_tokens, 1)
|
| 263 |
+
j = torch.arange(n_tokens, device=DEV).view(1, 1, 1, n_tokens)
|
| 264 |
+
dist = (j - i).clamp_min(0)
|
| 265 |
+
return -_alibi_slopes(n_heads) * dist
|
| 266 |
+
|
| 267 |
+
# βββββββββββββββββββββββββ Model components βββββββββββββββββββββββββ
|
| 268 |
+
class LowRankMHA(nn.Module):
|
| 269 |
+
def __init__(self, d: int, h: int, r: int, use_relpos: bool = True):
|
| 270 |
+
super().__init__()
|
| 271 |
+
assert d % h == 0
|
| 272 |
+
self.h, self.dk = h, d // h
|
| 273 |
+
self.use_relpos = use_relpos
|
| 274 |
+
self.q = nn.Linear(d, d, bias=False)
|
| 275 |
+
self.k = nn.Linear(d, d, bias=False)
|
| 276 |
+
self.v = nn.Linear(d, d, bias=False)
|
| 277 |
+
self.U = nn.Parameter(torch.randn(self.dk, r))
|
| 278 |
+
nn.init.orthogonal_(self.U)
|
| 279 |
+
self.proj = nn.Linear(h * r, d, bias=False)
|
| 280 |
+
self.drop = nn.Dropout(0.1)
|
| 281 |
+
|
| 282 |
+
def _proj(self, x):
|
| 283 |
+
B, N, _ = x.shape
|
| 284 |
+
return (x.view(B, N, self.h, self.dk).transpose(1, 2) @ self.U)
|
| 285 |
+
|
| 286 |
+
def forward(self, x, mask=None, rel_bias_tokens=None, kv_cache=None, use_cache=False):
|
| 287 |
+
q = self._proj(self.q(x))
|
| 288 |
+
k_new = self._proj(self.k(x))
|
| 289 |
+
v_new = self._proj(self.v(x))
|
| 290 |
+
|
| 291 |
+
if kv_cache is None: k, v = k_new, v_new
|
| 292 |
+
else:
|
| 293 |
+
k, v = kv_cache
|
| 294 |
+
if use_cache:
|
| 295 |
+
k, v = torch.cat([k, k_new], dim=2), torch.cat([v, v_new], dim=2)
|
| 296 |
+
|
| 297 |
+
att = (q @ k.transpose(-1, -2)) / math.sqrt(self.dk)
|
| 298 |
+
if q.size(2) == k.size(2):
|
| 299 |
+
if self.use_relpos and rel_bias_tokens is not None:
|
| 300 |
+
att = att + alibi_bias(self.h, rel_bias_tokens)
|
| 301 |
+
if mask is not None: att = att + mask
|
| 302 |
+
|
| 303 |
+
z = (att.softmax(-1) @ v).transpose(1, 2).reshape(x.size(0), x.size(1), -1)
|
| 304 |
+
out = self.drop(self.proj(z))
|
| 305 |
+
return (out, (k, v)) if use_cache else out
|
| 306 |
+
|
| 307 |
+
class Block(nn.Module):
|
| 308 |
+
def __init__(self, d: int, h: int, r: int):
|
| 309 |
+
super().__init__()
|
| 310 |
+
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 311 |
+
self.mha = LowRankMHA(d, h, r)
|
| 312 |
+
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.ReLU(), nn.Linear(4 * d, d))
|
| 313 |
+
|
| 314 |
+
def forward(self, x, mask, kv=None, use_cache=False):
|
| 315 |
+
n = x.size(1)
|
| 316 |
+
if use_cache:
|
| 317 |
+
y, new_kv = self.mha(self.ln1(x), mask, rel_bias_tokens=n if mask is not None else None, kv_cache=kv, use_cache=True)
|
| 318 |
+
x = x + y + self.ff(self.ln2(x + y))
|
| 319 |
+
return x, new_kv
|
| 320 |
+
else:
|
| 321 |
+
x = x + self.mha(self.ln1(x), mask, rel_bias_tokens=n)
|
| 322 |
+
return x + self.ff(self.ln2(x))
|
| 323 |
+
|
| 324 |
+
class Encoder(nn.Module):
|
| 325 |
+
def __init__(self, cfg):
|
| 326 |
+
super().__init__()
|
| 327 |
+
d, l, h, r = cfg["d"], cfg["layers"], cfg["heads"], cfg["rank"]
|
| 328 |
+
self.emb = nn.Embedding(VOCAB, d)
|
| 329 |
+
self.blocks = nn.ModuleList([Block(d, h, r) for _ in range(l)])
|
| 330 |
+
self.ln = nn.LayerNorm(d)
|
| 331 |
+
|
| 332 |
+
def forward(self, ids, mask, kv_caches=None, use_cache=False):
|
| 333 |
+
x = self.emb(ids)
|
| 334 |
+
if not use_cache:
|
| 335 |
+
for blk in self.blocks: x = blk(x, mask)
|
| 336 |
+
return self.ln(x)
|
| 337 |
+
new_kvs = []
|
| 338 |
+
for i, blk in enumerate(self.blocks):
|
| 339 |
+
kv = kv_caches[i] if kv_caches else None
|
| 340 |
+
x, kv_out = blk(x, mask, kv, use_cache=True)
|
| 341 |
+
new_kvs.append(kv_out)
|
| 342 |
+
return self.ln(x), new_kvs
|
| 343 |
+
|
| 344 |
+
class ARHead(nn.Module):
|
| 345 |
+
def __init__(self, d):
|
| 346 |
+
super().__init__()
|
| 347 |
+
self.proj = nn.Linear(d, VOCAB)
|
| 348 |
+
def forward(self, h): return self.proj(h)
|
| 349 |
+
|
| 350 |
+
class SATHead(nn.Module):
|
| 351 |
+
def __init__(self, d, mode="var"):
|
| 352 |
+
super().__init__()
|
| 353 |
+
self.proj = nn.Linear(d, VOCAB)
|
| 354 |
+
self.gate = nn.Linear(d, 2) if mode == "var" else None
|
| 355 |
+
def forward(self, h_last):
|
| 356 |
+
return self.proj(h_last), (self.gate(h_last[:, 0]) if self.gate else None)
|
| 357 |
+
|
| 358 |
+
# βββββββββββββββββββββββββ Masks βββββββββββββββββββββββββ
|
| 359 |
+
def causal_mask(n):
|
| 360 |
+
return torch.triu(torch.full((1, 1, n, n), float("-inf"), device=DEV), 1)
|
| 361 |
+
|
| 362 |
+
def sat_mask(n, block=SAT_BLOCK):
|
| 363 |
+
idx = torch.arange(n, device=DEV)
|
| 364 |
+
grp = idx.unsqueeze(0) // block
|
| 365 |
+
allow = (grp.T == grp) | (grp.T > grp)
|
| 366 |
+
return torch.where(allow, 0.0, float("-inf")).unsqueeze(0).unsqueeze(0)
|
| 367 |
+
|
| 368 |
+
# βββββββββββββββββββββββββ Checkpoint helpers βββββββββββββββββββββββββ
|
| 369 |
+
def save_ckpt(path: pathlib.Path, core, ar_h, sat_h, opt, scaler, meta):
|
| 370 |
+
path.parent.mkdir(exist_ok=True, parents=True)
|
| 371 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 372 |
+
state = {
|
| 373 |
+
"core": core.state_dict(), "ar": ar_h.state_dict(), "sat": sat_h.state_dict(),
|
| 374 |
+
"opt": opt.state_dict(), "scaler": scaler.state_dict(),
|
| 375 |
+
"cfg": meta.get("cfg"), "tokenizer_id": TOKENIZER_ID,
|
| 376 |
+
**{k: v for k, v in meta.items() if k != "cfg"}
|
| 377 |
+
}
|
| 378 |
+
torch.save(state, tmp, _use_new_zipfile_serialization=False)
|
| 379 |
+
tmp.replace(path)
|
| 380 |
+
(path.parent / "latest.json").write_text(json.dumps({"path": str(path), "step": meta["step"]}))
|
| 381 |
+
print(f"\nβ saved checkpoint {path.name}")
|
| 382 |
+
|
| 383 |
+
def load_ckpt(path, core, ar_h, sat_h, opt, scaler):
|
| 384 |
+
p = _resolve_ckpt(path) or path
|
| 385 |
+
ck = _try_load(p, map_location="cpu")
|
| 386 |
+
if ck is None: raise FileNotFoundError(f"No valid checkpoint at {p}")
|
| 387 |
+
core.load_state_dict(ck["core"])
|
| 388 |
+
ar_h.load_state_dict(ck["ar"])
|
| 389 |
+
sat_h.load_state_dict(ck["sat"])
|
| 390 |
+
opt.load_state_dict(ck["opt"])
|
| 391 |
+
scaler.load_state_dict(ck["scaler"])
|
| 392 |
+
return ck.get("step", 0), ck.get("seen_tok", 0), ck.get("wall_time", time.time())
|
| 393 |
+
|
| 394 |
+
def _safe_load_any(path: pathlib.Path, tgt: nn.Module, key: str | None = None):
|
| 395 |
+
p = _resolve_ckpt(path) or path
|
| 396 |
+
if not p.exists(): return 0
|
| 397 |
+
ck = _try_load(p, map_location="cpu")
|
| 398 |
+
if ck is None: return 0
|
| 399 |
+
sd = ck.get(key, ck) if key else ck
|
| 400 |
+
if isinstance(sd, dict) and "state_dict" in sd: sd = sd["state_dict"]
|
| 401 |
+
tgt_sd = tgt.state_dict()
|
| 402 |
+
filt = {k: v for k, v in sd.items() if k in tgt_sd and v.shape == tgt_sd[k].shape}
|
| 403 |
+
if filt: tgt.load_state_dict(filt, strict=False)
|
| 404 |
+
return len(filt)
|
| 405 |
+
|
| 406 |
+
def infer_cfg_from_ckpt(path: pathlib.Path):
|
| 407 |
+
p = _resolve_ckpt(path) or path
|
| 408 |
+
if not p.exists(): return None
|
| 409 |
+
sd = _try_load(p, map_location="cpu")
|
| 410 |
+
if sd is None: return None
|
| 411 |
+
if "cfg" in sd: return dict(sd["cfg"])
|
| 412 |
+
return None
|
| 413 |
+
|
| 414 |
+
# βββββββββββββββββββββββββ Training Logic βββββββββββββββββββββββββ
|
| 415 |
+
def _parse_grow_plan(s: str) -> List[int]:
|
| 416 |
+
return sorted(set([int(x.strip()) for x in s.split(",") if x.strip() and int(x.strip()) >= 128]))
|
| 417 |
+
|
| 418 |
+
def _count_enabled_params(*modules) -> int:
|
| 419 |
+
return sum(sum(p.numel() for p in m.parameters()) for m in modules if m is not None)
|
| 420 |
+
|
| 421 |
+
def _phase_freeze(core: nn.Module, *, freeze_core: bool, unfreeze_ln: bool, train_emb: bool):
|
| 422 |
+
for p in core.parameters(): p.requires_grad = not freeze_core
|
| 423 |
+
if freeze_core:
|
| 424 |
+
if unfreeze_ln:
|
| 425 |
+
for blk in core.blocks:
|
| 426 |
+
for p in blk.ln1.parameters(): p.requires_grad = True
|
| 427 |
+
for p in blk.ln2.parameters(): p.requires_grad = True
|
| 428 |
+
for p in core.ln.parameters(): p.requires_grad = True
|
| 429 |
+
if train_emb:
|
| 430 |
+
for p in core.emb.parameters(): p.requires_grad = True
|
| 431 |
+
|
| 432 |
+
def _train_phase(
|
| 433 |
+
args, phase_name: str,
|
| 434 |
+
core, ar_h, sat_h, opt, scaler,
|
| 435 |
+
start_step, seen_tok, resume_wall_time,
|
| 436 |
+
cfg, source, steps, block_size, batch_size,
|
| 437 |
+
chat_cfg: dict,
|
| 438 |
+
max_ckpts: int,
|
| 439 |
+
target_tokens_override: Optional[int] = None
|
| 440 |
+
):
|
| 441 |
+
BLOCK = block_size
|
| 442 |
+
BATCH = batch_size
|
| 443 |
+
|
| 444 |
+
if target_tokens_override is not None:
|
| 445 |
+
target_tokens = target_tokens_override
|
| 446 |
+
else:
|
| 447 |
+
ratio = 51.2 if args.chilla_max_double else 25
|
| 448 |
+
param_count = _count_enabled_params(core, ar_h, sat_h)
|
| 449 |
+
target_tokens = int(ratio * param_count)
|
| 450 |
+
|
| 451 |
+
if steps:
|
| 452 |
+
phase_target_tokens = steps * BLOCK * BATCH
|
| 453 |
+
total_tokens_needed = seen_tok + phase_target_tokens
|
| 454 |
+
else:
|
| 455 |
+
total_tokens_needed = target_tokens
|
| 456 |
+
if total_tokens_needed <= seen_tok:
|
| 457 |
+
print(f"[{phase_name}] target {total_tokens_needed} already reached.")
|
| 458 |
+
return start_step, seen_tok, resume_wall_time
|
| 459 |
+
|
| 460 |
+
stream = token_stream(
|
| 461 |
+
source, total_tokens_needed, seed=42,
|
| 462 |
+
chat=chat_cfg.get("chat", False),
|
| 463 |
+
chat_messages_key=chat_cfg.get("key", "messages"),
|
| 464 |
+
sft_add_generation_prompt=chat_cfg.get("gen_prompt", False),
|
| 465 |
+
dataset_field_text=chat_cfg.get("text_field", "text")
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
ce_tok = nn.CrossEntropyLoss(label_smoothing=0.1)
|
| 469 |
+
ce_gate = nn.CrossEntropyLoss()
|
| 470 |
+
|
| 471 |
+
pbar = tqdm(total=total_tokens_needed, initial=seen_tok, unit="tok")
|
| 472 |
+
|
| 473 |
+
grow_plan = _parse_grow_plan(args.grow_plan) if args.auto_grow else []
|
| 474 |
+
|
| 475 |
+
buf: list[int] = []
|
| 476 |
+
batch_accum: list[list[int]] = []
|
| 477 |
+
step = start_step
|
| 478 |
+
steps_since_last_grow = 0
|
| 479 |
+
|
| 480 |
+
now_wall = time.time()
|
| 481 |
+
last_save_mono = time.monotonic() - (now_wall - (resume_wall_time or now_wall))
|
| 482 |
+
|
| 483 |
+
print(f"[{phase_name}] Starting. Goal: {total_tokens_needed:,} tokens. Batch={BATCH}, Block={BLOCK}")
|
| 484 |
+
|
| 485 |
+
while seen_tok < total_tokens_needed:
|
| 486 |
+
try:
|
| 487 |
+
while len(buf) < BLOCK:
|
| 488 |
+
buf.append(next(stream))
|
| 489 |
+
except StopIteration:
|
| 490 |
+
break
|
| 491 |
+
|
| 492 |
+
seq = buf[:BLOCK]
|
| 493 |
+
buf = buf[BLOCK:]
|
| 494 |
+
batch_accum.append(seq)
|
| 495 |
+
|
| 496 |
+
if len(batch_accum) < BATCH:
|
| 497 |
+
continue
|
| 498 |
+
|
| 499 |
+
ids = torch.tensor(batch_accum, device=DEV)
|
| 500 |
+
batch_accum = []
|
| 501 |
+
|
| 502 |
+
tgt_ar = ids.clone()
|
| 503 |
+
|
| 504 |
+
try:
|
| 505 |
+
with amp(args.amp):
|
| 506 |
+
h_ar = core(ids, causal_mask(ids.size(1)))
|
| 507 |
+
logits_ar = ar_h(h_ar)[:, :-1]
|
| 508 |
+
loss_ar = ce_tok(logits_ar.reshape(-1, VOCAB), tgt_ar[:, 1:].reshape(-1))
|
| 509 |
+
|
| 510 |
+
h_sat = core(ids, sat_mask(ids.size(1)))
|
| 511 |
+
logits_sat, gate = sat_h(h_sat[:, -SAT_BLOCK:])
|
| 512 |
+
tgt_sat = ids[:, 1:SAT_BLOCK+1]
|
| 513 |
+
loss_sat = ce_tok(logits_sat.reshape(-1, VOCAB), tgt_sat.reshape(-1))
|
| 514 |
+
if gate is not None:
|
| 515 |
+
loss_sat += EMIT_LAMBDA * ce_gate(gate, torch.ones(ids.size(0), device=DEV, dtype=torch.long))
|
| 516 |
+
|
| 517 |
+
loss = loss_ar + loss_sat
|
| 518 |
+
|
| 519 |
+
scaler.scale(loss).backward()
|
| 520 |
+
scaler.unscale_(opt)
|
| 521 |
+
nn.utils.clip_grad_norm_(core.parameters(), 1.0)
|
| 522 |
+
scaler.step(opt)
|
| 523 |
+
scaler.update()
|
| 524 |
+
opt.zero_grad(set_to_none=True)
|
| 525 |
+
|
| 526 |
+
except RuntimeError as e:
|
| 527 |
+
msg = str(e).lower()
|
| 528 |
+
if "out of memory" in msg or "cuda error" in msg:
|
| 529 |
+
if BATCH > 1:
|
| 530 |
+
print(f"\n[{phase_name} OOM] Reducing Batch: {BATCH} -> {BATCH - 1}")
|
| 531 |
+
BATCH -= 1
|
| 532 |
+
else:
|
| 533 |
+
new_block = max(128, BLOCK // 2)
|
| 534 |
+
print(f"\n[{phase_name} OOM] Reducing Block: {BLOCK} -> {new_block}")
|
| 535 |
+
BLOCK = new_block
|
| 536 |
+
|
| 537 |
+
batch_accum = []
|
| 538 |
+
if DEV.type == "cuda": torch.cuda.empty_cache()
|
| 539 |
+
steps_since_last_grow = 0
|
| 540 |
+
continue
|
| 541 |
+
raise
|
| 542 |
+
|
| 543 |
+
step += 1
|
| 544 |
+
toks_processed = BLOCK * BATCH
|
| 545 |
+
seen_tok += toks_processed
|
| 546 |
+
pbar.update(toks_processed)
|
| 547 |
+
pbar.set_postfix(loss=f"{loss.item():.3f}", B=BATCH, L=BLOCK)
|
| 548 |
+
|
| 549 |
+
if args.save_every_sec > 0:
|
| 550 |
+
now_mono = time.monotonic()
|
| 551 |
+
if now_mono - last_save_mono >= args.save_every_sec:
|
| 552 |
+
ck_name = f"{phase_name}_step{step:08d}.pt"
|
| 553 |
+
save_ckpt(pathlib.Path(args.save_dir) / ck_name, core, ar_h, sat_h, opt, scaler,
|
| 554 |
+
meta={"cfg": cfg, "step": step, "seen_tok": seen_tok, "wall_time": time.time()})
|
| 555 |
+
_prune_checkpoints(pathlib.Path(args.save_dir), phase_name, max_ckpts)
|
| 556 |
+
last_save_mono = now_mono
|
| 557 |
+
|
| 558 |
+
if args.auto_grow:
|
| 559 |
+
steps_since_last_grow += 1
|
| 560 |
+
if steps_since_last_grow >= args.grow_every_steps:
|
| 561 |
+
steps_since_last_grow = 0
|
| 562 |
+
try:
|
| 563 |
+
idx = grow_plan.index(BLOCK)
|
| 564 |
+
if idx + 1 < len(grow_plan):
|
| 565 |
+
BLOCK = grow_plan[idx + 1]
|
| 566 |
+
print(f"[{phase_name} Grow] Block -> {BLOCK}")
|
| 567 |
+
if DEV.type == "cuda": torch.cuda.empty_cache()
|
| 568 |
+
except ValueError:
|
| 569 |
+
grow_plan = sorted(set(grow_plan + [BLOCK]))
|
| 570 |
+
|
| 571 |
+
pbar.close()
|
| 572 |
+
|
| 573 |
+
save_ckpt(pathlib.Path(args.save_dir) / f"{phase_name}_final.pt", core, ar_h, sat_h, opt, scaler,
|
| 574 |
+
meta={"cfg": cfg, "step": step, "seen_tok": seen_tok, "wall_time": time.time()})
|
| 575 |
+
|
| 576 |
+
return step, seen_tok, time.time()
|
| 577 |
+
|
| 578 |
+
# βββββββββββββββββββββββββ Main Orchestrator βββββββββββββββββββββββββ
|
| 579 |
+
def train(args):
|
| 580 |
+
cfg = PRESETS[args.preset].copy()
|
| 581 |
+
|
| 582 |
+
if not args.fresh:
|
| 583 |
+
src_probe = pathlib.Path(args.warmstart_from) if args.warmstart_from else pathlib.Path(args.save_dir) / "final.pt"
|
| 584 |
+
prev_cfg = infer_cfg_from_ckpt(src_probe)
|
| 585 |
+
else: prev_cfg = None
|
| 586 |
+
|
| 587 |
+
if prev_cfg:
|
| 588 |
+
cfg.update({k: v for k, v in prev_cfg.items() if k in cfg})
|
| 589 |
+
if args.x2 and prev_cfg.get("layers"): cfg["layers"] = max(cfg["layers"], prev_cfg["layers"] * 2)
|
| 590 |
+
|
| 591 |
+
if args.rank: cfg["rank"] = args.rank
|
| 592 |
+
if args.x2 and not prev_cfg: cfg["layers"] *= 2
|
| 593 |
+
|
| 594 |
+
print(f"Config: {cfg}")
|
| 595 |
+
|
| 596 |
+
core = Encoder(cfg).to(DEV)
|
| 597 |
+
ar_h = ARHead(cfg["d"]).to(DEV)
|
| 598 |
+
sat_h = SATHead(cfg["d"], mode="var").to(DEV)
|
| 599 |
+
|
| 600 |
+
if not args.fresh:
|
| 601 |
+
src = pathlib.Path(args.warmstart_from) if args.warmstart_from else pathlib.Path(args.save_dir) / "final.pt"
|
| 602 |
+
src = _resolve_ckpt(src)
|
| 603 |
+
if src:
|
| 604 |
+
loaded = _safe_load_any(src, core, key="core")
|
| 605 |
+
_safe_load_any(src, ar_h, key="ar")
|
| 606 |
+
_safe_load_any(src, sat_h, key="sat")
|
| 607 |
+
if loaded: print(f"Warm-start loaded from {src}")
|
| 608 |
+
|
| 609 |
+
_phase_freeze(core, freeze_core=args.freeze_core, unfreeze_ln=args.unfreeze_ln, train_emb=args.train_emb)
|
| 610 |
+
|
| 611 |
+
opt = torch.optim.AdamW([
|
| 612 |
+
{"params": [p for p in core.parameters() if p.requires_grad], "lr": args.lr_core},
|
| 613 |
+
{"params": ar_h.parameters(), "lr": args.lr_head},
|
| 614 |
+
{"params": sat_h.parameters(), "lr": args.lr_head},
|
| 615 |
+
])
|
| 616 |
+
scaler = GradScaler(enabled=(args.amp and DEV.type == "cuda"))
|
| 617 |
+
|
| 618 |
+
start_step, seen_tok, last_wall = 0, 0, None
|
| 619 |
+
if args.resume and not args.fresh:
|
| 620 |
+
start_step, seen_tok, last_wall = load_ckpt(pathlib.Path(args.resume), core, ar_h, sat_h, opt, scaler)
|
| 621 |
+
print(f"Resumed from step {start_step}")
|
| 622 |
+
|
| 623 |
+
step, seen_tok, last_wall = _train_phase(
|
| 624 |
+
args, "pretrain", core, ar_h, sat_h, opt, scaler,
|
| 625 |
+
start_step, seen_tok, last_wall, cfg,
|
| 626 |
+
args.source, args.steps,
|
| 627 |
+
args.block or DEFAULT_BLOCK,
|
| 628 |
+
args.batch_size or DEFAULT_BATCH,
|
| 629 |
+
chat_cfg={"chat": args.chat, "key": args.chat_messages_key, "gen_prompt": args.sft_add_generation_prompt, "text_field": args.dataset_field_text},
|
| 630 |
+
max_ckpts=args.max_ckpts,
|
| 631 |
+
target_tokens_override=args.target_tokens
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
if (not args.after_sft_source) and (args.after_sft_steps and args.after_sft_steps > 0):
|
| 635 |
+
args.after_sft_source = DEFAULT_AFTER_SFT_SOURCES
|
| 636 |
+
args.after_sft_chat = True
|
| 637 |
+
if args.after_sft_add_generation_prompt is None: args.after_sft_add_generation_prompt = True
|
| 638 |
+
if not args.after_sft_block: args.after_sft_block = DEFAULT_AFTER_SFT_BLOCK
|
| 639 |
+
|
| 640 |
+
if args.after_sft_source and args.after_sft_steps and args.after_sft_steps > 0:
|
| 641 |
+
print("\n[Orchestrator] Starting Post-Pretraining SFT Phase...")
|
| 642 |
+
|
| 643 |
+
_phase_freeze(core,
|
| 644 |
+
freeze_core=args.after_sft_freeze_core,
|
| 645 |
+
unfreeze_ln=args.after_sft_unfreeze_ln,
|
| 646 |
+
train_emb=args.after_sft_train_emb)
|
| 647 |
+
|
| 648 |
+
opt = torch.optim.AdamW([
|
| 649 |
+
{"params": [p for p in core.parameters() if p.requires_grad], "lr": args.after_sft_lr_core or args.lr_core},
|
| 650 |
+
{"params": ar_h.parameters(), "lr": args.after_sft_lr_head or args.lr_head},
|
| 651 |
+
{"params": sat_h.parameters(), "lr": args.after_sft_lr_head or args.lr_head},
|
| 652 |
+
])
|
| 653 |
+
|
| 654 |
+
step, seen_tok, last_wall = _train_phase(
|
| 655 |
+
args, "sft", core, ar_h, sat_h, opt, scaler,
|
| 656 |
+
step, seen_tok, last_wall, cfg,
|
| 657 |
+
args.after_sft_source, args.after_sft_steps,
|
| 658 |
+
args.after_sft_block or DEFAULT_AFTER_SFT_BLOCK,
|
| 659 |
+
args.batch_size or DEFAULT_BATCH,
|
| 660 |
+
chat_cfg={
|
| 661 |
+
"chat": args.after_sft_chat,
|
| 662 |
+
"key": args.after_sft_chat_messages_key,
|
| 663 |
+
"gen_prompt": args.after_sft_add_generation_prompt if args.after_sft_add_generation_prompt is not None else args.sft_add_generation_prompt,
|
| 664 |
+
"text_field": args.after_sft_dataset_field_text
|
| 665 |
+
},
|
| 666 |
+
max_ckpts=args.max_ckpts,
|
| 667 |
+
target_tokens_override=None
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
save_ckpt(pathlib.Path(args.save_dir) / "final.pt", core, ar_h, sat_h, opt, scaler,
|
| 671 |
+
meta={"cfg": cfg, "step": step, "seen_tok": seen_tok, "wall_time": time.time()})
|
| 672 |
+
print("π All Training Complete")
|
| 673 |
+
|
| 674 |
+
# βββββββββββββββββββββββββ Sampling βββββββββββββββββββββββββ
|
| 675 |
+
def _apply_penalties(logits, ids, n, rep_p, pres_p, freq_p):
|
| 676 |
+
if ids.numel() == 0: return logits
|
| 677 |
+
hist = ids[0, -n:].long() if n > 0 else ids[0].long()
|
| 678 |
+
uniq, counts = torch.unique(hist, return_counts=True)
|
| 679 |
+
if pres_p or freq_p:
|
| 680 |
+
logits[..., uniq] -= (pres_p + freq_p * counts.float())
|
| 681 |
+
if rep_p != 1.0:
|
| 682 |
+
sel = logits[..., uniq]
|
| 683 |
+
logits[..., uniq] = torch.where(sel > 0, sel / rep_p, sel * rep_p)
|
| 684 |
+
return logits
|
| 685 |
+
|
| 686 |
+
def _sample(logits, T, top_k, top_p, min_p, greedy):
|
| 687 |
+
if greedy: return logits.argmax(-1, keepdim=True)
|
| 688 |
+
probs = (logits / max(T, 1e-8)).softmax(-1)
|
| 689 |
+
if top_k:
|
| 690 |
+
v, i = torch.topk(probs, min(top_k, probs.size(-1)))
|
| 691 |
+
probs = torch.zeros_like(probs).scatter_(-1, i, v)
|
| 692 |
+
if top_p < 1.0:
|
| 693 |
+
s_probs, s_idx = torch.sort(probs, descending=True, dim=-1)
|
| 694 |
+
probs = torch.zeros_like(probs).scatter_(-1, s_idx, s_probs * (torch.cumsum(s_probs, -1) <= top_p).float())
|
| 695 |
+
if min_p > 0: probs[probs < min_p] = 0
|
| 696 |
+
if probs.sum() == 0: return logits.argmax(-1, keepdim=True)
|
| 697 |
+
return probs.div_(probs.sum()).multinomial(1)
|
| 698 |
+
|
| 699 |
+
@torch.no_grad()
|
| 700 |
+
def infer(args):
|
| 701 |
+
path = _resolve_ckpt(pathlib.Path(args.ckpt)) or pathlib.Path(args.ckpt)
|
| 702 |
+
sd = torch.load(path, map_location="cpu", weights_only=False)
|
| 703 |
+
cfg = sd["cfg"]
|
| 704 |
+
|
| 705 |
+
core = Encoder(cfg).to(DEV)
|
| 706 |
+
ar_h = ARHead(cfg["d"]).to(DEV)
|
| 707 |
+
sat_h = SATHead(cfg["d"]).to(DEV)
|
| 708 |
+
|
| 709 |
+
core.load_state_dict(sd["core"])
|
| 710 |
+
ar_h.load_state_dict(sd["ar"])
|
| 711 |
+
sat_h.load_state_dict(sd["sat"])
|
| 712 |
+
|
| 713 |
+
# Encode prompt
|
| 714 |
+
prompt_tokens = tok.encode(args.prompt)
|
| 715 |
+
ids = torch.tensor([prompt_tokens], device=DEV)
|
| 716 |
+
if ids.size(1) == 0: ids = torch.tensor([[EOS]], device=DEV)
|
| 717 |
+
|
| 718 |
+
prompt_len = ids.size(1)
|
| 719 |
+
|
| 720 |
+
print(f"Generating ({args.mode})...")
|
| 721 |
+
start = time.time()
|
| 722 |
+
|
| 723 |
+
# Print prompt in color
|
| 724 |
+
sys.stdout.write(f"{Colors.PROMPT}{Colors.BOLD}{args.prompt}{Colors.RESET}")
|
| 725 |
+
sys.stdout.flush()
|
| 726 |
+
|
| 727 |
+
if args.mode == "ar":
|
| 728 |
+
h, kvs = core(ids, causal_mask(ids.size(1)), use_cache=True)
|
| 729 |
+
for _ in range(args.max_new):
|
| 730 |
+
logits = ar_h(h)[:, -1]
|
| 731 |
+
logits = _apply_penalties(logits, ids, args.penalty_last_n, args.repetition_penalty, args.presence_penalty, args.frequency_penalty)
|
| 732 |
+
nxt = _sample(logits, args.temperature, args.top_k, args.top_p, args.min_p, args.greedy)
|
| 733 |
+
ids = torch.cat([ids, nxt], 1)
|
| 734 |
+
|
| 735 |
+
# Stream generated token in normal color
|
| 736 |
+
new_tok = tok.decode([nxt.item()])
|
| 737 |
+
sys.stdout.write(f"{Colors.GENERATED}{new_tok}")
|
| 738 |
+
sys.stdout.flush()
|
| 739 |
+
|
| 740 |
+
# Stop on EOS
|
| 741 |
+
if nxt.item() == EOS:
|
| 742 |
+
break
|
| 743 |
+
|
| 744 |
+
h, kvs = core(ids[:, -1:], None, kv_caches=kvs, use_cache=True)
|
| 745 |
+
else:
|
| 746 |
+
added = 0
|
| 747 |
+
while added < args.max_new:
|
| 748 |
+
h = core(ids, sat_mask(ids.size(1)))
|
| 749 |
+
logits_all, gate = sat_h(h[:, -SAT_BLOCK:])
|
| 750 |
+
stride = 2 if (not args.var or gate is None) else (gate.softmax(-1).multinomial(1).item() + 1)
|
| 751 |
+
|
| 752 |
+
for i in range(int(stride)):
|
| 753 |
+
logits = logits_all[:, i]
|
| 754 |
+
logits = _apply_penalties(logits, ids, args.penalty_last_n, args.repetition_penalty, args.presence_penalty, args.frequency_penalty)
|
| 755 |
+
nxt = _sample(logits, args.temperature, args.top_k, args.top_p, args.min_p, args.greedy)
|
| 756 |
+
ids = torch.cat([ids, nxt], 1)
|
| 757 |
+
|
| 758 |
+
# Stream generated token in normal color
|
| 759 |
+
new_tok = tok.decode([nxt.item()])
|
| 760 |
+
sys.stdout.write(f"{Colors.GENERATED}{new_tok}")
|
| 761 |
+
sys.stdout.flush()
|
| 762 |
+
|
| 763 |
+
added += 1
|
| 764 |
+
if added >= args.max_new: break
|
| 765 |
+
if nxt.item() == EOS: break
|
| 766 |
+
|
| 767 |
+
if nxt.item() == EOS: break
|
| 768 |
+
|
| 769 |
+
# Final newline and stats
|
| 770 |
+
print(f"\n{Colors.DIM}[{time.time()-start:.2f}s | {ids.size(1) - prompt_len} tokens generated]{Colors.RESET}")
|
| 771 |
+
|
| 772 |
+
# βββββββββββββββββββββββββ CLI βββββββββββββββββββββββββ
|
| 773 |
+
def main():
|
| 774 |
+
ap = argparse.ArgumentParser()
|
| 775 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 776 |
+
|
| 777 |
+
tr = sub.add_parser("train")
|
| 778 |
+
tr.add_argument("--preset", choices=PRESETS, default="small")
|
| 779 |
+
tr.add_argument("--rank", type=int)
|
| 780 |
+
tr.add_argument("--block", type=int, default=DEFAULT_BLOCK)
|
| 781 |
+
tr.add_argument("--batch_size", type=int, default=DEFAULT_BATCH)
|
| 782 |
+
tr.add_argument("--source", default=DEFAULT_PRETRAIN_SOURCES)
|
| 783 |
+
tr.add_argument("--target_tokens", type=int)
|
| 784 |
+
tr.add_argument("--steps", type=int)
|
| 785 |
+
tr.add_argument("--amp", action="store_true")
|
| 786 |
+
tr.add_argument("--save_every_sec", type=int, default=DEFAULT_SAVE_SEC)
|
| 787 |
+
tr.add_argument("--save_dir", default=str(CKDIR))
|
| 788 |
+
tr.add_argument("--resume", type=str)
|
| 789 |
+
tr.add_argument("--x2", action="store_true")
|
| 790 |
+
tr.add_argument("--warmstart_from", type=str)
|
| 791 |
+
tr.add_argument("--fresh", action="store_true")
|
| 792 |
+
tr.add_argument("--max_ckpts", type=int, default=None)
|
| 793 |
+
tr.add_argument("--chilla_max_double", action="store_true")
|
| 794 |
+
|
| 795 |
+
tr.add_argument("--freeze_core", action="store_true")
|
| 796 |
+
tr.add_argument("--unfreeze_ln", action="store_true")
|
| 797 |
+
tr.add_argument("--train_emb", action="store_true")
|
| 798 |
+
tr.add_argument("--lr_core", type=float, default=LR_CORE)
|
| 799 |
+
tr.add_argument("--lr_head", type=float, default=LR_HEAD)
|
| 800 |
+
|
| 801 |
+
tr.add_argument("--chat", action="store_true")
|
| 802 |
+
tr.add_argument("--chat_messages_key", default="messages")
|
| 803 |
+
tr.add_argument("--dataset_field_text", default="text")
|
| 804 |
+
tr.add_argument("--sft_add_generation_prompt", action="store_true")
|
| 805 |
+
|
| 806 |
+
tr.add_argument("--auto_grow", action="store_true")
|
| 807 |
+
tr.add_argument("--grow_plan", default="576,640,768,896,1024,1122")
|
| 808 |
+
tr.add_argument("--grow_every_steps", type=int, default=50000)
|
| 809 |
+
|
| 810 |
+
tr.add_argument("--after_sft_source", default="")
|
| 811 |
+
tr.add_argument("--after_sft_steps", type=int, default=0)
|
| 812 |
+
tr.add_argument("--after_sft_chat", action="store_true")
|
| 813 |
+
tr.add_argument("--after_sft_chat_messages_key", default="messages")
|
| 814 |
+
tr.add_argument("--after_sft_dataset_field_text", default="text")
|
| 815 |
+
tr.add_argument("--after_sft_add_generation_prompt", type=bool, default=None)
|
| 816 |
+
tr.add_argument("--after_sft_block", type=int, default=0)
|
| 817 |
+
tr.add_argument("--after_sft_freeze_core", action="store_true")
|
| 818 |
+
tr.add_argument("--after_sft_unfreeze_ln", action="store_true")
|
| 819 |
+
tr.add_argument("--after_sft_train_emb", action="store_true")
|
| 820 |
+
tr.add_argument("--after_sft_lr_core", type=float, default=0.0)
|
| 821 |
+
tr.add_argument("--after_sft_lr_head", type=float, default=0.0)
|
| 822 |
+
|
| 823 |
+
inf = sub.add_parser("infer")
|
| 824 |
+
inf.add_argument("--mode", choices=["ar", "sat"], required=True)
|
| 825 |
+
inf.add_argument("--ckpt", required=True)
|
| 826 |
+
inf.add_argument("--prompt", required=True)
|
| 827 |
+
inf.add_argument("--max_new", type=int, default=120)
|
| 828 |
+
inf.add_argument("--temperature", type=float, default=1.0)
|
| 829 |
+
inf.add_argument("--greedy", action="store_true")
|
| 830 |
+
inf.add_argument("--top_k", type=int, default=0)
|
| 831 |
+
inf.add_argument("--top_p", type=float, default=1.0)
|
| 832 |
+
inf.add_argument("--min_p", type=float, default=0.0)
|
| 833 |
+
inf.add_argument("--repetition_penalty", type=float, default=1.0)
|
| 834 |
+
inf.add_argument("--presence_penalty", type=float, default=0.0)
|
| 835 |
+
inf.add_argument("--frequency_penalty", type=float, default=0.0)
|
| 836 |
+
inf.add_argument("--penalty_last_n", type=int, default=64)
|
| 837 |
+
inf.add_argument("--var", action="store_true")
|
| 838 |
+
|
| 839 |
+
args = ap.parse_args()
|
| 840 |
+
if args.cmd == "train": train(args)
|
| 841 |
+
else: infer(args)
|
| 842 |
+
|
| 843 |
+
if __name__ == "__main__":
|
| 844 |
+
main()
|
pretrain_step00252235.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ed763f9f58d6b251614a4b7a34e34ac66722501073c831ea899139b89fadb829
|
| 3 |
+
size 5350539966
|