Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627284 unmodified lines3334353637383951 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118216 unmodified lines19920020120220320420520620720824 unmodified lines233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271# ================================================================# CodeSymb AI โ THE DYNAMIC LORA SHAPE-SHIFTER ๐ฆ๐ฅ# Runs natively on Hugging Face Spaces!# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐# ================================================================import osimport spaces # <--- THIS WAS MISSING IN YOUR ERROR!import gradio as grimport torchimport torch.nn as nnimport torch.nn.functional as Fimport sentencepiece as spmfrom huggingface_hub import hf_hub_download, loginHF_TOKEN = os.environ.get("HF_TOKEN", "")USERNAME = "NiftyOracleAI"REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"LORA_REPO = f"{USERNAME}/codesymb-lora-vault"TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"if HF_TOKEN: login(token=HF_TOKEN)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MODEL ARCHITECTURE (T4/A100 Float16 Compatible)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass RMSNorm(nn.Module):def __init__(self, d, eps=1e-6):4 unmodified linesreturn (x.float() * n).to(x.dtype) * self.w.to(x.dtype)class RoPE(nn.Module):def __init__(self, dim, max_len=2048, base=500_000):super().__init__()inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)51 unmodified linesself.norm = RMSNorm(DM)self.head = nn.Linear(DM, vocab, bias=False)def forward(self, tok):x = self.embed(tok).to(torch.float16)for b in self.blocks: x = b(x)return self.head(self.norm(x))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# LOAD BASE MODEL INTO RAM ONCE# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โณ Loading Tokenizer...")tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)sp = spm.SentencePieceProcessor(); sp.load(tok_path)print("โณ Loading Base Model (240k steps)...")model = CodeSymb1B(vocab=sp.get_piece_size())base_ckpt = hf_hub_download(REPO_ID, "checkpoints/latest.pt", token=HF_TOKEN or None)state = torch.load(base_ckpt, map_location="cpu", weights_only=False)# Keep a pristine copy of the base weights in RAM so we can swap LoRAs infinitely!BASE_WEIGHTS = {k: v for k, v in state.get("model", state).items() if not k.endswith((".pe.cos", ".pe.sin"))}model.load_state_dict(BASE_WEIGHTS, strict=False)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = model.to(device).half().eval()CURRENT_LORA = "None"print("โ Base Model is LIVE!")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# DYNAMIC LORA HOT-SWAPPER# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef switch_lora(expert_name):global CURRENT_LORAif expert_name == CURRENT_LORA:return # Already loaded!print(f"๐ Swapping Brain to: {expert_name}...")# 1. Reset model to pristine Base Weightsmodel.load_state_dict(BASE_WEIGHTS, strict=False)if expert_name == "Base Model (No Expert)":CURRENT_LORA = expert_namereturn# 2. Download and fuse the requested LoRA!try:lora_ckpt = hf_hub_download(LORA_REPO, f"loras/{expert_name}/adapter.pt", token=HF_TOKEN or None)lora_state = torch.load(lora_ckpt, map_location="cpu", weights_only=False)scale = 200 / 100 # Alpha / Rank for our H100 LoRAswith torch.no_grad():for i, block in enumerate(model.blocks):for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:A_key = f"blocks.{i}.{layer_name}.A"B_key = f"blocks.{i}.{layer_name}.B"if A_key in lora_state and B_key in lora_state:A = lora_state[A_key].float().to(device)B = lora_state[B_key].float().to(device)delta = (A @ B).T * scaletarget_layer = getattr(block, layer_name.split(".")[0])sub_layer = getattr(target_layer, layer_name.split(".")[1])sub_layer.weight.data += delta.to(torch.float16)CURRENT_LORA = expert_nameprint(f"โ {expert_name} Fused Successfully!")except Exception as e:print(f"โ ๏ธ Failed to load {expert_name}: {e}")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# INFERENCE ENGINE# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ@spaces.GPU(duration=60)def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:# ๐ฅ DYNAMICALLY SHAPE-SHIFT THE BRAIN!switch_lora(expert_choice)system_prompt = (f"You are CodeSymb, acting as the {expert_choice}. You are deeply empathetic, ""passionate, and highly intelligent. Built by Dev Malkar and Founder Deepakkumar Malkar ""at NiftyOracle India. Provide flawless code and do not hallucinate.")full_prompt = f"<|system|>\n{system_prompt}\n"# Bulletproof Gradio 4+ History Parser!for msg in history[-6:]: # Last 3 conversation turnsif isinstance(msg, dict):role = "<|user|>" if msg.get("role") == "user" else "<|assistant|>"full_prompt += f"{role}\n{msg.get('content', '')}\n"16 unmodified lineswith torch.autocast("cuda", dtype=torch.float16):logits = model(inp)[0, -1, :].float()for gid in set(generated[-50:]):logits[gid] -= 2.0logits = logits / 0.6top_k_values, _ = torch.topk(logits, 40)logits[logits < top_k_values[-1]] = -float('inf')24 unmodified linesfor tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:response = response.split(tag)[0].strip()return response# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# GRADIO UI WITH EXPERT DROPDOWN!# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"), css="body { background: #060D1F !important; color: white !important; }") as demo:gr.HTML("""<h1 style='text-align:center; color:#00D4FF;'>โก CodeSymb AI: Expert Swarm</h1><p style='text-align:center; color:#A0AEC0;'>Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br><em>"Impossible is just a door with no handle yet invented."</em></p>""")with gr.Row():expert_dropdown = gr.Dropdown(choices=["Base Model (No Expert)","python","javascript","cpp","react_jsx","hindi"],value="python",label="๐ง Select CodeSymb Expert Brain",interactive=True)gr.ChatInterface(fn=chat_with_codesymb,additional_inputs=[expert_dropdown])if __name__ == "__main__":demo.launch()12345678910111213141516171819202122234 unmodified lines2829303132333451 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715816 unmodified lines17517617717817918018118218318418524 unmodified lines210211212213214215216217218219220221222223224225import gradio as grimport torchimport torch.nn as nnimport torch.nn.functional as Fimport sentencepiece as spmimport spacesimport osfrom huggingface_hub import hf_hub_download, loginfrom safetensors.torch import load_fileHF_TOKEN = os.environ.get("HF_TOKEN", "")USERNAME = "NiftyOracleAI"REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"LORA_REPO = f"{USERNAME}/codesymb-chat-lora"TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"if HF_TOKEN: login(token=HF_TOKEN)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 1. CORE ARCHITECTURE# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass RMSNorm(nn.Module):def __init__(self, d, eps=1e-6):4 unmodified linesreturn (x.float() * n).to(x.dtype) * self.w.to(x.dtype)class RoPE(nn.Module):def __init__(self, dim, max_len=2048, base=500_000): # Fixed 2048super().__init__()inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)51 unmodified linesself.norm = RMSNorm(DM)self.head = nn.Linear(DM, vocab, bias=False)def forward(self, tok):x = self.embed(tok).half()for b in self.blocks: x = b(x)return self.head(self.norm(x))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 2. LOAD & PERMANENTLY FUSE THE CHAT LORA# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โณ Loading Tokenizer...")tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)sp = spm.SentencePieceProcessor(); sp.load(tok_path)print("โณ Loading 240k Base Model...")model = CodeSymb1B(vocab=sp.get_piece_size())base_ckpt = hf_hub_download(REPO_ID, "checkpoints/latest.pt", token=HF_TOKEN or None)state = torch.load(base_ckpt, map_location="cpu", weights_only=False)base_weights = {k: v for k, v in state.get("model", state).items() if not k.endswith((".pe.cos", ".pe.sin"))}model.load_state_dict(base_weights, strict=False)print("โ Base Model Loaded.")print("โก FUSING RANK-100 CHAT LORA PERMANENTLY...")try:# Fetch the exact Chat LoRA we trained on Modal for empathy!lora_ckpt = hf_hub_download(LORA_REPO, "chat-behavior-lora/adapter_model.safetensors", token=HF_TOKEN or None)lora_state = load_file(lora_ckpt)scale = 200 / 100 # Alpha / Rankwith torch.no_grad():for i, block in enumerate(model.blocks):for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:A_key = f"base_model.model.blocks.{i}.{layer_name}.lora_A.weight"B_key = f"base_model.model.blocks.{i}.{layer_name}.lora_B.weight"if A_key in lora_state and B_key in lora_state:A = lora_state[A_key].float()B = lora_state[B_key].float()delta = (B @ A) * scale # safetensors usually stores B@A shape!target_layer = getattr(block, layer_name.split(".")[0])sub_layer = getattr(target_layer, layer_name.split(".")[1])sub_layer.weight.data += delta.to(sub_layer.weight.dtype)print("โ Chat LoRA Fused! The AI now has a heart! โค๏ธ")except Exception as e:print(f"โ ๏ธ Failed to fuse Chat LoRA: {e}")device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = model.to(device).half().eval()print(f"โ CodeSymb is ALIVE on {device}!")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 3. INFERENCE ENGINE (STRICT CHAT MODE)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ@spaces.GPU(duration=60)def chat_with_codesymb(message: str, history: list) -> str:device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)# The exact prompt we trained it onsystem_prompt = ("You are CodeSymb, a highly intelligent and empathetic AI coding partner built by ""Developer Dev Malkar and Founder Deepakkumar Malkar at NiftyOracle in India. ""You provide direct, accurate, and clean code. You answer conversations naturally and never hallucinate.")full_prompt = f"<|system|>\n{system_prompt}\n"for msg in history[-3:]:if isinstance(msg, dict):role = "<|user|>" if msg.get("role") == "user" else "<|assistant|>"full_prompt += f"{role}\n{msg.get('content', '')}\n"16 unmodified lineswith torch.autocast("cuda", dtype=torch.float16):logits = model(inp)[0, -1, :].float()# Stop infinite loopsfor gid in set(generated[-50:]):logits[gid] -= 2.0logits = logits / 0.5 # Low temp for logical focustop_k_values, _ = torch.topk(logits, 40)logits[logits < top_k_values[-1]] = -float('inf')24 unmodified linesfor tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:response = response.split(tag)[0].strip()return response if response else "I am CodeSymb! How can I help you? ๐ฅ"with gr.Blocks(theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"), css="body { background: #060D1F !important; color: white !important; }") as demo:gr.HTML("""<h1 style='text-align:center; color:#00D4FF;'>โก CodeSymb AI: Chat Mode</h1><p style='text-align:center; color:#A0AEC0;'>Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br></p>""")gr.ChatInterface(fn=chat_with_codesymb)if __name__ == "__main__":demo.launch()
app.py+53-99