Upload code/serve_v7.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# ============================================================================# 🚀 ViuAI-500M SFT v7 — Studio Inference & Agentic Backend Server# ============================================================================# Connects directly to ViuAI Studio (Web UI) with:# - Streaming Token-by-Token generation# - Collapsible [THINK] Chain-of-Thought reasoning# - Live Agentic Search (DuckDuckGo, Weather, News)# - Python Code Execution Tool# ============================================================================
import osimport sysimport reimport jsonimport timeimport asyncioimport urllib.parseimport xml.etree.ElementTree as ETfrom datetime import datetime, timezone, timedelta
import torchimport torch.nn.functional as Ffrom huggingface_hub import hf_hub_downloadfrom transformers import PreTrainedTokenizerFast
from fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponse, JSONResponsefrom pydantic import BaseModelimport uvicorn
# 1. Download Model Architecture & SFT v7 Final CheckpointREPO_ID = "ViuAI/ViuAI-500M"device = "cuda" if torch.cuda.is_available() else "cpu"print(f"🚀 Initializing ViuAI-500M SFT v7 Server on {device.upper()}...")
from config import ViuAIConfigfrom model import ViuAI
# 2. Tokenizer Setuptokenizer_path = "tokenizer.json" if os.path.exists("tokenizer.json") else "tokenizer/tokenizer.json"if not os.path.exists(tokenizer_path): tokenizer_path = hf_hub_download(repo_id=REPO_ID, filename="tokenizer/tokenizer.json")
tokenizer = PreTrainedTokenizerFast( tokenizer_file=tokenizer_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>", additional_special_tokens=[ "<|user|>", "<|assistant|>", "<|endofturn|>", "<|endoftext|>", "<|system|>", "[THINK]", "[/THINK]", "<think>", "</think>", "<search>", "</search>", "<search_result>", "</search_result>" ])eot_id = tokenizer.convert_tokens_to_ids("<|endofturn|>")eot_text_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
# 3. Load SFT v7 Model Weightslocal_v7_final = "sft_checkpoints/sft_v7/sft_ckpt_final.pt"if os.path.exists(local_v7_final): ckpt_path = local_v7_finalelif os.path.exists("sft_ckpt_final.pt"): ckpt_path = "sft_ckpt_final.pt"else: try: ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="sft_checkpoints/sft_v7/sft_ckpt_final.pt") except Exception: ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="sft_checkpoints/sft_v7/sft_ckpt_latest.pt")
print(f"📥 Loading Checkpoint: {ckpt_path}")checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)
def strip_prefixes(state_dict): cleaned = {} for k, v in state_dict.items(): for p in ("module._orig_mod.", "_orig_mod.", "module."): if k.startswith(p): k = k[len(p):] break cleaned[k] = v return cleaned
raw_sd = checkpoint.get("model", checkpoint.get("model_state_dict", checkpoint))state_dict = strip_prefixes(raw_sd)ckpt_vocab_size = state_dict['tok_emb.weight'].shape[0]
config = ViuAIConfig(vocab_size=max(len(tokenizer), ckpt_vocab_size), use_checkpoint=False)CTX_LEN = getattr(config, 'context_length', getattr(config, 'max_seq_len', 2048))model = ViuAI(config).to(device)
if ckpt_vocab_size < len(tokenizer): d_model = state_dict['tok_emb.weight'].shape[1] pad_len = len(tokenizer) - ckpt_vocab_size state_dict['tok_emb.weight'] = torch.cat([state_dict['tok_emb.weight'], torch.randn(pad_len, d_model) * 0.02])
model.load_state_dict(state_dict, strict=False)model.head.weight = model.tok_emb.weightmodel.eval()
if device == "cuda" and hasattr(torch, "compile"): try: model = torch.compile(model) except Exception: pass
print(f"✅ ViuAI-500M SFT v7 Live & Ready! (Vocab: {len(tokenizer)}, Context: {CTX_LEN})")
# 4. Live Agentic Tools (Weather, News & DuckDuckGo Search)def perform_live_search(query: str) -> str: q_lower = query.lower() ist_tz = timezone(timedelta(hours=5, minutes=30)) today = datetime.now(ist_tz).strftime("%d %B %Y") # 1. Weather Intent if any(w in q_lower for w in ["temperature", "weather", "mausam"]): loc = re.sub(r'[^\w\s]', '', q_lower.replace("temperature", "").replace("weather", "").replace("mausam", "")).strip() or "Delhi" try: import requests r = requests.get(f"https://wttr.in/{urllib.parse.quote(loc)}?format=j1", timeout=5) if r.status_code == 200: d = r.json() temp = d['current_condition'][0]['temp_C'] desc = d['current_condition'][0]['weatherDesc'][0]['value'] return f"[Live Weather] Current temperature for {loc.title()} is {temp}°C, condition: {desc}." except Exception: pass
# 2. News Intent if any(w in q_lower for w in ["news", "latest", "khabar", "today"]): try: import requests r = requests.get(f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en", timeout=5) if r.status_code == 200: root = ET.fromstring(r.text) items = root.findall('./channel/item')[:4] if items: news_text = f"[Date: {today}] Live Headlines:\n" for i, it in enumerate(items, 1): news_text += f"{i}. {it.find('title').text}\n" return news_text[:1200] except Exception: pass
# 3. DuckDuckGo Fallback try: from duckduckgo_search import DDGS with DDGS() as ddgs: results = list(ddgs.text(query, max_results=3)) if results: ctx = f"[Date: {today}] Search Results:\n" for i, res in enumerate(results, 1): ctx += f"{i}. {res.get('title')}: {res.get('body')}\n" return ctx[:1200] except Exception as e: return f"Search error: {e}"
return f"[Date: {today}] No direct web results found."
# 5. FastAPI App for ViuAI Studio UIapp = FastAPI(title="ViuAI-500M SFT v7 Studio API")app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
class ModelInput(BaseModel): input_data: str system_prompt: str = "" parameters: dict = {} history: list = [] stream: bool = True
def build_prompt_and_check_search(data: ModelInput): user_msg = data.input_data.strip() sys_inst = data.system_prompt.strip() or "You are ViuAI, a helpful, intelligent, and factual AI assistant."
SEARCH_TRIGGERS = ["latest", "news", "today", "price", "weather", "temperature", "mausam", "score", "match", "current"] IDENTITY_KEYWORDS = ["who are you", "what is your name", "your name", "who created you"] msg_lower = user_msg.lower() is_identity = any(kw in msg_lower for kw in IDENTITY_KEYWORDS) needs_search = any(kw in msg_lower for kw in SEARCH_TRIGGERS) and not is_identity
conv_turns = [] for turn in data.history[-6:]: role = turn.get("role", "") content = turn.get("content", "").strip() if role == "user" and content: conv_turns.append(f"<|user|>\n{content}<|endofturn|>") elif role == "assistant" and content: clean_c = re.sub(r'\[THINK\].*?\[/THINK\]', '', content, flags=re.DOTALL) clean_c = re.sub(r'<think>.*?</think>', '', clean_c, flags=re.DOTALL) clean_c = re.sub(r'<search>.*?</search>', '', clean_c, flags=re.DOTALL) clean_c = re.sub(r'<search_result>.*?</search_result>', '', clean_c, flags=re.DOTALL).strip() if clean_c: conv_turns.append(f"<|assistant|>\n{clean_c}<|endofturn|>")
if needs_search: search_res = perform_live_search(user_msg) current_turn = ( f"<|user|>\n{user_msg}<|endofturn|>\n<|assistant|>\n" f"<search>{user_msg}</search>\n<search_result>\n{search_res}\n</search_result>\n" ) else: current_turn = f"<|user|>\n{user_msg}<|endofturn|>\n<|assistant|>\n"
if conv_turns: prompt = f"{sys_inst}\n\n" + "\n".join(conv_turns) + "\n" + current_turn else: prompt = f"{sys_inst}\n\n" + current_turn
return prompt
@app.get("/health")async def health(): return {"status": "ok", "model": "ViuAI-500M SFT v7"}
@app.post("/predict")async def predict(data: ModelInput): user_msg = data.input_data.strip() if user_msg.lower() == "ping": return {"prediction": "pong"}
temp = float(data.parameters.get("temperature", 0.6)) top_p = float(data.parameters.get("top_p", 0.9)) max_tokens = int(data.parameters.get("max_tokens", 512)) repetition_penalty = 1.15
prompt = build_prompt_and_check_search(data)
if data.stream: async def event_generator(): input_ids = tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device) generated_ids = [] full_reply_text = "" search_count = 0 last_decoded_len = 0
while True: if input_ids.size(1) > CTX_LEN: input_ids = input_ids[:, -CTX_LEN:]
max_new = min(max_tokens, max(1, CTX_LEN - input_ids.size(1))) triggered_search = False
for _ in range(max_new): with torch.no_grad(): with torch.autocast(device_type=device, dtype=torch.bfloat16 if device == "cuda" else torch.float32): logits = model(input_ids)[0][:, -1, :]
if repetition_penalty != 1.0 and len(generated_ids) > 0: unique_toks = torch.unique(torch.tensor(generated_ids, device=device)) score = logits[0, unique_toks] logits[0, unique_toks] = torch.where(score < 0, score * repetition_penalty, score / repetition_penalty)
logits = logits / max(temp, 1e-8) kth_vals, _ = torch.topk(logits, 40) logits[logits < kth_vals[:, [-1]]] = float('-inf')
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) > CTX_LEN: input_ids = input_ids[:, -CTX_LEN:]
next_id = idx_next.item() generated_ids.append(next_id)
full_decoded = tokenizer.decode(generated_ids, skip_special_tokens=False) new_token_text = full_decoded[last_decoded_len:] last_decoded_len = len(full_decoded) full_reply_text = full_decoded
if new_token_text: yield f"data: {json.dumps({'token': new_token_text})}\n\n" await asyncio.sleep(0.001)
if next_id in (eot_id, eot_text_id, tokenizer.eos_token_id): break
current_search_count = full_reply_text.count("</search>") if current_search_count > search_count: search_count = current_search_count triggered_search = True break
if triggered_search: search_matches = re.findall(r'<search>(.*?)</search>', full_reply_text, re.DOTALL) query = search_matches[-1].strip() if search_matches else "" result_text = perform_live_search(query) if query else "No query found."
injection = f"\n<search_result>\n{result_text}\n</search_result>\n" full_reply_text += injection yield f"data: {json.dumps({'token': injection})}\n\n"
injection_ids = tokenizer(injection, add_special_tokens=False, return_tensors="pt").input_ids.to(device) input_ids = torch.cat([input_ids, injection_ids], dim=1) generated_ids.extend(injection_ids[0].tolist()) last_decoded_len = len(tokenizer.decode(generated_ids, skip_special_tokens=False)) continue else: break
return StreamingResponse(event_generator(), media_type="text/event-stream")
if __name__ == "__main__": port = int(os.environ.get("PORT", 8000)) print(f"🚀 Starting ViuAI Studio Backend on port {port}...") uvicorn.run(app, host="0.0.0.0", port=port)code/serve_v7.pyAdded+320