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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# app.py — AGILLM2 chat app for Hugging Face Spaces (single-file).
|
| 3 |
+
# Loads a torch .pt checkpoint from the Hub, rebuilds the tiny AR-only model,
|
| 4 |
+
# applies Qwen chat templating, and serves a Gradio chat UI with streaming.
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
import os, re, math, time, pathlib
|
| 8 |
+
from typing import List, Dict, Optional, Tuple, Any
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
import gradio as gr
|
| 15 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 16 |
+
from transformers import AutoTokenizer, logging as hf_log
|
| 17 |
+
|
| 18 |
+
# =============== Config ===============
|
| 19 |
+
REPO_ID = os.environ.get("REPO_ID", "OpenTransformer/AGILLM2-fast-training")
|
| 20 |
+
TOKENIZER_ID = os.environ.get("TOKENIZER_ID", "Qwen/Qwen3-235B-A22B-Thinking-2507")
|
| 21 |
+
SYSTEM_DEFAULT = os.environ.get("SYSTEM_PROMPT", "You are a concise, helpful assistant.")
|
| 22 |
+
# =====================================
|
| 23 |
+
|
| 24 |
+
hf_log.set_verbosity_error()
|
| 25 |
+
DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 26 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 27 |
+
try:
|
| 28 |
+
torch.set_float32_matmul_precision("high")
|
| 29 |
+
except Exception:
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
# -------- Tokenizer (same as training) --------
|
| 33 |
+
tok = AutoTokenizer.from_pretrained(TOKENIZER_ID, use_fast=True, trust_remote_code=True)
|
| 34 |
+
if tok.pad_token is None:
|
| 35 |
+
tok.add_special_tokens({"pad_token": "[PAD]"})
|
| 36 |
+
VOCAB = max(tok.get_vocab().values()) + 1
|
| 37 |
+
BLANK = tok.pad_token_id
|
| 38 |
+
EOS = tok.eos_token_id if tok.eos_token_id is not None else tok.sep_token_id
|
| 39 |
+
|
| 40 |
+
# -------- Tiny-arch presets (fallback only) --------
|
| 41 |
+
PRESETS = {
|
| 42 |
+
"small": dict(d=512, layers=8, heads=16, rank=64),
|
| 43 |
+
"smallx2": dict(d=512, layers=16, heads=16, rank=64),
|
| 44 |
+
"base": dict(d=768, layers=12, heads=24, rank=96),
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
# -------- AMP helper --------
|
| 48 |
+
try:
|
| 49 |
+
from torch.amp import autocast as _ac # noqa: F401
|
| 50 |
+
except ImportError:
|
| 51 |
+
from torch.cuda.amp import autocast as _ac # noqa: F401
|
| 52 |
+
|
| 53 |
+
def _auto_amp_dtype():
|
| 54 |
+
if DEV.type != "cuda":
|
| 55 |
+
return torch.float32
|
| 56 |
+
try:
|
| 57 |
+
return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 58 |
+
except Exception:
|
| 59 |
+
return torch.float16
|
| 60 |
+
|
| 61 |
+
def amp(enabled: bool):
|
| 62 |
+
if not (enabled and DEV.type == "cuda"):
|
| 63 |
+
from contextlib import nullcontext
|
| 64 |
+
return nullcontext()
|
| 65 |
+
return _ac(device_type="cuda", dtype=_auto_amp_dtype())
|
| 66 |
+
|
| 67 |
+
# -------- ALiBi --------
|
| 68 |
+
def _alibi_slopes(n_heads: int):
|
| 69 |
+
import math as _m
|
| 70 |
+
def pow2slopes(n):
|
| 71 |
+
start = 2 ** (-2 ** -(_m.log2(n) - 3))
|
| 72 |
+
ratio = start
|
| 73 |
+
return [start * (ratio ** i) for i in range(n)]
|
| 74 |
+
if _m.log2(n_heads).is_integer():
|
| 75 |
+
vals = pow2slopes(n_heads)
|
| 76 |
+
else:
|
| 77 |
+
closest = 2 ** _m.floor(_m.log2(n_heads))
|
| 78 |
+
vals = pow2slopes(closest)
|
| 79 |
+
extra = pow2slopes(2 * closest)
|
| 80 |
+
vals += extra[0::2][: n_heads - closest]
|
| 81 |
+
return torch.tensor(vals, device=DEV).view(1, n_heads, 1, 1)
|
| 82 |
+
|
| 83 |
+
def alibi_bias(n_heads: int, n_tokens: int):
|
| 84 |
+
i = torch.arange(n_tokens, device=DEV).view(1, 1, n_tokens, 1)
|
| 85 |
+
j = torch.arange(n_tokens, device=DEV).view(1, 1, 1, n_tokens)
|
| 86 |
+
dist = (j - i).clamp_min(0)
|
| 87 |
+
slopes = _alibi_slopes(n_heads)
|
| 88 |
+
return -slopes * dist
|
| 89 |
+
|
| 90 |
+
# -------- Model --------
|
| 91 |
+
class LowRankMHA(nn.Module):
|
| 92 |
+
def __init__(self, d: int, h: int, r: int, use_relpos: bool = True):
|
| 93 |
+
super().__init__()
|
| 94 |
+
assert d % h == 0, "d must be divisible by number of heads"
|
| 95 |
+
self.h, self.dk = h, d // h
|
| 96 |
+
self.use_relpos = use_relpos
|
| 97 |
+
self.q = nn.Linear(d, d, bias=False)
|
| 98 |
+
self.k = nn.Linear(d, d, bias=False)
|
| 99 |
+
self.v = nn.Linear(d, d, bias=False)
|
| 100 |
+
self.U = nn.Parameter(torch.randn(self.dk, r))
|
| 101 |
+
nn.init.orthogonal_(self.U)
|
| 102 |
+
self.proj = nn.Linear(h * r, d, bias=False)
|
| 103 |
+
self.drop = nn.Dropout(0.0)
|
| 104 |
+
|
| 105 |
+
def _proj(self, x):
|
| 106 |
+
B, N, _ = x.shape
|
| 107 |
+
return (x.view(B, N, self.h, self.dk).transpose(1, 2) @ self.U)
|
| 108 |
+
|
| 109 |
+
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None,
|
| 110 |
+
rel_bias_tokens: Optional[int] = None,
|
| 111 |
+
kv_cache: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 112 |
+
use_cache: bool = False):
|
| 113 |
+
q = self._proj(self.q(x))
|
| 114 |
+
k_new = self._proj(self.k(x))
|
| 115 |
+
v_new = self._proj(self.v(x))
|
| 116 |
+
|
| 117 |
+
if kv_cache is None:
|
| 118 |
+
k, v = k_new, v_new
|
| 119 |
+
else:
|
| 120 |
+
k, v = kv_cache
|
| 121 |
+
if use_cache:
|
| 122 |
+
k = torch.cat([k, k_new], dim=2)
|
| 123 |
+
v = torch.cat([v, v_new], dim=2)
|
| 124 |
+
|
| 125 |
+
att = (q @ k.transpose(-1, -2)) / math.sqrt(self.dk)
|
| 126 |
+
|
| 127 |
+
if q.size(2) == k.size(2):
|
| 128 |
+
if self.use_relpos and rel_bias_tokens is not None:
|
| 129 |
+
att = att + alibi_bias(self.h, rel_bias_tokens)
|
| 130 |
+
if mask is not None:
|
| 131 |
+
att = att + mask
|
| 132 |
+
|
| 133 |
+
z = (att.softmax(-1) @ v).transpose(1, 2)
|
| 134 |
+
z = z.reshape(x.size(0), x.size(1), -1)
|
| 135 |
+
out = self.drop(self.proj(z))
|
| 136 |
+
return (out, (k, v)) if use_cache else out
|
| 137 |
+
|
| 138 |
+
class Block(nn.Module):
|
| 139 |
+
def __init__(self, d: int, h: int, r: int):
|
| 140 |
+
super().__init__()
|
| 141 |
+
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 142 |
+
self.mha = LowRankMHA(d, h, r, use_relpos=True)
|
| 143 |
+
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.ReLU(), nn.Linear(4 * d, d))
|
| 144 |
+
|
| 145 |
+
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor],
|
| 146 |
+
kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 147 |
+
use_cache: bool = False):
|
| 148 |
+
n = x.size(1)
|
| 149 |
+
if use_cache:
|
| 150 |
+
y, new_kv = self.mha(self.ln1(x), mask,
|
| 151 |
+
rel_bias_tokens=n if mask is not None else None,
|
| 152 |
+
kv_cache=kv, use_cache=True)
|
| 153 |
+
x = x + y
|
| 154 |
+
x = x + self.ff(self.ln2(x))
|
| 155 |
+
return x, new_kv
|
| 156 |
+
else:
|
| 157 |
+
x = x + self.mha(self.ln1(x), mask, rel_bias_tokens=n)
|
| 158 |
+
return x + self.ff(self.ln2(x))
|
| 159 |
+
|
| 160 |
+
class Encoder(nn.Module):
|
| 161 |
+
def __init__(self, cfg: Dict[str, int]):
|
| 162 |
+
super().__init__()
|
| 163 |
+
d, l, h, r = cfg["d"], cfg["layers"], cfg["heads"], cfg["rank"]
|
| 164 |
+
self.emb = nn.Embedding(VOCAB, d)
|
| 165 |
+
self.blocks = nn.ModuleList([Block(d, h, r) for _ in range(l)])
|
| 166 |
+
self.ln = nn.LayerNorm(d)
|
| 167 |
+
|
| 168 |
+
def forward(self, ids: torch.Tensor, mask: Optional[torch.Tensor],
|
| 169 |
+
kv_caches: Optional[List[Optional[Tuple[torch.Tensor, torch.Tensor]]]] = None,
|
| 170 |
+
use_cache: bool = False):
|
| 171 |
+
x = self.emb(ids)
|
| 172 |
+
if not use_cache:
|
| 173 |
+
for blk in self.blocks:
|
| 174 |
+
x = blk(x, mask)
|
| 175 |
+
return self.ln(x)
|
| 176 |
+
new_kvs: List[Tuple[torch.Tensor, torch.Tensor]] = []
|
| 177 |
+
for i, blk in enumerate(self.blocks):
|
| 178 |
+
kv = kv_caches[i] if (kv_caches is not None) else None
|
| 179 |
+
x, kv_out = blk(x, mask, kv, use_cache=True)
|
| 180 |
+
new_kvs.append(kv_out)
|
| 181 |
+
return self.ln(x), new_kvs
|
| 182 |
+
|
| 183 |
+
class ARHead(nn.Module):
|
| 184 |
+
def __init__(self, d):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.proj = nn.Linear(d, VOCAB)
|
| 187 |
+
def forward(self, h): return self.proj(h)
|
| 188 |
+
|
| 189 |
+
def causal_mask(n):
|
| 190 |
+
m = torch.full((1, 1, n, n), float("-inf"), device=DEV)
|
| 191 |
+
return torch.triu(m, 1)
|
| 192 |
+
|
| 193 |
+
# -------- Checkpoint loading from Hub --------
|
| 194 |
+
def _try_load(path: pathlib.Path):
|
| 195 |
+
try:
|
| 196 |
+
return torch.load(path, map_location="cpu")
|
| 197 |
+
except Exception as e:
|
| 198 |
+
print(f"[ckpt] failed to load {path}: {e}")
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
def _prefer_ckpt(repo_id: str) -> pathlib.Path:
|
| 202 |
+
api = HfApi()
|
| 203 |
+
files = api.list_repo_files(repo_id=repo_id, repo_type="model")
|
| 204 |
+
if "final.pt" in files:
|
| 205 |
+
f = hf_hub_download(repo_id=repo_id, repo_type="model", filename="final.pt")
|
| 206 |
+
return pathlib.Path(f)
|
| 207 |
+
step_files = [f for f in files if re.match(r"step\d+\.pt$", f)]
|
| 208 |
+
if not step_files:
|
| 209 |
+
raise FileNotFoundError("No final.pt or step*.pt found in the repo.")
|
| 210 |
+
step_files.sort(key=lambda s: int(re.findall(r"\d+", s)[0]), reverse=True)
|
| 211 |
+
f = hf_hub_download(repo_id=repo_id, repo_type="model", filename=step_files[0])
|
| 212 |
+
return pathlib.Path(f)
|
| 213 |
+
|
| 214 |
+
def infer_cfg_from_ckpt_blob(sd: Dict[str, Any]) -> Optional[Dict[str, int]]:
|
| 215 |
+
if isinstance(sd, dict) and "cfg" in sd and isinstance(sd["cfg"], dict):
|
| 216 |
+
return dict(sd["cfg"])
|
| 217 |
+
core = sd.get("core") if isinstance(sd, dict) else None
|
| 218 |
+
if core is None: return None
|
| 219 |
+
emb_w = core.get("emb.weight")
|
| 220 |
+
if emb_w is None: return None
|
| 221 |
+
d = emb_w.shape[1]
|
| 222 |
+
layer_ids = []
|
| 223 |
+
for k in core.keys():
|
| 224 |
+
if k.startswith("blocks."):
|
| 225 |
+
parts = k.split(".")
|
| 226 |
+
if len(parts) > 2 and parts[1].isdigit():
|
| 227 |
+
layer_ids.append(int(parts[1]))
|
| 228 |
+
layers = (max(layer_ids) + 1) if layer_ids else None
|
| 229 |
+
U = core.get("blocks.0.mha.U")
|
| 230 |
+
heads = rank = None
|
| 231 |
+
if U is not None:
|
| 232 |
+
dk, r = U.shape
|
| 233 |
+
rank = r
|
| 234 |
+
heads = d // dk if dk > 0 else None
|
| 235 |
+
out = {"d": d}
|
| 236 |
+
if layers is not None: out["layers"] = layers
|
| 237 |
+
if heads is not None: out["heads"] = heads
|
| 238 |
+
if rank is not None: out["rank"] = rank
|
| 239 |
+
return out
|
| 240 |
+
|
| 241 |
+
def load_joint_from_hub(repo_id: str, fallback_preset: str = "smallx2"):
|
| 242 |
+
path = _prefer_ckpt(repo_id)
|
| 243 |
+
ck = _try_load(path)
|
| 244 |
+
if ck is None:
|
| 245 |
+
raise FileNotFoundError("Could not load checkpoint from Hub.")
|
| 246 |
+
cfg = infer_cfg_from_ckpt_blob(ck) or PRESETS[fallback_preset]
|
| 247 |
+
core = Encoder(cfg).to(DEV)
|
| 248 |
+
ar_h = ARHead(cfg["d"]).to(DEV)
|
| 249 |
+
core.load_state_dict(ck["core"])
|
| 250 |
+
if "ar" in ck:
|
| 251 |
+
ar_h.load_state_dict(ck["ar"])
|
| 252 |
+
core.eval(); ar_h.eval()
|
| 253 |
+
return core, ar_h, cfg
|
| 254 |
+
|
| 255 |
+
# -------- Sampling utils --------
|
| 256 |
+
def _apply_no_repeat_ngram(logits: torch.Tensor, ids: torch.Tensor, n: int):
|
| 257 |
+
if n <= 0 or ids.size(1) < n - 1:
|
| 258 |
+
return logits
|
| 259 |
+
prefix = ids[0, -(n - 1):].tolist()
|
| 260 |
+
banned = []
|
| 261 |
+
tokens = ids[0].tolist()
|
| 262 |
+
for i in range(len(tokens) - n + 1):
|
| 263 |
+
if tokens[i:i + n - 1] == prefix:
|
| 264 |
+
banned.append(tokens[i + n - 1])
|
| 265 |
+
if banned:
|
| 266 |
+
banned_idx = torch.tensor(banned, device=logits.device, dtype=torch.long)
|
| 267 |
+
logits[..., banned_idx] = float("-inf")
|
| 268 |
+
return logits
|
| 269 |
+
|
| 270 |
+
def _apply_rep_presence_frequency(
|
| 271 |
+
logits: torch.Tensor, ids: torch.Tensor, last_n: int,
|
| 272 |
+
repetition_penalty: float, presence_penalty: float, frequency_penalty: float
|
| 273 |
+
):
|
| 274 |
+
if ids.numel() == 0:
|
| 275 |
+
return logits
|
| 276 |
+
hist = ids[0, -last_n:].to(torch.long) if last_n > 0 else ids[0].to(torch.long)
|
| 277 |
+
if hist.numel() == 0:
|
| 278 |
+
return logits
|
| 279 |
+
uniq, counts = torch.unique(hist, return_counts=True)
|
| 280 |
+
if presence_penalty != 0.0 or frequency_penalty != 0.0:
|
| 281 |
+
adjust = presence_penalty + frequency_penalty * counts.to(logits.dtype)
|
| 282 |
+
logits[..., uniq] = logits[..., uniq] - adjust
|
| 283 |
+
if repetition_penalty and abs(repetition_penalty - 1.0) > 1e-6:
|
| 284 |
+
sel = logits[..., uniq]
|
| 285 |
+
sel = torch.where(sel > 0, sel / repetition_penalty, sel * repetition_penalty)
|
| 286 |
+
logits[..., uniq] = sel
|
| 287 |
+
return logits
|
| 288 |
+
|
| 289 |
+
def _filter_top_k_top_p_min_p(
|
| 290 |
+
logits: torch.Tensor, top_k: int, top_p: float, min_p: float, temperature: float
|
| 291 |
+
) -> torch.Tensor:
|
| 292 |
+
logits = logits / max(temperature, 1e-8)
|
| 293 |
+
if logits.dim() == 1:
|
| 294 |
+
logits = logits.unsqueeze(0)
|
| 295 |
+
probs = logits.softmax(-1)
|
| 296 |
+
|
| 297 |
+
V = probs.size(-1)
|
| 298 |
+
if top_k and top_k < V:
|
| 299 |
+
vals, idx = torch.topk(probs, top_k, dim=-1)
|
| 300 |
+
mask = torch.full_like(probs, 0.0)
|
| 301 |
+
mask.scatter_(1, idx, 1.0)
|
| 302 |
+
probs = probs * mask
|
| 303 |
+
|
| 304 |
+
if top_p < 1.0:
|
| 305 |
+
sorted_probs, sorted_idx = torch.sort(probs, descending=True, dim=-1)
|
| 306 |
+
cumsum = torch.cumsum(sorted_probs, dim=-1)
|
| 307 |
+
keep = cumsum <= top_p
|
| 308 |
+
keep[..., 0] = True
|
| 309 |
+
mask = torch.zeros_like(probs)
|
| 310 |
+
mask.scatter_(1, sorted_idx, keep.to(mask.dtype))
|
| 311 |
+
probs = probs * mask
|
| 312 |
+
|
| 313 |
+
if min_p > 0.0:
|
| 314 |
+
probs = torch.where(probs >= min_p, probs, torch.zeros_like(probs))
|
| 315 |
+
|
| 316 |
+
sums = probs.sum(-1, keepdim=True)
|
| 317 |
+
empty = (sums == 0)
|
| 318 |
+
if empty.any():
|
| 319 |
+
fallback_idx = logits.argmax(-1, keepdim=True)
|
| 320 |
+
probs = torch.where(empty, torch.zeros_like(probs), probs)
|
| 321 |
+
probs.scatter_(-1, fallback_idx, torch.where(empty, torch.ones_like(sums), torch.zeros_like(sums)))
|
| 322 |
+
|
| 323 |
+
probs = probs / probs.sum(-1, keepdim=True)
|
| 324 |
+
return probs
|
| 325 |
+
|
| 326 |
+
# -------- Chat generation (streaming) --------
|
| 327 |
+
@torch.no_grad()
|
| 328 |
+
def generate_stream(core, ar_h,
|
| 329 |
+
messages: List[Dict[str, str]],
|
| 330 |
+
max_new: int = 192,
|
| 331 |
+
temperature: float = 0.8,
|
| 332 |
+
top_k: int = 0,
|
| 333 |
+
top_p: float = 0.95,
|
| 334 |
+
min_p: float = 0.0,
|
| 335 |
+
repetition_penalty: float = 1.05,
|
| 336 |
+
presence_penalty: float = 0.0,
|
| 337 |
+
frequency_penalty: float = 0.0,
|
| 338 |
+
penalty_last_n: int = 64,
|
| 339 |
+
no_repeat_ngram_size: int = 0,
|
| 340 |
+
use_amp: bool = True):
|
| 341 |
+
# Use tokenizer chat template
|
| 342 |
+
try:
|
| 343 |
+
prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 344 |
+
except Exception:
|
| 345 |
+
# Fallback if someone breaks the template
|
| 346 |
+
parts = []
|
| 347 |
+
for m in messages:
|
| 348 |
+
r = m.get("role","user")
|
| 349 |
+
parts.append(("User: " if r=="user" else "Assistant: ") + str(m.get("content","")))
|
| 350 |
+
prompt = "\n".join(parts) + "\nAssistant:"
|
| 351 |
+
|
| 352 |
+
ids = torch.tensor([tok.encode(prompt)], device=DEV)
|
| 353 |
+
out_tokens: List[int] = []
|
| 354 |
+
text_last = ""
|
| 355 |
+
|
| 356 |
+
with amp(use_amp):
|
| 357 |
+
# Prime context
|
| 358 |
+
h_full, kvs = core(ids, causal_mask(ids.size(1)), use_cache=True)
|
| 359 |
+
for _ in range(max_new):
|
| 360 |
+
logits = ar_h(h_full)[:, -1]
|
| 361 |
+
logits = _apply_no_repeat_ngram(logits, ids, no_repeat_ngram_size)
|
| 362 |
+
logits = _apply_rep_presence_frequency(
|
| 363 |
+
logits, ids, penalty_last_n, repetition_penalty, presence_penalty, frequency_penalty
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
if temperature <= 1e-6 and top_k == 0 and top_p >= 1.0 and min_p <= 0.0:
|
| 367 |
+
nxt = logits.argmax(-1, keepdim=True)
|
| 368 |
+
else:
|
| 369 |
+
probs = _filter_top_k_top_p_min_p(logits.squeeze(0), top_k, top_p, min_p, temperature)
|
| 370 |
+
nxt = probs.multinomial(1)
|
| 371 |
+
|
| 372 |
+
token_id = int(nxt.item())
|
| 373 |
+
out_tokens.append(token_id)
|
| 374 |
+
ids = torch.cat([ids, nxt.unsqueeze(0) if nxt.dim()==1 else nxt], 1)
|
| 375 |
+
|
| 376 |
+
x = ids[:, -1:]
|
| 377 |
+
h_full, kvs = core(x, None, kv_caches=kvs, use_cache=True)
|
| 378 |
+
|
| 379 |
+
# Stream partial text
|
| 380 |
+
text_now = tok.decode(out_tokens, skip_special_tokens=True)
|
| 381 |
+
if text_now != text_last:
|
| 382 |
+
yield text_now
|
| 383 |
+
text_last = text_now
|
| 384 |
+
|
| 385 |
+
if token_id == EOS:
|
| 386 |
+
break
|
| 387 |
+
|
| 388 |
+
# ================== Load model once at app start ==================
|
| 389 |
+
core, ar_h, cfg = load_joint_from_hub(REPO_ID)
|
| 390 |
+
print(f"[ready] repo={REPO_ID} cfg={cfg} device={DEV}")
|
| 391 |
+
|
| 392 |
+
# ================== Gradio UI ==================
|
| 393 |
+
def chat_stream_ui(history, user, system,
|
| 394 |
+
temp, top_p, top_k, max_new,
|
| 395 |
+
rep_pen, pres_pen, freq_pen, ngram, last_n):
|
| 396 |
+
if not user or not user.strip():
|
| 397 |
+
return history, ""
|
| 398 |
+
# Convert history [(user, bot), ...] to messages
|
| 399 |
+
messages: List[Dict[str,str]] = [{"role":"system","content":system or SYSTEM_DEFAULT}]
|
| 400 |
+
for u, a in history:
|
| 401 |
+
if u: messages.append({"role":"user","content":u})
|
| 402 |
+
if a: messages.append({"role":"assistant","content":a})
|
| 403 |
+
messages.append({"role":"user","content":user})
|
| 404 |
+
|
| 405 |
+
# Start streaming
|
| 406 |
+
reply = ""
|
| 407 |
+
history = history + [(user, reply)]
|
| 408 |
+
gen_iter = generate_stream(core, ar_h, messages,
|
| 409 |
+
max_new=int(max_new),
|
| 410 |
+
temperature=float(temp),
|
| 411 |
+
top_k=int(top_k), top_p=float(top_p),
|
| 412 |
+
repetition_penalty=float(rep_pen),
|
| 413 |
+
presence_penalty=float(pres_pen),
|
| 414 |
+
frequency_penalty=float(freq_pen),
|
| 415 |
+
penalty_last_n=int(last_n),
|
| 416 |
+
no_repeat_ngram_size=int(ngram),
|
| 417 |
+
use_amp=True)
|
| 418 |
+
t0 = time.time()
|
| 419 |
+
for chunk in gen_iter:
|
| 420 |
+
reply = chunk
|
| 421 |
+
history[-1] = (user, reply)
|
| 422 |
+
yield history, ""
|
| 423 |
+
dt = time.time() - t0
|
| 424 |
+
print(f"[gen] {len(tok.encode(reply))} tok in {dt:.2f}s")
|
| 425 |
+
|
| 426 |
+
with gr.Blocks(fill_height=True) as demo:
|
| 427 |
+
gr.Markdown("## AGILLM2 Chat · OpenTransformer")
|
| 428 |
+
with gr.Row():
|
| 429 |
+
system = gr.Textbox(value=SYSTEM_DEFAULT, label="System prompt", lines=2)
|
| 430 |
+
chatbot = gr.Chatbot(height=480, type="tuple")
|
| 431 |
+
with gr.Row():
|
| 432 |
+
temp = gr.Slider(0.0, 1.5, value=0.8, step=0.05, label="Temperature")
|
| 433 |
+
top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.01, label="top_p")
|
| 434 |
+
top_k = gr.Slider(0, 200, value=0, step=1, label="top_k")
|
| 435 |
+
max_new = gr.Slider(16, 1024, value=256, step=8, label="Max new tokens")
|
| 436 |
+
with gr.Row():
|
| 437 |
+
rep_pen = gr.Slider(1.0, 1.5, value=1.05, step=0.01, label="Repetition penalty")
|
| 438 |
+
pres_pen = gr.Slider(0.0, 1.0, value=0.0, step=0.05, label="Presence penalty")
|
| 439 |
+
freq_pen = gr.Slider(0.0, 1.0, value=0.0, step=0.05, label="Frequency penalty")
|
| 440 |
+
ngram = gr.Slider(0, 6, value=0, step=1, label="No-repeat n-gram")
|
| 441 |
+
last_n = gr.Slider(16, 1024, value=64, step=16, label="Penalty last-N")
|
| 442 |
+
with gr.Row():
|
| 443 |
+
msg = gr.Textbox(placeholder="Type a message and press Enter", lines=2, scale=4)
|
| 444 |
+
with gr.Row():
|
| 445 |
+
send = gr.Button("Send", variant="primary")
|
| 446 |
+
clear = gr.Button("Clear history")
|
| 447 |
+
|
| 448 |
+
send.click(chat_stream_ui,
|
| 449 |
+
inputs=[chatbot, msg, system, temp, top_p, top_k, max_new, rep_pen, pres_pen, freq_pen, ngram, last_n],
|
| 450 |
+
outputs=[chatbot, msg],
|
| 451 |
+
queue=True)
|
| 452 |
+
msg.submit(chat_stream_ui,
|
| 453 |
+
inputs=[chatbot, msg, system, temp, top_p, top_k, max_new, rep_pen, pres_pen, freq_pen, ngram, last_n],
|
| 454 |
+
outputs=[chatbot, msg],
|
| 455 |
+
queue=True)
|
| 456 |
+
clear.click(lambda: [], None, chatbot, queue=False)
|
| 457 |
+
|
| 458 |
+
demo.queue(max_size=32).launch()
|