Upload code/agentic_chat.py with huggingface_hub
Browse files123456789101112131415168 unmodified lines2526272829303132333435363736 unmodified lines7475767778794 unmodified lines848586878889908 unmodified lines991001011021031041056 unmodified lines1121131141151161171181191201211221232 unmodified lines1261271281291301311321331345 unmodified lines1401411421431441451461471481491501511521531541556 unmodified lines162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245"""ViuAI-500M Agentic Chat (Tool-Use)==================================This script implements a pause-and-resume agentic loop.If the model emits </search>, generation pauses, a real internet search is executed,the result is injected as <search_result>...</search_result>, and generation resumes."""import argparseimport osimport refrom datetime import datetimeimport torchfrom huggingface_hub import hf_hub_downloadfrom transformers import PreTrainedTokenizerFast8 unmodified lineslogging.getLogger("transformers").setLevel(logging.ERROR)# ============================================================================# 1. Internet Search (DuckDuckGo)# ============================================================================def do_search(query: str) -> str:"""Search DuckDuckGo and return a truncated context string."""results = []try:import sysold_stderr = sys.stderrsys.stderr = open(os.devnull, 'w')36 unmodified linescontext += snippetreturn context.strip()# ============================================================================# 2. Model Loading# ============================================================================4 unmodified linespad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>",additional_special_tokens=["<|user|>", "<|assistant|>", "<|endofturn|>", "<think>", "</think>"])# Add search tokens explicitly if they aren't somehow in the base tokenizertokenizer.add_tokens(["<search>", "</search>", "<search_result>", "</search_result>"], special_tokens=True)return tokenizer8 unmodified linesreturn cleaned# ============================================================================# 3. Main Agentic Loop# ============================================================================def main():parser = argparse.ArgumentParser(description="Agentic Chat with ViuAI-500M")6 unmodified linesprint(f"🚀 Loading Agentic ViuAI-500M on {device.upper()}...")tokenizer = load_tokenizer(args.repo_id, token)# We always load the SFT checkpoint for the chat scripttry:# Try to download the newly uploaded SFT checkpoint (now in sft_v3)ckpt_path = hf_hub_download(repo_id=args.repo_id, filename="sft_checkpoints/sft_v3/sft_ckpt_latest.pt", token=token)except:# Fallback to local or baseckpt_path = "checkpoints/ckpt_latest_updated.pt"if not os.path.exists(ckpt_path):print("⚠️ Could not find SFT checkpoint on HF, downloading base updated local...")2 unmodified linescheckpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)state_dict = strip_training_prefixes(checkpoint["model"])# Dynamically find vocab size from the checkpoint to prevent config mismatchesckpt_vocab_size = state_dict['tok_emb.weight'].shape[0]config = ViuAIConfig(vocab_size=ckpt_vocab_size, use_checkpoint=False)model = ViuAI(config).to(device)model.load_state_dict(state_dict, strict=True)5 unmodified linesprint(f" Type 'quit' or 'exit' to stop.\n")eot_id = tokenizer.convert_tokens_to_ids("<|endofturn|>")end_search_id = tokenizer.convert_tokens_to_ids("</search>")# Ensure they existassert eot_id is not None and end_search_id is not Nonestop_tokens = (eot_id, end_search_id)while True:try:message = input("👤 You: ").strip()except (EOFError, KeyboardInterrupt):print()break6 unmodified linesinput_ids = tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device)full_reply_text = ""while True:# Generate until we hit EOT or </search>max_new = min(1024, 2048 - input_ids.size(1))if max_new < 32:print("\n\033[31m[Max Context Length Reached]\033[0m")breakoutput_ids = model.generate(input_ids,max_new_tokens=max_new,temperature=0.6,top_k=40,top_p=0.9,repetition_penalty=1.15,eos_token_id=stop_tokens, # Our modified model.py supports tuple)# The last token generated is what stopped it (or it maxed out)last_token_id = output_ids[0, -1].item()# Decode the newly generated chunknew_chunk_ids = output_ids[0, input_ids.size(1):]chunk_text = tokenizer.decode(new_chunk_ids, skip_special_tokens=False)full_reply_text += chunk_text# Update input_ids for the next loop (if any)input_ids = output_ids# Handle stopsif last_token_id == eot_id:# Finished answeringbreakelif last_token_id == end_search_id:# Agent triggered a search!print("\n\033[33m🔍 [Agent is Searching the Internet...]\033[0m")# Extract query between <search> and </search>search_match = re.search(r'<search>(.*?)</search>$', full_reply_text, re.DOTALL)query = search_match.group(1).strip() if search_match else ""if query:print(f"\033[36m Query: {query}\033[0m")result_text = do_search(query)else:result_text = "No query provided."print(f"\033[36m Result length: {len(result_text)} chars\033[0m")# Format the injectioninjection = f"\n<search_result>\n{result_text}\n</search_result>\n"full_reply_text += injection# Append injection to input_idsinj_ids = tokenizer.encode(injection, add_special_tokens=False, return_tensors="pt").to(device)input_ids = torch.cat([input_ids, inj_ids], dim=1)# The loop continues to generate the synthesis...else:# Hit max_new_tokensbreak# Display final response cleanlyfull_reply_text = full_reply_text.replace("<|endofturn|>", "").strip()# Colorize think and search blocks for terminaldef colorize(match):tag = match.group(0)if "[THINK]" in tag: return f"\033[90m{tag}\033[0m"if "<search>" in tag: return f"\033[33m{tag}\033[0m"if "<search_result>" in tag: return f"\033[36m{tag}\033[0m"return tagdisplay_text = re.sub(r'\[THINK\].*?\[/THINK\]', colorize, full_reply_text, flags=re.DOTALL)display_text = re.sub(r'<search>.*?</search>', colorize, display_text, flags=re.DOTALL)display_text = re.sub(r'<search_result>.*?</search_result>', colorize, display_text, flags=re.DOTALL)print(f"\n🤖 ViuAI:\n{display_text}\n")if __name__ == "__main__":main()123456789101112131415161718192021228 unmodified lines313233343536373839404136 unmodified lines78798081828384858687888990919293944 unmodified lines991001011021031048 unmodified lines1131141151161171181196 unmodified lines1261271281291301311321331342 unmodified lines1371381391401411421435 unmodified lines1491501511521531541551561571581591601611621631641656 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302"""ViuAI-500M Agentic Chat (Advanced UI & Streaming)=================================================This script implements a pause-and-resume agentic loop with word-by-word streaming.- Manual Autoregressive Loop for true streaming.- Dynamic colorization for [THINK] (grey) and <search> (yellow).- Timeout protection (10s) on DuckDuckGo search.- String interception for robust </search> handling (Repetition Bug Fix)."""import argparseimport osimport reimport sysimport threadingfrom concurrent.futures import ThreadPoolExecutor, TimeoutErrorfrom datetime import datetimeimport torchimport torch.nn.functional as Ffrom huggingface_hub import hf_hub_downloadfrom transformers import PreTrainedTokenizerFast8 unmodified lineslogging.getLogger("transformers").setLevel(logging.ERROR)# ============================================================================# 1. Internet Search (DuckDuckGo with Timeout Protection)# ============================================================================def _ddgs_search_sync(query: str) -> str:results = []try:old_stderr = sys.stderrsys.stderr = open(os.devnull, 'w')36 unmodified linescontext += snippetreturn context.strip()def do_search(query: str, timeout: int = 10) -> str:"""Search with strict timeout to prevent hangs."""with ThreadPoolExecutor(max_workers=1) as executor:future = executor.submit(_ddgs_search_sync, query)try:return future.result(timeout=timeout)except TimeoutError:return "Search timed out after 10 seconds. Please rely on internal knowledge."except Exception as e:return f"Search error: {e}"# ============================================================================# 2. Model Loading# ============================================================================4 unmodified linespad_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)return tokenizer8 unmodified linesreturn cleaned# ============================================================================# 3. Main Agentic Loop with Streaming# ============================================================================def main():parser = argparse.ArgumentParser(description="Agentic Chat with ViuAI-500M")6 unmodified linesprint(f"🚀 Loading Agentic ViuAI-500M on {device.upper()}...")tokenizer = load_tokenizer(args.repo_id, token)try:ckpt_path = hf_hub_download(repo_id=args.repo_id, filename="sft_checkpoints/sft_v3/sft_ckpt_latest.pt", token=token)except:ckpt_path = "checkpoints/ckpt_latest_updated.pt"if not os.path.exists(ckpt_path):print("⚠️ Could not find SFT checkpoint on HF, downloading base updated local...")2 unmodified linescheckpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)state_dict = strip_training_prefixes(checkpoint["model"])ckpt_vocab_size = state_dict['tok_emb.weight'].shape[0]config = ViuAIConfig(vocab_size=ckpt_vocab_size, use_checkpoint=False)model = ViuAI(config).to(device)model.load_state_dict(state_dict, strict=True)5 unmodified linesprint(f" Type 'quit' or 'exit' to stop.\n")eot_id = tokenizer.convert_tokens_to_ids("<|endofturn|>")# Colors for Terminal UIRESET = "\033[0m"GREY = "\033[90m"YELLOW = "\033[33m"CYAN = "\033[36m"RED = "\033[31m"while True:try:message = input(f"👤 You: ").strip()except (EOFError, KeyboardInterrupt):print()break6 unmodified linesinput_ids = tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device)full_reply_text = ""print(f"\n🤖 ViuAI:")current_color = RESETwhile True:max_new = min(1024, 2048 - input_ids.size(1))if max_new < 32:print(f"\n{RED}[Max Context Length Reached]{RESET}")breaktriggered_search = Falselast_decoded_len = len(tokenizer.decode(input_ids[0], skip_special_tokens=False))# --- Custom Autoregressive Streaming Loop ---for _ in range(max_new):cond_idx = input_ids if input_ids.size(1) <= config.block_size else input_ids[:, -config.block_size:]with torch.no_grad():logits = model(cond_idx)[0]logits = logits[:, -1, :] # last token onlytemperature = 0.6top_k = 40top_p = 0.9repetition_penalty = 1.15# Apply Repetition Penaltyif repetition_penalty != 1.0:for i in range(input_ids.shape[1]):token_idx = input_ids[0, i].item()score = logits[0, token_idx]logits[0, token_idx] = torch.where(score < 0, score * repetition_penalty, score / repetition_penalty)# Temperature Scalinglogits = logits / max(temperature, 1e-8)# Top Kkth_vals, _ = torch.topk(logits, top_k)logits[logits < kth_vals[:, [-1]]] = float('-inf')# Top Psorted_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_psorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()sorted_indices_to_remove[..., 0] = Falseindices_to_remove = torch.zeros_like(logits, dtype=torch.bool).scatter_(1, sorted_indices, sorted_indices_to_remove)logits[indices_to_remove] = float('-inf')# Sampleprobs = F.softmax(logits, dim=-1)idx_next = torch.multinomial(probs, num_samples=1)# Append to sequenceinput_ids = torch.cat([input_ids, idx_next], dim=1)new_token_id = idx_next.item()# Safe UTF-8 decoding by checking differencefull_decoded = tokenizer.decode(input_ids[0], skip_special_tokens=False)new_text = full_decoded[last_decoded_len:]last_decoded_len = len(full_decoded)full_reply_text += new_text# --- Live Colorization Logic ---if "[THINK]" in full_reply_text and "[/THINK]" not in full_reply_text:if current_color != GREY:sys.stdout.write(GREY)current_color = GREYelif "<search>" in full_reply_text and "</search>" not in full_reply_text:if current_color != YELLOW:sys.stdout.write(YELLOW)current_color = YELLOWelif "[/THINK]" in full_reply_text or "</search>" in full_reply_text:if current_color != RESET:sys.stdout.write(RESET)current_color = RESET# Stream out (Hide the invisible EOT token from UI)if new_token_id != eot_id:sys.stdout.write(new_text)sys.stdout.flush()# --- Stop Conditions ---if new_token_id == eot_id:break# String Intercept for Repetition Bug (Fixes <search> loop)if "</search>" in full_reply_text:triggered_search = Truebreak# Handle post-stream Agentic Actions (Search)if triggered_search:# Guarantee color resetssys.stdout.write(RESET)print(f"\n\n{CYAN}🔍 [Agent is Searching the Internet...]{RESET}")search_match = re.search(r'<search>(.*?)</search>', full_reply_text, re.DOTALL)query = search_match.group(1).strip() if search_match else ""if query:print(f"{CYAN} Query: {query}{RESET}")result_text = do_search(query, timeout=10)else:result_text = "No query provided."print(f"{CYAN} Result length: {len(result_text)} chars{RESET}\n")# Inject knowledge (Silent to UI)sys.stdout.write(f"{GREY}[Context Injected. Resuming...]{RESET}\n")sys.stdout.flush()injection = f"\n<search_result>\n{result_text}\n</search_result>\n"full_reply_text += injection# Convert injection to tokens and appendinj_ids = tokenizer.encode(injection, add_special_tokens=False, return_tensors="pt").to(device)input_ids = torch.cat([input_ids, inj_ids], dim=1)# Continue outer loop to resume generation based on injected knowledgecontinueelse:# Finished generating naturallyprint("\n")breakif __name__ == "__main__":main()
code/agentic_chat.py+135-78