omurberaisik's picture
Upload 9 files
377e8b9 verified
Raw History Blame Contribute Delete
12.9 kB
"""NoTokenLM-ImageGen-Class-2.5 çekirdeği: model, Muon hibriti, cihaz-içi augmentation.
Saf JAX (Flax yok). Bu dosya eğitimi yapan notebook tarafından repoya da yüklenir.
Girdi: (N,H,W,3) görüntü, değerler 0..255 (uint8 ya da float). H,W 16'nın katı.
"""
import math
from dataclasses import dataclass
from typing import Any, NamedTuple
import numpy as np
import jax
import jax.numpy as jnp
from jax import lax
import optax
BF16, F32 = jnp.bfloat16, jnp.float32
@dataclass(frozen=True)
class Cfg:
widths: tuple = (64, 128, 256, 384)
depths: tuple = (2, 3, 3, 2)
ratios: tuple = (4, 4, 4, 3)
heads: int = 4
head_dim: int = 1024
num_classes: int = 1000
dw_k: int = 7
ls_init: float = 1e-2
drop_path: float = 0.1
# ---------------------------------------------------------------- başlatma
def tn(key, shape, std=0.02):
return jax.random.truncated_normal(key, -2.0, 2.0, shape, F32) * std
def zeros(n):
return jnp.zeros((n,), F32)
def ln_p(c):
return {"ln_g": jnp.ones((c,), F32), "ln_b": zeros(c)}
def init_fused(key, c, e, cfg):
k1, k2 = jax.random.split(key)
return {**ln_p(c),
"conv_w": tn(k1, (3, 3, c, c * e)), "conv_b": zeros(c * e),
"pw_w": tn(k2, (c * e, c)), "pw_b": zeros(c),
"gamma": jnp.full((c,), cfg.ls_init, F32)}
def init_convnext(key, c, r, cfg, attn=False):
ks = jax.random.split(key, 5)
p = {"dw_w": tn(ks[0], (cfg.dw_k, cfg.dw_k, 1, c)), "dw_b": zeros(c),
**ln_p(c),
"pw1_w": tn(ks[1], (c, c * r)), "pw1_b": zeros(c * r),
"pw2_w": tn(ks[2], (c * r, c)), "pw2_b": zeros(c),
"gamma": jnp.full((c,), cfg.ls_init, F32)}
if attn:
p.update({"a_ln_g": jnp.ones((c,), F32), "a_ln_b": zeros(c),
"qkv_w": tn(ks[3], (c, 3 * c)), "qkv_b": zeros(3 * c),
"proj_w": tn(ks[4], (c, c)), "proj_b": zeros(c),
"a_gamma": jnp.full((c,), cfg.ls_init, F32)})
return p
def init_params(key, cfg):
ks = iter(jax.random.split(key, 256))
nk = lambda: next(ks)
w = cfg.widths
P = {"stem": {"conv_w": tn(nk(), (3, 3, 48, w[0])), "conv_b": zeros(w[0]), **ln_p(w[0])}}
P["s1"] = [init_fused(nk(), w[0], cfg.ratios[0], cfg) for _ in range(cfg.depths[0])]
for i in (1, 2, 3):
cin, cout = w[i - 1], w[i]
if i < 3:
P[f"down{i}"] = {**ln_p(cin), "conv_w": tn(nk(), (2, 2, cin, cout)), "conv_b": zeros(cout)}
else:
P["down3"] = {**ln_p(cin), "pw_w": tn(nk(), (cin, cout)), "pw_b": zeros(cout)}
P[f"s{i + 1}"] = [
init_convnext(nk(), cout, cfg.ratios[i], cfg,
attn=(i == 3 and j == cfg.depths[i] - 1))
for j in range(cfg.depths[i])]
P["head"] = {**ln_p(w[3]),
"pw_w": tn(nk(), (w[3], cfg.head_dim)), "pw_b": zeros(cfg.head_dim),
"cls_w": tn(nk(), (cfg.head_dim, cfg.num_classes)), "cls_b": zeros(cfg.num_classes)}
return P
def count(tree):
return int(sum(np.prod(a.shape) for a in jax.tree_util.tree_leaves(tree)))
def named_leaves(tree):
out = {}
for path, leaf in jax.tree_util.tree_flatten_with_path(tree)[0]:
name = ".".join(str(getattr(k, "key", getattr(k, "idx", k))) for k in path)
out[name] = np.asarray(leaf)
return out
# ---------------------------------------------------------------- model
def layer_norm(x, g, b, eps=1e-6):
xf = x.astype(F32)
mu = xf.mean(-1, keepdims=True)
var = ((xf - mu) ** 2).mean(-1, keepdims=True)
return (((xf - mu) * lax.rsqrt(var + eps)) * g + b).astype(x.dtype)
def dense(x, w, b):
return jnp.einsum("...c,cd->...d", x, w.astype(x.dtype)) + b.astype(x.dtype)
def conv(x, w, b, stride=1, padding="SAME", groups=1):
y = lax.conv_general_dilated(
x, w.astype(x.dtype), (stride, stride), padding,
dimension_numbers=("NHWC", "HWIO", "NHWC"), feature_group_count=groups)
return y + b.astype(x.dtype)
def dwconv(x, w, b):
return conv(x, w, b, groups=x.shape[-1])
def gelu(x):
return jax.nn.gelu(x, approximate=True)
def space_to_depth(x, r=4):
n, h, w, c = x.shape
x = x.reshape(n, h // r, r, w // r, r, c).transpose(0, 1, 3, 2, 4, 5)
return x.reshape(n, h // r, w // r, r * r * c)
def drop_path(y, rate, key):
if rate == 0.0 or key is None:
return y
keep = 1.0 - rate
m = jax.random.bernoulli(key, keep, (y.shape[0], 1, 1, 1)).astype(y.dtype)
return y * m / keep
def fused_block(x, p, rate=0.0, key=None):
y = layer_norm(x, p["ln_g"], p["ln_b"])
y = gelu(conv(y, p["conv_w"], p["conv_b"]))
y = dense(y, p["pw_w"], p["pw_b"])
return x + p["gamma"].astype(x.dtype) * drop_path(y, rate, key)
def attention(x, p, heads, rate=0.0, key=None):
n, h, w, c = x.shape
y = layer_norm(x, p["a_ln_g"], p["a_ln_b"]).reshape(n, h * w, c)
qkv = dense(y, p["qkv_w"], p["qkv_b"]).reshape(n, h * w, 3, heads, c // heads)
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
s = jnp.einsum("nqhd,nkhd->nhqk", q, k) * (c // heads) ** -0.5
a = jax.nn.softmax(s.astype(F32), -1).astype(y.dtype)
o = jnp.einsum("nhqk,nkhd->nqhd", a, v).reshape(n, h * w, c)
o = dense(o, p["proj_w"], p["proj_b"]).reshape(n, h, w, c)
return x + p["a_gamma"].astype(x.dtype) * drop_path(o, rate, key)
def convnext_block(x, p, heads=4, rate=0.0, key=None):
y = dwconv(x, p["dw_w"], p["dw_b"])
y = layer_norm(y, p["ln_g"], p["ln_b"])
y = gelu(dense(y, p["pw1_w"], p["pw1_b"]))
y = dense(y, p["pw2_w"], p["pw2_b"])
k1 = jax.random.fold_in(key, 0) if key is not None else None
k2 = jax.random.fold_in(key, 1) if key is not None else None
x = x + p["gamma"].astype(x.dtype) * drop_path(y, rate, k1)
if "qkv_w" in p:
x = attention(x, p, heads, rate, k2)
return x
def apply(params, x, cfg, train=False, key=None):
"""x: (N,H,W,3) 0..255. Dönüş: f32 logit."""
total = sum(cfg.depths)
rates = [cfg.drop_path * i / max(total - 1, 1) for i in range(total)] if train else [0.0] * total
bi = 0
def bkey():
return jax.random.fold_in(key, bi) if (train and key is not None) else None
x = (x.astype(BF16) - 127.5) / 127.5
with jax.named_scope("stem"):
p = params["stem"]
x = layer_norm(conv(space_to_depth(x, 4), p["conv_w"], p["conv_b"]), p["ln_g"], p["ln_b"])
with jax.named_scope("s1"):
for blk in params["s1"]:
x = fused_block(x, blk, rates[bi], bkey()); bi += 1
for i in (1, 2, 3):
with jax.named_scope(f"down{i}"):
p = params[f"down{i}"]
x = layer_norm(x, p["ln_g"], p["ln_b"])
x = conv(x, p["conv_w"], p["conv_b"], stride=2, padding="VALID") if i < 3 \
else dense(x, p["pw_w"], p["pw_b"])
with jax.named_scope(f"s{i + 1}"):
for blk in params[f"s{i + 1}"]:
x = convnext_block(x, blk, cfg.heads, rates[bi], bkey()); bi += 1
with jax.named_scope("head"):
p = params["head"]
x = layer_norm(x.mean((1, 2)), p["ln_g"], p["ln_b"])
x = gelu(dense(x, p["pw_w"], p["pw_b"]))
return dense(x, p["cls_w"], p["cls_b"]).astype(F32)
# ---------------------------------------------------------------- Muon
def newton_schulz(G, steps=5):
a, b, c = 3.4445, -4.7750, 2.0315
X = G.astype(BF16)
tr = X.shape[-2] > X.shape[-1]
if tr:
X = jnp.swapaxes(X, -1, -2)
nrm = jnp.linalg.norm(X.astype(F32), axis=(-2, -1), keepdims=True) + 1e-7
X = X / nrm.astype(BF16)
for _ in range(steps):
A = X @ jnp.swapaxes(X, -1, -2)
B = b * A + c * (A @ A)
X = a * X + B @ X
return jnp.swapaxes(X, -1, -2) if tr else X
def _ns_batched(leaves, steps):
canon, flags = [], []
for l in leaves:
t = l.shape[0] > l.shape[1]
canon.append(l.T if t else l)
flags.append(t)
groups = {}
for i, c in enumerate(canon):
groups.setdefault(c.shape, []).append(i)
out = [None] * len(leaves)
for _, idxs in groups.items():
res = newton_schulz(jnp.stack([canon[i] for i in idxs]), steps)
for j, i in enumerate(idxs):
out[i] = res[j].T if flags[i] else res[j]
return out
class MuonState(NamedTuple):
mu: Any
def scale_by_muon(beta=0.95, ns_steps=5, batched=True, rms_match=0.2):
def init_fn(params):
return MuonState(mu=jax.tree_util.tree_map(jnp.zeros_like, params))
def update_fn(updates, state, params=None):
del params
mu = jax.tree_util.tree_map(lambda m, g: beta * m + g, state.mu, updates)
u = jax.tree_util.tree_map(lambda m, g: g + beta * m, mu, updates) # Nesterov
leaves, treedef = jax.tree_util.tree_flatten(u)
outs = _ns_batched(leaves, ns_steps) if batched else \
[newton_schulz(l, ns_steps) for l in leaves]
outs = [o.astype(F32) * (rms_match * math.sqrt(max(l.shape))) for o, l in zip(outs, leaves)]
return treedef.unflatten(outs), MuonState(mu=mu)
return optax.GradientTransformation(init_fn, update_fn)
def label_tree(params):
def f(path, leaf):
name = path[-1].key
return "muon" if (name.endswith("_w") and leaf.ndim == 2 and name != "cls_w") else "adamw"
return jax.tree_util.tree_map_with_path(f, params)
def make_schedule(total_steps, warmup_steps, peak_lr, final_frac=0.01, ext=None):
"""Ana program (0..total_steps) + isteğe bağlı uzatma parçaları.
ext: [dict(start, steps, peak, warmup, final_frac)]; start'tan itibaren yeni warmup+cosine geçerli olur."""
base = optax.warmup_cosine_decay_schedule(0.0, peak_lr, warmup_steps, total_steps,
end_value=peak_lr * final_frac)
if not ext:
return base
scheds, bounds = [base], []
for e in ext:
scheds.append(optax.warmup_cosine_decay_schedule(0.0, e["peak"], e["warmup"], e["steps"],
end_value=e["peak"] * e["final_frac"]))
bounds.append(e["start"])
return optax.join_schedules(scheds, bounds)
def make_optimizer(params, total_steps, warmup_steps, peak_lr, wd, final_frac=0.01, clip=1.0, ns_steps=5, ext=None):
sched = make_schedule(total_steps, warmup_steps, peak_lr, final_frac, ext)
wd_mask = jax.tree_util.tree_map(lambda x: x.ndim >= 2, params)
tx = optax.chain(
optax.clip_by_global_norm(clip),
optax.multi_transform({"muon": scale_by_muon(ns_steps=ns_steps, batched=True),
"adamw": optax.scale_by_adam()}, label_tree(params)),
optax.add_decayed_weights(wd, mask=wd_mask),
optax.scale_by_schedule(lambda c: -sched(c)),
)
return tx, sched
# ---------------------------------------------------------------- augmentation
def soft_targets(y, num_classes, smoothing):
oh = jax.nn.one_hot(y, num_classes)
return oh * (1.0 - smoothing) + smoothing / num_classes
def random_resized_crop_flip(key, imgs_u8, out_res, min_scale):
"""Cihazda: RandomResizedCrop (alan [min_scale,1], oran [3/4,4/3]) + yatay çevirme."""
x = imgs_u8.astype(F32)
B, S = x.shape[0], x.shape[1]
k1, k2, k3, k4 = jax.random.split(key, 4)
area = jax.random.uniform(k1, (B,), minval=min_scale, maxval=1.0)
ar = jnp.exp(jax.random.uniform(k2, (B,), minval=math.log(3 / 4), maxval=math.log(4 / 3)))
w = jnp.clip(jnp.sqrt(area * ar), 0.05, 1.0)
h = jnp.clip(jnp.sqrt(area / ar), 0.05, 1.0)
u = jax.random.uniform(k3, (B, 2))
y0, x0 = u[:, 0] * (1 - h) * S, u[:, 1] * (1 - w) * S
sy, sx = out_res / (h * S), out_res / (w * S)
def one(img, sy, sx, ty, tx):
return jax.image.scale_and_translate(
img, (out_res, out_res, img.shape[-1]), (0, 1),
jnp.stack([sy, sx]), jnp.stack([ty, tx]), method="linear")
out = jax.vmap(one)(x, sy, sx, -y0 * sy, -x0 * sx)
flip = jax.random.bernoulli(k4, 0.5, (B, 1, 1, 1))
out = jnp.where(flip, out[:, :, ::-1], out)
return jnp.clip(out, 0.0, 255.0)
def cutmix(key, x, y_soft, alpha=1.0):
B, H, W, _ = x.shape
k1, k2, k3 = jax.random.split(key, 3)
lam = jax.random.beta(k1, alpha, alpha)
cut = jnp.sqrt(1.0 - lam)
ch, cw = (cut * H).astype(jnp.int32), (cut * W).astype(jnp.int32)
cy, cx = jax.random.randint(k2, (), 0, H), jax.random.randint(k3, (), 0, W)
y1, y2 = jnp.clip(cy - ch // 2, 0, H), jnp.clip(cy + ch // 2, 0, H)
x1, x2 = jnp.clip(cx - cw // 2, 0, W), jnp.clip(cx + cw // 2, 0, W)
ys, xs = jnp.arange(H)[:, None], jnp.arange(W)[None, :]
mask = ((ys >= y1) & (ys < y2) & (xs >= x1) & (xs < x2))[None, :, :, None]
perm = jnp.roll(jnp.arange(B), 1)
xm = jnp.where(mask, x[perm], x)
lam_adj = 1.0 - ((y2 - y1) * (x2 - x1)).astype(F32) / (H * W)
return xm, lam_adj * y_soft + (1.0 - lam_adj) * y_soft[perm]