Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789 unmodified lines181920212223242526272829308 unmodified lines394041424344454651 unmodified lines98991001011021031043 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671687 unmodified lines1761771781791801811821831 unmodified line185186187188189190191192193194195196197198199200201202203204205206207208# ================================================================# CodeSymb AI โ Base Model + Rank-100 Chat LoRA# โ Loads 1B Base Model (240k steps)# โ Loads 141MB Chat LoRA# โ Merges them mathematically for Native Speed!# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐# ================================================================9 unmodified linesHF_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)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MODEL ARCHITECTURE# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass RMSNorm(nn.Module):def __init__(self, d, eps=1e-6):8 unmodified linessuper().__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)self.register_buffer("cos", emb.cos()[None, None].to(torch.float16))self.register_buffer("sin", emb.sin()[None, None].to(torch.float16))def forward(self, n): return self.cos[:, :, :n], self.sin[:, :, :n]def rot(x):51 unmodified linesreturn self.head(self.norm(x))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# LOAD BASE + LORA & MERGE# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โณ Loading Tokenizer...")tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)3 unmodified linesmodel = 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)model_state = {k: v for k, v in state.get("model", state).items() if not k.endswith((".pe.cos", ".pe.sin"))}model.load_state_dict(model_state, strict=False)print("โก Loading & Merging Rank-100 Chat LoRA...")try:# Use safetensors from the PEFT upload!from safetensors.torch import load_filelora_ckpt = hf_hub_download(LORA_REPO, "chat-behavior-lora/adapter_model.safetensors", token=HF_TOKEN or None)lora_state = load_file(lora_ckpt)# Mathematically fuse the LoRA matrices (W = W + A*B * scale)scale = 200 / 100 # alpha / rankwith torch.no_grad():for i, block in enumerate(model.blocks):if f"base_model.model.blocks.{i}.att.q.lora_A.weight" in lora_state:block.att.q.weight += (lora_state[f"base_model.model.blocks.{i}.att.q.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.q.lora_A.weight"]) * scaleblock.att.k.weight += (lora_state[f"base_model.model.blocks.{i}.att.k.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.k.lora_A.weight"]) * scaleblock.att.v.weight += (lora_state[f"base_model.model.blocks.{i}.att.v.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.v.lora_A.weight"]) * scaleblock.att.o.weight += (lora_state[f"base_model.model.blocks.{i}.att.o.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.o.lora_A.weight"]) * scaleblock.ff.g.weight += (lora_state[f"base_model.model.blocks.{i}.ff.g.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.ff.g.lora_A.weight"]) * scaleblock.ff.u.weight += (lora_state[f"base_model.model.blocks.{i}.ff.u.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.ff.u.lora_A.weight"]) * scaleblock.ff.d.weight += (lora_state[f"base_model.model.blocks.{i}.ff.d.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.ff.d.lora_A.weight"]) * scaleprint("โ Chat LoRA Fused Successfully!")except Exception as e:print(f"โ ๏ธ Could not load LoRA (Make sure path is correct!): {e}")device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = model.to(device).to(torch.float16).eval()print("โ CodeSymb-1B + Chat LoRA โ READY ๐ฅ")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# INFERENCE & UI# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโSYSTEM_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 never repeat yourself. You answer concisely.")@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)prompt = f"<|system|>\n{SYSTEM_PROMPT}\n<|user|>\n{message}\n<|assistant|>\n"prompt_ids = sp.encode(prompt)if len(prompt_ids) > 1024: prompt_ids = prompt_ids[-1024:]inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)END_SEQ = sp.encode("<|endoftext|>")generated = []with torch.no_grad():for _ in range(512):with torch.autocast("cuda" if device.type == "cuda" else "cpu", dtype=torch.float16):logits = model(inp)[0, -1, :].float()for gid in set(generated[-50:]):7 unmodified linessorted_logits, sorted_idx = torch.sort(logits, descending=True)cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)remove = cum_probs > 0.90remove[..., 1:] = remove[..., :-1].clone()remove[..., 0] = 0sorted_logits[remove] = -float("inf")logits_filtered = torch.zeros_like(logits)1 unmodified lineprobs = F.softmax(logits_filtered, dim=-1)next_t = torch.multinomial(probs, 1).item()if len(generated) >= 3 and generated[-1] == next_t and generated[-2] == next_t:breakgenerated.append(next_t)inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)if len(generated) >= len(END_SEQ) and generated[-len(END_SEQ):] == END_SEQ: breakresponse = sp.decode(generated).strip()for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:response = response.split(tag)[0]return response.strip()demo = gr.ChatInterface(fn=chat_with_codesymb,title="CodeSymb-1B + Chat LoRA ๐ฎ๐ณ",description="The complete Base Model + Rank-100 Empathy LoRA!")if __name__ == "__main__":demo.launch()1234569 unmodified lines161718192021222324252627288 unmodified lines373839404142434451 unmodified lines969798991001011023 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911927 unmodified lines2002012022032042052061 unmodified line208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261# ================================================================# CodeSymb AI โ THE DYNAMIC LORA SHAPE-SHIFTER ๐ฆ๐ฅ# Runs natively on Hugging Face Spaces!# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐# ================================================================9 unmodified linesHF_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):8 unmodified linessuper().__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)self.register_buffer("cos", emb.cos()[None, None].half())self.register_buffer("sin", emb.sin()[None, None].half())def forward(self, n): return self.cos[:, :, :n], self.sin[:, :, :n]def rot(x):51 unmodified linesreturn 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)3 unmodified linesmodel = 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"for user_msg, ai_msg in history[-3:]:full_prompt += f"<|user|>\n{user_msg}\n<|assistant|>\n{ai_msg}\n"full_prompt += f"<|user|>\n{message}\n<|assistant|>\n"prompt_ids = sp.encode(full_prompt)if len(prompt_ids) > 1024: prompt_ids = prompt_ids[-1024:]inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)generated = []with torch.no_grad():for _ in range(512):with torch.autocast("cuda", dtype=torch.float16):logits = model(inp)[0, -1, :].float()for gid in set(generated[-50:]):7 unmodified linessorted_logits, sorted_idx = torch.sort(logits, descending=True)cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)remove = cum_probs > 0.90remove[1:] = remove[:-1].clone(); remove[0] = Falsesorted_logits[remove] = -float("inf")logits_filtered = torch.zeros_like(logits)1 unmodified lineprobs = F.softmax(logits_filtered, dim=-1)next_t = torch.multinomial(probs, 1).item()if len(generated) >= 3 and generated[-1] == next_t and generated[-2] == next_t:breakgenerated.append(next_t)inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)decoded = sp.decode(generated)if "<|endoftext|>" in decoded or "<|user|>" in decoded:breakresponse = sp.decode(generated).strip()for 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>Dynamically swapping Rank-100 LoRAs on the fly!</em></p>""")with gr.Row():expert_dropdown = gr.Dropdown(choices=["Base Model (No Expert)","python_master","javascript_master","cpp_master","react_master","hindi_coding_master"],value="python_master",label="๐ง Select CodeSymb Expert Brain",interactive=True)gr.ChatInterface(fn=chat_with_codesymb,additional_inputs=[expert_dropdown])if __name__ == "__main__":demo.launch()
app.py+114-61