File size: 12,101 Bytes
ed22c7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# ==============================================================================
# 🚀 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()