Delete code/serve_v9.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259# ==============================================================================# ViuAI-500M — SFT v9 Model Serving API (FastAPI + SSE Streaming for ViuAI Studio)# ==============================================================================# - Real-time word-by-word SSE streaming (/predict, /stream, /generate, /)# - Special thinking tags [THINK] ... [/THINK]# - Full backward compatibility with ViuAI Studio Web UI# ==============================================================================
import osimport sysimport jsonimport timeimport asynciofrom typing import Optional, List, Dict, Anyfrom pydantic import BaseModelimport torchimport torch.nn.functional as Ffrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponse, JSONResponseimport uvicornfrom huggingface_hub import hf_hub_downloadfrom transformers import PreTrainedTokenizerFast
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace")
# Add ViuAI_500M/code to path if presentmodel_code_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "ViuAI_500M", "code"))if os.path.exists(model_code_dir) and model_code_dir not in sys.path: sys.path.insert(0, model_code_dir)
app = FastAPI(title="ViuAI 500M SFT v9 Inference Server")
# Enable CORS for ViuAI Studio Web UIapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
HF_TOKEN = os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"])REPO_ID = os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")CHECKPOINT_PATH = os.environ.get("CHECKPOINT_PATH", "sft_checkpoints/sft_v9/sft_ckpt_final.pt")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print("=" * 70)print(f"🚀 Loading ViuAI-500M SFT v9 Model on {DEVICE.upper()}...")print(f" Checkpoint: {CHECKPOINT_PATH}")print("=" * 70)
from config import ViuAIConfigfrom model import ViuAI
# 1. Load Tokenizertry: tok_path = hf_hub_download(repo_id=REPO_ID, filename="tokenizer/tokenizer.json", repo_type="model", token=HF_TOKEN)except Exception: tok_path = "tokenizer/tokenizer.json"
tokenizer = PreTrainedTokenizerFast( tokenizer_file=tok_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>", additional_special_tokens=["<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]"])tokenizer.add_tokens(["<search>", "</search>", "<search_result>", "</search_result>"], special_tokens=True)vocab_size = len(tokenizer)print(f"✅ Tokenizer loaded. Vocab size: {vocab_size}")
# 2. Load Model Architecture & SFT v9 Weightscfg = ViuAIConfig(vocab_size=64009, use_checkpoint=False)model = ViuAI(cfg).to(DEVICE)
local_ckpt_candidates = [ os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "ViuAI_500M", "code", "checkpoints", "sft_v9", "sft_ckpt_final.pt")), os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "ViuAI_500M", "checkpoints", "sft_v9", "sft_ckpt_final.pt")), "checkpoints/sft_v9/sft_ckpt_final.pt", "sft_ckpt_final.pt"]
actual_ckpt_path = Nonefor cand in local_ckpt_candidates: if os.path.exists(cand): actual_ckpt_path = cand break
if not actual_ckpt_path: print(f"📥 Downloading SFT v9 Checkpoint from Hugging Face: {REPO_ID} ({CHECKPOINT_PATH})...") actual_ckpt_path = hf_hub_download( repo_id=REPO_ID, filename=CHECKPOINT_PATH, token=HF_TOKEN )
print(f"📥 Loading weights from: {actual_ckpt_path}")ckpt = torch.load(actual_ckpt_path, map_location=DEVICE, weights_only=False)state_dict = ckpt.get("model_state_dict", ckpt.get("model", ckpt))
clean_sd = {}for k, v in state_dict.items(): clean_k = k.replace("module._orig_mod.", "").replace("_orig_mod.", "").replace("module.", "") clean_sd[clean_k] = v
model.load_state_dict(clean_sd, strict=False)if hasattr(model, "head") and hasattr(model, "tok_emb"): model.head.weight = model.tok_emb.weight
model.eval()print(f"✅ ViuAI-500M SFT v9 Model Loaded Successfully on {DEVICE.upper()}!")print("=" * 70)
# Request Modelsclass PredictRequest(BaseModel): input_data: Optional[str] = None inputs: Optional[str] = None prompt: Optional[str] = None system_prompt: Optional[str] = None parameters: Optional[Dict[str, Any]] = None history: Optional[List[Dict[str, Any]]] = None messages: Optional[List[Dict[str, Any]]] = None stream: Optional[bool] = True
@app.get("/")@app.get("/health")async def health_check(): return { "status": "healthy", "model": "ViuAI-500M SFT v9", "device": DEVICE, "vocab_size": vocab_size, "checkpoint": CHECKPOINT_PATH }
# 3. Core Autoregressive Generatordef generate_tokens_stream(prompt_text: str, temperature=0.7, top_p=0.9, top_k=40, max_tokens=512, repetition_penalty=1.15): encoded = tokenizer(prompt_text, add_special_tokens=False, return_tensors="pt") input_ids = encoded.input_ids.to(DEVICE) if input_ids.size(1) > cfg.context_length: input_ids = input_ids[:, -cfg.context_length:] generated_ids = [] last_len = 0 eot_id = tokenizer.convert_tokens_to_ids("<|endofturn|>") for _ in range(max_tokens): with torch.no_grad(): logits = model(input_ids)[0] logits = logits[:, -1, :] # Repetition Penalty if repetition_penalty != 1.0 and len(generated_ids) > 0: unique_ids = torch.unique(torch.tensor(generated_ids, device=DEVICE)) score = logits[0, unique_ids] logits[0, unique_ids] = torch.where( score < 0, score * repetition_penalty, score / repetition_penalty ) logits = logits / max(temperature, 1e-8) # Top-K if top_k > 0: top_k_val = min(top_k, logits.size(-1)) kth_vals, _ = torch.topk(logits, top_k_val) logits[logits < kth_vals[:, [-1]]] = float('-inf') # Top-P (Nucleus) if top_p < 1.0: sorted_logits, sorted_indices = torch.sort(logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) sorted_indices_to_remove = cumulative_probs > top_p sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = False indices_to_remove = torch.zeros_like(logits, dtype=torch.bool).scatter_(1, sorted_indices, sorted_indices_to_remove) logits[indices_to_remove] = float('-inf') probs = F.softmax(logits, dim=-1) idx_next = torch.multinomial(probs, num_samples=1) input_ids = torch.cat([input_ids, idx_next], dim=1) if input_ids.size(1) > cfg.context_length: input_ids = input_ids[:, -cfg.context_length:] token_id = idx_next.item() if token_id in [eot_id, tokenizer.eos_token_id or 64002]: break generated_ids.append(token_id) # Decode piece decoded = tokenizer.decode(generated_ids, skip_special_tokens=False) chunk = decoded[last_len:] last_len = len(decoded) if chunk: yield chunk
@app.post("/")@app.post("/predict")@app.post("/stream")@app.post("/generate")@app.post("/chat")@app.post("/api/chat")@app.post("/v1/chat/completions")async def predict(req: PredictRequest): user_text = req.input_data or req.inputs or req.prompt or "" if user_text.strip() == "ping": return JSONResponse({"status": "healthy", "response": "pong"}) if not user_text.strip() and not req.history and not req.messages: return JSONResponse({"error": "Empty input"}, status_code=400) params = req.parameters or {} temperature = float(params.get("temperature", 0.7)) top_p = float(params.get("top_p", 0.9)) max_tokens = int(params.get("max_tokens", params.get("max_new_tokens", 512))) # Build conversation context formatted_prompt = "" turns = req.history or req.messages or [] for turn in turns: role = turn.get("role", "user") content = turn.get("content", "") if role.lower() in ["user", "human"]: formatted_prompt += f"<|user|>\n{content}<|endofturn|>\n" elif role.lower() in ["assistant", "bot", "model"]: formatted_prompt += f"<|assistant|>\n{content}<|endofturn|>\n" if user_text: formatted_prompt += f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n" else: formatted_prompt += "<|assistant|>\n" # Streaming Response (SSE) if req.stream: async def event_generator(): full_resp = "" for token_chunk in generate_tokens_stream( formatted_prompt, temperature=temperature, top_p=top_p, max_tokens=max_tokens ): full_resp += token_chunk data = json.dumps({"token": token_chunk, "full_text": full_resp}) yield f"data: {data}\n\n" await asyncio.sleep(0.005) yield f"data: {json.dumps({'done': True, 'full_text': full_resp})}\n\n" return StreamingResponse(event_generator(), media_type="text/event-stream") else: full_resp = "".join(list(generate_tokens_stream( formatted_prompt, temperature=temperature, top_p=top_p, max_tokens=max_tokens ))) return JSONResponse({"response": full_resp, "generated_text": full_resp})
if __name__ == "__main__": uvicorn.run("serve_v9:app", host="0.0.0.0", port=8000, reload=False)code/serve_v9.pyDeleted-259