Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,21 @@
|
|
| 1 |
"""
|
| 2 |
-
π§¬
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
import sys, os, signal, time, uuid
|
| 6 |
print(f"[BOOT] Python {sys.version}", flush=True)
|
| 7 |
|
| 8 |
-
# ββ
|
| 9 |
-
|
| 10 |
-
# ββ TriAttention νμ±ν μλ ββ
|
| 11 |
TRIATT_ENABLED = False
|
| 12 |
try:
|
| 13 |
import aither_kvcache
|
| 14 |
os.environ["VLLM_ATTENTION_BACKEND"] = "CUSTOM"
|
| 15 |
TRIATT_ENABLED = True
|
| 16 |
-
print("[TRIATT] aither-kvcache
|
| 17 |
except ImportError:
|
| 18 |
-
print("[TRIATT] aither-kvcache not
|
| 19 |
|
| 20 |
import base64, re, json
|
| 21 |
from typing import Generator, Optional
|
|
@@ -32,70 +32,51 @@ from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
|
|
| 32 |
from urllib.parse import urlencode
|
| 33 |
import pathlib, secrets
|
| 34 |
|
| 35 |
-
import urllib3
|
| 36 |
-
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 37 |
-
|
| 38 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
# 1. CONFIG
|
| 40 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
-
MODEL_ID = "
|
| 42 |
-
MODEL_NAME = "
|
| 43 |
MODEL_CAP = {
|
| 44 |
-
"arch": "
|
| 45 |
-
"ctx": "
|
| 46 |
-
"max_tokens":
|
| 47 |
}
|
| 48 |
|
| 49 |
PRESETS = {
|
| 50 |
-
"general": "You are
|
| 51 |
-
"code": "You are an expert software engineer. Write clean, efficient, well-commented code.
|
| 52 |
-
"math": "You are a world-class mathematician. Break problems step-by-step. Show full working.
|
| 53 |
-
"creative": "You are a brilliant creative writer. Be imaginative, vivid, and engaging.
|
| 54 |
-
"
|
| 55 |
-
"research": "You are a rigorous research analyst. Provide structured, well-reasoned analysis. Identify assumptions and acknowledge uncertainty.",
|
| 56 |
}
|
| 57 |
|
| 58 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
# 2. MTI β Minimal Test-Time Intervention (arxiv 2510.13940)
|
| 60 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 61 |
-
# νμ΅ μμ΄ μλΉ μ κ³ μνΈλ‘νΌ ν ν°μλ§ CFGλ₯Ό μ μ©νμ¬ μΆλ‘ μ νλ +9~11%.
|
| 62 |
-
# ν΅μ¬ λ°κ²¬: μΆλ‘ λΆνμ€μ±μ κ³ λλ‘ κ΅μν β μμ κ³ μνΈλ‘νΌ ν ν°λ§μ΄
|
| 63 |
-
# μΆλ ₯ μ νλμ κ²°μ μ μν₯. λλ¨Έμ§ ν ν°μ 건λλ¦¬μ§ μμ λΉμ© μ΅μ.
|
| 64 |
-
|
| 65 |
class MTILogitsProcessor:
|
| 66 |
"""
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
κ³ μνΈλ‘νΌ(λΆνμ€) ν ν°μμλ§ classifier-free guidanceλ₯Ό μ μ©:
|
| 70 |
-
- entropy > threshold β logitsλ₯Ό mean κΈ°μ€μΌλ‘ cfg_scaleλ§νΌ μ¦ν
|
| 71 |
-
- entropy <= threshold β logits κ·Έλλ‘ ν΅κ³Ό (λΉμ© 0)
|
| 72 |
-
|
| 73 |
-
ν¨κ³Ό: DeepSeek-R1-7B κΈ°μ€ 6κ° λ²€μΉλ§ν¬ νκ· +9.28%
|
| 74 |
-
λΉμ©: μ 체 ν ν° μ€ ~15%λ§ κ°μ
β μΆλ‘ μ€λ²ν€λ λ―Έλ―Έ
|
| 75 |
"""
|
| 76 |
def __init__(self, cfg_scale: float = 1.5, entropy_threshold: float = 2.0):
|
| 77 |
self.cfg_scale = cfg_scale
|
| 78 |
self.entropy_threshold = entropy_threshold
|
| 79 |
self._interventions = 0
|
| 80 |
self._total = 0
|
| 81 |
-
|
| 82 |
def __call__(self, token_ids, logits):
|
| 83 |
self._total += 1
|
| 84 |
-
|
| 85 |
-
# νμ¬ ν ν°μ μνΈλ‘νΌ κ³μ°
|
| 86 |
probs = torch.softmax(logits, dim=-1)
|
| 87 |
entropy = -(probs * torch.log(probs + 1e-10)).sum(dim=-1)
|
| 88 |
-
|
| 89 |
if entropy.item() > self.entropy_threshold:
|
| 90 |
-
# κ³ μνΈλ‘νΌ ν ν° β CFG κ°μ΄λ
|
| 91 |
-
# unconditional logitsλ₯Ό meanμΌλ‘ κ·Όμ¬ (KV μΊμ μ¬νμ©)
|
| 92 |
mean_logit = logits.mean(dim=-1, keepdim=True)
|
| 93 |
guided = logits + self.cfg_scale * (logits - mean_logit)
|
| 94 |
self._interventions += 1
|
| 95 |
return guided
|
| 96 |
-
|
| 97 |
return logits
|
| 98 |
-
|
| 99 |
@property
|
| 100 |
def intervention_rate(self):
|
| 101 |
return self._interventions / max(self._total, 1)
|
|
@@ -103,198 +84,88 @@ class MTILogitsProcessor:
|
|
| 103 |
print("[MTI] MTILogitsProcessor ready (cfg=1.5, threshold=2.0)", flush=True)
|
| 104 |
|
| 105 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 106 |
-
# 3. vLLM ENGINE β
|
| 107 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 108 |
from vllm.engine.arg_utils import EngineArgs
|
| 109 |
from vllm.engine.llm_engine import LLMEngine
|
| 110 |
from vllm import SamplingParams, TokensPrompt
|
| 111 |
from transformers import AutoTokenizer
|
| 112 |
-
from huggingface_hub import snapshot_download
|
| 113 |
|
| 114 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 115 |
print(f"[vLLM] Tokenizer loaded β", flush=True)
|
| 116 |
|
| 117 |
-
# ββ λͺ¨λΈ λ€μ΄λ‘λ (λ‘컬 볡μ¬, symlink μλ μ€μ νμΌ) ββ
|
| 118 |
-
print(f"[vLLM] Downloading {MODEL_ID} to /app/model ...", flush=True)
|
| 119 |
-
MODEL_PATH = snapshot_download(MODEL_ID, local_dir="/app/model")
|
| 120 |
-
print(f"[vLLM] Downloaded β {MODEL_PATH}", flush=True)
|
| 121 |
-
print(f"[vLLM] Files: {os.listdir(MODEL_PATH)[:15]}", flush=True)
|
| 122 |
-
|
| 123 |
-
_config_path = os.path.join(MODEL_PATH, "config.json")
|
| 124 |
-
try:
|
| 125 |
-
with open(_config_path) as f:
|
| 126 |
-
_config = json.load(f)
|
| 127 |
-
|
| 128 |
-
_orig_arch = _config.get("architectures", [])
|
| 129 |
-
|
| 130 |
-
# 1. ConditionalGeneration β CausalLM
|
| 131 |
-
if any("ConditionalGeneration" in a for a in _orig_arch):
|
| 132 |
-
_config["architectures"] = [a.replace("ConditionalGeneration", "CausalLM") for a in _orig_arch]
|
| 133 |
-
|
| 134 |
-
# 2. λ©ν°λͺ¨λ¬ μ€μ λΈλ‘λ§ μ κ±° (μ μ ν€λ 보쑴)
|
| 135 |
-
_mm_config_keys = ["vision_config", "video_config", "audio_config",
|
| 136 |
-
"visual_config", "video_processor_config",
|
| 137 |
-
"image_processor_config"]
|
| 138 |
-
_removed_keys = []
|
| 139 |
-
for key in list(_config.keys()):
|
| 140 |
-
if key in _mm_config_keys:
|
| 141 |
-
del _config[key]
|
| 142 |
-
_removed_keys.append(key)
|
| 143 |
-
|
| 144 |
-
# 3. auto_mapμμ λ©ν°λͺ¨λ¬ μ°Έμ‘°λ§ μ κ±° (AutoProcessor λ±μ μ μ§)
|
| 145 |
-
if "auto_map" in _config:
|
| 146 |
-
_auto = _config["auto_map"]
|
| 147 |
-
_mm_auto_keys = [k for k in _auto if k in ["AutoImageProcessor", "AutoVideoProcessor", "AutoFeatureExtractor"]]
|
| 148 |
-
for k in _mm_auto_keys:
|
| 149 |
-
del _auto[k]
|
| 150 |
-
_removed_keys.append(f"auto_map.{k}")
|
| 151 |
-
|
| 152 |
-
# 4. model_typeμ΄ λ©ν°λͺ¨λ¬μ κ°λ¦¬ν€λ©΄ ν
μ€νΈ μ μ©μΌλ‘
|
| 153 |
-
mt = _config.get("model_type", "")
|
| 154 |
-
if mt in ["qwen3_5_vl", "qwen2_vl", "qwen2_5_vl"]:
|
| 155 |
-
_config["model_type"] = mt.replace("_vl", "")
|
| 156 |
-
_removed_keys.append(f"model_type: {mt} β {_config['model_type']}")
|
| 157 |
-
|
| 158 |
-
with open(_config_path, "w") as f:
|
| 159 |
-
json.dump(_config, f, indent=2)
|
| 160 |
-
print(f"[vLLM] Config patched β {_config['architectures']}", flush=True)
|
| 161 |
-
if _removed_keys:
|
| 162 |
-
print(f"[vLLM] Removed MM keys: {_removed_keys}", flush=True)
|
| 163 |
-
|
| 164 |
-
# 5. preprocessor_config.json ν¨μΉ β video processor μ°Έμ‘° μ κ±°
|
| 165 |
-
_preproc_path = os.path.join(MODEL_PATH, "preprocessor_config.json")
|
| 166 |
-
if os.path.exists(_preproc_path):
|
| 167 |
-
try:
|
| 168 |
-
with open(_preproc_path) as f:
|
| 169 |
-
_preproc = json.load(f)
|
| 170 |
-
# video κ΄λ ¨ ν€ μ κ±°
|
| 171 |
-
_video_keys = [k for k in _preproc if "video" in k.lower()]
|
| 172 |
-
for k in _video_keys:
|
| 173 |
-
del _preproc[k]
|
| 174 |
-
_removed_keys.append(f"preproc.{k}")
|
| 175 |
-
# processor_classκ° λΉλμ€λ₯Ό μ°Έμ‘°νλ©΄ μ κ±°
|
| 176 |
-
if "processor_class" in _preproc:
|
| 177 |
-
_removed_keys.append(f"preproc.processor_class={_preproc['processor_class']}")
|
| 178 |
-
with open(_preproc_path, "w") as f:
|
| 179 |
-
json.dump(_preproc, f, indent=2)
|
| 180 |
-
print(f"[vLLM] preprocessor_config.json patched", flush=True)
|
| 181 |
-
except Exception as e:
|
| 182 |
-
print(f"[vLLM] preprocessor patch error: {e}", flush=True)
|
| 183 |
-
|
| 184 |
-
# video_preprocessor_config.jsonμ΄ μμΌλ©΄ μμ (μ΄κ±΄ νμ μμ)
|
| 185 |
-
_vidproc = os.path.join(MODEL_PATH, "video_preprocessor_config.json")
|
| 186 |
-
if os.path.exists(_vidproc):
|
| 187 |
-
os.remove(_vidproc)
|
| 188 |
-
print(f"[vLLM] Removed video_preprocessor_config.json", flush=True)
|
| 189 |
-
|
| 190 |
-
print(f"[vLLM] Preprocessor files handled", flush=True)
|
| 191 |
-
|
| 192 |
-
except Exception as e:
|
| 193 |
-
print(f"[vLLM] Config patch failed: {e} β proceeding with original", flush=True)
|
| 194 |
-
|
| 195 |
-
# ββ λ¨κ³μ μμ§ μ΄κΈ°ν: μ€ν¨ μ μ μ§μ fallback ββ
|
| 196 |
engine = None
|
| 197 |
-
MAX_MODEL_LEN = 32768
|
| 198 |
|
| 199 |
# μλ 1: TriAttention + 32K
|
| 200 |
if engine is None and TRIATT_ENABLED:
|
| 201 |
try:
|
| 202 |
-
print(f"[vLLM] Try 1: TriAttention +
|
| 203 |
-
|
| 204 |
-
model=
|
| 205 |
max_model_len=MAX_MODEL_LEN,
|
| 206 |
gpu_memory_utilization=0.92,
|
| 207 |
trust_remote_code=True,
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
print(f"[vLLM] β TriAttention engine ready
|
| 211 |
except Exception as e:
|
| 212 |
print(f"[vLLM] β TriAttention failed: {e}", flush=True)
|
| 213 |
os.environ.pop("VLLM_ATTENTION_BACKEND", None)
|
| 214 |
TRIATT_ENABLED = False
|
| 215 |
engine = None
|
| 216 |
|
| 217 |
-
# μλ 2: νμ€
|
| 218 |
if engine is None:
|
| 219 |
MAX_MODEL_LEN = 16384
|
| 220 |
try:
|
| 221 |
-
print(f"[vLLM] Try 2: Standard
|
| 222 |
-
|
| 223 |
-
model=
|
| 224 |
max_model_len=MAX_MODEL_LEN,
|
| 225 |
gpu_memory_utilization=0.92,
|
| 226 |
trust_remote_code=True,
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
print(f"[vLLM] β Standard engine ready
|
| 230 |
except Exception as e:
|
| 231 |
print(f"[vLLM] β 16K failed: {e}", flush=True)
|
| 232 |
engine = None
|
| 233 |
|
| 234 |
-
# μλ 3: μ΅μ
|
| 235 |
if engine is None:
|
| 236 |
MAX_MODEL_LEN = 8192
|
| 237 |
try:
|
| 238 |
-
print(f"[vLLM] Try 3: Minimal +
|
| 239 |
-
|
| 240 |
-
model=
|
| 241 |
max_model_len=MAX_MODEL_LEN,
|
| 242 |
gpu_memory_utilization=0.90,
|
| 243 |
trust_remote_code=True,
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
print(f"[vLLM] β Minimal engine ready
|
| 247 |
except Exception as e:
|
| 248 |
-
print(f"[vLLM] βββ All
|
| 249 |
sys.exit(1)
|
| 250 |
|
| 251 |
-
# max_tokens μ‘°μ
|
| 252 |
MODEL_CAP["max_tokens"] = min(MODEL_CAP["max_tokens"], MAX_MODEL_LEN)
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
print(f"[vLLM] Final: {attn_mode}, max_model_len={MAX_MODEL_LEN}, "
|
| 256 |
-
f"max_tokens={MODEL_CAP['max_tokens']}", flush=True)
|
| 257 |
|
| 258 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 259 |
-
# 4. THINKING MODE HELPERS
|
| 260 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 261 |
def parse_think_blocks(text: str) -> tuple[str, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
m = re.search(r"<think>(.*?)</think>\s*", text, re.DOTALL)
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
l = line.strip()
|
| 267 |
-
if not l: return True
|
| 268 |
-
think_starts = [
|
| 269 |
-
"The user", "the user", "This is", "this is", "I should", "I need to",
|
| 270 |
-
"Let me", "let me", "My task", "my task", "I'll ", "I will",
|
| 271 |
-
"Since ", "since ", "Now,", "now,", "So,", "so,", "First,", "first,",
|
| 272 |
-
"Okay", "okay", "Alright", "Hmm", "Wait", "Actually",
|
| 273 |
-
"The question", "the question", "The input", "the input",
|
| 274 |
-
"The request", "the request", "The prompt", "the prompt",
|
| 275 |
-
"Thinking Process", "Thinking process", "**Thinking",
|
| 276 |
-
"Step ", "step ", "Approach:", "Analysis:", "Reasoning:",
|
| 277 |
-
"1. **", "2. **", "3. **", "4. **", "5. **",
|
| 278 |
-
]
|
| 279 |
-
for s in think_starts:
|
| 280 |
-
if l.startswith(s): return True
|
| 281 |
-
if l.startswith(("- ", "* ", "β ")) and any(c.isascii() and c.isalpha() for c in l[:20]):
|
| 282 |
-
if not any(ord(c) > 0x1100 for c in l[:30]): return True
|
| 283 |
-
return False
|
| 284 |
-
|
| 285 |
-
def _split_thinking_answer(raw: str) -> tuple:
|
| 286 |
-
lines = raw.split("\n")
|
| 287 |
-
answer_start = -1
|
| 288 |
-
for i, line in enumerate(lines):
|
| 289 |
-
if not _is_thinking_line(line):
|
| 290 |
-
if any(ord(c) > 0x1100 for c in line.strip()[:10]):
|
| 291 |
-
answer_start = i; break
|
| 292 |
-
if i > 2 and not _is_thinking_line(line):
|
| 293 |
-
if all(not lines[j].strip() for j in range(max(0,i-2), i)):
|
| 294 |
-
answer_start = i; break
|
| 295 |
-
if answer_start > 0:
|
| 296 |
-
return "\n".join(lines[:answer_start]).strip(), "\n".join(lines[answer_start:]).strip()
|
| 297 |
-
return "", raw
|
| 298 |
|
| 299 |
def format_response(raw: str) -> str:
|
| 300 |
chain, answer = parse_think_blocks(raw)
|
|
@@ -303,30 +174,22 @@ def format_response(raw: str) -> str:
|
|
| 303 |
"<details>\n<summary>π§ Reasoning Chain β click to expand</summary>\n\n"
|
| 304 |
f"{chain}\n\n</details>\n\n{answer}"
|
| 305 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
if "<think>" in raw and "</think>" not in raw:
|
| 307 |
think_len = len(raw) - raw.index("<think>") - 7
|
| 308 |
-
return f"π§
|
| 309 |
-
first_line = raw.strip().split("\n")[0] if raw.strip() else ""
|
| 310 |
-
if _is_thinking_line(first_line) and len(raw) > 20:
|
| 311 |
-
thinking, answer = _split_thinking_answer(raw)
|
| 312 |
-
if thinking and answer:
|
| 313 |
-
return (
|
| 314 |
-
f"<details>\n<summary>π§ Reasoning Chain ({len(thinking)} chars)</summary>\n\n"
|
| 315 |
-
f"{thinking}\n\n</details>\n\n{answer}"
|
| 316 |
-
)
|
| 317 |
-
elif thinking and not answer:
|
| 318 |
-
return f"π§ Reasoning... ({len(raw)} chars)"
|
| 319 |
return raw
|
| 320 |
|
| 321 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 322 |
-
# 5. GENERATION β vLLM Engine +
|
| 323 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 324 |
def _engine_generate(prompt_text: str, params: SamplingParams, queue: Queue):
|
| 325 |
-
"""vLLM μμ§
|
| 326 |
try:
|
| 327 |
request_id = str(uuid.uuid4())
|
| 328 |
-
|
| 329 |
-
# ν ν¬λμ΄μ¦
|
| 330 |
token_ids = tokenizer.encode(prompt_text)
|
| 331 |
engine.add_request(request_id, TokensPrompt(prompt_token_ids=token_ids), params)
|
| 332 |
|
|
@@ -334,16 +197,13 @@ def _engine_generate(prompt_text: str, params: SamplingParams, queue: Queue):
|
|
| 334 |
while engine.has_unfinished_requests():
|
| 335 |
step_outputs = engine.step()
|
| 336 |
for output in step_outputs:
|
| 337 |
-
if output.finished:
|
| 338 |
-
text = output.outputs[0].text
|
| 339 |
-
if len(text) > prev_len:
|
| 340 |
-
queue.put(text[prev_len:])
|
| 341 |
-
queue.put(None)
|
| 342 |
-
return
|
| 343 |
text = output.outputs[0].text
|
| 344 |
if len(text) > prev_len:
|
| 345 |
queue.put(text[prev_len:])
|
| 346 |
prev_len = len(text)
|
|
|
|
|
|
|
|
|
|
| 347 |
|
| 348 |
queue.put(None)
|
| 349 |
except Exception as e:
|
|
@@ -352,20 +212,13 @@ def _engine_generate(prompt_text: str, params: SamplingParams, queue: Queue):
|
|
| 352 |
|
| 353 |
|
| 354 |
def generate_reply(
|
| 355 |
-
message
|
| 356 |
-
|
| 357 |
-
thinking_mode: str,
|
| 358 |
-
image_input,
|
| 359 |
-
system_prompt: str,
|
| 360 |
-
max_new_tokens: int,
|
| 361 |
-
temperature: float,
|
| 362 |
-
top_p: float,
|
| 363 |
) -> Generator[str, None, None]:
|
| 364 |
|
| 365 |
max_new_tokens = min(int(max_new_tokens), MODEL_CAP["max_tokens"])
|
| 366 |
temperature = min(float(temperature), MODEL_CAP["temp_max"])
|
| 367 |
|
| 368 |
-
# ββ λ©μμ§ κ΅¬μ± ββ
|
| 369 |
messages: list[dict] = []
|
| 370 |
if system_prompt.strip():
|
| 371 |
messages.append({"role": "system", "content": system_prompt.strip()})
|
|
@@ -383,17 +236,14 @@ def generate_reply(
|
|
| 383 |
_, clean = parse_think_blocks(text)
|
| 384 |
messages.append({"role":"assistant","content":clean})
|
| 385 |
else:
|
| 386 |
-
try:
|
| 387 |
-
|
| 388 |
-
except (IndexError, TypeError):
|
| 389 |
-
continue
|
| 390 |
def _txt(v):
|
| 391 |
if v is None: return None
|
| 392 |
if isinstance(v, list):
|
| 393 |
-
return " ".join(p.get("text","") for p in v
|
| 394 |
-
if isinstance(p,dict) and p.get("type")=="text")
|
| 395 |
return str(v)
|
| 396 |
-
ut = _txt(u)
|
| 397 |
if ut: messages.append({"role":"user","content":ut})
|
| 398 |
if at:
|
| 399 |
_, clean = parse_think_blocks(at)
|
|
@@ -401,7 +251,6 @@ def generate_reply(
|
|
| 401 |
|
| 402 |
messages.append({"role": "user", "content": message})
|
| 403 |
|
| 404 |
-
# ββ ν둬ννΈ κ΅¬μ± ββ
|
| 405 |
try:
|
| 406 |
prompt_text = tokenizer.apply_chat_template(
|
| 407 |
messages, tokenize=False, add_generation_prompt=True,
|
|
@@ -412,9 +261,8 @@ def generate_reply(
|
|
| 412 |
|
| 413 |
input_len = len(tokenizer.encode(prompt_text))
|
| 414 |
print(f"[GEN] tokens={input_len}, max_new={max_new_tokens}, "
|
| 415 |
-
f"temp={temperature}, MTI=on,
|
| 416 |
|
| 417 |
-
# ββ MTI LogitsProcessor + SamplingParams ββ
|
| 418 |
mti = MTILogitsProcessor(cfg_scale=1.5, entropy_threshold=2.0)
|
| 419 |
|
| 420 |
params = SamplingParams(
|
|
@@ -424,7 +272,6 @@ def generate_reply(
|
|
| 424 |
logits_processors=[mti],
|
| 425 |
)
|
| 426 |
|
| 427 |
-
# ββ vLLM μμ§ μ€νΈλ¦¬λ° ββ
|
| 428 |
queue = Queue()
|
| 429 |
thread = Thread(target=_engine_generate, args=(prompt_text, params, queue))
|
| 430 |
thread.start()
|
|
@@ -433,8 +280,7 @@ def generate_reply(
|
|
| 433 |
try:
|
| 434 |
while True:
|
| 435 |
chunk = queue.get(timeout=120)
|
| 436 |
-
if chunk is None:
|
| 437 |
-
break
|
| 438 |
output += chunk
|
| 439 |
yield format_response(output)
|
| 440 |
except Exception as e:
|
|
@@ -445,8 +291,8 @@ def generate_reply(
|
|
| 445 |
|
| 446 |
if output:
|
| 447 |
mti_rate = f"{mti.intervention_rate*100:.1f}%"
|
| 448 |
-
print(f"[GEN] Done β {len(output)} chars, MTI
|
| 449 |
-
f"({mti._interventions}/{mti._total}
|
| 450 |
yield format_response(output)
|
| 451 |
else:
|
| 452 |
yield "**β οΈ λͺ¨λΈμ΄ λΉ μλ΅μ λ°ννμ΅λλ€.** λ€μ μλν΄ μ£ΌμΈμ."
|
|
@@ -457,20 +303,17 @@ def generate_reply(
|
|
| 457 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 458 |
with gr.Blocks(title=MODEL_NAME) as gradio_demo:
|
| 459 |
thinking_toggle = gr.Radio(
|
| 460 |
-
choices=["β‘ Fast Mode
|
| 461 |
-
|
| 462 |
-
value="β‘ Fast Mode (direct answer)",
|
| 463 |
-
visible=False,
|
| 464 |
)
|
| 465 |
image_input = gr.Textbox(value="", visible=False)
|
| 466 |
system_prompt = gr.Textbox(value=PRESETS["general"], visible=False)
|
| 467 |
max_new_tokens = gr.Slider(minimum=64, maximum=MODEL_CAP["max_tokens"], value=4096, visible=False)
|
| 468 |
-
temperature = gr.Slider(minimum=0.0, maximum=
|
| 469 |
-
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.9,
|
| 470 |
|
| 471 |
gr.ChatInterface(
|
| 472 |
-
fn=generate_reply,
|
| 473 |
-
api_name="chat",
|
| 474 |
additional_inputs=[
|
| 475 |
thinking_toggle, image_input,
|
| 476 |
system_prompt, max_new_tokens, temperature, top_p,
|
|
@@ -478,7 +321,7 @@ with gr.Blocks(title=MODEL_NAME) as gradio_demo:
|
|
| 478 |
)
|
| 479 |
|
| 480 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 481 |
-
# 7. FASTAPI
|
| 482 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 483 |
fapp = FastAPI()
|
| 484 |
SESSIONS: dict[str, dict] = {}
|
|
@@ -488,17 +331,15 @@ CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "")
|
|
| 488 |
CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "")
|
| 489 |
SPACE_HOST = os.getenv("SPACE_HOST", "localhost:7860")
|
| 490 |
REDIRECT_URI = f"https://{SPACE_HOST}/login/callback"
|
| 491 |
-
|
| 492 |
-
print(f"[OAuth] CLIENT_ID set: {bool(CLIENT_ID)}")
|
| 493 |
-
print(f"[OAuth] SPACE_HOST: {SPACE_HOST}")
|
| 494 |
HF_AUTH_URL = "https://huggingface.co/oauth/authorize"
|
| 495 |
HF_TOKEN_URL = "https://huggingface.co/oauth/token"
|
| 496 |
HF_USER_URL = "https://huggingface.co/oauth/userinfo"
|
| 497 |
SCOPES = os.getenv("OAUTH_SCOPES", "openid profile")
|
| 498 |
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
def
|
|
|
|
| 502 |
sid = _sid(req)
|
| 503 |
return SESSIONS.get(sid) if sid else None
|
| 504 |
|
|
@@ -514,16 +355,14 @@ async def oauth_user(request: Request):
|
|
| 514 |
|
| 515 |
@fapp.get("/oauth/login")
|
| 516 |
async def oauth_login(request: Request):
|
| 517 |
-
if not CLIENT_ID:
|
| 518 |
-
return RedirectResponse("/?oauth_error=not_configured")
|
| 519 |
state = secrets.token_urlsafe(16)
|
| 520 |
params = {"response_type":"code","client_id":CLIENT_ID,"redirect_uri":REDIRECT_URI,"scope":SCOPES,"state":state}
|
| 521 |
return RedirectResponse(f"{HF_AUTH_URL}?{urlencode(params)}", status_code=302)
|
| 522 |
|
| 523 |
@fapp.get("/login/callback")
|
| 524 |
async def oauth_callback(code: str = "", error: str = "", state: str = ""):
|
| 525 |
-
if error or not code:
|
| 526 |
-
return RedirectResponse("/?auth_error=1")
|
| 527 |
basic = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
|
| 528 |
async with httpx.AsyncClient() as client:
|
| 529 |
tok = await client.post(HF_TOKEN_URL, data={"grant_type":"authorization_code","code":code,"redirect_uri":REDIRECT_URI},
|
|
@@ -557,13 +396,13 @@ async def oauth_logout(request: Request):
|
|
| 557 |
@fapp.get("/health")
|
| 558 |
async def health():
|
| 559 |
return {
|
| 560 |
-
"status": "ok",
|
| 561 |
-
"model": MODEL_ID,
|
| 562 |
"backend": "vLLM-Engine",
|
| 563 |
-
"
|
| 564 |
"mti": "enabled",
|
| 565 |
"max_tokens": MODEL_CAP["max_tokens"],
|
| 566 |
-
"max_model_len":
|
|
|
|
| 567 |
}
|
| 568 |
|
| 569 |
BRAVE_API_KEY = os.getenv("BRAVE_API_KEY", "")
|
|
@@ -572,18 +411,17 @@ BRAVE_API_KEY = os.getenv("BRAVE_API_KEY", "")
|
|
| 572 |
async def api_search(request: Request):
|
| 573 |
body = await request.json()
|
| 574 |
query = body.get("query", "").strip()
|
| 575 |
-
if not query: return JSONResponse({"error": "empty
|
| 576 |
-
if not BRAVE_API_KEY: return JSONResponse({"error": "
|
| 577 |
try:
|
| 578 |
r = requests.get("https://api.search.brave.com/res/v1/web/search",
|
| 579 |
headers={"X-Subscription-Token": BRAVE_API_KEY, "Accept": "application/json"},
|
| 580 |
params={"q": query, "count": 5}, timeout=10)
|
| 581 |
r.raise_for_status()
|
| 582 |
results = r.json().get("web", {}).get("results", [])
|
| 583 |
-
|
| 584 |
-
return JSONResponse({"results": items})
|
| 585 |
except Exception as e:
|
| 586 |
-
return JSONResponse({"error": str(e)},
|
| 587 |
|
| 588 |
@fapp.post("/api/extract-pdf")
|
| 589 |
async def api_extract_pdf(request: Request):
|
|
@@ -598,12 +436,10 @@ async def api_extract_pdf(request: Request):
|
|
| 598 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 599 |
for page in doc: text += page.get_text() + "\n"
|
| 600 |
except ImportError:
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
text = text.strip()[:8000]
|
| 604 |
-
return JSONResponse({"text": text, "chars": len(text)})
|
| 605 |
except Exception as e:
|
| 606 |
-
return JSONResponse({"error": str(e)},
|
| 607 |
|
| 608 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 609 |
# 8. MOUNT & RUN
|
|
@@ -611,13 +447,11 @@ async def api_extract_pdf(request: Request):
|
|
| 611 |
app = gr.mount_gradio_app(fapp, gradio_demo, path="/gradio")
|
| 612 |
|
| 613 |
def _shutdown(sig, frame):
|
| 614 |
-
print("[BOOT]
|
| 615 |
sys.exit(0)
|
| 616 |
-
|
| 617 |
signal.signal(signal.SIGTERM, _shutdown)
|
| 618 |
signal.signal(signal.SIGINT, _shutdown)
|
| 619 |
|
| 620 |
if __name__ == "__main__":
|
| 621 |
-
_attn
|
| 622 |
-
print(f"[BOOT] {MODEL_NAME} Β· vLLM Engine Β· BF16 Β· {_attn} Β· MTI Β· max_len={MAX_MODEL_LEN} Β· Ready", flush=True)
|
| 623 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
"""
|
| 2 |
+
𧬠Gemma 4 E4B β vLLM + MTI + TriAttention
|
| 3 |
+
Multimodal (Vision+Audio+Text) Β· Effective 4.5B Β· Apache 2.0
|
| 4 |
+
MTI: +9~11% reasoning accuracy (training-free)
|
| 5 |
+
TriAttention: ~10x KV cache compression
|
| 6 |
"""
|
| 7 |
import sys, os, signal, time, uuid
|
| 8 |
print(f"[BOOT] Python {sys.version}", flush=True)
|
| 9 |
|
| 10 |
+
# ββ TriAttention μλ ββ
|
|
|
|
|
|
|
| 11 |
TRIATT_ENABLED = False
|
| 12 |
try:
|
| 13 |
import aither_kvcache
|
| 14 |
os.environ["VLLM_ATTENTION_BACKEND"] = "CUSTOM"
|
| 15 |
TRIATT_ENABLED = True
|
| 16 |
+
print("[TRIATT] aither-kvcache β VLLM_ATTENTION_BACKEND=CUSTOM", flush=True)
|
| 17 |
except ImportError:
|
| 18 |
+
print("[TRIATT] aither-kvcache not found β standard attention", flush=True)
|
| 19 |
|
| 20 |
import base64, re, json
|
| 21 |
from typing import Generator, Optional
|
|
|
|
| 32 |
from urllib.parse import urlencode
|
| 33 |
import pathlib, secrets
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
# 1. CONFIG
|
| 37 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
+
MODEL_ID = "google/gemma-4-E4B-it"
|
| 39 |
+
MODEL_NAME = "Gemma-4-E4B"
|
| 40 |
MODEL_CAP = {
|
| 41 |
+
"arch": "Gemma4 PLE", "active": "4.5B", "total": "~8B",
|
| 42 |
+
"ctx": "128K", "thinking": True, "vision": True, "audio": True,
|
| 43 |
+
"max_tokens": 16384, "temp_max": 2.0,
|
| 44 |
}
|
| 45 |
|
| 46 |
PRESETS = {
|
| 47 |
+
"general": "You are Gemma 4 E4B, a highly capable multimodal AI. Think step by step for complex questions.",
|
| 48 |
+
"code": "You are an expert software engineer. Write clean, efficient, well-commented code.",
|
| 49 |
+
"math": "You are a world-class mathematician. Break problems step-by-step. Show full working.",
|
| 50 |
+
"creative": "You are a brilliant creative writer. Be imaginative, vivid, and engaging.",
|
| 51 |
+
"vision": "You are an expert at analyzing images. Describe what you see in detail, extract text, and answer questions about visual content.",
|
|
|
|
| 52 |
}
|
| 53 |
|
| 54 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 55 |
# 2. MTI β Minimal Test-Time Intervention (arxiv 2510.13940)
|
| 56 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
class MTILogitsProcessor:
|
| 58 |
"""
|
| 59 |
+
κ³ μνΈλ‘νΌ(λΆνμ€) ν ν°μλ§ CFG μ μ© β μΆλ‘ μ νλ +9~11%.
|
| 60 |
+
νμ΅ μμ΄ μλΉ μ μ μ©. μ 체 ν ν°μ ~15%μλ§ κ°μ
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
"""
|
| 62 |
def __init__(self, cfg_scale: float = 1.5, entropy_threshold: float = 2.0):
|
| 63 |
self.cfg_scale = cfg_scale
|
| 64 |
self.entropy_threshold = entropy_threshold
|
| 65 |
self._interventions = 0
|
| 66 |
self._total = 0
|
| 67 |
+
|
| 68 |
def __call__(self, token_ids, logits):
|
| 69 |
self._total += 1
|
|
|
|
|
|
|
| 70 |
probs = torch.softmax(logits, dim=-1)
|
| 71 |
entropy = -(probs * torch.log(probs + 1e-10)).sum(dim=-1)
|
| 72 |
+
|
| 73 |
if entropy.item() > self.entropy_threshold:
|
|
|
|
|
|
|
| 74 |
mean_logit = logits.mean(dim=-1, keepdim=True)
|
| 75 |
guided = logits + self.cfg_scale * (logits - mean_logit)
|
| 76 |
self._interventions += 1
|
| 77 |
return guided
|
|
|
|
| 78 |
return logits
|
| 79 |
+
|
| 80 |
@property
|
| 81 |
def intervention_rate(self):
|
| 82 |
return self._interventions / max(self._total, 1)
|
|
|
|
| 84 |
print("[MTI] MTILogitsProcessor ready (cfg=1.5, threshold=2.0)", flush=True)
|
| 85 |
|
| 86 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
+
# 3. vLLM ENGINE β Gemma 4 Day 0 μ§μ, ν¨μΉ λΆνμ
|
| 88 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
from vllm.engine.arg_utils import EngineArgs
|
| 90 |
from vllm.engine.llm_engine import LLMEngine
|
| 91 |
from vllm import SamplingParams, TokensPrompt
|
| 92 |
from transformers import AutoTokenizer
|
|
|
|
| 93 |
|
| 94 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 95 |
print(f"[vLLM] Tokenizer loaded β", flush=True)
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
engine = None
|
| 98 |
+
MAX_MODEL_LEN = 32768
|
| 99 |
|
| 100 |
# μλ 1: TriAttention + 32K
|
| 101 |
if engine is None and TRIATT_ENABLED:
|
| 102 |
try:
|
| 103 |
+
print(f"[vLLM] Try 1: TriAttention + {MAX_MODEL_LEN}", flush=True)
|
| 104 |
+
engine = LLMEngine.from_engine_args(EngineArgs(
|
| 105 |
+
model=MODEL_ID, dtype="bfloat16",
|
| 106 |
max_model_len=MAX_MODEL_LEN,
|
| 107 |
gpu_memory_utilization=0.92,
|
| 108 |
trust_remote_code=True,
|
| 109 |
+
limit_mm_per_prompt={"image": 0, "audio": 0},
|
| 110 |
+
))
|
| 111 |
+
print(f"[vLLM] β TriAttention engine ready", flush=True)
|
| 112 |
except Exception as e:
|
| 113 |
print(f"[vLLM] β TriAttention failed: {e}", flush=True)
|
| 114 |
os.environ.pop("VLLM_ATTENTION_BACKEND", None)
|
| 115 |
TRIATT_ENABLED = False
|
| 116 |
engine = None
|
| 117 |
|
| 118 |
+
# μλ 2: νμ€ + 16K
|
| 119 |
if engine is None:
|
| 120 |
MAX_MODEL_LEN = 16384
|
| 121 |
try:
|
| 122 |
+
print(f"[vLLM] Try 2: Standard + {MAX_MODEL_LEN}", flush=True)
|
| 123 |
+
engine = LLMEngine.from_engine_args(EngineArgs(
|
| 124 |
+
model=MODEL_ID, dtype="bfloat16",
|
| 125 |
max_model_len=MAX_MODEL_LEN,
|
| 126 |
gpu_memory_utilization=0.92,
|
| 127 |
trust_remote_code=True,
|
| 128 |
+
limit_mm_per_prompt={"image": 0, "audio": 0},
|
| 129 |
+
))
|
| 130 |
+
print(f"[vLLM] β Standard engine ready", flush=True)
|
| 131 |
except Exception as e:
|
| 132 |
print(f"[vLLM] β 16K failed: {e}", flush=True)
|
| 133 |
engine = None
|
| 134 |
|
| 135 |
+
# μλ 3: μ΅μ 8K
|
| 136 |
if engine is None:
|
| 137 |
MAX_MODEL_LEN = 8192
|
| 138 |
try:
|
| 139 |
+
print(f"[vLLM] Try 3: Minimal + {MAX_MODEL_LEN}", flush=True)
|
| 140 |
+
engine = LLMEngine.from_engine_args(EngineArgs(
|
| 141 |
+
model=MODEL_ID, dtype="bfloat16",
|
| 142 |
max_model_len=MAX_MODEL_LEN,
|
| 143 |
gpu_memory_utilization=0.90,
|
| 144 |
trust_remote_code=True,
|
| 145 |
+
limit_mm_per_prompt={"image": 0, "audio": 0},
|
| 146 |
+
))
|
| 147 |
+
print(f"[vLLM] β Minimal engine ready", flush=True)
|
| 148 |
except Exception as e:
|
| 149 |
+
print(f"[vLLM] βββ All failed: {e}", flush=True)
|
| 150 |
sys.exit(1)
|
| 151 |
|
|
|
|
| 152 |
MODEL_CAP["max_tokens"] = min(MODEL_CAP["max_tokens"], MAX_MODEL_LEN)
|
| 153 |
+
_attn = "TriAttention" if TRIATT_ENABLED else "Standard"
|
| 154 |
+
print(f"[vLLM] Final: {_attn}, max_len={MAX_MODEL_LEN}, max_tokens={MODEL_CAP['max_tokens']}", flush=True)
|
|
|
|
|
|
|
| 155 |
|
| 156 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 157 |
+
# 4. THINKING MODE HELPERS
|
| 158 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 159 |
def parse_think_blocks(text: str) -> tuple[str, str]:
|
| 160 |
+
# Gemma 4 thinking format: <|channel|>thought\n...<channel|>answer
|
| 161 |
+
m = re.search(r"<\|channel\|>thought\s*\n(.*?)<channel\|>", text, re.DOTALL)
|
| 162 |
+
if m:
|
| 163 |
+
return m.group(1).strip(), text[m.end():].strip()
|
| 164 |
+
# Fallback: <think>...</think>
|
| 165 |
m = re.search(r"<think>(.*?)</think>\s*", text, re.DOTALL)
|
| 166 |
+
if m:
|
| 167 |
+
return m.group(1).strip(), text[m.end():].strip()
|
| 168 |
+
return "", text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
def format_response(raw: str) -> str:
|
| 171 |
chain, answer = parse_think_blocks(raw)
|
|
|
|
| 174 |
"<details>\n<summary>π§ Reasoning Chain β click to expand</summary>\n\n"
|
| 175 |
f"{chain}\n\n</details>\n\n{answer}"
|
| 176 |
)
|
| 177 |
+
# Gemma 4 thinking in progress
|
| 178 |
+
if "<|channel|>thought" in raw and "<channel|>" not in raw:
|
| 179 |
+
think_len = len(raw) - raw.index("<|channel|>thought") - 18
|
| 180 |
+
return f"π§ Thinking... ({think_len} chars)"
|
| 181 |
if "<think>" in raw and "</think>" not in raw:
|
| 182 |
think_len = len(raw) - raw.index("<think>") - 7
|
| 183 |
+
return f"π§ Thinking... ({think_len} chars)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
return raw
|
| 185 |
|
| 186 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 187 |
+
# 5. GENERATION β vLLM Engine + MTI Streaming
|
| 188 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 189 |
def _engine_generate(prompt_text: str, params: SamplingParams, queue: Queue):
|
| 190 |
+
"""vLLM μμ§ μμ± + Queue μ€νΈλ¦¬λ°"""
|
| 191 |
try:
|
| 192 |
request_id = str(uuid.uuid4())
|
|
|
|
|
|
|
| 193 |
token_ids = tokenizer.encode(prompt_text)
|
| 194 |
engine.add_request(request_id, TokensPrompt(prompt_token_ids=token_ids), params)
|
| 195 |
|
|
|
|
| 197 |
while engine.has_unfinished_requests():
|
| 198 |
step_outputs = engine.step()
|
| 199 |
for output in step_outputs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
text = output.outputs[0].text
|
| 201 |
if len(text) > prev_len:
|
| 202 |
queue.put(text[prev_len:])
|
| 203 |
prev_len = len(text)
|
| 204 |
+
if output.finished:
|
| 205 |
+
queue.put(None)
|
| 206 |
+
return
|
| 207 |
|
| 208 |
queue.put(None)
|
| 209 |
except Exception as e:
|
|
|
|
| 212 |
|
| 213 |
|
| 214 |
def generate_reply(
|
| 215 |
+
message, history, thinking_mode, image_input,
|
| 216 |
+
system_prompt, max_new_tokens, temperature, top_p,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
) -> Generator[str, None, None]:
|
| 218 |
|
| 219 |
max_new_tokens = min(int(max_new_tokens), MODEL_CAP["max_tokens"])
|
| 220 |
temperature = min(float(temperature), MODEL_CAP["temp_max"])
|
| 221 |
|
|
|
|
| 222 |
messages: list[dict] = []
|
| 223 |
if system_prompt.strip():
|
| 224 |
messages.append({"role": "system", "content": system_prompt.strip()})
|
|
|
|
| 236 |
_, clean = parse_think_blocks(text)
|
| 237 |
messages.append({"role":"assistant","content":clean})
|
| 238 |
else:
|
| 239 |
+
try: u, a = (turn[0] or None), (turn[1] if len(turn)>1 else None)
|
| 240 |
+
except: continue
|
|
|
|
|
|
|
| 241 |
def _txt(v):
|
| 242 |
if v is None: return None
|
| 243 |
if isinstance(v, list):
|
| 244 |
+
return " ".join(p.get("text","") for p in v if isinstance(p,dict) and p.get("type")=="text")
|
|
|
|
| 245 |
return str(v)
|
| 246 |
+
ut, at = _txt(u), _txt(a)
|
| 247 |
if ut: messages.append({"role":"user","content":ut})
|
| 248 |
if at:
|
| 249 |
_, clean = parse_think_blocks(at)
|
|
|
|
| 251 |
|
| 252 |
messages.append({"role": "user", "content": message})
|
| 253 |
|
|
|
|
| 254 |
try:
|
| 255 |
prompt_text = tokenizer.apply_chat_template(
|
| 256 |
messages, tokenize=False, add_generation_prompt=True,
|
|
|
|
| 261 |
|
| 262 |
input_len = len(tokenizer.encode(prompt_text))
|
| 263 |
print(f"[GEN] tokens={input_len}, max_new={max_new_tokens}, "
|
| 264 |
+
f"temp={temperature}, MTI=on, Attn={_attn}", flush=True)
|
| 265 |
|
|
|
|
| 266 |
mti = MTILogitsProcessor(cfg_scale=1.5, entropy_threshold=2.0)
|
| 267 |
|
| 268 |
params = SamplingParams(
|
|
|
|
| 272 |
logits_processors=[mti],
|
| 273 |
)
|
| 274 |
|
|
|
|
| 275 |
queue = Queue()
|
| 276 |
thread = Thread(target=_engine_generate, args=(prompt_text, params, queue))
|
| 277 |
thread.start()
|
|
|
|
| 280 |
try:
|
| 281 |
while True:
|
| 282 |
chunk = queue.get(timeout=120)
|
| 283 |
+
if chunk is None: break
|
|
|
|
| 284 |
output += chunk
|
| 285 |
yield format_response(output)
|
| 286 |
except Exception as e:
|
|
|
|
| 291 |
|
| 292 |
if output:
|
| 293 |
mti_rate = f"{mti.intervention_rate*100:.1f}%"
|
| 294 |
+
print(f"[GEN] Done β {len(output)} chars, MTI={mti_rate} "
|
| 295 |
+
f"({mti._interventions}/{mti._total})", flush=True)
|
| 296 |
yield format_response(output)
|
| 297 |
else:
|
| 298 |
yield "**β οΈ λͺ¨λΈμ΄ λΉ μλ΅μ λ°ννμ΅λλ€.** λ€μ μλν΄ μ£ΌμΈμ."
|
|
|
|
| 303 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 304 |
with gr.Blocks(title=MODEL_NAME) as gradio_demo:
|
| 305 |
thinking_toggle = gr.Radio(
|
| 306 |
+
choices=["β‘ Fast Mode", "π§ Thinking Mode"],
|
| 307 |
+
value="β‘ Fast Mode", visible=False,
|
|
|
|
|
|
|
| 308 |
)
|
| 309 |
image_input = gr.Textbox(value="", visible=False)
|
| 310 |
system_prompt = gr.Textbox(value=PRESETS["general"], visible=False)
|
| 311 |
max_new_tokens = gr.Slider(minimum=64, maximum=MODEL_CAP["max_tokens"], value=4096, visible=False)
|
| 312 |
+
temperature = gr.Slider(minimum=0.0, maximum=2.0, value=0.6, visible=False)
|
| 313 |
+
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, visible=False)
|
| 314 |
|
| 315 |
gr.ChatInterface(
|
| 316 |
+
fn=generate_reply, api_name="chat",
|
|
|
|
| 317 |
additional_inputs=[
|
| 318 |
thinking_toggle, image_input,
|
| 319 |
system_prompt, max_new_tokens, temperature, top_p,
|
|
|
|
| 321 |
)
|
| 322 |
|
| 323 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 324 |
+
# 7. FASTAPI
|
| 325 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 326 |
fapp = FastAPI()
|
| 327 |
SESSIONS: dict[str, dict] = {}
|
|
|
|
| 331 |
CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "")
|
| 332 |
SPACE_HOST = os.getenv("SPACE_HOST", "localhost:7860")
|
| 333 |
REDIRECT_URI = f"https://{SPACE_HOST}/login/callback"
|
|
|
|
|
|
|
|
|
|
| 334 |
HF_AUTH_URL = "https://huggingface.co/oauth/authorize"
|
| 335 |
HF_TOKEN_URL = "https://huggingface.co/oauth/token"
|
| 336 |
HF_USER_URL = "https://huggingface.co/oauth/userinfo"
|
| 337 |
SCOPES = os.getenv("OAUTH_SCOPES", "openid profile")
|
| 338 |
|
| 339 |
+
print(f"[OAuth] CLIENT_ID={bool(CLIENT_ID)}, SPACE_HOST={SPACE_HOST}")
|
| 340 |
+
|
| 341 |
+
def _sid(req): return req.cookies.get("mc_session")
|
| 342 |
+
def _user(req):
|
| 343 |
sid = _sid(req)
|
| 344 |
return SESSIONS.get(sid) if sid else None
|
| 345 |
|
|
|
|
| 355 |
|
| 356 |
@fapp.get("/oauth/login")
|
| 357 |
async def oauth_login(request: Request):
|
| 358 |
+
if not CLIENT_ID: return RedirectResponse("/?oauth_error=not_configured")
|
|
|
|
| 359 |
state = secrets.token_urlsafe(16)
|
| 360 |
params = {"response_type":"code","client_id":CLIENT_ID,"redirect_uri":REDIRECT_URI,"scope":SCOPES,"state":state}
|
| 361 |
return RedirectResponse(f"{HF_AUTH_URL}?{urlencode(params)}", status_code=302)
|
| 362 |
|
| 363 |
@fapp.get("/login/callback")
|
| 364 |
async def oauth_callback(code: str = "", error: str = "", state: str = ""):
|
| 365 |
+
if error or not code: return RedirectResponse("/?auth_error=1")
|
|
|
|
| 366 |
basic = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
|
| 367 |
async with httpx.AsyncClient() as client:
|
| 368 |
tok = await client.post(HF_TOKEN_URL, data={"grant_type":"authorization_code","code":code,"redirect_uri":REDIRECT_URI},
|
|
|
|
| 396 |
@fapp.get("/health")
|
| 397 |
async def health():
|
| 398 |
return {
|
| 399 |
+
"status": "ok", "model": MODEL_ID,
|
|
|
|
| 400 |
"backend": "vLLM-Engine",
|
| 401 |
+
"attention": "TriAttention" if TRIATT_ENABLED else "Standard",
|
| 402 |
"mti": "enabled",
|
| 403 |
"max_tokens": MODEL_CAP["max_tokens"],
|
| 404 |
+
"max_model_len": MAX_MODEL_LEN,
|
| 405 |
+
"multimodal": "vision+audio",
|
| 406 |
}
|
| 407 |
|
| 408 |
BRAVE_API_KEY = os.getenv("BRAVE_API_KEY", "")
|
|
|
|
| 411 |
async def api_search(request: Request):
|
| 412 |
body = await request.json()
|
| 413 |
query = body.get("query", "").strip()
|
| 414 |
+
if not query: return JSONResponse({"error": "empty"}, 400)
|
| 415 |
+
if not BRAVE_API_KEY: return JSONResponse({"error": "no key"}, 500)
|
| 416 |
try:
|
| 417 |
r = requests.get("https://api.search.brave.com/res/v1/web/search",
|
| 418 |
headers={"X-Subscription-Token": BRAVE_API_KEY, "Accept": "application/json"},
|
| 419 |
params={"q": query, "count": 5}, timeout=10)
|
| 420 |
r.raise_for_status()
|
| 421 |
results = r.json().get("web", {}).get("results", [])
|
| 422 |
+
return JSONResponse({"results": [{"title":i.get("title",""),"desc":i.get("description",""),"url":i.get("url","")} for i in results[:5]]})
|
|
|
|
| 423 |
except Exception as e:
|
| 424 |
+
return JSONResponse({"error": str(e)}, 500)
|
| 425 |
|
| 426 |
@fapp.post("/api/extract-pdf")
|
| 427 |
async def api_extract_pdf(request: Request):
|
|
|
|
| 436 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 437 |
for page in doc: text += page.get_text() + "\n"
|
| 438 |
except ImportError:
|
| 439 |
+
text = pdf_bytes.decode("utf-8", errors="ignore")
|
| 440 |
+
return JSONResponse({"text": text.strip()[:8000], "chars": len(text)})
|
|
|
|
|
|
|
| 441 |
except Exception as e:
|
| 442 |
+
return JSONResponse({"error": str(e)}, 500)
|
| 443 |
|
| 444 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 445 |
# 8. MOUNT & RUN
|
|
|
|
| 447 |
app = gr.mount_gradio_app(fapp, gradio_demo, path="/gradio")
|
| 448 |
|
| 449 |
def _shutdown(sig, frame):
|
| 450 |
+
print("[BOOT] Shutdown", flush=True)
|
| 451 |
sys.exit(0)
|
|
|
|
| 452 |
signal.signal(signal.SIGTERM, _shutdown)
|
| 453 |
signal.signal(signal.SIGINT, _shutdown)
|
| 454 |
|
| 455 |
if __name__ == "__main__":
|
| 456 |
+
print(f"[BOOT] {MODEL_NAME} Β· vLLM Β· {_attn} Β· MTI Β· max_len={MAX_MODEL_LEN} Β· Ready", flush=True)
|
|
|
|
| 457 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|