Spaces:
Sleeping
Sleeping
Update app.py
Browse files1237 unmodified lines111213141516171819202122234 unmodified lines28293031323334353637383946 unmodified lines8687888990919293949596978 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331342 unmodified lines13713813914014114214314414514614714814915024 unmodified lines175176177178179180181182183184185import gradio as grimport torchimport torch.nn as nn7 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)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 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)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):46 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)8 unmodified linesmodel.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}")2 unmodified linesprint(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. "24 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')123456789107 unmodified lines181920212223242526272829304 unmodified lines35363738394041424344454646 unmodified lines939495969798991001011021031048 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461472 unmodified lines15015115215315415515615715815916016116224 unmodified lines187188189190191192193194195196197# ================================================================# CodeSymb AI โ HuggingFace Space app.py# โ EXACT URL FIX: codesymb-chat-lora/chat_lora_latest# โ Safetensors PEFT Matrix Fusion# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐# ================================================================import gradio as grimport torchimport torch.nn as nn7 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN", "")USERNAME = "NiftyOracleAI"REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"LORA_REPO = f"{USERNAME}/codesymb-chat-lora" # ๐ฅ MATCHES YOUR EXACT URL!if HF_TOKEN: login(token=HF_TOKEN)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MODEL 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):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)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):46 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))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 1. LOAD BASE MODEL# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โณ Loading Tokenizer...")tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)8 unmodified linesmodel.load_state_dict(base_weights, strict=False)print("โ Base Model Loaded.")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 2. LOAD & FUSE THE EXACT CHAT LORA YOU PROVIDED# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โก FUSING RANK-100 CHAT LORA PERMANENTLY...")try:# ๐ฅ PULLING YOUR EXACT URL!lora_ckpt = hf_hub_download(LORA_REPO, "chat_lora_latest/adapter_model.safetensors", token=HF_TOKEN or None)lora_state = load_file(lora_ckpt)scale = 200 / 100 # Alpha 200 / Rank 100 = 2.0with 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"]:# PEFT standard safetensors keysA_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() # [rank, in_features]B = lora_state[B_key].float() # [out_features, rank]# PEFT Matrix Fusion: W_new = W_old + (B @ A) * scaledelta = (B @ A) * scaletarget_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 its Empathy overrides active! โค๏ธ")except Exception as e:print(f"โ ๏ธ Failed to fuse Chat LoRA: {e}")2 unmodified linesprint(f"โ CodeSymb is ALIVE on {device}!")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 3. INFERENCE ENGINE# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ@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)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. "24 unmodified lineswith torch.autocast("cuda", dtype=torch.float16):logits = model(inp)[0, -1, :].float()# Anti-Stutter / Repetition Penaltyfor gid in set(generated[-50:]):logits[gid] -= 2.0logits = logits / 0.5 # Focus Modetop_k_values, _ = torch.topk(logits, 40)logits[logits < top_k_values[-1]] = -float('inf')
app.py+30-18