ViuAI-500M / code /inference_web_chat.py
ViuAI's picture
Upload code/inference_web_chat.py with huggingface_hub
ed22c7e verified
Raw History Blame Contribute Delete
12.1 kB
# ==============================================================================
# 🚀 ViuAI Sarus-500M — Trilingual Live Web-Search & Multi-Turn Chat Engine
# ==============================================================================
# Features:
# 1. Trilingual Support: English, Hindi (Devanagari), and Roman Hinglish.
# 2. Dynamic Temporal Header: Automatically injects current date & locale.
# 3. Two-Pass Autonomous Tool Calling:
# - Pass 1: Generates or detects `[SEARCH: query]` trigger.
# - Execution: Queries DuckDuckGo for top live snippets.
# - Pass 2: Generates grounded response synthesizing web search snippets.
# 4. Ephemeral Snippet Pruning:
# - Raw search snippets are pruned from persistent multi-turn history.
# - Only clean (user_query, assistant_response) pairs are saved.
# 5. Sliding Window Memory: Caps history at <= 1,400 tokens (max context 2,048).
# ==============================================================================
import os
import sys
import re
import time
import argparse
import datetime
import torch
from model import ViuAIForCausalLM
from config import ViuAIConfig
from tokenizers import Tokenizer
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
# Special token constants
USER_TOKEN = "<|user|>"
ASSISTANT_TOKEN = "<|assistant|>"
EOT_TOKEN = "<|endofturn|>"
USER_ID = 64000
ASSISTANT_ID = 64001
EOT_ID = 64002
TEMPORAL_KEYWORDS = [
"today", "aaj", "live", "current", "latest", "now", "abhi",
"score", "match", "ipl", "weather", "mausam", "aqi", "temperature",
"stock", "share", "price", "rate", "bhav", "gold", "silver", "crude",
"news", "taza", "khabar", "result", "election", "cabinet", "who won"
]
def perform_web_search(query: str, max_results: int = 3, timeout: int = 6) -> str:
"""Executes a live web search using DuckDuckGo search library with fallback."""
print(f" 🔍 Searching Live Web: '{query}'...")
try:
from duckduckgo_search import DDGS
with DDGS(timeout=timeout) as ddgs:
results = list(ddgs.text(query, max_results=max_results))
if not results:
return "No relevant search results found on the live web."
formatted_snippets = []
for idx, r in enumerate(results, 1):
title = r.get("title", "").strip()
body = r.get("body", "").strip()
source = r.get("href", "").split("/")[2] if "href" in r else "Web"
formatted_snippets.append(f"{idx}. ({source}) {title}: {body}")
return "\n".join(formatted_snippets)
except Exception as e:
return f"Web search could not be completed ({str(e)}). Proceeding with model knowledge base."
def clean_search_trigger(text: str) -> str:
"""Extracts search query from [SEARCH: query] pattern."""
match = re.search(r"\[SEARCH:\s*([^\]]+)\]", text, re.IGNORECASE)
if match:
return match.group(1).strip()
return ""
def generate_tokens(model, input_ids: torch.Tensor, max_new_tokens: int = 256,
temperature: float = 0.7, top_k: int = 40, top_p: float = 0.9,
stop_token_ids: list = None) -> str:
"""Generates tokens autoregressively with KV cache and sampling controls."""
if stop_token_ids is None:
stop_token_ids = [EOT_ID]
device = input_ids.device
curr_ids = input_ids.clone()
generated = []
model.eval()
with torch.no_grad():
for _ in range(max_new_tokens):
if curr_ids.shape[1] >= 2048:
break
logits = model(curr_ids)[:, -1, :]
if temperature > 0:
logits = logits / temperature
if top_k > 0:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float('Inf')
if top_p < 1.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(torch.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] = 0
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
logits[indices_to_remove] = -float('Inf')
probs = torch.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
else:
next_token = torch.argmax(logits, dim=-1, keepdim=True)
token_id = next_token.item()
if token_id in stop_token_ids:
break
generated.append(token_id)
curr_ids = torch.cat([curr_ids, next_token], dim=1)
return generated
def build_prompt_with_history(history: list, current_turn_prompt: str, tokenizer: Tokenizer, max_tokens: int = 1400) -> str:
"""Builds prompt string with sliding window context <= max_tokens."""
# Prune history from left if token count exceeds max_tokens
rendered_history = []
for u, a in history:
rendered_history.append(f"{USER_TOKEN}\n{u}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n{a}{EOT_TOKEN}\n")
# Calculate tokens
full_prompt = "".join(rendered_history) + current_turn_prompt
while len(tokenizer.encode(full_prompt).ids) > max_tokens and len(rendered_history) > 1:
rendered_history.pop(0)
full_prompt = "".join(rendered_history) + current_turn_prompt
return full_prompt
def interactive_chat_session(model, tokenizer, device: str = "cuda"):
print("=" * 80)
print("🌟 ViuAI Sarus-500M — Live Trilingual Web-Search Interactive Chat")
print("=" * 80)
print("Type your questions in English, Hindi (हिंदी), or Hinglish.")
print("Commands: 'exit' or 'quit' to terminate | 'clear' to reset conversation memory.")
print("=" * 80 + "\n")
conversation_history = [] # Stores (user_query, final_assistant_answer)
today_str = datetime.date.today().strftime("%Y-%m-%d")
context_header = f"[Context: Current Date is {today_str}. Location: India. Model: Sarus by ViuAI]"
while True:
try:
user_input = input("\n👤 You: ").strip()
except (KeyboardInterrupt, EOFError):
print("\nExiting session. Goodbye!")
break
if not user_input:
continue
if user_input.lower() in ("exit", "quit"):
print("Dhanyawaad / Thank you! Exiting Sarus chat session.")
break
if user_input.lower() == "clear":
conversation_history.clear()
print("🧹 Conversation memory cleared!")
continue
# Check if query likely requires real-time information
lower_input = user_input.lower()
temporal_hint = any(kw in lower_input for kw in TEMPORAL_KEYWORDS)
# Pass 1: Prepare prompt for search trigger check
first_user_turn = f"{context_header}\n\n{user_input}"
current_prompt = f"{USER_TOKEN}\n{first_user_turn}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n"
full_prompt_str = build_prompt_with_history(conversation_history, current_prompt, tokenizer)
input_ids = torch.tensor([tokenizer.encode(full_prompt_str).ids], dtype=torch.long, device=device)
# Fast generation (check if model initiates search trigger)
t0 = time.time()
pass1_tokens = generate_tokens(model, input_ids, max_new_tokens=40, temperature=0.1)
pass1_text = tokenizer.decode(pass1_tokens).strip()
search_query = clean_search_trigger(pass1_text)
# Heuristic fallback if model didn't trigger but query is strongly temporal
if not search_query and temporal_hint and ("price" in lower_input or "weather" in lower_input or "score" in lower_input or "rate" in lower_input or "aaj" in lower_input):
search_query = user_input.replace("?", "").strip()
if search_query:
# Perform Live Search
snippets = perform_web_search(search_query)
# Pass 2: Grounded Synthesis with snippets
grounded_instruction = (
f"{context_header}\n\n"
f"[Web Search Results]:\n{snippets}\n\n"
f"User Question: {user_input}"
)
grounded_prompt = f"{USER_TOKEN}\n{grounded_instruction}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n"
full_grounded_str = build_prompt_with_history(conversation_history, grounded_prompt, tokenizer)
grounded_ids = torch.tensor([tokenizer.encode(full_grounded_str).ids], dtype=torch.long, device=device)
pass2_tokens = generate_tokens(model, grounded_ids, max_new_tokens=256, temperature=0.6)
final_response = tokenizer.decode(pass2_tokens).strip()
else:
# Standard generation without web search
pass1_more_tokens = generate_tokens(model, input_ids, max_new_tokens=256, temperature=0.7)
final_response = tokenizer.decode(pass1_more_tokens).strip()
latency = time.time() - t0
tok_count = len(tokenizer.encode(final_response).ids)
speed = tok_count / max(0.001, latency)
print(f"\n🦅 Sarus: {final_response}")
print(f" [⚡ {speed:.1f} tok/s | Latency: {latency:.2f}s]")
# ----------------------------------------------------------------------
# EPHEMERAL SNIPPET PRUNING:
# Save ONLY clean (user_input, final_response) into persistent history!
# Raw search snippets are never retained, keeping memory clean & bounded!
# ----------------------------------------------------------------------
conversation_history.append((user_input, final_response))
def main():
parser = argparse.ArgumentParser(description="ViuAI Sarus-500M Trilingual Web-Search Interactive Chat")
parser.add_argument("--checkpoint", type=str, default="", help="Path to checkpoint weights (.pt)")
parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
parser.add_argument("--tokenizer", type=str, default="tokenizer/tokenizer.json")
args = parser.parse_args()
# Determine Checkpoint Path
ckpt_path = args.checkpoint
if not ckpt_path or not os.path.exists(ckpt_path):
candidates = [
"sft_checkpoints/sft_v3/sft_v3_final.pt",
"sft_checkpoints/sft_v3/sft_v3_best.pt",
"checkpoints/ckpt_latest.pt"
]
for c in candidates:
if os.path.exists(c):
ckpt_path = c
break
if not ckpt_path or not os.path.exists(ckpt_path):
print(f"❌ Error: No valid checkpoint found. Please specify --checkpoint <path>.")
sys.exit(1)
print(f"📦 Loading Model Weights: {ckpt_path}...")
cfg = ViuAIConfig()
model = ViuAIForCausalLM(cfg)
# Load weights safely
ckpt = torch.load(ckpt_path, map_location="cpu")
state_dict = ckpt.get("model", ckpt)
# Strip DDP prefix if present
state_dict = {k.replace("_orig_mod.", "").replace("module.", ""): v for k, v in state_dict.items()}
model.load_state_dict(state_dict, strict=False)
device = torch.device(args.device)
model.to(device)
if device.type == "cuda":
model.to(dtype=torch.bfloat16)
model.eval()
# Load Tokenizer
tok_path = args.tokenizer if os.path.exists(args.tokenizer) else "tokenizer.json"
if not os.path.exists(tok_path):
print(f"❌ Error: Tokenizer not found at {tok_path}.")
sys.exit(1)
tokenizer = Tokenizer.from_file(tok_path)
print(f"✅ Tokenizer bound. Vocab: {tokenizer.get_vocab_size():,}")
interactive_chat_session(model, tokenizer, device=str(device))
if __name__ == "__main__":
main()