File size: 8,353 Bytes
6071ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Load / save Slayer1B native checkpoints (wagi_*.pt) and greedy/temperature generation for evals.



Checkpoint format (as published in SlayerLab/Slayer1B-1.09-checkpoints): {"model": state_dict, "config": dict, "step": int}.

The model class is GPT from train_gpt_ref_r24_2.py (pinned SHA-256 below, file from SlayerLab/Slayer1B-1.09).

"""
from __future__ import annotations

import hashlib
import importlib.util
import os
from pathlib import Path
from types import SimpleNamespace

import torch

TRAINER_SHA256 = None   # filled from the downloaded file on first load and recorded in run metadata
DEFAULT_TRAINER = Path(os.environ.get("SLAYER_TRAINER", str(Path(__file__).resolve().parents[2]
                                                         / "slayer-general-talk-pl-en/_research/slayer1b/train_gpt_ref_r24_2.py")))


def sha256(path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while b := f.read(1 << 22):
            h.update(b)
    return h.hexdigest()


def trainer_module(path: Path = DEFAULT_TRAINER):
    spec = importlib.util.spec_from_file_location("slayer_native_trainer", str(path))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def load(ckpt: str, device="cuda", dtype=torch.float32, trainer_path: Path = DEFAULT_TRAINER, expect_sha256: str | None = None):
    if expect_sha256 and sha256(ckpt) != expect_sha256:
        raise ValueError(f"checkpoint sha256 mismatch: {ckpt}")
    T = trainer_module(trainer_path)
    st = torch.load(ckpt, map_location="cpu", weights_only=True, mmap=False)   # mmap + .to(cuda) segfaults on Windows
    cfg = SimpleNamespace(**st["config"])
    with torch.device("meta"):
        model = T.GPT(cfg.vocab, cfg.n_layer, cfg.n_embd, cfg.n_head, cfg.block, cfg)
    model.load_state_dict(st["model"], strict=True, assign=True)
    model.head.weight = model.tok.weight
    model = model.to(device=device, dtype=dtype)
    return model, cfg, st.get("step")


def save(model, cfg, path, step, extra: dict | None = None, state_dict=None):
    sd = state_dict if state_dict is not None else {k: v.detach().float().cpu() for k, v in model.state_dict().items()}
    out ={"model": sd, "config": dict(vars(cfg)), "step": step}
    if extra:
        out["sft"] = extra
    tmp = str(path) + ".tmp"
    torch.save(out, tmp)
    os.replace(tmp, path)


# ---------------------------------------------------------------- KV cache (ported from slayerlabs/benchmarks-fabryka-ai
# @2f4c0491 research/common/slayer_serving/slayer_kv_lm.py; valid only for the Slayer 1.09 configuration: A blocks,
# interleaved RoPE over the full head dim, QK-norm, value residual, MHA)
def _rope(x, pos0, theta):
    T, dim = x.shape[2], x.shape[3]
    pos = torch.arange(pos0, pos0 + T, device=x.device, dtype=torch.float32)
    freq = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device, dtype=torch.float32) / dim))
    ang = torch.outer(pos, freq)
    cos, sin = ang.cos().to(x.dtype)[None, None], ang.sin().to(x.dtype)[None, None]
    even, odd = x[..., ::2], x[..., 1::2]
    return torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1).flatten(-2)


def kv_supported(model) -> bool:
    c = model.cfg
    return (getattr(c, "arch", "gpt") == "gpt" and c.pos == "rope" and bool(c.qk_norm) and bool(c.value_residual)
            and getattr(c, "rope_style", "interleaved") == "interleaved" and not int(getattr(c, "rope_dims", 0) or 0)
            and not int(getattr(c, "imha_t", 0) or 0) and set(getattr(c, "mixer_layout", None) or "A") == {"A"}
            and not getattr(c, "xsa", 0) and not getattr(c, "logit_cap", 0.0) and not getattr(c, "emb_dim", 0))


def _kv_step(m, idx, cache, theta):
    import torch.nn.functional as F
    pos0, T = cache["n"], idx.shape[1]
    x = m.tok(idx)
    v0 = None
    for li, b in enumerate(m.blocks):
        B, _, D = x.size()
        hd = D // b.nh
        q, k, v = b.qkv(b.ln1(x)).split([b.d, b.kvd, b.kvd], dim=2)
        q = b.q_norm(q.view(B, T, b.nh, hd).transpose(1, 2))
        k = b.k_norm(k.view(B, T, b.nkv, hd).transpose(1, 2))
        v = v.view(B, T, b.nkv, hd).transpose(1, 2)
        q, k = _rope(q, pos0, theta), _rope(k, pos0, theta)
        if b.is_first:
            v0 = v
        else:
            v = v + b.vr_lambda * v0
        cache["K"][li][:, :, pos0:pos0 + T] = k
        cache["V"][li][:, :, pos0:pos0 + T] = v
        k, v = cache["K"][li][:, :, :pos0 + T], cache["V"][li][:, :, :pos0 + T]
        y = F.scaled_dot_product_attention(q, k, v, is_causal=T > 1)
        x = x + b.proj(y.transpose(1, 2).contiguous().view(B, T, D))
        x = x + b.mlp(b.ln2(x))
    cache["n"] = pos0 + T
    return m._head(m.lnf(x))[0, -1].float()


def _pick(lg, out, temperature, top_p, repetition_penalty, generator):
    """Next token: optional repetition penalty on tokens generated so far (HF/CTRL rule: positive logits / p, negative * p),

    then greedy (temperature <= 0) or temperature + nucleus sampling. Defaults reproduce plain argmax."""
    if repetition_penalty != 1.0 and out:
        idx = torch.tensor(sorted(set(out)), device=lg.device)
        v = lg[idx]
        lg = lg.clone()
        lg[idx] = torch.where(v > 0, v / repetition_penalty, v * repetition_penalty)
    if temperature <= 0:
        return int(lg.argmax())
    p = torch.softmax(lg / temperature, -1)
    if top_p < 1.0:
        sp, si = torch.sort(p, descending=True)
        keep = sp.cumsum(0) - sp <= top_p
        p = torch.zeros_like(p).scatter(0, si[keep], sp[keep])
        p = p / p.sum()
    return int(torch.multinomial(p, 1, generator=generator))


@torch.inference_mode()
def generate(model, prompt_ids: list[int], *, stop_ids: set[int], max_new_tokens=256, temperature=0.0, top_p=1.0,

             block=4096, generator=None, device="cuda", kv: bool = True, repetition_penalty: float = 1.0) -> tuple[list[int], str]:
    if kv and kv_supported(model):
        ids = list(prompt_ids)[-block:]
        n = min(block, len(ids) + max_new_tokens)
        hd = model.blocks[0].d // model.blocks[0].nh
        dt = next(model.parameters()).dtype
        cache = {"n": 0, "K": [torch.empty((1, b.nkv, n, hd), dtype=dt, device=device) for b in model.blocks],
                 "V": [torch.empty((1, b.nkv, n, hd), dtype=dt, device=device) for b in model.blocks]}
        theta = float(model.cfg.rope_theta)
        lg = _kv_step(model, torch.tensor([ids], device=device), cache, theta)
        out = []
        while True:
            t = _pick(lg.float(), out, temperature, top_p, repetition_penalty, generator)
            if t in stop_ids:
                return out, "stop"
            out.append(t)
            if len(out) >= max_new_tokens:
                return out, "max_new_tokens"
            if cache["n"] >= n:
                return out, "context_full"
            lg = _kv_step(model, torch.tensor([[t]], device=device), cache, theta)
    return _generate_nocache(model, prompt_ids, stop_ids=stop_ids, max_new_tokens=max_new_tokens, temperature=temperature,
                             top_p=top_p, block=block, generator=generator, device=device, repetition_penalty=repetition_penalty)


@torch.inference_mode()
def _generate_nocache(model, prompt_ids: list[int], *, stop_ids: set[int], max_new_tokens=256, temperature=0.0, top_p=1.0,

                      block=4096, generator=None, device="cuda", repetition_penalty: float = 1.0) -> tuple[list[int], str]:
    """Returns (new token ids without the stop token, stop_reason). No KV cache in the native model: the prompt is

    re-encoded each step (fine for evaluation-sized prompts)."""
    ids = list(prompt_ids)
    out = []
    for _ in range(max_new_tokens):
        x = torch.tensor([ids[-block:]], device=device)
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device == "cuda")):
            logits, _ = model(x)
        t = _pick(logits[0, -1].float(), out, temperature, top_p, repetition_penalty, generator)
        if t in stop_ids:
            return out, "stop"
        ids.append(t)
        out.append(t)
        if len(ids) >= block:
            return out, "context_full"
    return out, "max_new_tokens"