# sft.py — run-076 : le fine-tuning supervisé COMPLET d'un modèle fr-mini (l'étape instruct), sur GPU.
# python sft.py <données instruct> <validation brute> <modele.pt de base> <resultats.json de base> <sortie> '<runs en JSON>'
#  - données instruct : <jeu>.lignes.bin / <jeu>.masque.bin de prep_instruct.py (lignes de 513 jetons, 1 = jeton noté) ;
#  - validation brute : tokenizer.json et v16384_{web,wiki,livres}.val.bin, la validation de tous les runs ;
#  - un run : {"nom", "donnees": "humain"|"tout", "passes", "lr"} ; tous les poids sont ajustés (pas de LoRA).
#    run-080 : "graine" (76 par défaut : l'ordre des lignes et l'initialisation), "sauver_passes" (un modèle à la fin de
#    chaque passe, pour choisir ensuite le meilleur sur les consignes), "ajout": {"jeu", "lignes"} (des lignes d'un autre
#    jeu ajoutées : réponses du modèle vérifiées, consignes à deux contraintes…).
# Mesures : la perte sur les réponses des 1 655 conversations mises de côté (avant, pendant, après) et l'oubli :
# les bits par octet sur web, wiki, livres, calculés de la même façon pour le modèle de base et pour le modèle ajusté.
import json, math, os, sys, time
import numpy as np
import torch, torch.nn as nn, torch.nn.functional as F
from tokenizers import Tokenizer

DON, VALB, BASE_PT, BASE_RES, OUT, RUNS = sys.argv[1:7]
RUNS = json.loads(RUNS)
DEV, CTX = os.environ.get("SFT_DEV", "cuda"), 512          # SFT_DEV=cpu : essai rapide sur le poste
BASE = json.load(open(BASE_RES, encoding="utf-8"))
EB = BASE["experience"]
LARG, COUCHES, TETES = int(EB.get("largeur", 512)), int(EB.get("couches", 8)), int(EB.get("tetes", 8))
CACHEE = 32 * round(8 / 3 * LARG / 32)
tk = Tokenizer.from_file(os.path.join(VALB, "tokenizer.json"))
VOCAB = tk.get_vocab_size()
DT = torch.bfloat16 if DEV == "cpu" or torch.cuda.get_device_capability()[0] >= 8 else torch.float16   # T4 : fp16
T0 = time.time()
def log(*a):
    print(f"[{(time.time() - T0) / 60:6.1f} min]", *a, flush=True)

# ---------- le modèle, comme train.py ----------
class RMSNorm(nn.Module):
    def __init__(self, d):
        super().__init__(); self.w = nn.Parameter(torch.ones(d))
    def forward(self, x):
        return self.w * x * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + 1e-6).to(x.dtype)
dh = LARG // TETES
_f = torch.outer(torch.arange(CTX, device=DEV).float(), 1.0 / (10000 ** (torch.arange(0, dh, 2, device=DEV).float() / dh)))
COS, SIN = _f.cos(), _f.sin()
def appliquer(x):
    x1, x2 = x[..., ::2], x[..., 1::2]
    T = x.shape[-2]
    c, s = COS[:T].to(x.dtype), SIN[:T].to(x.dtype)
    return torch.stack((x1 * c - x2 * s, x1 * s + x2 * c), -1).flatten(-2)
class Bloc(nn.Module):
    def __init__(self):
        super().__init__()
        self.n1, self.n2 = RMSNorm(LARG), RMSNorm(LARG)
        self.qkv = nn.Linear(LARG, 3 * LARG, bias=False)
        self.o = nn.Linear(LARG, LARG, bias=False)
        self.g, self.u, self.d = nn.Linear(LARG, CACHEE, bias=False), nn.Linear(LARG, CACHEE, bias=False), nn.Linear(CACHEE, LARG, bias=False)
    def forward(self, x):
        B, T, C = x.shape
        q, k, v = self.qkv(self.n1(x)).view(B, T, 3, TETES, C // TETES).permute(2, 0, 3, 1, 4)
        a = F.scaled_dot_product_attention(appliquer(q), appliquer(k), v, is_causal=True)
        x = x + self.o(a.transpose(1, 2).reshape(B, T, C))
        h = self.n2(x)
        return x + self.d(F.silu(self.g(h)) * self.u(h))
class Modele(nn.Module):
    def __init__(self):
        super().__init__()
        self.emb = nn.Embedding(VOCAB, LARG)
        self.blocs = nn.ModuleList(Bloc() for _ in range(COUCHES))
        self.nf = RMSNorm(LARG)
    def forward(self, x):
        h = self.emb(x)
        for b in self.blocs:
            h = b(h)
        return self.nf(h) @ self.emb.weight.T
class LoRA(nn.Module):
    """une couche linéaire gelée plus une correction de rang r : W·x + (α/r)·B·A·x ; B part de zéro"""
    def __init__(self, lin, r, alpha):
        super().__init__()
        self.lin, self.s = lin, alpha / r
        self.a = nn.Parameter(torch.randn(r, lin.in_features, device=lin.weight.device) / math.sqrt(lin.in_features))
        self.b = nn.Parameter(torch.zeros(lin.out_features, r, device=lin.weight.device))
    def forward(self, x):
        return self.lin(x) + (x @ self.a.T.to(x.dtype) @ self.b.T.to(x.dtype)) * self.s
def charger_base():
    m = Modele().to(DEV)
    m.load_state_dict({k: v.float() for k, v in torch.load(BASE_PT, map_location=DEV).items()})
    return m

# ---------- les mesures ----------
VAL_SRC = ["web", "wiki", "livres"]
val = {s: np.fromfile(os.path.join(VALB, f"v16384_{s}.val.bin"), dtype=np.uint16) for s in VAL_SRC}
OCTETS = {s: len(tk.decode(val[s][:2_000_000].tolist()).encode("utf-8")) / min(len(val[s]), 2_000_000) for s in VAL_SRC}

ESSAI = os.environ.get("SFT_ESSAI") == "1"              # essai : mesures réduites
@torch.no_grad()
def oubli(m, n_fen=32 if ESSAI else 1024):
    """les bits par octet sur la validation habituelle, comme evaluer() de train.py (1 024 fenêtres par source)"""
    m.eval(); r = {}
    for s in VAL_SRC:
        v = val[s]; pas_f = (len(v) - CTX - 1) // n_fen; pertes = []
        for i in range(0, n_fen, 32):
            xs = torch.from_numpy(np.stack([v[j * pas_f: j * pas_f + CTX + 1] for j in range(i, min(n_fen, i + 32))]).astype(np.int64)).to(DEV)
            with torch.autocast(DEV, dtype=DT):
                lg = m(xs[:, :-1])
            pertes.append(F.cross_entropy(lg.float().reshape(-1, VOCAB), xs[:, 1:].reshape(-1)).item())
        p = sum(pertes) / len(pertes)
        r[s] = {"perte": round(p, 4), "bpo": round(p / math.log(2) / OCTETS[s], 4)}
    m.train(); return r

def lignes(jeu):
    I = np.fromfile(os.path.join(DON, f"{jeu}.lignes.bin"), dtype=np.uint16).reshape(-1, CTX + 1)
    M = np.fromfile(os.path.join(DON, f"{jeu}.masque.bin"), dtype=np.uint8).reshape(-1, CTX + 1)
    return I, M
VI, VM = lignes("val")
if ESSAI:
    VI, VM = VI[:64], VM[:64]

def perte_lot(mm, I, M):
    x = torch.from_numpy(I.astype(np.int64)).to(DEV); msk = torch.from_numpy(M[:, 1:].astype(np.float32)).to(DEV)
    with torch.autocast(DEV, dtype=DT):
        lg = mm(x[:, :-1])
    ce = F.cross_entropy(lg.float().reshape(-1, VOCAB), x[:, 1:].reshape(-1), reduction="none")
    return (ce * msk.reshape(-1)).sum(), msk.sum()

@torch.no_grad()
def perte_reponses(m):
    """perte moyenne (nats par jeton) sur les réponses des conversations mises de côté"""
    m.eval(); tot = n = 0.0
    for i in range(0, len(VI), 32):
        a, b = perte_lot(m, VI[i:i + 32], VM[i:i + 32]); tot += a.item(); n += b.item()
    m.train(); return round(tot / n, 4)

# ---------- le modèle de base, mesuré une fois avec les mêmes fonctions ----------
mb = charger_base()
REF = {"oubli": oubli(mb), "perte_reponses": perte_reponses(mb)}
log("modèle de base", REF)
del mb

for R in RUNS:
    nom, LR, PASSES, LOT = R["nom"], float(R.get("lr", 1e-4)), float(R.get("passes", 2)), int(R.get("lot", 64))
    GR = int(R.get("graine", 76))
    torch.manual_seed(GR); rng = np.random.default_rng(GR)
    I, M = lignes(R["donnees"])
    if R.get("part"):                                  # la quantité : seulement une part des conversations (lignes tirées au hasard)
        garde = np.sort(np.random.default_rng(77).permutation(len(I))[: int(R["part"] * len(I))])
        I, M = I[garde], M[garde]
    if R.get("consignes_lignes"):                      # run-078 : des exemples « consigne vérifiable » ajoutés (gen_consignes_instruct.py)
        CI = np.fromfile(os.path.join(DON, "consignes.lignes.bin"), dtype=np.uint16).reshape(-1, CTX + 1)
        CM = np.fromfile(os.path.join(DON, "consignes.masque.bin"), dtype=np.uint8).reshape(-1, CTX + 1)
        nc = min(len(CI), int(R["consignes_lignes"]))
        I, M = np.concatenate([I, CI[:nc]]), np.concatenate([M, CM[:nc]])
    if R.get("ajout"):                                 # run-080 : un autre jeu de lignes, en plus
        AI, AM = lignes(R["ajout"]["jeu"])
        na = min(len(AI), int(R["ajout"].get("lignes", len(AI))))
        I, M = np.concatenate([I, AI[:na]]), np.concatenate([M, AM[:na]])
    if R.get("noter_question"):                        # run-078 : la perte compte aussi la question (tous les vrais jetons)
        M = np.where(I != 0, 1, M).astype(np.uint8); M[:, 0] = 0
    if R.get("brut"):                                  # replay : une part de texte ordinaire du pré-entraînement, noté en entier
        BI = np.fromfile(os.path.join(DON, "brut.lignes.bin"), dtype=np.uint16).reshape(-1, CTX + 1)
        nb = min(len(BI), int(len(I) * R["brut"] / (1 - R["brut"])))
        BM = np.ones((nb, CTX + 1), dtype=np.uint8); BM[:, 0] = 0
        I, M = np.concatenate([I, BI[:nb]]), np.concatenate([M, BM])
    PAS = int(PASSES * len(I) // LOT)
    CHAUFFE, LR_MIN = max(1, int(0.03 * PAS)), LR / 10
    def lr_au(p):
        if p < CHAUFFE:
            return LR * (p + 1) / CHAUFFE
        return LR_MIN + 0.5 * (LR - LR_MIN) * (1 + math.cos(math.pi * (p - CHAUFFE) / max(1, PAS - CHAUFFE)))
    m = charger_base()
    LORAS = []
    if R.get("lora"):                                  # LoRA : le modèle est gelé, seules de petites matrices A et B apprennent
        r_, al_ = int(R["lora"]), float(R.get("lora_alpha", 2 * int(R["lora"])))
        for p_ in m.parameters():
            p_.requires_grad_(False)
        for b in m.blocs:
            for nom_l in ("qkv", "o", "g", "u", "d"):
                lo = LoRA(getattr(b, nom_l), r_, al_); setattr(b, nom_l, lo); LORAS.append((b, nom_l, lo))
    if R.get("geler"):                                 # geler : les plongements (liés à la sortie) et les k premiers blocs ne bougent pas
        for p_ in list(m.emb.parameters()) + [q for b in m.blocs[:int(R["geler"])] for q in b.parameters()]:
            p_.requires_grad_(False)
    if R.get("neftune"):                               # NEFTune : un léger bruit sur les plongements, seulement pendant l'entraînement
        al_n = float(R["neftune"])
        def bruit(mod, inp, out):
            if mod.training:
                return out + torch.empty_like(out).uniform_(-1, 1) * (al_n / math.sqrt(out.shape[-2] * out.shape[-1]))
        m.emb.register_forward_hook(bruit)
    ENTRAINES = sum(p.numel() for p in m.parameters() if p.requires_grad)
    dec = [p for p in m.parameters() if p.dim() == 2 and p.requires_grad]; nodec = [p for p in m.parameters() if p.dim() < 2 and p.requires_grad]
    opt = torch.optim.AdamW([{"params": dec, "weight_decay": float(R.get("wd", 0.0))}, {"params": nodec, "weight_decay": 0.0}],
                            lr=LR, betas=(0.9, 0.95), fused=DEV == "cuda")
    scaler = torch.amp.GradScaler(enabled=DT == torch.float16)
    mc = torch.compile(m) if DEV == "cuda" else m
    log(f"{nom} : {R['donnees']}, {len(I)} lignes, {PASSES} passe(s), {PAS} pas de {LOT} lignes, lr {LR}")
    ordre = np.concatenate([rng.permutation(len(I)) for _ in range(math.ceil(PASSES))])
    courbe, t1, debut_debit = [], time.time(), time.time()
    for p in range(PAS):
        for g in opt.param_groups:
            g["lr"] = lr_au(p)
        idx = np.sort(ordre[p * LOT:(p + 1) * LOT])
        MICRO = int(R.get("micro", LOT))                 # sur T4 (16 Go) : le lot est calculé en petits morceaux
        n_tot = float(M[idx][:, 1:].sum())
        opt.zero_grad(set_to_none=True)
        loss = 0.0
        for k in range(0, LOT, MICRO):
            s, _ = perte_lot(mc, I[idx[k:k + MICRO]], M[idx[k:k + MICRO]])
            scaler.scale(s / n_tot).backward()
            loss += s.detach() / n_tot
        scaler.unscale_(opt); torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)
        scaler.step(opt); scaler.update()
        if R.get("sauver_passes") and (p + 1) % max(1, PAS // math.ceil(PASSES)) == 0 and p < PAS - 1:
            k_ = (p + 1) // max(1, PAS // math.ceil(PASSES)); ep = os.path.join(OUT, f"{nom}-p{k_}"); os.makedirs(ep, exist_ok=True)
            torch.save({k: v.half() for k, v in m.state_dict().items()}, os.path.join(ep, "modele.pt"))
            pv = {"oubli": oubli(m), "perte_reponses": perte_reponses(m)}
            json.dump({"experience": dict(EB, nom=f"{nom}-p{k_}", base=BASE["experience"]["nom"], sft=dict(R, passe=k_)),
                       "validation_finale": pv["oubli"], "validation_base_meme_calcul": REF["oubli"],
                       "perte_reponses_val": {"base": REF["perte_reponses"], "apres": pv["perte_reponses"]}},
                      open(os.path.join(ep, "resultats.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
            log(f"{nom} passe {k_} sauvée", pv)
        if p % max(1, PAS // 8) == 0 or p == PAS - 1:
            pr = perte_reponses(m)
            debit = LOT * CTX * (p + 1) / (time.time() - debut_debit)
            courbe.append({"pas": p, "perte_train": round(loss.item(), 4), "perte_reponses_val": pr, "lr": lr_au(p), "jetons_par_s": round(debit)})
            log(f"{nom} pas {p}/{PAS} train {loss.item():.3f} réponses val {pr:.4f}, {debit:,.0f} j/s")
    minutes = (time.time() - t1) / 60
    with torch.no_grad():                              # LoRA : on range B·A dans les poids, le modèle redevient ordinaire
        for b, nom_l, lo in LORAS:
            lo.lin.weight += lo.s * (lo.b @ lo.a); setattr(b, nom_l, lo.lin)
    fin = {"oubli": oubli(m), "perte_reponses": perte_reponses(m)}
    log(nom, "après", fin)
    ech = os.path.join(OUT, nom); os.makedirs(ech, exist_ok=True)
    torch.save({k: v.half() for k, v in m.state_dict().items()}, os.path.join(ech, "modele.pt"))
    experience = dict(EB, nom=nom, base=BASE["experience"]["nom"], sft=R)
    res = {"experience": experience, "parametres": sum(p.numel() for p in m.parameters()), "parametres_entraines": ENTRAINES,
           "jetons_vus": int(PAS * LOT * CTX), "jetons_notes_vus": int(M[ordre[:PAS * LOT]].sum()),
           "lignes": len(I), "pas": PAS, "minutes": round(minutes, 1), "type_calcul": str(DT),
           "validation_finale": fin["oubli"], "validation_base_meme_calcul": REF["oubli"],
           "perte_reponses_val": {"base": REF["perte_reponses"], "apres": fin["perte_reponses"]},
           "courbe": courbe, "memoire_max_go": round(torch.cuda.max_memory_allocated() / 1e9, 2) if DEV == "cuda" else None}
    json.dump(res, open(os.path.join(ech, "resultats.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    log(nom, f"fini en {minutes:.1f} min")
    s = loss = None; opt.zero_grad(set_to_none=True)          # la dernière perte garde le graphe du run
    del m, mc, opt
    import gc; gc.collect()
    if DEV == "cuda":
        torch.cuda.empty_cache()
print("fini", flush=True)
