Commit
·
bf6d44e
1
Parent(s):
0e8e333
- hf_backend.py +84 -38
hf_backend.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# hf_backend.py
|
| 2 |
-
import time, logging
|
| 3 |
from contextlib import nullcontext
|
| 4 |
from typing import Any, Dict, AsyncIterable, Tuple
|
| 5 |
|
|
@@ -10,15 +10,30 @@ from config import settings
|
|
| 10 |
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
try:
|
| 14 |
import spaces
|
| 15 |
from spaces.zero import client as zero_client
|
| 16 |
except ImportError:
|
| 17 |
spaces, zero_client = None, None
|
| 18 |
|
| 19 |
-
#
|
| 20 |
MODEL_ID = settings.LlmHFModelID or "Qwen/Qwen2.5-1.5B-Instruct"
|
| 21 |
-
logger.info(f"
|
| 22 |
|
| 23 |
tokenizer, load_error = None, None
|
| 24 |
try:
|
|
@@ -27,36 +42,39 @@ try:
|
|
| 27 |
trust_remote_code=True,
|
| 28 |
use_fast=False,
|
| 29 |
)
|
|
|
|
|
|
|
| 30 |
except Exception as e:
|
| 31 |
load_error = f"Failed to load tokenizer: {e}"
|
| 32 |
logger.exception(load_error)
|
| 33 |
|
| 34 |
|
| 35 |
-
#
|
| 36 |
def _pick_cpu_dtype() -> torch.dtype:
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
logger.info("Falling back to torch.float32 on CPU")
|
| 45 |
return torch.float32
|
| 46 |
|
| 47 |
|
| 48 |
-
#
|
| 49 |
_MODEL_CACHE: Dict[tuple[str, torch.dtype], AutoModelForCausalLM] = {}
|
| 50 |
|
| 51 |
|
| 52 |
def _get_model(device: str, dtype: torch.dtype) -> Tuple[AutoModelForCausalLM, torch.dtype]:
|
| 53 |
key = (device, dtype)
|
| 54 |
if key in _MODEL_CACHE:
|
|
|
|
| 55 |
return _MODEL_CACHE[key], dtype
|
| 56 |
|
|
|
|
| 57 |
cfg = AutoConfig.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 58 |
if hasattr(cfg, "quantization_config"):
|
| 59 |
-
logger.warning("
|
| 60 |
delattr(cfg, "quantization_config")
|
| 61 |
|
| 62 |
eff_dtype = dtype
|
|
@@ -71,7 +89,7 @@ def _get_model(device: str, dtype: torch.dtype) -> Tuple[AutoModelForCausalLM, t
|
|
| 71 |
)
|
| 72 |
except Exception as e:
|
| 73 |
if device == "cpu" and dtype == torch.bfloat16:
|
| 74 |
-
logger.warning(f"BF16 load failed on CPU
|
| 75 |
eff_dtype = torch.float32
|
| 76 |
model = AutoModelForCausalLM.from_pretrained(
|
| 77 |
MODEL_ID,
|
|
@@ -82,92 +100,120 @@ def _get_model(device: str, dtype: torch.dtype) -> Tuple[AutoModelForCausalLM, t
|
|
| 82 |
low_cpu_mem_usage=False,
|
| 83 |
)
|
| 84 |
else:
|
|
|
|
| 85 |
raise
|
| 86 |
|
| 87 |
if device == "cpu":
|
|
|
|
| 88 |
model = model.to(device=device, dtype=eff_dtype)
|
| 89 |
else:
|
|
|
|
| 90 |
model = model.to(device=device)
|
| 91 |
|
| 92 |
model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
_MODEL_CACHE[(device, eff_dtype)] = model
|
| 94 |
return model, eff_dtype
|
| 95 |
|
| 96 |
|
| 97 |
-
#
|
| 98 |
class HFChatBackend(ChatBackend):
|
| 99 |
async def stream(self, request: Dict[str, Any]) -> AsyncIterable[Dict[str, Any]]:
|
| 100 |
if load_error:
|
| 101 |
raise RuntimeError(load_error)
|
| 102 |
|
| 103 |
messages = request.get("messages", [])
|
|
|
|
| 104 |
temperature = float(request.get("temperature", settings.LlmTemp or 0.7))
|
| 105 |
max_tokens = int(request.get("max_tokens", settings.LlmOpenAICtxSize or 512))
|
| 106 |
|
| 107 |
rid = f"chatcmpl-hf-{int(time.time())}"
|
| 108 |
now = int(time.time())
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
x_ip_token = request.get("x_ip_token")
|
| 111 |
if x_ip_token and zero_client:
|
| 112 |
zero_client.HEADERS["X-IP-Token"] = x_ip_token
|
| 113 |
-
logger.
|
| 114 |
|
|
|
|
| 115 |
if hasattr(tokenizer, "apply_chat_template") and getattr(tokenizer, "chat_template", None):
|
| 116 |
try:
|
| 117 |
prompt = tokenizer.apply_chat_template(
|
| 118 |
messages,
|
|
|
|
| 119 |
tokenize=False,
|
| 120 |
add_generation_prompt=True,
|
| 121 |
)
|
| 122 |
-
logger.
|
| 123 |
except Exception as e:
|
| 124 |
-
logger.warning(f"
|
| 125 |
prompt = messages[-1]["content"] if messages else "(empty)"
|
|
|
|
| 126 |
else:
|
| 127 |
prompt = messages[-1]["content"] if messages else "(empty)"
|
|
|
|
| 128 |
|
| 129 |
def _run_once(prompt: str, device: str, req_dtype: torch.dtype) -> str:
|
| 130 |
model, eff_dtype = _get_model(device, req_dtype)
|
| 131 |
|
| 132 |
inputs = tokenizer(prompt, return_tensors="pt")
|
|
|
|
|
|
|
|
|
|
| 133 |
inputs = {k: v.to(device) if hasattr(v, "to") else v for k, v in inputs.items()}
|
| 134 |
|
| 135 |
with torch.inference_mode():
|
| 136 |
if device != "cpu":
|
| 137 |
autocast_ctx = torch.autocast(device_type=device, dtype=eff_dtype)
|
| 138 |
else:
|
| 139 |
-
if eff_dtype == torch.bfloat16
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
with autocast_ctx:
|
| 145 |
-
outputs = model.generate(
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
do_sample=True,
|
| 150 |
-
use_cache=True,
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
# Slice: keep only newly generated tokens
|
| 154 |
-
input_len = inputs["input_ids"].shape[-1]
|
| 155 |
generated_ids = outputs[0][input_len:]
|
|
|
|
| 156 |
text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
|
|
|
| 157 |
return text
|
| 158 |
|
|
|
|
| 159 |
if spaces:
|
| 160 |
@spaces.GPU(duration=120)
|
| 161 |
def run_once(prompt: str) -> str:
|
| 162 |
if torch.cuda.is_available():
|
|
|
|
| 163 |
return _run_once(prompt, device="cuda", req_dtype=torch.float16)
|
|
|
|
| 164 |
return _run_once(prompt, device="cpu", req_dtype=_pick_cpu_dtype())
|
| 165 |
|
| 166 |
text = run_once(prompt)
|
| 167 |
else:
|
|
|
|
| 168 |
text = _run_once(prompt, device="cpu", req_dtype=_pick_cpu_dtype())
|
| 169 |
|
| 170 |
-
|
|
|
|
| 171 |
"id": rid,
|
| 172 |
"object": "chat.completion.chunk",
|
| 173 |
"created": now,
|
|
@@ -176,12 +222,12 @@ class HFChatBackend(ChatBackend):
|
|
| 176 |
{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": "stop"}
|
| 177 |
],
|
| 178 |
}
|
|
|
|
|
|
|
| 179 |
|
| 180 |
|
| 181 |
-
#
|
| 182 |
class StubImagesBackend(ImagesBackend):
|
| 183 |
async def generate_b64(self, request: Dict[str, Any]) -> str:
|
| 184 |
logger.warning("Image generation not supported in HF backend.")
|
| 185 |
-
return
|
| 186 |
-
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP4BwQACfsD/etCJH0AAAAASUVORK5CYII="
|
| 187 |
-
)
|
|
|
|
| 1 |
# hf_backend.py
|
| 2 |
+
import time, logging, json
|
| 3 |
from contextlib import nullcontext
|
| 4 |
from typing import Any, Dict, AsyncIterable, Tuple
|
| 5 |
|
|
|
|
| 10 |
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
+
# ---------- logging helpers ----------
|
| 14 |
+
def _snippet(txt: str, n: int = 800) -> str:
|
| 15 |
+
if not isinstance(txt, str):
|
| 16 |
+
return f"<non-str:{type(txt)}>"
|
| 17 |
+
return txt if len(txt) <= n else txt[:n] + f"... <+{len(txt)-n} chars>"
|
| 18 |
+
|
| 19 |
+
def _json_snippet(obj: Any, n: int = 800) -> str:
|
| 20 |
+
try:
|
| 21 |
+
s = json.dumps(obj, ensure_ascii=False, indent=2)
|
| 22 |
+
except Exception:
|
| 23 |
+
s = str(obj)
|
| 24 |
+
return _snippet(s, n)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------- HF Spaces imports ----------
|
| 28 |
try:
|
| 29 |
import spaces
|
| 30 |
from spaces.zero import client as zero_client
|
| 31 |
except ImportError:
|
| 32 |
spaces, zero_client = None, None
|
| 33 |
|
| 34 |
+
# ---------- Model setup ----------
|
| 35 |
MODEL_ID = settings.LlmHFModelID or "Qwen/Qwen2.5-1.5B-Instruct"
|
| 36 |
+
logger.info(f"[init] MODEL_ID={MODEL_ID}")
|
| 37 |
|
| 38 |
tokenizer, load_error = None, None
|
| 39 |
try:
|
|
|
|
| 42 |
trust_remote_code=True,
|
| 43 |
use_fast=False,
|
| 44 |
)
|
| 45 |
+
has_template = hasattr(tokenizer, "apply_chat_template") and getattr(tokenizer, "chat_template", None)
|
| 46 |
+
logger.info(f"[init] tokenizer loaded. chat_template={'yes' if has_template else 'no'}")
|
| 47 |
except Exception as e:
|
| 48 |
load_error = f"Failed to load tokenizer: {e}"
|
| 49 |
logger.exception(load_error)
|
| 50 |
|
| 51 |
|
| 52 |
+
# ---------- helpers ----------
|
| 53 |
def _pick_cpu_dtype() -> torch.dtype:
|
| 54 |
+
try:
|
| 55 |
+
if hasattr(torch, "cpu") and hasattr(torch.cpu, "is_bf16_supported") and torch.cpu.is_bf16_supported():
|
| 56 |
+
logger.info("[dtype] CPU BF16 supported -> torch.bfloat16")
|
| 57 |
+
return torch.bfloat16
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.warning(f"[dtype] BF16 probe failed: {e}")
|
| 60 |
+
logger.info("[dtype] fallback -> torch.float32")
|
|
|
|
| 61 |
return torch.float32
|
| 62 |
|
| 63 |
|
| 64 |
+
# ---------- global cache ----------
|
| 65 |
_MODEL_CACHE: Dict[tuple[str, torch.dtype], AutoModelForCausalLM] = {}
|
| 66 |
|
| 67 |
|
| 68 |
def _get_model(device: str, dtype: torch.dtype) -> Tuple[AutoModelForCausalLM, torch.dtype]:
|
| 69 |
key = (device, dtype)
|
| 70 |
if key in _MODEL_CACHE:
|
| 71 |
+
logger.info(f"[cache] hit model for device={device} dtype={dtype}")
|
| 72 |
return _MODEL_CACHE[key], dtype
|
| 73 |
|
| 74 |
+
logger.info(f"[load] begin from_pretrained device={device} dtype={dtype}")
|
| 75 |
cfg = AutoConfig.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 76 |
if hasattr(cfg, "quantization_config"):
|
| 77 |
+
logger.warning("[load] removing quantization_config from config to avoid FP8 path")
|
| 78 |
delattr(cfg, "quantization_config")
|
| 79 |
|
| 80 |
eff_dtype = dtype
|
|
|
|
| 89 |
)
|
| 90 |
except Exception as e:
|
| 91 |
if device == "cpu" and dtype == torch.bfloat16:
|
| 92 |
+
logger.warning(f"[load] BF16 load failed on CPU ({e}). retry FP32.")
|
| 93 |
eff_dtype = torch.float32
|
| 94 |
model = AutoModelForCausalLM.from_pretrained(
|
| 95 |
MODEL_ID,
|
|
|
|
| 100 |
low_cpu_mem_usage=False,
|
| 101 |
)
|
| 102 |
else:
|
| 103 |
+
logger.exception("[load] from_pretrained failed")
|
| 104 |
raise
|
| 105 |
|
| 106 |
if device == "cpu":
|
| 107 |
+
logger.info(f"[load] casting all weights to CPU dtype={eff_dtype}")
|
| 108 |
model = model.to(device=device, dtype=eff_dtype)
|
| 109 |
else:
|
| 110 |
+
logger.info(f"[load] moving model to device={device} (no recast)")
|
| 111 |
model = model.to(device=device)
|
| 112 |
|
| 113 |
model.eval()
|
| 114 |
+
try:
|
| 115 |
+
first_dtype = next(model.parameters()).dtype
|
| 116 |
+
logger.info(f"[load] ready. effective_dtype={eff_dtype} first_param_dtype={first_dtype}")
|
| 117 |
+
except Exception:
|
| 118 |
+
logger.info(f"[load] ready. effective_dtype={eff_dtype} (param dtype probe failed)")
|
| 119 |
+
|
| 120 |
_MODEL_CACHE[(device, eff_dtype)] = model
|
| 121 |
return model, eff_dtype
|
| 122 |
|
| 123 |
|
| 124 |
+
# ---------- Chat Backend ----------
|
| 125 |
class HFChatBackend(ChatBackend):
|
| 126 |
async def stream(self, request: Dict[str, Any]) -> AsyncIterable[Dict[str, Any]]:
|
| 127 |
if load_error:
|
| 128 |
raise RuntimeError(load_error)
|
| 129 |
|
| 130 |
messages = request.get("messages", [])
|
| 131 |
+
tools = request.get("tools")
|
| 132 |
temperature = float(request.get("temperature", settings.LlmTemp or 0.7))
|
| 133 |
max_tokens = int(request.get("max_tokens", settings.LlmOpenAICtxSize or 512))
|
| 134 |
|
| 135 |
rid = f"chatcmpl-hf-{int(time.time())}"
|
| 136 |
now = int(time.time())
|
| 137 |
|
| 138 |
+
logger.info(f"[req] rid={rid} temp={temperature} max_tokens={max_tokens} "
|
| 139 |
+
f"msgs={len(messages)} tools={'yes' if tools else 'no'} "
|
| 140 |
+
f"spaces={'yes' if spaces else 'no'} cuda={'yes' if torch.cuda.is_available() else 'no'}")
|
| 141 |
+
|
| 142 |
+
# X-IP-Token for ZeroGPU
|
| 143 |
x_ip_token = request.get("x_ip_token")
|
| 144 |
if x_ip_token and zero_client:
|
| 145 |
zero_client.HEADERS["X-IP-Token"] = x_ip_token
|
| 146 |
+
logger.info("[req] injected X-IP-Token into ZeroGPU headers")
|
| 147 |
|
| 148 |
+
# Build prompt
|
| 149 |
if hasattr(tokenizer, "apply_chat_template") and getattr(tokenizer, "chat_template", None):
|
| 150 |
try:
|
| 151 |
prompt = tokenizer.apply_chat_template(
|
| 152 |
messages,
|
| 153 |
+
tools=tools,
|
| 154 |
tokenize=False,
|
| 155 |
add_generation_prompt=True,
|
| 156 |
)
|
| 157 |
+
logger.info(f"[prompt] built via chat_template. len={len(prompt)}\n{_snippet(prompt, 1200)}")
|
| 158 |
except Exception as e:
|
| 159 |
+
logger.warning(f"[prompt] chat_template failed -> fallback. err={e}")
|
| 160 |
prompt = messages[-1]["content"] if messages else "(empty)"
|
| 161 |
+
logger.info(f"[prompt] fallback content len={len(prompt)}\n{_snippet(prompt, 800)}")
|
| 162 |
else:
|
| 163 |
prompt = messages[-1]["content"] if messages else "(empty)"
|
| 164 |
+
logger.info(f"[prompt] no template. using last user text len={len(prompt)}\n{_snippet(prompt, 800)}")
|
| 165 |
|
| 166 |
def _run_once(prompt: str, device: str, req_dtype: torch.dtype) -> str:
|
| 167 |
model, eff_dtype = _get_model(device, req_dtype)
|
| 168 |
|
| 169 |
inputs = tokenizer(prompt, return_tensors="pt")
|
| 170 |
+
input_ids = inputs["input_ids"]
|
| 171 |
+
logger.info(f"[gen] device={device} dtype={eff_dtype} input_tokens={input_ids.shape[-1]}")
|
| 172 |
+
|
| 173 |
inputs = {k: v.to(device) if hasattr(v, "to") else v for k, v in inputs.items()}
|
| 174 |
|
| 175 |
with torch.inference_mode():
|
| 176 |
if device != "cpu":
|
| 177 |
autocast_ctx = torch.autocast(device_type=device, dtype=eff_dtype)
|
| 178 |
else:
|
| 179 |
+
autocast_ctx = torch.cpu.amp.autocast(dtype=torch.bfloat16) if eff_dtype == torch.bfloat16 else nullcontext()
|
| 180 |
+
|
| 181 |
+
gen_kwargs = dict(
|
| 182 |
+
max_new_tokens=max_tokens,
|
| 183 |
+
temperature=temperature,
|
| 184 |
+
do_sample=True,
|
| 185 |
+
use_cache=True,
|
| 186 |
+
)
|
| 187 |
+
logger.info(f"[gen] kwargs={gen_kwargs}")
|
| 188 |
|
| 189 |
with autocast_ctx:
|
| 190 |
+
outputs = model.generate(**inputs, **gen_kwargs)
|
| 191 |
+
|
| 192 |
+
# Only decode newly generated tokens
|
| 193 |
+
input_len = input_ids.shape[-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
generated_ids = outputs[0][input_len:]
|
| 195 |
+
logger.info(f"[gen] new_tokens={generated_ids.shape[-1]}")
|
| 196 |
text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
| 197 |
+
logger.info(f"[gen] text len={len(text)}\n{_snippet(text, 1200)}")
|
| 198 |
return text
|
| 199 |
|
| 200 |
+
# Dispatch with or without ZeroGPU
|
| 201 |
if spaces:
|
| 202 |
@spaces.GPU(duration=120)
|
| 203 |
def run_once(prompt: str) -> str:
|
| 204 |
if torch.cuda.is_available():
|
| 205 |
+
logger.info("[path] ZeroGPU + CUDA")
|
| 206 |
return _run_once(prompt, device="cuda", req_dtype=torch.float16)
|
| 207 |
+
logger.info("[path] ZeroGPU but no CUDA -> CPU fallback")
|
| 208 |
return _run_once(prompt, device="cpu", req_dtype=_pick_cpu_dtype())
|
| 209 |
|
| 210 |
text = run_once(prompt)
|
| 211 |
else:
|
| 212 |
+
logger.info("[path] CPU-only runtime")
|
| 213 |
text = _run_once(prompt, device="cpu", req_dtype=_pick_cpu_dtype())
|
| 214 |
|
| 215 |
+
# Emit single OpenAI-style chunk
|
| 216 |
+
chunk = {
|
| 217 |
"id": rid,
|
| 218 |
"object": "chat.completion.chunk",
|
| 219 |
"created": now,
|
|
|
|
| 222 |
{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": "stop"}
|
| 223 |
],
|
| 224 |
}
|
| 225 |
+
logger.info(f"[out] chunk summary -> id={rid} content_len={len(text)}")
|
| 226 |
+
yield chunk
|
| 227 |
|
| 228 |
|
| 229 |
+
# ---------- Stub Images Backend ----------
|
| 230 |
class StubImagesBackend(ImagesBackend):
|
| 231 |
async def generate_b64(self, request: Dict[str, Any]) -> str:
|
| 232 |
logger.warning("Image generation not supported in HF backend.")
|
| 233 |
+
return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP4BwQACfsD/etCJH0AAAAASUVORK5CYII="
|
|
|
|
|
|