Upload folder using huggingface_hub
Browse filesFiles changed (9)
- code/__pycache__/chat.cpython-313.pycAdded
- code/__pycache__/config.cpython-313.pycAdded
- code/__pycache__/model.cpython-313.pycAdded
- code/__pycache__/train.cpython-313.pycAdded
- code/__pycache__/train_sft.cpython-313.pycAdded
- code/chat.pyAdded+128
- code/chat_internet.pyAdded+315
- code/prepare_sft_data.pyAdded+404
- code/train_sft.py+3-4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import argparseimport os
import torchfrom huggingface_hub import hf_hub_downloadfrom transformers import PreTrainedTokenizerFast
from config import ViuAIConfigfrom model import ViuAI
def strip_training_prefixes(state_dict): """Make checkpoints saved with DDP and/or torch.compile loadable.""" cleaned = {} for key, value in state_dict.items(): for prefix in ("module._orig_mod.", "_orig_mod.", "module."): if key.startswith(prefix): key = key[len(prefix):] break cleaned[key] = value return cleaned
def load_tokenizer(repo_id, token): tokenizer_path = hf_hub_download( repo_id=repo_id, filename="tokenizer/tokenizer.json", token=token, ) return PreTrainedTokenizerFast( tokenizer_file=tokenizer_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>", additional_special_tokens=["<|user|>", "<|assistant|>", "<|endofturn|>", "<think>", "</think>"], )
def download_checkpoint(repo_id, checkpoint_kind, sft_checkpoint_dir, token): candidates = ( [ f"{sft_checkpoint_dir}/sft_ckpt_best.pt", f"{sft_checkpoint_dir}/sft_ckpt_latest.pt", # Backward-compatible fallback for the original flat layout. "sft_checkpoints/sft_ckpt_best.pt", "sft_checkpoints/sft_ckpt_latest.pt", ] if checkpoint_kind == "sft" else ["checkpoints/ckpt_latest.pt", "checkpoints/ckpt_best.pt"] ) errors = [] for filename in candidates: try: return hf_hub_download(repo_id=repo_id, filename=filename, token=token), filename except Exception as exc: errors.append(f"{filename}: {type(exc).__name__}") raise RuntimeError("Could not download a checkpoint. Tried " + "; ".join(errors))
def main(): parser = argparse.ArgumentParser(description="Chat with ViuAI-500M.") parser.add_argument("--repo-id", default=os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")) parser.add_argument("--checkpoint", choices=("sft", "base"), default="sft") parser.add_argument( "--sft-checkpoint-dir", default=os.environ.get("SFT_CHECKPOINT_DIR", "sft_checkpoints/sft_v1"), help="Hugging Face directory containing the SFT checkpoints.", ) args = parser.parse_args()
token = os.environ.get("HF_TOKEN") device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Loading ViuAI-500M on {device.upper()} ({args.checkpoint} checkpoint)...")
tokenizer = load_tokenizer(args.repo_id, token) checkpoint_path, checkpoint_name = download_checkpoint( args.repo_id, args.checkpoint, args.sft_checkpoint_dir.strip("/"), token ) checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
vocab_size = 64005 if args.checkpoint == "sft" else 64000 model = ViuAI(ViuAIConfig(vocab_size=vocab_size, use_checkpoint=False)).to(device) model.load_state_dict(strip_training_prefixes(checkpoint["model"]), strict=True) model.head.weight = model.tok_emb.weight model.eval() print(f"Ready: {checkpoint_name}. Type 'quit' or 'exit' to stop.")
end_of_turn_id = tokenizer.convert_tokens_to_ids("<|endofturn|>") while True: try: message = input("You: ").strip() except (EOFError, KeyboardInterrupt): print() break if message.lower() in {"quit", "exit"}: break if not message: continue
# This must match the special-token format used while building SFT data. prompt = f"<|user|>{message}<|endofturn|><|assistant|>" input_ids = tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device) output_ids = model.generate( input_ids, max_new_tokens=256, temperature=0.7, top_k=40, top_p=0.9, repetition_penalty=1.1, eos_token_id=end_of_turn_id, ) # Decode with special tokens to catch <think> tags reply = tokenizer.decode(output_ids[0, input_ids.size(1):], skip_special_tokens=False) reply = reply.replace("<|endofturn|>", "") import re think_match = re.search(r'<think>(.*?)</think>', reply, re.DOTALL) if think_match: thinking = think_match.group(1).strip() reply = re.sub(r'<think>.*?</think>', '', reply, flags=re.DOTALL).strip() print(f"\033[90m🤔 [Thinking...]\n{thinking}\033[0m\n" + "-"*40) print(f"🤖 ViuAI: {reply.strip()}\n")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""ViuAI-500M Chat with Internet Access (RAG)===========================================Yeh script model ko real-time internet search ka power deti hai.- Simple sawaalon ka seedha jawaab (bina internet ke)- Time-sensitive sawaalon pe auto-detect karke internet search- /search command se manual force search bhi kar sakte ho- <think> tags ke sath integration
Usage: python chat_internet.py python chat_internet.py --checkpoint base python chat_internet.py --tavily-key tvly-xxxxx"""
import argparseimport osimport refrom datetime import datetime
import torchfrom huggingface_hub import hf_hub_downloadfrom transformers import PreTrainedTokenizerFast
from config import ViuAIConfigfrom model import ViuAI
# ============================================================================# 1. Search Triggers — Auto-detect keywords# ============================================================================SEARCH_TRIGGERS = [ # English "today", "latest", "current", "now", "recent", "new", "yesterday", "tomorrow", "this week", "this month", "this year", "news", "score", "match", "result", "won", "lost", "winner", "weather", "temperature", "forecast", "price", "rate", "stock", "market", "sensex", "nifty", "who is", "what is the", "how much", "how many", "2024", "2025", "2026", "2027", # Hindi / Hinglish "aaj", "abhi", "kal", "latest", "nayi", "naya", "khabar", "samachar", "news", "mausam", "taapmaan", "kimat", "rate", "bhav", "daam", "kisne jeeta", "kaun jeeta", "score kya", "kya hua", "kab hua",]
def needs_search(message: str) -> bool: """Check if user's message needs an internet search.""" msg_lower = message.lower() # Manual force: /search command if msg_lower.startswith("/search"): return True # Auto-detect return any(trigger in msg_lower for trigger in SEARCH_TRIGGERS)
def clean_search_query(message: str) -> str: """Extract the actual search query from the user message.""" if message.lower().startswith("/search"): return message[7:].strip() return message
# ============================================================================# 2. Internet Search Functions# ============================================================================def search_with_googlesearch(query: str, num_results: int = 3) -> list[dict]: """Search using googlesearch-python (no API key needed).""" try: from googlesearch import search as gsearch results = [] for url in gsearch(query, num_results=num_results, lang="en"): results.append({"title": url, "body": url}) return results except ImportError: return [] except Exception: return []
def search_with_ddgs(query: str, num_results: int = 3) -> list[dict]: """Search using duckduckgo-search (fallback, no API key needed).""" try: from duckduckgo_search import DDGS with DDGS() as ddgs: results = list(ddgs.text(query, max_results=num_results)) return results except ImportError: return [] except Exception: return []
def search_with_tavily(query: str, api_key: str, num_results: int = 3) -> list[dict]: """Search using Tavily API (best quality, needs free API key).""" try: from tavily import TavilyClient client = TavilyClient(api_key=api_key) response = client.search(query, max_results=num_results) results = [] for r in response.get("results", []): results.append({ "title": r.get("title", ""), "body": r.get("content", ""), }) return results except ImportError: return [] except Exception: return []
def do_search(query: str, tavily_key: str = None) -> str: """ Try search providers in order of reliability: 1. Tavily (if API key provided) 2. googlesearch-python (free, no key) 3. duckduckgo-search (fallback) Returns formatted search context string, truncated to ~600 tokens. """ results = [] source = ""
# Try Tavily first (best quality) if tavily_key: results = search_with_tavily(query, tavily_key) source = "Tavily"
# Try googlesearch-python if not results: results = search_with_googlesearch(query) source = "Google"
# Fallback to DuckDuckGo if not results: results = search_with_ddgs(query) source = "DuckDuckGo"
if not results: return ""
# Format results and truncate to ~600 tokens (~2400 chars) MAX_CHARS = 2400 today = datetime.now().strftime("%d %B %Y") context = f"[Today's Date: {today}]\n[Internet Search Results ({source})]:\n"
for i, r in enumerate(results[:3], 1): title = r.get("title", "").strip() body = r.get("body", "").strip() snippet = f"{i}. {title}: {body}\n" if len(context) + len(snippet) > MAX_CHARS: # Truncate this snippet to fit remaining = MAX_CHARS - len(context) if remaining > 50: context += snippet[:remaining] + "...\n" break context += snippet
print(f"\033[36m📡 [{source}] Found {len(results)} results for: \"{query}\"\033[0m") return context.strip()
# ============================================================================# 3. Model Loading (same as chat.py)# ============================================================================def strip_training_prefixes(state_dict): """Make checkpoints saved with DDP and/or torch.compile loadable.""" cleaned = {} for key, value in state_dict.items(): for prefix in ("module._orig_mod.", "_orig_mod.", "module."): if key.startswith(prefix): key = key[len(prefix):] break cleaned[key] = value return cleaned
def load_tokenizer(repo_id, token): tokenizer_path = hf_hub_download( repo_id=repo_id, filename="tokenizer/tokenizer.json", token=token, ) return PreTrainedTokenizerFast( tokenizer_file=tokenizer_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>", additional_special_tokens=["<|user|>", "<|assistant|>", "<|endofturn|>", "<think>", "</think>"], )
def download_checkpoint(repo_id, checkpoint_kind, sft_checkpoint_dir, token): candidates = ( [ f"{sft_checkpoint_dir}/sft_ckpt_best.pt", f"{sft_checkpoint_dir}/sft_ckpt_latest.pt", "sft_checkpoints/sft_ckpt_best.pt", "sft_checkpoints/sft_ckpt_latest.pt", ] if checkpoint_kind == "sft" else ["checkpoints/ckpt_latest.pt", "checkpoints/ckpt_best.pt"] ) errors = [] for filename in candidates: try: return hf_hub_download(repo_id=repo_id, filename=filename, token=token), filename except Exception as exc: errors.append(f"{filename}: {type(exc).__name__}") raise RuntimeError("Could not download a checkpoint. Tried " + "; ".join(errors))
# ============================================================================# 4. Main Chat Loop with Internet# ============================================================================def main(): parser = argparse.ArgumentParser(description="Chat with ViuAI-500M (with Internet Access).") parser.add_argument("--repo-id", default=os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")) parser.add_argument("--checkpoint", choices=("sft", "base"), default="sft") parser.add_argument( "--sft-checkpoint-dir", default=os.environ.get("SFT_CHECKPOINT_DIR", "sft_checkpoints/sft_v1"), help="Hugging Face directory containing the SFT checkpoints.", ) parser.add_argument( "--tavily-key", default=os.environ.get("TAVILY_API_KEY"), help="Optional Tavily API key for better search results.", ) args = parser.parse_args()
token = os.environ.get("HF_TOKEN") device = "cuda" if torch.cuda.is_available() else "cpu" tavily_key = args.tavily_key
print(f"🚀 Loading ViuAI-500M on {device.upper()} ({args.checkpoint} checkpoint)...")
tokenizer = load_tokenizer(args.repo_id, token) checkpoint_path, checkpoint_name = download_checkpoint( args.repo_id, args.checkpoint, args.sft_checkpoint_dir.strip("/"), token ) checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
vocab_size = 64005 if args.checkpoint == "sft" else 64000 model = ViuAI(ViuAIConfig(vocab_size=vocab_size, use_checkpoint=False)).to(device) model.load_state_dict(strip_training_prefixes(checkpoint["model"]), strict=True) model.head.weight = model.tok_emb.weight model.eval()
print(f"✅ Ready: {checkpoint_name}") print(f"🌐 Internet: {'Tavily ✅' if tavily_key else 'Google/DDG (free)'}") print(f"💡 Tips: Type normally for chat. Internet auto-detects time-sensitive questions.") print(f" Use '/search <query>' to force internet search.") print(f" Type 'quit' or 'exit' to stop.\n")
end_of_turn_id = tokenizer.convert_tokens_to_ids("<|endofturn|>")
while True: try: message = input("👤 You: ").strip() except (EOFError, KeyboardInterrupt): print() break if message.lower() in {"quit", "exit"}: break if not message: continue
# --- Check if internet search is needed --- search_context = "" if needs_search(message): query = clean_search_query(message) print(f"\033[33m🔍 Auto-detected: Searching internet...\033[0m") search_context = do_search(query, tavily_key) if not search_context: print(f"\033[31m⚠️ Internet search failed. Answering without search.\033[0m")
# --- Build prompt --- if search_context: # RAG prompt: inject search context into user message user_content = f"{search_context}\n\nSawaal: {message}" else: user_content = message
prompt = f"<|user|>{user_content}<|endofturn|><|assistant|>" input_ids = tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device)
# --- Check token budget --- max_new = min(512, 2048 - input_ids.size(1)) if max_new < 64: print(f"\033[31m⚠️ Search results too long, truncating...\033[0m") # Truncate input to leave room input_ids = input_ids[:, -1536:] max_new = 512
# --- Generate --- output_ids = model.generate( input_ids, max_new_tokens=max_new, temperature=0.7, top_k=40, top_p=0.9, repetition_penalty=1.1, eos_token_id=end_of_turn_id, )
# --- Decode and parse think tags --- reply = tokenizer.decode(output_ids[0, input_ids.size(1):], skip_special_tokens=False) reply = reply.replace("<|endofturn|>", "")
think_match = re.search(r'<think>(.*?)</think>', reply, re.DOTALL) if think_match: thinking = think_match.group(1).strip() reply = re.sub(r'<think>.*?</think>', '', reply, flags=re.DOTALL).strip() print(f"\033[90m🤔 [Thinking...]\n{thinking}\033[0m\n" + "-" * 40)
print(f"🤖 ViuAI: {reply.strip()}\n")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404# ============================================================================# ViuAI 500M — SFT Data Preparation Script# ============================================================================# Yeh script Kaggle/GPU notebook pe ek cell mein run karein.# Kya karegi:# 1. Raw JSONL data download (ViuAI/viuai-250m-sft-data)# 2. 500M tokenizer download (ViuAI/ViuAI-500M)# 3. Special tokens register (<|user|>=64000, <|assistant|>=64001, <|endofturn|>=64002)# 4. Proper ChatML format mein tokenize# 5. .npy files save + upload to ViuAI/viuai-500m-sft-tokenized# ============================================================================
import os, sys, json, randomimport numpy as npfrom huggingface_hub import HfApi, hf_hub_download, create_repofrom transformers import PreTrainedTokenizerFastfrom tokenizers import AddedToken
# --- Settings ---# Maine token yahan direct daal diya hai taaki Kaggle pe error na aayeHF_TOKEN = os.environ.get("HF_TOKEN")
MODEL_REPO = "ViuAI/ViuAI-500M"RAW_DATA_REPO = "ViuAI/viuai-250m-sft-data"OUTPUT_REPO = "ViuAI/viuai-500m-sft-tokenized"
api = HfApi(token=HF_TOKEN)
# ============================================================================# 1. Download Tokenizer from 500M Repo# ============================================================================print("📥 Step 1: Downloading 500M tokenizer...")tok_path = hf_hub_download( repo_id=MODEL_REPO, filename="tokenizer/tokenizer.json", repo_type="model", token=HF_TOKEN)tokenizer = PreTrainedTokenizerFast(tokenizer_file=tok_path)print(f" Base vocab size: {tokenizer.vocab_size}")
# Register 5 special tokens (3 for chat, 2 for reasoning)special_tokens = [ AddedToken("<|user|>", single_word=True, special=True), AddedToken("<|assistant|>", single_word=True, special=True), AddedToken("<|endofturn|>", single_word=True, special=True), AddedToken("<think>", single_word=True, special=True), AddedToken("</think>", single_word=True, special=True),]tokenizer.add_tokens(special_tokens)
# Verify special token IDsassert tokenizer.encode("<|user|>") == [64000], f"<|user|> = {tokenizer.encode('<|user|>')}, expected [64000]"assert tokenizer.encode("<|assistant|>") == [64001], f"<|assistant|> = {tokenizer.encode('<|assistant|>')}, expected [64001]"assert tokenizer.encode("<|endofturn|>") == [64002], f"<|endofturn|> = {tokenizer.encode('<|endofturn|>')}, expected [64002]"assert tokenizer.encode("<think>") == [64003], f"<think> = {tokenizer.encode('<think>')}, expected [64003]"assert tokenizer.encode("</think>") == [64004], f"</think> = {tokenizer.encode('</think>')}, expected [64004]"print(f" ✅ Special tokens: <|user|>=64000, <|assistant|>=64001, <|endofturn|>=64002, <think>=64003, </think>=64004")print(f" Total vocab: {tokenizer.vocab_size + len(tokenizer.added_tokens_encoder)} (64000 base + 5 special)")
# ============================================================================# 2. Download Raw JSONL Data# ============================================================================print("\n📥 Step 2: Downloading raw SFT data...")raw_files = ["casual_chat.jsonl", "casual_hinglish.jsonl", "sft_train.jsonl", "sft_val.jsonl"]local_paths = {}
for fname in raw_files: try: p = hf_hub_download(repo_id=RAW_DATA_REPO, filename=fname, repo_type="dataset", token=HF_TOKEN) local_paths[fname] = p print(f" ✅ {fname}") except Exception as e: print(f" ⚠️ {fname}: {e}")
# ============================================================================# 3. Parse All Conversations from JSONL# ============================================================================print("\n🔄 Step 3: Parsing conversations...")
def parse_jsonl(filepath): """Parse JSONL or JSON array file into list of (user, assistant) pairs.""" conversations = [] with open(filepath, 'r', encoding='utf-8') as f: content = f.read().strip() # Try as JSON array first items = [] try: parsed = json.loads(content) if isinstance(parsed, list): items = parsed elif isinstance(parsed, dict): items = [parsed] except json.JSONDecodeError: # Fall back to JSONL (line by line) for line in content.split('\n'): line = line.strip() if not line: continue try: parsed = json.loads(line) if isinstance(parsed, list): items.extend(parsed) elif isinstance(parsed, dict): items.append(parsed) except json.JSONDecodeError: continue for item in items: if not isinstance(item, dict): continue user_text = "" assistant_text = "" # Format 1: messages array (ChatML) if "messages" in item and isinstance(item["messages"], list): for msg in item["messages"]: role = msg.get("role", "") content = msg.get("content", "") if role in ["user", "human"]: user_text = content elif role in ["assistant", "model", "bot"]: assistant_text = content # Format 2: conversations array (ShareGPT) elif "conversations" in item and isinstance(item["conversations"], list): for convo in item["conversations"]: from_role = convo.get("from", "") val = convo.get("value", "") if from_role == "human": user_text = val elif from_role in ["gpt", "assistant", "bot"]: assistant_text = val # Format 3: Direct keys else: user_text = item.get("user") or item.get("instruction") or item.get("prompt") or item.get("q", "") assistant_text = item.get("assistant") or item.get("output") or item.get("response") or item.get("a", "") input_text = item.get("input", "") if input_text and user_text: user_text = f"{user_text}\n{input_text}" if user_text and assistant_text: conversations.append((user_text.strip(), assistant_text.strip())) return conversations
# Parse all filestrain_convos = []val_convos = []
# Train filesfor fname in ["sft_train.jsonl", "casual_chat.jsonl", "casual_hinglish.jsonl"]: if fname in local_paths: convos = parse_jsonl(local_paths[fname]) train_convos.extend(convos) print(f" {fname}: {len(convos)} conversations")
# Val filesif "sft_val.jsonl" in local_paths: convos = parse_jsonl(local_paths["sft_val.jsonl"]) val_convos.extend(convos) print(f" sft_val.jsonl: {len(convos)} conversations")
# ============================================================================# 3.5 Download and Add Reasoning Data (Bespoke-Stratos-17k)# ============================================================================print("\n🧠 Step 3.5: Downloading Reasoning Data (Stratos-17k)...")try: from datasets import load_datasetexcept ImportError: import subprocess print(" Installing 'datasets' library...") subprocess.check_call([sys.executable, "-m", "pip", "install", "datasets", "-q"]) from datasets import load_dataset
try: reasoning_ds = load_dataset("bespokelabs/Bespoke-Stratos-17k", split="train") reasoning_convos = [] for item in reasoning_ds: msgs = item.get("messages", []) if len(msgs) >= 2: user_text = "" assistant_text = "" for msg in msgs: if msg.get("role") == "user": user_text = msg.get("content", "") elif msg.get("role") == "assistant": assistant_text = msg.get("content", "") if user_text and assistant_text and "<think>" in assistant_text: # Filter out very long reasoning chains (approx > 1024 words) to fit 500M model if len(assistant_text.split()) < 1024: reasoning_convos.append((user_text, assistant_text)) print(f" ✅ Loaded {len(reasoning_convos)} valid reasoning examples (filtered short ones).") # Mix reasoning into training data train_convos.extend(reasoning_convos)except Exception as e: print(f" ⚠️ Failed to load reasoning dataset: {e}")
# ============================================================================# 4. Add ViuAI Identity Data# ============================================================================print("\n🤖 Step 4: Adding ViuAI identity data...")
identity_data = [ ("Who are you?", "I am ViuAI, a helpful AI assistant. I'm here to help you with questions, conversations, and tasks. How can I help you today?"), ("What is your name?", "My name is ViuAI. I am an AI language model designed to be helpful, harmless, and honest."), ("Tell me about yourself.", "I am ViuAI, an AI assistant created to help people with a wide range of tasks. I can answer questions, write text, help with coding, and have conversations in both English and Hindi."), ("Are you ChatGPT?", "No, I am not ChatGPT. I am ViuAI, a different AI assistant. While we are both language models, I was created independently with my own training and capabilities."), ("Are you GPT?", "No, I am ViuAI, not GPT. I am a separate AI model with my own architecture and training. I'm happy to help you with any questions!"), ("तुम कौन हो?", "मैं ViuAI हूँ, एक AI सहायक। मैं आपकी मदद करने के लिए यहाँ हूँ। आप मुझसे कोई भी सवाल पूछ सकते हैं!"), ("तुम्हारा नाम क्या है?", "मेरा नाम ViuAI है। मैं एक AI भाषा मॉडल हूँ जो लोगों की मदद करने के लिए बनाया गया है।"), ("क्या तुम ChatGPT हो?", "नहीं, मैं ChatGPT नहीं हूँ। मेरा नाम ViuAI है और मैं एक अलग AI मॉडल हूँ। मैं आपकी किसी भी सवाल में मदद कर सकता हूँ!"), ("Hello!", "Hello! I'm ViuAI, your AI assistant. How can I help you today?"), ("Hi there!", "Hi! I'm ViuAI. Feel free to ask me anything — I'm here to help!"), ("नमस्ते!", "नमस्ते! मैं ViuAI हूँ। आज मैं आपकी कैसे मदद कर सकता हूँ?"), ("What can you do?", "As ViuAI, I can help you with many things! I can answer questions, write text, help with coding, explain concepts, translate between languages, and have conversations in English and Hindi. What would you like help with?"), ("तुम क्या कर सकते हो?", "मैं ViuAI हूँ और मैं बहुत कुछ कर सकता हूँ! मैं सवालों के जवाब दे सकता हूँ, लेख लिख सकता हूँ, कोडिंग में मदद कर सकता हूँ, और हिंदी और अंग्रेजी दोनों में बातचीत कर सकता हूँ।"), ("Who created you?", "I am ViuAI, created by the ViuAI team. I was built to be a helpful, safe, and informative AI assistant."), ("तुम्हें किसने बनाया?", "मुझे ViuAI टीम ने बनाया है। मैं एक सहायक, सुरक्षित और जानकारीपूर्ण AI सहायक के रूप में बनाया गया हूँ।"),]
# Repeat identity data to increase weight (model ko zyada baar dikhega)identity_repeated = identity_data * 20 # 15 examples * 20 = 300 examplesrandom.seed(42)random.shuffle(identity_repeated)
train_convos.extend(identity_repeated)print(f" Added {len(identity_repeated)} identity examples")
# Shuffle training datarandom.shuffle(train_convos)
print(f"\n📊 Final counts:")print(f" Train: {len(train_convos)} conversations")print(f" Val: {len(val_convos)} conversations")
# ============================================================================# 5. Tokenize with Proper ChatML Format# ============================================================================print("\n🔄 Step 5: Tokenizing with ChatML special tokens...")
USER_TOKEN_ID = 64000 # <|user|>ASSISTANT_TOKEN_ID = 64001 # <|assistant|>EOT_TOKEN_ID = 64002 # <|endofturn|>NEWLINE_IDS = tokenizer.encode("\n", add_special_tokens=False)
def tokenize_conversation(user_text, assistant_text): """ Tokenize a single conversation into ChatML format: <|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n{answer}<|endofturn|> Labels: -100 on user turn, actual IDs on assistant turn """ # User turn tokens user_content_ids = tokenizer.encode(user_text, add_special_tokens=False) user_turn = [USER_TOKEN_ID] + NEWLINE_IDS + user_content_ids + [EOT_TOKEN_ID] + NEWLINE_IDS # Assistant turn tokens assistant_content_ids = tokenizer.encode(assistant_text, add_special_tokens=False) assistant_turn = [ASSISTANT_TOKEN_ID] + NEWLINE_IDS + assistant_content_ids + [EOT_TOKEN_ID] # Full sequence input_ids = user_turn + assistant_turn # Labels: mask user turn (-100), keep assistant turn # Note: We also mask the <|assistant|> token itself and the \n after it # The model learns to predict starting from the first content token of assistant assistant_prefix_len = 1 + len(NEWLINE_IDS) # <|assistant|> + \n masked_len = len(user_turn) + assistant_prefix_len labels = [-100] * masked_len + assistant_content_ids + [EOT_TOKEN_ID] assert len(input_ids) == len(labels), f"Length mismatch: ids={len(input_ids)}, labels={len(labels)}" return input_ids, labels
def process_conversations(conversations, prefix): """Process list of (user, assistant) tuples into .npy files.""" all_ids = [] all_labels = [] offsets = [] current_offset = 0 skipped = 0 for i, (user, assistant) in enumerate(conversations): try: ids, labels = tokenize_conversation(user, assistant) # Skip very short or very long examples if len(ids) < 5: skipped += 1 continue if len(ids) > 4096: # Truncate to 4096 ids = ids[:4096] labels = labels[:4096] offsets.append(current_offset) all_ids.extend(ids) all_labels.extend(labels) current_offset += len(ids) except Exception as e: skipped += 1 if skipped <= 5: print(f" ⚠️ Skipped example {i}: {e}") if not all_ids: print(f" ❌ No data for {prefix}!") return [] # Add final offset sentinel offsets.append(current_offset) ids_np = np.array(all_ids, dtype=np.int64) labels_np = np.array(all_labels, dtype=np.int64) offsets_np = np.array(offsets, dtype=np.int64) print(f" 📊 {prefix}: {len(offsets)-1} examples, {len(all_ids):,} tokens, {skipped} skipped") print(f" Min ID: {ids_np.min()}, Max ID: {ids_np.max()}") # Verify special tokens exist has_user = np.any(ids_np == 64000) has_asst = np.any(ids_np == 64001) has_eot = np.any(ids_np == 64002) print(f" <|user|>(64000): {'✅' if has_user else '❌'} | <|assistant|>(64001): {'✅' if has_asst else '❌'} | <|endofturn|>(64002): {'✅' if has_eot else '❌'}") # Save .npy files files = [] for suffix, arr in [("ids", ids_np), ("labels", labels_np), ("offsets", offsets_np)]: fname = f"{prefix}_{suffix}.npy" np.save(fname, arr) files.append(fname) print(f" 💾 Saved {fname} ({arr.nbytes / 1e6:.1f} MB)") return files
# Process train and valtrain_files = process_conversations(train_convos, "sft_train")val_files = process_conversations(val_convos, "sft_val")
# ============================================================================# 6. Decode Sample to Verify# ============================================================================print(f"\n{'='*60}")print("🔍 Step 6: Verification - Decoding first 3 examples")print(f"{'='*60}")
ids_check = np.load("sft_train_ids.npy", mmap_mode='r')labels_check = np.load("sft_train_labels.npy", mmap_mode='r')offsets_check = np.load("sft_train_offsets.npy")
for i in range(min(3, len(offsets_check)-1)): start = int(offsets_check[i]) end = int(offsets_check[i+1]) ex_ids = ids_check[start:end].tolist() ex_labels = labels_check[start:end].tolist() decoded = tokenizer.decode(ex_ids) masked = sum(1 for l in ex_labels if l == -100) active = sum(1 for l in ex_labels if l != -100) print(f"\n--- Example {i} (len={len(ex_ids)}, masked={masked}, active={active}) ---") print(decoded[:300])
# ============================================================================# 7. Upload to HuggingFace# ============================================================================print(f"\n{'='*60}")print(f"🚀 Step 7: Uploading to {OUTPUT_REPO}...")print(f"{'='*60}")
create_repo(OUTPUT_REPO, repo_type="dataset", token=HF_TOKEN, exist_ok=True, private=True)
all_files = train_files + val_filesfor fpath in all_files: print(f" Uploading {fpath}...") api.upload_file( path_or_fileobj=fpath, path_in_repo=fpath, repo_id=OUTPUT_REPO, repo_type="dataset", token=HF_TOKEN, ) print(f" ✅ {fpath} uploaded!")
print(f"\n🎉 ALL DONE! New tokenized data uploaded to {OUTPUT_REPO}")print(f" Now update train_sft.py:")print(f" - SFT_VOCAB_SIZE = 64005")print(f" - SFT_DATA_REPO = '{OUTPUT_REPO}'")
print(f"\n💾 Saving and Uploading Updated Tokenizer with <think> tags...")tokenizer.save_pretrained("updated_tokenizer")api.upload_folder( folder_path="updated_tokenizer", repo_id=OUTPUT_REPO, repo_type="dataset", token=HF_TOKEN,)print(" ✅ Tokenizer uploaded successfully!")226 unmodified lines227228229230231232233234235389 unmodified lines625626627628629630631226 unmodified linesEVAL_EVERY = 1000CKPT_EVERY = 4000# Vocab size: 64003 because new SFT data uses 3 special tokens (<|user|>, <|assistant|>, <|endofturn|>)# Base model was trained with 64000 vocab, so embedding resize will happenSFT_VOCAB_SIZE = 64003TARGET_EFFECTIVE_BATCH = int(os.environ.get("TARGET_EFFECTIVE_BATCH", "64"))GRAD_ACCUM = max(1, TARGET_EFFECTIVE_BATCH // (MICRO_BATCH * world_size))389 unmodified lines# 12. Model Initialization# ============================================================================cfg = ViuAIConfig(vocab_size=SFT_VOCAB_SIZE, # 64003 (includes <|user|>, <|assistant|>, <|endofturn|>)context_length=CONTEXT_LEN,use_checkpoint=True, # Gradient checkpointing (saves VRAM)z_loss_weight=0.0, # Disable z-loss for SFT226 unmodified lines227228229230231232233234389 unmodified lines624625626627628629630226 unmodified linesEVAL_EVERY = 1000CKPT_EVERY = 4000# Vocab size: 64005 because new SFT data uses 5 special tokens (<|user|>, <|assistant|>, <|endofturn|>, <think>, </think>)SFT_VOCAB_SIZE = 64005TARGET_EFFECTIVE_BATCH = int(os.environ.get("TARGET_EFFECTIVE_BATCH", "64"))GRAD_ACCUM = max(1, TARGET_EFFECTIVE_BATCH // (MICRO_BATCH * world_size))389 unmodified lines# 12. Model Initialization# ============================================================================cfg = ViuAIConfig(vocab_size=SFT_VOCAB_SIZE, # 64005 (includes <|user|>, <|assistant|>, <|endofturn|>, <think>, </think>)context_length=CONTEXT_LEN,use_checkpoint=True, # Gradient checkpointing (saves VRAM)z_loss_weight=0.0, # Disable z-loss for SFT
code/__pycache__/chat.cpython-313.pycAdded
code/__pycache__/config.cpython-313.pycAdded
code/__pycache__/model.cpython-313.pycAdded
code/__pycache__/train.cpython-313.pycAdded
code/__pycache__/train_sft.cpython-313.pycAdded
code/chat.pyAdded+128
code/chat_internet.pyAdded+315
code/prepare_sft_data.pyAdded+404
code/train_sft.py+3-4