Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789107 unmodified lines1819201421222324252620272829304 unmodified lines35363731383940413536424344454646 unmodified lines9394958996979899100941011021031048 unmodified lines1131141151161171181191201111121211221231241151251261271281291301311321331231241251341351361371381391401411421431311441451461472 unmodified lines15015115214015315415515615715815914716016116224 unmodified lines187188189178190191192193182194195196197# ================================================================# 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"LORA_REPO = f"{USERNAME}/codesymb-chat-lora"TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"LORA_REPO = f"{USERNAME}/codesymb-chat-lora" # ๐ฅ MATCHES YOUR EXACT URL!
if HF_TOKEN: login(token=HF_TOKEN)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 1. CORE ARCHITECTURE# MODEL ARCHITECTURE # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass RMSNorm(nn.Module): def __init__(self, d, eps=1e-6):4 unmodified lines return (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 2048 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].half()) self.register_buffer("sin", emb.sin()[None, None].half()) 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 lines self.norm = RMSNorm(DM) self.head = nn.Linear(DM, vocab, bias=False) def forward(self, tok): x = self.embed(tok).half() x = self.embed(tok).to(torch.float16) for b in self.blocks: x = b(x) return self.head(self.norm(x))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# 2. LOAD & PERMANENTLY FUSE THE CHAT LORA# 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: # 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) # ๐ฅ 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 / Rank scale = 200 / 100 # Alpha 200 / Rank 100 = 2.0 with 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 keys 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! 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) * scale delta = (B @ A) * scale 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! โค๏ธ") 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 (STRICT CHAT MODE)# 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)
# The exact prompt we trained it on 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 lines with torch.autocast("cuda", dtype=torch.float16): logits = model(inp)[0, -1, :].float()
# Stop infinite loops # Anti-Stutter / Repetition Penalty for gid in set(generated[-50:]): logits[gid] -= 2.0
logits = logits / 0.5 # Low temp for logical focus logits = logits / 0.5 # Focus Mode top_k_values, _ = torch.topk(logits, 40) logits[logits < top_k_values[-1]] = -float('inf')app.py+30-18