Update inference.py
Browse files- inference.py +353 -353
inference.py
CHANGED
|
@@ -1,353 +1,353 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import argparse
|
| 4 |
-
import json
|
| 5 |
-
import sys
|
| 6 |
-
import time
|
| 7 |
-
from dataclasses import dataclass
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
|
| 10 |
-
import torch
|
| 11 |
-
import torch.nn as nn
|
| 12 |
-
import torch.nn.functional as F
|
| 13 |
-
from safetensors.torch import load_file
|
| 14 |
-
from tokenizers import Tokenizer
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
@dataclass(frozen=True)
|
| 18 |
-
class ModelConfig:
|
| 19 |
-
vocab_size: int = 32000
|
| 20 |
-
hidden_size: int = 768
|
| 21 |
-
intermediate_size: int = 2048
|
| 22 |
-
num_hidden_layers: int = 12
|
| 23 |
-
num_attention_heads: int = 12
|
| 24 |
-
num_key_value_heads: int = 4
|
| 25 |
-
rms_norm_eps: float = 1e-5
|
| 26 |
-
max_position_embeddings: int =
|
| 27 |
-
rope_theta: float = 10000.0
|
| 28 |
-
attention_dropout: float = 0.0
|
| 29 |
-
attn_window: int = 0
|
| 30 |
-
attn_block_size: int = 256
|
| 31 |
-
initializer_range: float = 0.02
|
| 32 |
-
tie_word_embeddings: bool = True
|
| 33 |
-
pad_token_id: int = 0
|
| 34 |
-
bos_token_id: int = 2
|
| 35 |
-
eos_token_id: int = 3
|
| 36 |
-
|
| 37 |
-
@property
|
| 38 |
-
def head_dim(self) -> int:
|
| 39 |
-
return self.hidden_size // self.num_attention_heads
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
class RMSNorm(nn.Module):
|
| 43 |
-
def __init__(self, dim: int, eps: float):
|
| 44 |
-
super().__init__()
|
| 45 |
-
self.eps = eps
|
| 46 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 47 |
-
|
| 48 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 49 |
-
orig_dtype = x.dtype
|
| 50 |
-
x = x.float()
|
| 51 |
-
var = x.pow(2).mean(dim=-1, keepdim=True)
|
| 52 |
-
x = x * torch.rsqrt(var + self.eps)
|
| 53 |
-
return (x.to(orig_dtype)) * self.weight
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
class RotaryEmbedding(nn.Module):
|
| 57 |
-
def __init__(self, head_dim: int, max_pos: int, theta: float):
|
| 58 |
-
super().__init__()
|
| 59 |
-
self.head_dim = head_dim
|
| 60 |
-
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
|
| 61 |
-
t = torch.arange(max_pos, dtype=inv_freq.dtype)
|
| 62 |
-
freqs = torch.einsum("i,j->ij", t, inv_freq)
|
| 63 |
-
emb = torch.cat([freqs, freqs], dim=-1)
|
| 64 |
-
self.register_buffer("_cos", emb.cos(), persistent=False)
|
| 65 |
-
self.register_buffer("_sin", emb.sin(), persistent=False)
|
| 66 |
-
|
| 67 |
-
def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 68 |
-
b, h, t, hd = q.shape
|
| 69 |
-
cos = self._cos[:t].to(q.dtype).unsqueeze(0).unsqueeze(0)
|
| 70 |
-
sin = self._sin[:t].to(q.dtype).unsqueeze(0).unsqueeze(0)
|
| 71 |
-
|
| 72 |
-
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 73 |
-
x1 = x[..., : hd // 2]
|
| 74 |
-
x2 = x[..., hd // 2 :]
|
| 75 |
-
return torch.cat([-x2, x1], dim=-1)
|
| 76 |
-
|
| 77 |
-
q_out = (q * cos) + (rotate_half(q) * sin)
|
| 78 |
-
k_out = (k * cos) + (rotate_half(k) * sin)
|
| 79 |
-
return q_out, k_out
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
class LlamaMLP(nn.Module):
|
| 83 |
-
def __init__(self, cfg: ModelConfig):
|
| 84 |
-
super().__init__()
|
| 85 |
-
self.gate_proj = nn.Linear(cfg.hidden_size, cfg.intermediate_size, bias=False)
|
| 86 |
-
self.up_proj = nn.Linear(cfg.hidden_size, cfg.intermediate_size, bias=False)
|
| 87 |
-
self.down_proj = nn.Linear(cfg.intermediate_size, cfg.hidden_size, bias=False)
|
| 88 |
-
|
| 89 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 90 |
-
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
class LlamaAttention(nn.Module):
|
| 94 |
-
def __init__(self, cfg: ModelConfig):
|
| 95 |
-
super().__init__()
|
| 96 |
-
self.cfg = cfg
|
| 97 |
-
self.num_heads = cfg.num_attention_heads
|
| 98 |
-
self.num_kv_heads = cfg.num_key_value_heads
|
| 99 |
-
self.head_dim = cfg.head_dim
|
| 100 |
-
self.kv_repeat = self.num_heads // self.num_kv_heads
|
| 101 |
-
self.q_proj = nn.Linear(cfg.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 102 |
-
self.k_proj = nn.Linear(cfg.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
|
| 103 |
-
self.v_proj = nn.Linear(cfg.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
|
| 104 |
-
self.o_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=False)
|
| 105 |
-
self.rotary = RotaryEmbedding(self.head_dim, cfg.max_position_embeddings, cfg.rope_theta)
|
| 106 |
-
self.attn_dropout = float(cfg.attention_dropout)
|
| 107 |
-
|
| 108 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 109 |
-
b, t, d = x.shape
|
| 110 |
-
q = self.q_proj(x).view(b, t, self.num_heads, self.head_dim).transpose(1, 2)
|
| 111 |
-
k = self.k_proj(x).view(b, t, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 112 |
-
v = self.v_proj(x).view(b, t, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 113 |
-
q, k = self.rotary(q, k)
|
| 114 |
-
if self.kv_repeat != 1:
|
| 115 |
-
k = k.repeat_interleave(self.kv_repeat, dim=1)
|
| 116 |
-
v = v.repeat_interleave(self.kv_repeat, dim=1)
|
| 117 |
-
y = F.scaled_dot_product_attention(
|
| 118 |
-
q, k, v,
|
| 119 |
-
attn_mask=None,
|
| 120 |
-
dropout_p=self.attn_dropout if self.training else 0.0,
|
| 121 |
-
is_causal=True,
|
| 122 |
-
)
|
| 123 |
-
y = y.transpose(1, 2).contiguous().view(b, t, d)
|
| 124 |
-
return self.o_proj(y)
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
class LlamaDecoderLayer(nn.Module):
|
| 128 |
-
def __init__(self, cfg: ModelConfig):
|
| 129 |
-
super().__init__()
|
| 130 |
-
self.input_layernorm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 131 |
-
self.self_attn = LlamaAttention(cfg)
|
| 132 |
-
self.post_attention_layernorm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 133 |
-
self.mlp = LlamaMLP(cfg)
|
| 134 |
-
|
| 135 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 136 |
-
x = x + self.self_attn(self.input_layernorm(x))
|
| 137 |
-
x = x + self.mlp(self.post_attention_layernorm(x))
|
| 138 |
-
return x
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
class LlamaModel(nn.Module):
|
| 142 |
-
def __init__(self, cfg: ModelConfig):
|
| 143 |
-
super().__init__()
|
| 144 |
-
self.cfg = cfg
|
| 145 |
-
self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.hidden_size, padding_idx=cfg.pad_token_id)
|
| 146 |
-
self.layers = nn.ModuleList([LlamaDecoderLayer(cfg) for _ in range(cfg.num_hidden_layers)])
|
| 147 |
-
self.norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 148 |
-
|
| 149 |
-
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 150 |
-
x = self.embed_tokens(input_ids)
|
| 151 |
-
for layer in self.layers:
|
| 152 |
-
x = layer(x)
|
| 153 |
-
x = self.norm(x)
|
| 154 |
-
return x
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
class MonostichForCausalLM(nn.Module):
|
| 158 |
-
def __init__(self, cfg: ModelConfig):
|
| 159 |
-
super().__init__()
|
| 160 |
-
self.config = cfg
|
| 161 |
-
self.model = LlamaModel(cfg)
|
| 162 |
-
self.lm_head = nn.Linear(cfg.hidden_size, cfg.vocab_size, bias=False)
|
| 163 |
-
if cfg.tie_word_embeddings:
|
| 164 |
-
self.lm_head.weight = self.model.embed_tokens.weight
|
| 165 |
-
|
| 166 |
-
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 167 |
-
x = self.model(input_ids)
|
| 168 |
-
return self.lm_head(x)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
def _apply_repetition_penalty(logits: torch.Tensor, token_ids: list[int], penalty: float) -> torch.Tensor:
|
| 172 |
-
if penalty == 1.0 or not token_ids:
|
| 173 |
-
return logits
|
| 174 |
-
unique = torch.tensor(list(set(token_ids)), dtype=torch.long, device=logits.device)
|
| 175 |
-
score = logits[unique]
|
| 176 |
-
score = torch.where(score > 0, score / penalty, score * penalty)
|
| 177 |
-
logits[unique] = score
|
| 178 |
-
return logits
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def sample_next_id(logits: torch.Tensor, temperature: float, top_p: float, top_k: int, generator: torch.Generator) -> int:
|
| 182 |
-
if temperature <= 0:
|
| 183 |
-
return int(torch.argmax(logits).item())
|
| 184 |
-
logits = logits / float(temperature)
|
| 185 |
-
if top_k and top_k > 0:
|
| 186 |
-
v, ix = torch.topk(logits, k=int(top_k))
|
| 187 |
-
probs = torch.softmax(v, dim=-1)
|
| 188 |
-
idx = torch.multinomial(probs, num_samples=1, generator=generator).item()
|
| 189 |
-
return int(ix[idx].item())
|
| 190 |
-
probs = torch.softmax(logits, dim=-1)
|
| 191 |
-
if top_p >= 1.0:
|
| 192 |
-
return int(torch.multinomial(probs, num_samples=1, generator=generator).item())
|
| 193 |
-
sorted_probs, sorted_ix = torch.sort(probs, descending=True)
|
| 194 |
-
cdf = torch.cumsum(sorted_probs, dim=-1)
|
| 195 |
-
mask = cdf <= float(top_p)
|
| 196 |
-
mask[0] = True
|
| 197 |
-
filtered_probs = sorted_probs[mask]
|
| 198 |
-
filtered_ix = sorted_ix[mask]
|
| 199 |
-
filtered_probs = filtered_probs / filtered_probs.sum()
|
| 200 |
-
idx = torch.multinomial(filtered_probs, num_samples=1, generator=generator).item()
|
| 201 |
-
return int(filtered_ix[idx].item())
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
def _render_chat(messages: list[tuple[str, str]], add_generation_prompt: bool) -> str:
|
| 205 |
-
BOS, EOS = "<|bos|>", "<|eos|>"
|
| 206 |
-
START, END = "<|start_header_id|>", "<|end_header_id|>"
|
| 207 |
-
NL2 = "\n\n"
|
| 208 |
-
out = []
|
| 209 |
-
for role, content in messages:
|
| 210 |
-
r = (role or "").strip().lower()
|
| 211 |
-
if r not in {"user", "assistant"}:
|
| 212 |
-
continue
|
| 213 |
-
c = (content or "").strip()
|
| 214 |
-
if not c:
|
| 215 |
-
continue
|
| 216 |
-
if not out:
|
| 217 |
-
out.append(f"{BOS}{START}{r}{END}{NL2}{c}{EOS}")
|
| 218 |
-
else:
|
| 219 |
-
out.append(f"{START}{r}{END}{NL2}{c}{EOS}")
|
| 220 |
-
if add_generation_prompt:
|
| 221 |
-
out.append(f"{START}assistant{END}{NL2}")
|
| 222 |
-
return "".join(out)
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
REPO_ID = "kerzgrr/monostich"
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
def _download_file(filename: str) -> Path:
|
| 229 |
-
from huggingface_hub import hf_hub_download
|
| 230 |
-
return Path(hf_hub_download(repo_id=REPO_ID, filename=filename))
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
def main() -> int:
|
| 234 |
-
ap = argparse.ArgumentParser()
|
| 235 |
-
ap.add_argument("--prompt", default=None)
|
| 236 |
-
ap.add_argument("--max-new-tokens", type=int, default=None)
|
| 237 |
-
ap.add_argument("--temperature", type=float, default=0.28)
|
| 238 |
-
ap.add_argument("--top-p", type=float, default=0.95)
|
| 239 |
-
ap.add_argument("--top-k", type=int, default=0)
|
| 240 |
-
ap.add_argument("--repetition-penalty", type=float, default=1.2)
|
| 241 |
-
ap.add_argument("--seed", type=int, default=1234)
|
| 242 |
-
ap.add_argument("--device", default="cuda", choices=["cuda", "cpu"])
|
| 243 |
-
args = ap.parse_args()
|
| 244 |
-
|
| 245 |
-
print(f"Loading model from huggingface.co/{REPO_ID} ...", flush=True)
|
| 246 |
-
weights_path = _download_file("monostich.safetensors")
|
| 247 |
-
tok_path = _download_file("tokenizer.json")
|
| 248 |
-
cfg_path = _download_file("config.json")
|
| 249 |
-
|
| 250 |
-
torch.manual_seed(args.seed)
|
| 251 |
-
if args.device == "cuda":
|
| 252 |
-
torch.cuda.manual_seed_all(args.seed)
|
| 253 |
-
|
| 254 |
-
tok = Tokenizer.from_file(str(tok_path))
|
| 255 |
-
raw = json.loads(cfg_path.read_text(encoding="utf-8"))
|
| 256 |
-
cfg = ModelConfig(
|
| 257 |
-
vocab_size=int(raw["vocab_size"]),
|
| 258 |
-
hidden_size=int(raw["hidden_size"]),
|
| 259 |
-
intermediate_size=int(raw["intermediate_size"]),
|
| 260 |
-
num_hidden_layers=int(raw["num_hidden_layers"]),
|
| 261 |
-
num_attention_heads=int(raw["num_attention_heads"]),
|
| 262 |
-
num_key_value_heads=int(raw["num_key_value_heads"]),
|
| 263 |
-
rms_norm_eps=float(raw.get("rms_norm_eps", 1e-5)),
|
| 264 |
-
max_position_embeddings=int(raw.get("max_position_embeddings",
|
| 265 |
-
rope_theta=float(raw.get("rope_theta", 10000.0)),
|
| 266 |
-
attention_dropout=float(raw.get("attention_dropout", 0.0)),
|
| 267 |
-
attn_window=int(raw.get("attn_window", 0) or 0),
|
| 268 |
-
attn_block_size=int(raw.get("attn_block_size", 256) or 256),
|
| 269 |
-
tie_word_embeddings=bool(raw.get("tie_word_embeddings", True)),
|
| 270 |
-
pad_token_id=int(raw.get("pad_token_id", 0)),
|
| 271 |
-
bos_token_id=int(raw.get("bos_token_id", 2)),
|
| 272 |
-
eos_token_id=int(raw.get("eos_token_id", 3)),
|
| 273 |
-
)
|
| 274 |
-
|
| 275 |
-
device = torch.device(args.device)
|
| 276 |
-
dtype = torch.bfloat16
|
| 277 |
-
model = MonostichForCausalLM(cfg)
|
| 278 |
-
model.load_state_dict(load_file(str(weights_path)), strict=True)
|
| 279 |
-
model.to(device=device, dtype=dtype)
|
| 280 |
-
model.eval()
|
| 281 |
-
|
| 282 |
-
eos_id = cfg.eos_token_id
|
| 283 |
-
max_ctx = cfg.max_position_embeddings
|
| 284 |
-
g = torch.Generator(device=device)
|
| 285 |
-
g.manual_seed(args.seed)
|
| 286 |
-
max_new = args.max_new_tokens if args.max_new_tokens is not None else max_ctx
|
| 287 |
-
|
| 288 |
-
rep_pen = float(args.repetition_penalty)
|
| 289 |
-
|
| 290 |
-
def generate(prompt_ids: list[int], stream: bool = False) -> tuple[str, int]:
|
| 291 |
-
generated = list(prompt_ids)
|
| 292 |
-
out_ids = []
|
| 293 |
-
with torch.no_grad():
|
| 294 |
-
for _ in range(max_new):
|
| 295 |
-
ctx = generated[-max_ctx:]
|
| 296 |
-
x = torch.tensor(ctx, device=device, dtype=torch.long).unsqueeze(0)
|
| 297 |
-
with torch.autocast(device_type=str(device.type), dtype=dtype) if device.type == "cuda" else torch.no_grad():
|
| 298 |
-
logits = model(x)
|
| 299 |
-
next_logits = _apply_repetition_penalty(logits[0, -1, :].float(), generated, rep_pen)
|
| 300 |
-
next_id = sample_next_id(next_logits, args.temperature, args.top_p, args.top_k, g)
|
| 301 |
-
generated.append(next_id)
|
| 302 |
-
if next_id == eos_id:
|
| 303 |
-
break
|
| 304 |
-
out_ids.append(next_id)
|
| 305 |
-
if stream:
|
| 306 |
-
print(tok.decode([next_id], skip_special_tokens=False), end="", flush=True)
|
| 307 |
-
text = tok.decode(out_ids, skip_special_tokens=False)
|
| 308 |
-
if stream:
|
| 309 |
-
print()
|
| 310 |
-
return text, len(out_ids)
|
| 311 |
-
|
| 312 |
-
if args.prompt is not None:
|
| 313 |
-
hist = [("user", args.prompt)]
|
| 314 |
-
prompt_text = _render_chat(hist, add_generation_prompt=True)
|
| 315 |
-
enc = tok.encode(prompt_text, add_special_tokens=False)
|
| 316 |
-
text, _ = generate(list(enc.ids))
|
| 317 |
-
print(text)
|
| 318 |
-
return 0
|
| 319 |
-
|
| 320 |
-
print("Interactive chat. /exit to quit, /reset to clear history.", flush=True)
|
| 321 |
-
history: list[tuple[str, str]] = []
|
| 322 |
-
while True:
|
| 323 |
-
try:
|
| 324 |
-
user_input = input("user> ").strip()
|
| 325 |
-
except EOFError:
|
| 326 |
-
break
|
| 327 |
-
if not user_input:
|
| 328 |
-
continue
|
| 329 |
-
if user_input.lower() in ("/exit", "/quit"):
|
| 330 |
-
break
|
| 331 |
-
if user_input.lower() == "/reset":
|
| 332 |
-
history = []
|
| 333 |
-
continue
|
| 334 |
-
|
| 335 |
-
hist = history + [("user", user_input)]
|
| 336 |
-
prompt_text = _render_chat(hist, add_generation_prompt=True)
|
| 337 |
-
prompt_ids = list(tok.encode(prompt_text, add_special_tokens=False).ids)
|
| 338 |
-
while len(prompt_ids) >= max_ctx and len(hist) > 1:
|
| 339 |
-
hist = hist[1:]
|
| 340 |
-
if hist and hist[0][0] == "assistant":
|
| 341 |
-
hist = hist[1:]
|
| 342 |
-
prompt_text = _render_chat(hist, add_generation_prompt=True)
|
| 343 |
-
prompt_ids = list(tok.encode(prompt_text, add_special_tokens=False).ids)
|
| 344 |
-
|
| 345 |
-
print("assistant> ", end="", flush=True)
|
| 346 |
-
text, _ = generate(prompt_ids, stream=True)
|
| 347 |
-
history = hist + [("assistant", text)]
|
| 348 |
-
|
| 349 |
-
return 0
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
if __name__ == "__main__":
|
| 353 |
-
sys.exit(main())
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from safetensors.torch import load_file
|
| 14 |
+
from tokenizers import Tokenizer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class ModelConfig:
|
| 19 |
+
vocab_size: int = 32000
|
| 20 |
+
hidden_size: int = 768
|
| 21 |
+
intermediate_size: int = 2048
|
| 22 |
+
num_hidden_layers: int = 12
|
| 23 |
+
num_attention_heads: int = 12
|
| 24 |
+
num_key_value_heads: int = 4
|
| 25 |
+
rms_norm_eps: float = 1e-5
|
| 26 |
+
max_position_embeddings: int = 1024
|
| 27 |
+
rope_theta: float = 10000.0
|
| 28 |
+
attention_dropout: float = 0.0
|
| 29 |
+
attn_window: int = 0
|
| 30 |
+
attn_block_size: int = 256
|
| 31 |
+
initializer_range: float = 0.02
|
| 32 |
+
tie_word_embeddings: bool = True
|
| 33 |
+
pad_token_id: int = 0
|
| 34 |
+
bos_token_id: int = 2
|
| 35 |
+
eos_token_id: int = 3
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def head_dim(self) -> int:
|
| 39 |
+
return self.hidden_size // self.num_attention_heads
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class RMSNorm(nn.Module):
|
| 43 |
+
def __init__(self, dim: int, eps: float):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.eps = eps
|
| 46 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 47 |
+
|
| 48 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
orig_dtype = x.dtype
|
| 50 |
+
x = x.float()
|
| 51 |
+
var = x.pow(2).mean(dim=-1, keepdim=True)
|
| 52 |
+
x = x * torch.rsqrt(var + self.eps)
|
| 53 |
+
return (x.to(orig_dtype)) * self.weight
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class RotaryEmbedding(nn.Module):
|
| 57 |
+
def __init__(self, head_dim: int, max_pos: int, theta: float):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.head_dim = head_dim
|
| 60 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
|
| 61 |
+
t = torch.arange(max_pos, dtype=inv_freq.dtype)
|
| 62 |
+
freqs = torch.einsum("i,j->ij", t, inv_freq)
|
| 63 |
+
emb = torch.cat([freqs, freqs], dim=-1)
|
| 64 |
+
self.register_buffer("_cos", emb.cos(), persistent=False)
|
| 65 |
+
self.register_buffer("_sin", emb.sin(), persistent=False)
|
| 66 |
+
|
| 67 |
+
def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 68 |
+
b, h, t, hd = q.shape
|
| 69 |
+
cos = self._cos[:t].to(q.dtype).unsqueeze(0).unsqueeze(0)
|
| 70 |
+
sin = self._sin[:t].to(q.dtype).unsqueeze(0).unsqueeze(0)
|
| 71 |
+
|
| 72 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 73 |
+
x1 = x[..., : hd // 2]
|
| 74 |
+
x2 = x[..., hd // 2 :]
|
| 75 |
+
return torch.cat([-x2, x1], dim=-1)
|
| 76 |
+
|
| 77 |
+
q_out = (q * cos) + (rotate_half(q) * sin)
|
| 78 |
+
k_out = (k * cos) + (rotate_half(k) * sin)
|
| 79 |
+
return q_out, k_out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class LlamaMLP(nn.Module):
|
| 83 |
+
def __init__(self, cfg: ModelConfig):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.gate_proj = nn.Linear(cfg.hidden_size, cfg.intermediate_size, bias=False)
|
| 86 |
+
self.up_proj = nn.Linear(cfg.hidden_size, cfg.intermediate_size, bias=False)
|
| 87 |
+
self.down_proj = nn.Linear(cfg.intermediate_size, cfg.hidden_size, bias=False)
|
| 88 |
+
|
| 89 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 90 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class LlamaAttention(nn.Module):
|
| 94 |
+
def __init__(self, cfg: ModelConfig):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.cfg = cfg
|
| 97 |
+
self.num_heads = cfg.num_attention_heads
|
| 98 |
+
self.num_kv_heads = cfg.num_key_value_heads
|
| 99 |
+
self.head_dim = cfg.head_dim
|
| 100 |
+
self.kv_repeat = self.num_heads // self.num_kv_heads
|
| 101 |
+
self.q_proj = nn.Linear(cfg.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 102 |
+
self.k_proj = nn.Linear(cfg.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
|
| 103 |
+
self.v_proj = nn.Linear(cfg.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
|
| 104 |
+
self.o_proj = nn.Linear(cfg.hidden_size, cfg.hidden_size, bias=False)
|
| 105 |
+
self.rotary = RotaryEmbedding(self.head_dim, cfg.max_position_embeddings, cfg.rope_theta)
|
| 106 |
+
self.attn_dropout = float(cfg.attention_dropout)
|
| 107 |
+
|
| 108 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
b, t, d = x.shape
|
| 110 |
+
q = self.q_proj(x).view(b, t, self.num_heads, self.head_dim).transpose(1, 2)
|
| 111 |
+
k = self.k_proj(x).view(b, t, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 112 |
+
v = self.v_proj(x).view(b, t, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 113 |
+
q, k = self.rotary(q, k)
|
| 114 |
+
if self.kv_repeat != 1:
|
| 115 |
+
k = k.repeat_interleave(self.kv_repeat, dim=1)
|
| 116 |
+
v = v.repeat_interleave(self.kv_repeat, dim=1)
|
| 117 |
+
y = F.scaled_dot_product_attention(
|
| 118 |
+
q, k, v,
|
| 119 |
+
attn_mask=None,
|
| 120 |
+
dropout_p=self.attn_dropout if self.training else 0.0,
|
| 121 |
+
is_causal=True,
|
| 122 |
+
)
|
| 123 |
+
y = y.transpose(1, 2).contiguous().view(b, t, d)
|
| 124 |
+
return self.o_proj(y)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class LlamaDecoderLayer(nn.Module):
|
| 128 |
+
def __init__(self, cfg: ModelConfig):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.input_layernorm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 131 |
+
self.self_attn = LlamaAttention(cfg)
|
| 132 |
+
self.post_attention_layernorm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 133 |
+
self.mlp = LlamaMLP(cfg)
|
| 134 |
+
|
| 135 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 136 |
+
x = x + self.self_attn(self.input_layernorm(x))
|
| 137 |
+
x = x + self.mlp(self.post_attention_layernorm(x))
|
| 138 |
+
return x
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class LlamaModel(nn.Module):
|
| 142 |
+
def __init__(self, cfg: ModelConfig):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.cfg = cfg
|
| 145 |
+
self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.hidden_size, padding_idx=cfg.pad_token_id)
|
| 146 |
+
self.layers = nn.ModuleList([LlamaDecoderLayer(cfg) for _ in range(cfg.num_hidden_layers)])
|
| 147 |
+
self.norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 148 |
+
|
| 149 |
+
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 150 |
+
x = self.embed_tokens(input_ids)
|
| 151 |
+
for layer in self.layers:
|
| 152 |
+
x = layer(x)
|
| 153 |
+
x = self.norm(x)
|
| 154 |
+
return x
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class MonostichForCausalLM(nn.Module):
|
| 158 |
+
def __init__(self, cfg: ModelConfig):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.config = cfg
|
| 161 |
+
self.model = LlamaModel(cfg)
|
| 162 |
+
self.lm_head = nn.Linear(cfg.hidden_size, cfg.vocab_size, bias=False)
|
| 163 |
+
if cfg.tie_word_embeddings:
|
| 164 |
+
self.lm_head.weight = self.model.embed_tokens.weight
|
| 165 |
+
|
| 166 |
+
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 167 |
+
x = self.model(input_ids)
|
| 168 |
+
return self.lm_head(x)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _apply_repetition_penalty(logits: torch.Tensor, token_ids: list[int], penalty: float) -> torch.Tensor:
|
| 172 |
+
if penalty == 1.0 or not token_ids:
|
| 173 |
+
return logits
|
| 174 |
+
unique = torch.tensor(list(set(token_ids)), dtype=torch.long, device=logits.device)
|
| 175 |
+
score = logits[unique]
|
| 176 |
+
score = torch.where(score > 0, score / penalty, score * penalty)
|
| 177 |
+
logits[unique] = score
|
| 178 |
+
return logits
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def sample_next_id(logits: torch.Tensor, temperature: float, top_p: float, top_k: int, generator: torch.Generator) -> int:
|
| 182 |
+
if temperature <= 0:
|
| 183 |
+
return int(torch.argmax(logits).item())
|
| 184 |
+
logits = logits / float(temperature)
|
| 185 |
+
if top_k and top_k > 0:
|
| 186 |
+
v, ix = torch.topk(logits, k=int(top_k))
|
| 187 |
+
probs = torch.softmax(v, dim=-1)
|
| 188 |
+
idx = torch.multinomial(probs, num_samples=1, generator=generator).item()
|
| 189 |
+
return int(ix[idx].item())
|
| 190 |
+
probs = torch.softmax(logits, dim=-1)
|
| 191 |
+
if top_p >= 1.0:
|
| 192 |
+
return int(torch.multinomial(probs, num_samples=1, generator=generator).item())
|
| 193 |
+
sorted_probs, sorted_ix = torch.sort(probs, descending=True)
|
| 194 |
+
cdf = torch.cumsum(sorted_probs, dim=-1)
|
| 195 |
+
mask = cdf <= float(top_p)
|
| 196 |
+
mask[0] = True
|
| 197 |
+
filtered_probs = sorted_probs[mask]
|
| 198 |
+
filtered_ix = sorted_ix[mask]
|
| 199 |
+
filtered_probs = filtered_probs / filtered_probs.sum()
|
| 200 |
+
idx = torch.multinomial(filtered_probs, num_samples=1, generator=generator).item()
|
| 201 |
+
return int(filtered_ix[idx].item())
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _render_chat(messages: list[tuple[str, str]], add_generation_prompt: bool) -> str:
|
| 205 |
+
BOS, EOS = "<|bos|>", "<|eos|>"
|
| 206 |
+
START, END = "<|start_header_id|>", "<|end_header_id|>"
|
| 207 |
+
NL2 = "\n\n"
|
| 208 |
+
out = []
|
| 209 |
+
for role, content in messages:
|
| 210 |
+
r = (role or "").strip().lower()
|
| 211 |
+
if r not in {"user", "assistant"}:
|
| 212 |
+
continue
|
| 213 |
+
c = (content or "").strip()
|
| 214 |
+
if not c:
|
| 215 |
+
continue
|
| 216 |
+
if not out:
|
| 217 |
+
out.append(f"{BOS}{START}{r}{END}{NL2}{c}{EOS}")
|
| 218 |
+
else:
|
| 219 |
+
out.append(f"{START}{r}{END}{NL2}{c}{EOS}")
|
| 220 |
+
if add_generation_prompt:
|
| 221 |
+
out.append(f"{START}assistant{END}{NL2}")
|
| 222 |
+
return "".join(out)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
REPO_ID = "kerzgrr/monostich"
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _download_file(filename: str) -> Path:
|
| 229 |
+
from huggingface_hub import hf_hub_download
|
| 230 |
+
return Path(hf_hub_download(repo_id=REPO_ID, filename=filename))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def main() -> int:
|
| 234 |
+
ap = argparse.ArgumentParser()
|
| 235 |
+
ap.add_argument("--prompt", default=None)
|
| 236 |
+
ap.add_argument("--max-new-tokens", type=int, default=None)
|
| 237 |
+
ap.add_argument("--temperature", type=float, default=0.28)
|
| 238 |
+
ap.add_argument("--top-p", type=float, default=0.95)
|
| 239 |
+
ap.add_argument("--top-k", type=int, default=0)
|
| 240 |
+
ap.add_argument("--repetition-penalty", type=float, default=1.2)
|
| 241 |
+
ap.add_argument("--seed", type=int, default=1234)
|
| 242 |
+
ap.add_argument("--device", default="cuda", choices=["cuda", "cpu"])
|
| 243 |
+
args = ap.parse_args()
|
| 244 |
+
|
| 245 |
+
print(f"Loading model from huggingface.co/{REPO_ID} ...", flush=True)
|
| 246 |
+
weights_path = _download_file("monostich.safetensors")
|
| 247 |
+
tok_path = _download_file("tokenizer.json")
|
| 248 |
+
cfg_path = _download_file("config.json")
|
| 249 |
+
|
| 250 |
+
torch.manual_seed(args.seed)
|
| 251 |
+
if args.device == "cuda":
|
| 252 |
+
torch.cuda.manual_seed_all(args.seed)
|
| 253 |
+
|
| 254 |
+
tok = Tokenizer.from_file(str(tok_path))
|
| 255 |
+
raw = json.loads(cfg_path.read_text(encoding="utf-8"))
|
| 256 |
+
cfg = ModelConfig(
|
| 257 |
+
vocab_size=int(raw["vocab_size"]),
|
| 258 |
+
hidden_size=int(raw["hidden_size"]),
|
| 259 |
+
intermediate_size=int(raw["intermediate_size"]),
|
| 260 |
+
num_hidden_layers=int(raw["num_hidden_layers"]),
|
| 261 |
+
num_attention_heads=int(raw["num_attention_heads"]),
|
| 262 |
+
num_key_value_heads=int(raw["num_key_value_heads"]),
|
| 263 |
+
rms_norm_eps=float(raw.get("rms_norm_eps", 1e-5)),
|
| 264 |
+
max_position_embeddings=int(raw.get("max_position_embeddings", 1024)),
|
| 265 |
+
rope_theta=float(raw.get("rope_theta", 10000.0)),
|
| 266 |
+
attention_dropout=float(raw.get("attention_dropout", 0.0)),
|
| 267 |
+
attn_window=int(raw.get("attn_window", 0) or 0),
|
| 268 |
+
attn_block_size=int(raw.get("attn_block_size", 256) or 256),
|
| 269 |
+
tie_word_embeddings=bool(raw.get("tie_word_embeddings", True)),
|
| 270 |
+
pad_token_id=int(raw.get("pad_token_id", 0)),
|
| 271 |
+
bos_token_id=int(raw.get("bos_token_id", 2)),
|
| 272 |
+
eos_token_id=int(raw.get("eos_token_id", 3)),
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
device = torch.device(args.device)
|
| 276 |
+
dtype = torch.bfloat16
|
| 277 |
+
model = MonostichForCausalLM(cfg)
|
| 278 |
+
model.load_state_dict(load_file(str(weights_path)), strict=True)
|
| 279 |
+
model.to(device=device, dtype=dtype)
|
| 280 |
+
model.eval()
|
| 281 |
+
|
| 282 |
+
eos_id = cfg.eos_token_id
|
| 283 |
+
max_ctx = cfg.max_position_embeddings
|
| 284 |
+
g = torch.Generator(device=device)
|
| 285 |
+
g.manual_seed(args.seed)
|
| 286 |
+
max_new = args.max_new_tokens if args.max_new_tokens is not None else max_ctx
|
| 287 |
+
|
| 288 |
+
rep_pen = float(args.repetition_penalty)
|
| 289 |
+
|
| 290 |
+
def generate(prompt_ids: list[int], stream: bool = False) -> tuple[str, int]:
|
| 291 |
+
generated = list(prompt_ids)
|
| 292 |
+
out_ids = []
|
| 293 |
+
with torch.no_grad():
|
| 294 |
+
for _ in range(max_new):
|
| 295 |
+
ctx = generated[-max_ctx:]
|
| 296 |
+
x = torch.tensor(ctx, device=device, dtype=torch.long).unsqueeze(0)
|
| 297 |
+
with torch.autocast(device_type=str(device.type), dtype=dtype) if device.type == "cuda" else torch.no_grad():
|
| 298 |
+
logits = model(x)
|
| 299 |
+
next_logits = _apply_repetition_penalty(logits[0, -1, :].float(), generated, rep_pen)
|
| 300 |
+
next_id = sample_next_id(next_logits, args.temperature, args.top_p, args.top_k, g)
|
| 301 |
+
generated.append(next_id)
|
| 302 |
+
if next_id == eos_id:
|
| 303 |
+
break
|
| 304 |
+
out_ids.append(next_id)
|
| 305 |
+
if stream:
|
| 306 |
+
print(tok.decode([next_id], skip_special_tokens=False), end="", flush=True)
|
| 307 |
+
text = tok.decode(out_ids, skip_special_tokens=False)
|
| 308 |
+
if stream:
|
| 309 |
+
print()
|
| 310 |
+
return text, len(out_ids)
|
| 311 |
+
|
| 312 |
+
if args.prompt is not None:
|
| 313 |
+
hist = [("user", args.prompt)]
|
| 314 |
+
prompt_text = _render_chat(hist, add_generation_prompt=True)
|
| 315 |
+
enc = tok.encode(prompt_text, add_special_tokens=False)
|
| 316 |
+
text, _ = generate(list(enc.ids))
|
| 317 |
+
print(text)
|
| 318 |
+
return 0
|
| 319 |
+
|
| 320 |
+
print("Interactive chat. /exit to quit, /reset to clear history.", flush=True)
|
| 321 |
+
history: list[tuple[str, str]] = []
|
| 322 |
+
while True:
|
| 323 |
+
try:
|
| 324 |
+
user_input = input("user> ").strip()
|
| 325 |
+
except EOFError:
|
| 326 |
+
break
|
| 327 |
+
if not user_input:
|
| 328 |
+
continue
|
| 329 |
+
if user_input.lower() in ("/exit", "/quit"):
|
| 330 |
+
break
|
| 331 |
+
if user_input.lower() == "/reset":
|
| 332 |
+
history = []
|
| 333 |
+
continue
|
| 334 |
+
|
| 335 |
+
hist = history + [("user", user_input)]
|
| 336 |
+
prompt_text = _render_chat(hist, add_generation_prompt=True)
|
| 337 |
+
prompt_ids = list(tok.encode(prompt_text, add_special_tokens=False).ids)
|
| 338 |
+
while len(prompt_ids) >= max_ctx and len(hist) > 1:
|
| 339 |
+
hist = hist[1:]
|
| 340 |
+
if hist and hist[0][0] == "assistant":
|
| 341 |
+
hist = hist[1:]
|
| 342 |
+
prompt_text = _render_chat(hist, add_generation_prompt=True)
|
| 343 |
+
prompt_ids = list(tok.encode(prompt_text, add_special_tokens=False).ids)
|
| 344 |
+
|
| 345 |
+
print("assistant> ", end="", flush=True)
|
| 346 |
+
text, _ = generate(prompt_ids, stream=True)
|
| 347 |
+
history = hist + [("assistant", text)]
|
| 348 |
+
|
| 349 |
+
return 0
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
if __name__ == "__main__":
|
| 353 |
+
sys.exit(main())
|