Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,364 +1,386 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
# app.py β Chat inference for AGILLM2 (loads checkpoint from HF Hub)
|
| 3 |
-
# - Downloads final.pt from OpenTransformer/AGILLM2-fast-training
|
| 4 |
-
# -
|
| 5 |
-
# -
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
import torch
|
| 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 |
-
return
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def
|
| 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 |
-
self.
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
if
|
| 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 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
return logits
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
return logits
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
if
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
if
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# app.py β Chat inference for AGILLM2 (loads checkpoint from HF Hub)
|
| 3 |
+
# - Downloads final.pt (or chosen file) from OpenTransformer/AGILLM2-fast-training
|
| 4 |
+
# - Rebuilds your 5L-style AR model from checkpoint cfg
|
| 5 |
+
# - Qwen chat template for multi-turn
|
| 6 |
+
# - Auto-Gradio on Hugging Face Spaces; optional CLI locally
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
import os, sys, time, math, pathlib, argparse
|
| 10 |
+
from typing import Optional, Tuple, List, Dict, Any
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
from transformers import AutoTokenizer, logging as hf_log
|
| 18 |
+
import warnings
|
| 19 |
+
|
| 20 |
+
# βββββββββββ Quiet logs
|
| 21 |
+
hf_log.set_verbosity_error()
|
| 22 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 23 |
+
|
| 24 |
+
# βββββββββββ Config (env-overridable)
|
| 25 |
+
MODEL_REPO = os.getenv("MODEL_REPO", "OpenTransformer/AGILLM2-fast-training")
|
| 26 |
+
CKPT_NAME = os.getenv("CKPT_NAME", "final.pt") # e.g. "step04121612.pt"
|
| 27 |
+
TOKENIZER_ID = os.getenv("TOKENIZER_ID", "Qwen/Qwen3-235B-A22B-Thinking-2507")
|
| 28 |
+
|
| 29 |
+
# Device + TF32 policy (new API; harmless on CPU)
|
| 30 |
+
DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 31 |
+
if DEV.type == "cuda":
|
| 32 |
+
try:
|
| 33 |
+
torch.backends.cuda.matmul.fp32_precision = "high" # alt: "ieee"
|
| 34 |
+
except Exception:
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
# βββββββββββ Tokenizer
|
| 38 |
+
tok = AutoTokenizer.from_pretrained(TOKENIZER_ID, use_fast=True, trust_remote_code=True)
|
| 39 |
+
if tok.pad_token is None:
|
| 40 |
+
tok.add_special_tokens({"pad_token": "[PAD]"})
|
| 41 |
+
VOCAB = max(tok.get_vocab().values()) + 1
|
| 42 |
+
BLANK = tok.pad_token_id
|
| 43 |
+
EOS = tok.eos_token_id if tok.eos_token_id is not None else tok.sep_token_id
|
| 44 |
+
|
| 45 |
+
# βββββββββββ AMP helper
|
| 46 |
+
try:
|
| 47 |
+
from torch.amp import autocast as _ac, GradScaler # noqa
|
| 48 |
+
except Exception:
|
| 49 |
+
from torch.cuda.amp import autocast as _ac, GradScaler # noqa
|
| 50 |
+
|
| 51 |
+
def _supports_fp8() -> bool:
|
| 52 |
+
return hasattr(torch, "float8_e4m3fn")
|
| 53 |
+
|
| 54 |
+
def _auto_amp_dtype(prefer_fp8: bool = False):
|
| 55 |
+
if DEV.type != "cuda":
|
| 56 |
+
return torch.float32
|
| 57 |
+
if prefer_fp8 and _supports_fp8():
|
| 58 |
+
return torch.float8_e4m3fn
|
| 59 |
+
try:
|
| 60 |
+
if torch.cuda.is_bf16_supported():
|
| 61 |
+
return torch.bfloat16
|
| 62 |
+
return torch.float16
|
| 63 |
+
except Exception:
|
| 64 |
+
return torch.float16
|
| 65 |
+
|
| 66 |
+
def amp(enabled: bool, prefer_fp8: bool = False):
|
| 67 |
+
if not (enabled and DEV.type == "cuda"):
|
| 68 |
+
from contextlib import nullcontext
|
| 69 |
+
return nullcontext()
|
| 70 |
+
return _ac(device_type="cuda", dtype=_auto_amp_dtype(prefer_fp8=prefer_fp8))
|
| 71 |
+
|
| 72 |
+
# βββββββββββ ALiBi helpers
|
| 73 |
+
def _alibi_slopes(n_heads: int):
|
| 74 |
+
import math as _m
|
| 75 |
+
def pow2slopes(n):
|
| 76 |
+
start = 2 ** (-2 ** -(_m.log2(n) - 3))
|
| 77 |
+
ratio = start
|
| 78 |
+
return [start * (ratio ** i) for i in range(n)]
|
| 79 |
+
if _m.log2(n_heads).is_integer():
|
| 80 |
+
vals = pow2slopes(n_heads)
|
| 81 |
+
else:
|
| 82 |
+
closest = 2 ** _m.floor(_m.log2(n_heads))
|
| 83 |
+
vals = pow2slopes(closest)
|
| 84 |
+
extra = pow2slopes(2 * closest)
|
| 85 |
+
vals += extra[0::2][: n_heads - closest]
|
| 86 |
+
return torch.tensor(vals, device=DEV).view(1, n_heads, 1, 1)
|
| 87 |
+
|
| 88 |
+
def alibi_bias(n_heads: int, n_tokens: int):
|
| 89 |
+
i = torch.arange(n_tokens, device=DEV).view(1, 1, n_tokens, 1)
|
| 90 |
+
j = torch.arange(n_tokens, device=DEV).view(1, 1, 1, n_tokens)
|
| 91 |
+
dist = (j - i).clamp_min(0)
|
| 92 |
+
slopes = _alibi_slopes(n_heads)
|
| 93 |
+
return -slopes * dist
|
| 94 |
+
|
| 95 |
+
# βββββββββββ Model (5L core + AR head, matches your training)
|
| 96 |
+
class LowRankMHA(nn.Module):
|
| 97 |
+
def __init__(self, d: int, h: int, r: int, use_relpos: bool = True):
|
| 98 |
+
super().__init__()
|
| 99 |
+
assert d % h == 0, "d must be divisible by number of heads"
|
| 100 |
+
self.h, self.dk = h, d // h
|
| 101 |
+
self.use_relpos = use_relpos
|
| 102 |
+
self.q = nn.Linear(d, d, bias=False)
|
| 103 |
+
self.k = nn.Linear(d, d, bias=False)
|
| 104 |
+
self.v = nn.Linear(d, d, bias=False)
|
| 105 |
+
self.U = nn.Parameter(torch.randn(self.dk, r))
|
| 106 |
+
nn.init.orthogonal_(self.U)
|
| 107 |
+
self.proj = nn.Linear(h * r, d, bias=False)
|
| 108 |
+
self.drop = nn.Dropout(0.1)
|
| 109 |
+
|
| 110 |
+
def _proj(self, x):
|
| 111 |
+
B, N, _ = x.shape
|
| 112 |
+
return (x.view(B, N, self.h, self.dk).transpose(1, 2) @ self.U)
|
| 113 |
+
|
| 114 |
+
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None,
|
| 115 |
+
rel_bias_tokens: Optional[int] = None,
|
| 116 |
+
kv_cache: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 117 |
+
use_cache: bool = False):
|
| 118 |
+
q = self._proj(self.q(x))
|
| 119 |
+
k_new = self._proj(self.k(x))
|
| 120 |
+
v_new = self._proj(self.v(x))
|
| 121 |
+
if kv_cache is None:
|
| 122 |
+
k, v = k_new, v_new
|
| 123 |
+
else:
|
| 124 |
+
k, v = kv_cache
|
| 125 |
+
if use_cache:
|
| 126 |
+
k = torch.cat([k, k_new], dim=2)
|
| 127 |
+
v = torch.cat([v, v_new], dim=2)
|
| 128 |
+
att = (q @ k.transpose(-1, -2)) / math.sqrt(self.dk)
|
| 129 |
+
if q.size(2) == k.size(2):
|
| 130 |
+
if self.use_relpos and rel_bias_tokens is not None:
|
| 131 |
+
att = att + alibi_bias(self.h, rel_bias_tokens)
|
| 132 |
+
if mask is not None:
|
| 133 |
+
att = att + mask
|
| 134 |
+
z = (att.softmax(-1) @ v).transpose(1, 2)
|
| 135 |
+
z = z.reshape(x.size(0), x.size(1), -1)
|
| 136 |
+
out = self.drop(self.proj(z))
|
| 137 |
+
return (out, (k, v)) if use_cache else out
|
| 138 |
+
|
| 139 |
+
class Block(nn.Module):
|
| 140 |
+
def __init__(self, d: int, h: int, r: int):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 143 |
+
self.mha = LowRankMHA(d, h, r, use_relpos=True)
|
| 144 |
+
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.ReLU(), nn.Linear(4 * d, d))
|
| 145 |
+
|
| 146 |
+
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor],
|
| 147 |
+
kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 148 |
+
use_cache: bool = False):
|
| 149 |
+
n = x.size(1)
|
| 150 |
+
if use_cache:
|
| 151 |
+
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)
|
| 152 |
+
x = x + y
|
| 153 |
+
x = x + self.ff(self.ln2(x))
|
| 154 |
+
return x, new_kv
|
| 155 |
+
else:
|
| 156 |
+
x = x + self.mha(self.ln1(x), mask, rel_bias_tokens=n)
|
| 157 |
+
return x + self.ff(self.ln2(x))
|
| 158 |
+
|
| 159 |
+
class Encoder(nn.Module):
|
| 160 |
+
def __init__(self, cfg: Dict[str, int]):
|
| 161 |
+
super().__init__()
|
| 162 |
+
d, l, h, r = cfg["d"], cfg["layers"], cfg["heads"], cfg["rank"]
|
| 163 |
+
self.emb = nn.Embedding(VOCAB, d)
|
| 164 |
+
self.blocks = nn.ModuleList([Block(d, h, r) for _ in range(l)])
|
| 165 |
+
self.ln = nn.LayerNorm(d)
|
| 166 |
+
|
| 167 |
+
def forward(self, ids: torch.Tensor, mask: Optional[torch.Tensor],
|
| 168 |
+
kv_caches: Optional[List[Optional[Tuple[torch.Tensor, torch.Tensor]]]] = None,
|
| 169 |
+
use_cache: bool = False):
|
| 170 |
+
x = self.emb(ids)
|
| 171 |
+
if not use_cache:
|
| 172 |
+
for blk in self.blocks:
|
| 173 |
+
x = blk(x, mask)
|
| 174 |
+
return self.ln(x)
|
| 175 |
+
new_kvs: List[Tuple[torch.Tensor, torch.Tensor]] = []
|
| 176 |
+
for i, blk in enumerate(self.blocks):
|
| 177 |
+
kv = kv_caches[i] if (kv_caches is not None) else None
|
| 178 |
+
x, kv_out = blk(x, mask, kv, use_cache=True)
|
| 179 |
+
new_kvs.append(kv_out)
|
| 180 |
+
return self.ln(x), new_kvs
|
| 181 |
+
|
| 182 |
+
class ARHead(nn.Module):
|
| 183 |
+
def __init__(self, d):
|
| 184 |
+
super().__init__()
|
| 185 |
+
self.proj = nn.Linear(d, VOCAB)
|
| 186 |
+
def forward(self, h): return self.proj(h)
|
| 187 |
+
|
| 188 |
+
# βββββββββββ Misc
|
| 189 |
+
def causal_mask(n: int):
|
| 190 |
+
m = torch.full((1, 1, n, n), float("-inf"), device=DEV)
|
| 191 |
+
return torch.triu(m, 1)
|
| 192 |
+
|
| 193 |
+
def _resolve_cfg_from_ckpt(sd: dict) -> Dict[str, int]:
|
| 194 |
+
if isinstance(sd, dict) and "cfg" in sd and isinstance(sd["cfg"], dict):
|
| 195 |
+
return dict(sd["cfg"])
|
| 196 |
+
core = sd.get("core", {})
|
| 197 |
+
emb_w = core.get("emb.weight")
|
| 198 |
+
if emb_w is None:
|
| 199 |
+
raise RuntimeError("Checkpoint missing core.emb.weight; cannot infer d/l/h/r.")
|
| 200 |
+
d = emb_w.shape[1]
|
| 201 |
+
layer_ids = []
|
| 202 |
+
for k in core.keys():
|
| 203 |
+
if k.startswith("blocks."):
|
| 204 |
+
parts = k.split(".")
|
| 205 |
+
if len(parts) > 2 and parts[1].isdigit():
|
| 206 |
+
layer_ids.append(int(parts[1]))
|
| 207 |
+
layers = (max(layer_ids) + 1) if layer_ids else 0
|
| 208 |
+
U = core.get("blocks.0.mha.U")
|
| 209 |
+
if U is None:
|
| 210 |
+
raise RuntimeError("Checkpoint missing blocks.0.mha.U; cannot infer rank/heads.")
|
| 211 |
+
dk, r = U.shape
|
| 212 |
+
h = d // dk
|
| 213 |
+
return {"d": d, "layers": layers, "heads": h, "rank": r}
|
| 214 |
+
|
| 215 |
+
def load_joint_from_hub(repo_id: str, filename: str):
|
| 216 |
+
ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 217 |
+
sd = torch.load(ckpt_path, map_location="cpu")
|
| 218 |
+
cfg = _resolve_cfg_from_ckpt(sd)
|
| 219 |
+
core = Encoder(cfg).to(DEV)
|
| 220 |
+
ar_h = ARHead(cfg["d"]).to(DEV)
|
| 221 |
+
core.load_state_dict(sd["core"])
|
| 222 |
+
if "ar" in sd: ar_h.load_state_dict(sd["ar"])
|
| 223 |
+
core.eval(); ar_h.eval()
|
| 224 |
+
return core, ar_h, cfg
|
| 225 |
+
|
| 226 |
+
# βββββββββββ Chat helpers
|
| 227 |
+
def render_chat(messages: List[Dict[str, str]], add_generation_prompt: bool = True) -> str:
|
| 228 |
+
# messages: [{"role":"system/user/assistant","content": "..."}]
|
| 229 |
+
return tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=add_generation_prompt)
|
| 230 |
+
|
| 231 |
+
def _apply_no_repeat_ngram(logits: torch.Tensor, ids: torch.Tensor, n: int):
|
| 232 |
+
if n <= 0 or ids.size(1) < n - 1: return logits
|
| 233 |
+
prefix = ids[0, -(n - 1):].tolist()
|
| 234 |
+
banned, tokens = [], ids[0].tolist()
|
| 235 |
+
for i in range(len(tokens) - n + 1):
|
| 236 |
+
if tokens[i:i + n - 1] == prefix:
|
| 237 |
+
banned.append(tokens[i + n - 1])
|
| 238 |
+
if banned:
|
| 239 |
+
banned_idx = torch.tensor(banned, device=logits.device, dtype=torch.long)
|
| 240 |
+
logits[..., banned_idx] = float("-inf")
|
| 241 |
+
return logits
|
| 242 |
+
|
| 243 |
+
def _apply_rep_presence_frequency(logits, ids, last_n, repetition_penalty, presence_penalty, frequency_penalty):
|
| 244 |
+
if ids.numel() == 0: return logits
|
| 245 |
+
hist = ids[0, -last_n:].to(torch.long) if last_n > 0 else ids[0].to(torch.long)
|
| 246 |
+
if hist.numel() == 0: return logits
|
| 247 |
+
uniq, counts = torch.unique(hist, return_counts=True)
|
| 248 |
+
if presence_penalty != 0.0 or frequency_penalty != 0.0:
|
| 249 |
+
adjust = presence_penalty + frequency_penalty * counts.to(logits.dtype)
|
| 250 |
+
logits[..., uniq] = logits[..., uniq] - adjust
|
| 251 |
+
if repetition_penalty and abs(repetition_penalty - 1.0) > 1e-6:
|
| 252 |
+
sel = logits[..., uniq]
|
| 253 |
+
sel = torch.where(sel > 0, sel / repetition_penalty, sel * repetition_penalty)
|
| 254 |
+
logits[..., uniq] = sel
|
| 255 |
+
return logits
|
| 256 |
+
|
| 257 |
+
def _filter_top_k_top_p_min_p(logits: torch.Tensor, top_k: int, top_p: float, min_p: float, temperature: float):
|
| 258 |
+
logits = logits / max(temperature, 1e-8)
|
| 259 |
+
if logits.dim() == 1: logits = logits.unsqueeze(0)
|
| 260 |
+
probs = logits.softmax(-1)
|
| 261 |
+
V = probs.size(-1)
|
| 262 |
+
if top_k and top_k < V:
|
| 263 |
+
_, idx = torch.topk(probs, top_k, dim=-1)
|
| 264 |
+
mask = torch.full_like(probs, 0.0); mask.scatter_(1, idx, 1.0); probs = probs * mask
|
| 265 |
+
if top_p < 1.0:
|
| 266 |
+
sorted_probs, sorted_idx = torch.sort(probs, descending=True, dim=-1)
|
| 267 |
+
cumsum = torch.cumsum(sorted_probs, dim=-1)
|
| 268 |
+
keep = cumsum <= top_p; keep[..., 0] = True
|
| 269 |
+
mask = torch.zeros_like(probs); mask.scatter_(1, sorted_idx, keep.to(mask.dtype))
|
| 270 |
+
probs = probs * mask
|
| 271 |
+
if min_p > 0.0:
|
| 272 |
+
probs = torch.where(probs >= min_p, probs, torch.zeros_like(probs))
|
| 273 |
+
sums = probs.sum(-1, keepdim=True); empty = (sums == 0)
|
| 274 |
+
if empty.any():
|
| 275 |
+
fallback_idx = logits.argmax(-1, keepdim=True)
|
| 276 |
+
probs = torch.where(empty, torch.zeros_like(probs), probs)
|
| 277 |
+
probs.scatter_(-1, fallback_idx, torch.where(empty, torch.ones_like(sums), torch.zeros_like(sums)))
|
| 278 |
+
probs = probs / probs.sum(-1, keepdim=True)
|
| 279 |
+
return probs
|
| 280 |
+
|
| 281 |
+
@torch.no_grad()
|
| 282 |
+
def chat_decode(core, ar_h, messages: List[Dict[str, str]], max_new: int = 200, T: float = 0.9,
|
| 283 |
+
greedy: bool = False, top_k: int = 50, top_p: float = 0.9, min_p: float = 0.0,
|
| 284 |
+
repetition_penalty: float = 1.1, presence_penalty: float = 0.3, frequency_penalty: float = 0.2,
|
| 285 |
+
penalty_last_n: int = 128, no_repeat_ngram_size: int = 3,
|
| 286 |
+
use_fp8: bool = False, fp8_fallback: bool = True) -> str:
|
| 287 |
+
prompt = render_chat(messages, add_generation_prompt=True)
|
| 288 |
+
ids = torch.tensor([tok.encode(prompt)], device=DEV)
|
| 289 |
+
prompt_len = ids.size(1)
|
| 290 |
+
|
| 291 |
+
with amp(use_fp8 or False, prefer_fp8=(use_fp8 and (_supports_fp8() or fp8_fallback))):
|
| 292 |
+
h_full, kvs = core(ids, causal_mask(ids.size(1)), use_cache=True)
|
| 293 |
+
for _ in range(max_new):
|
| 294 |
+
logits = ar_h(h_full)[:, -1]
|
| 295 |
+
logits = _apply_no_repeat_ngram(logits, ids, no_repeat_ngram_size)
|
| 296 |
+
logits = _apply_rep_presence_frequency(logits, ids, penalty_last_n,
|
| 297 |
+
repetition_penalty, presence_penalty, frequency_penalty)
|
| 298 |
+
if greedy:
|
| 299 |
+
nxt = logits.argmax(-1, keepdim=True)
|
| 300 |
+
else:
|
| 301 |
+
probs = _filter_top_k_top_p_min_p(logits.squeeze(0), top_k, top_p, min_p, T)
|
| 302 |
+
nxt = probs.multinomial(1)
|
| 303 |
+
ids = torch.cat([ids, nxt.unsqueeze(0) if nxt.dim()==1 else nxt], 1)
|
| 304 |
+
x = ids[:, -1:]
|
| 305 |
+
h_full, kvs = core(x, None, kv_caches=kvs, use_cache=True)
|
| 306 |
+
|
| 307 |
+
full_ids = ids[0].tolist()
|
| 308 |
+
return tok.decode(full_ids[prompt_len:], skip_special_tokens=True).strip()
|
| 309 |
+
|
| 310 |
+
# βββββββββββ Entrypoint
|
| 311 |
+
def main():
|
| 312 |
+
ap = argparse.ArgumentParser()
|
| 313 |
+
ap.add_argument("--gradio", action="store_true", help="Launch a minimal Gradio chat UI")
|
| 314 |
+
ap.add_argument("--fp8-only", action="store_true")
|
| 315 |
+
ap.add_argument("--greedy", action="store_true")
|
| 316 |
+
ap.add_argument("--top_k", type=int, default=50)
|
| 317 |
+
ap.add_argument("--top_p", type=float, default=0.9)
|
| 318 |
+
ap.add_argument("--temperature", type=float, default=0.9)
|
| 319 |
+
ap.add_argument("--max_new", type=int, default=200)
|
| 320 |
+
args = ap.parse_args()
|
| 321 |
+
|
| 322 |
+
# Force Gradio on HF Spaces (stdin is unavailable there)
|
| 323 |
+
if os.getenv("SPACE_ID"):
|
| 324 |
+
args.gradio = True
|
| 325 |
+
|
| 326 |
+
print(f"[init] downloading checkpoint {CKPT_NAME} from {MODEL_REPO} β¦", flush=True)
|
| 327 |
+
core, ar_h, cfg = load_joint_from_hub(MODEL_REPO, CKPT_NAME)
|
| 328 |
+
print(f"[ready] cfg={cfg} device={DEV.type} vocab={VOCAB}")
|
| 329 |
+
|
| 330 |
+
if args.gradio:
|
| 331 |
+
import gradio as gr
|
| 332 |
+
with gr.Blocks() as demo:
|
| 333 |
+
gr.Markdown("### OpenTransformer / AGILLM2 β Chat")
|
| 334 |
+
chatbox = gr.Chatbot(height=520)
|
| 335 |
+
with gr.Row():
|
| 336 |
+
msg = gr.Textbox(placeholder="Type your messageβ¦", scale=8)
|
| 337 |
+
send = gr.Button("Send", variant="primary", scale=1)
|
| 338 |
+
clear = gr.Button("Clear", scale=1)
|
| 339 |
+
|
| 340 |
+
def _chat(history, user_msg):
|
| 341 |
+
if not user_msg:
|
| 342 |
+
return history, ""
|
| 343 |
+
messages = [{"role":"system","content":"You are a helpful, concise assistant."}]
|
| 344 |
+
for u,a in history or []:
|
| 345 |
+
messages.append({"role":"user","content":u})
|
| 346 |
+
messages.append({"role":"assistant","content":a})
|
| 347 |
+
messages.append({"role":"user","content":user_msg})
|
| 348 |
+
reply = chat_decode(core, ar_h, messages, max_new=args.max_new, T=args.temperature,
|
| 349 |
+
greedy=args.greedy, top_k=args.top_k, top_p=args.top_p,
|
| 350 |
+
use_fp8=args.fp8_only, fp8_fallback=True)
|
| 351 |
+
history = (history or []) + [(user_msg, reply)]
|
| 352 |
+
return history, ""
|
| 353 |
+
|
| 354 |
+
send.click(_chat, [chatbox, msg], [chatbox, msg], queue=False)
|
| 355 |
+
msg.submit(_chat, [chatbox, msg], [chatbox, msg], queue=False)
|
| 356 |
+
clear.click(lambda: None, None, chatbox, queue=False)
|
| 357 |
+
|
| 358 |
+
demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))
|
| 359 |
+
return
|
| 360 |
+
|
| 361 |
+
# Local-only CLI REPL
|
| 362 |
+
history: List[Tuple[str,str]] = []
|
| 363 |
+
print("Type to chat. Ctrl+C to exit.")
|
| 364 |
+
while True:
|
| 365 |
+
try:
|
| 366 |
+
user = input("\nYou: ").strip()
|
| 367 |
+
if not user:
|
| 368 |
+
continue
|
| 369 |
+
messages = [{"role":"system","content":"You are a helpful, concise assistant."}]
|
| 370 |
+
for u,a in history:
|
| 371 |
+
messages.append({"role":"user","content":u})
|
| 372 |
+
messages.append({"role":"assistant","content":a})
|
| 373 |
+
messages.append({"role":"user","content":user})
|
| 374 |
+
t0 = time.time()
|
| 375 |
+
reply = chat_decode(core, ar_h, messages, max_new=args.max_new, T=args.temperature,
|
| 376 |
+
greedy=args.greedy, top_k=args.top_k, top_p=args.top_p,
|
| 377 |
+
use_fp8=args.fp8_only, fp8_fallback=True)
|
| 378 |
+
dt = time.time() - t0
|
| 379 |
+
print(f"Bot: {reply}\n[{len(tok.encode(reply))} tok in {dt:.2f}s]")
|
| 380 |
+
history.append((user, reply))
|
| 381 |
+
except KeyboardInterrupt:
|
| 382 |
+
print("\nbye.")
|
| 383 |
+
break
|
| 384 |
+
|
| 385 |
+
if __name__ == "__main__":
|
| 386 |
+
main()
|