Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 2 |
# DYNAMIC LORA HOT-SWAPPER
|
| 3 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
@@ -17,11 +135,10 @@ def switch_lora(expert_name):
|
|
| 17 |
|
| 18 |
# 2. Download and fuse the requested LoRA!
|
| 19 |
try:
|
| 20 |
-
# ๐ฅ FIX 1: Exact folder name matching!
|
| 21 |
lora_ckpt = hf_hub_download(LORA_REPO, f"loras/{expert_name}/adapter.pt", token=HF_TOKEN or None)
|
| 22 |
lora_state = torch.load(lora_ckpt, map_location="cpu", weights_only=False)
|
| 23 |
|
| 24 |
-
scale = 200 / 100 # Alpha / Rank
|
| 25 |
with torch.no_grad():
|
| 26 |
for i, block in enumerate(model.blocks):
|
| 27 |
for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:
|
|
@@ -47,6 +164,7 @@ def switch_lora(expert_name):
|
|
| 47 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 48 |
@spaces.GPU(duration=60)
|
| 49 |
def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
|
|
|
| 50 |
switch_lora(expert_choice)
|
| 51 |
|
| 52 |
system_prompt = (
|
|
@@ -57,7 +175,7 @@ def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
|
| 57 |
|
| 58 |
full_prompt = f"<|system|>\n{system_prompt}\n"
|
| 59 |
|
| 60 |
-
#
|
| 61 |
for msg in history[-6:]: # Last 3 conversation turns
|
| 62 |
if isinstance(msg, dict):
|
| 63 |
role = "<|user|>" if msg.get("role") == "user" else "<|assistant|>"
|
|
@@ -66,7 +184,6 @@ def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
|
| 66 |
role = "<|user|>" if msg.role == "user" else "<|assistant|>"
|
| 67 |
full_prompt += f"{role}\n{msg.content}\n"
|
| 68 |
else:
|
| 69 |
-
# Fallback for old tuples
|
| 70 |
full_prompt += f"<|user|>\n{msg[0]}\n<|assistant|>\n{msg[1]}\n"
|
| 71 |
|
| 72 |
full_prompt += f"<|user|>\n{message}\n<|assistant|>\n"
|
|
@@ -119,7 +236,7 @@ def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
|
| 119 |
return response
|
| 120 |
|
| 121 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 122 |
-
# GRADIO UI WITH
|
| 123 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 124 |
with gr.Blocks(theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"), css="body { background: #060D1F !important; color: white !important; }") as demo:
|
| 125 |
gr.HTML("""
|
|
@@ -134,11 +251,11 @@ with gr.Blocks(theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"), c
|
|
| 134 |
expert_dropdown = gr.Dropdown(
|
| 135 |
choices=[
|
| 136 |
"Base Model (No Expert)",
|
| 137 |
-
"python",
|
| 138 |
"javascript",
|
| 139 |
"cpp",
|
| 140 |
"react_jsx",
|
| 141 |
-
"hindi"
|
| 142 |
],
|
| 143 |
value="python",
|
| 144 |
label="๐ง Select CodeSymb Expert Brain",
|
|
|
|
| 1 |
+
# ================================================================
|
| 2 |
+
# CodeSymb AI โ THE DYNAMIC LORA SHAPE-SHIFTER ๐ฆ๐ฅ
|
| 3 |
+
# Runs natively on Hugging Face Spaces!
|
| 4 |
+
# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐
|
| 5 |
+
# ================================================================
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import spaces # <--- THIS WAS MISSING IN YOUR ERROR!
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import sentencepiece as spm
|
| 14 |
+
from huggingface_hub import hf_hub_download, login
|
| 15 |
+
|
| 16 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 17 |
+
USERNAME = "NiftyOracleAI"
|
| 18 |
+
REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"
|
| 19 |
+
LORA_REPO = f"{USERNAME}/codesymb-lora-vault"
|
| 20 |
+
TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"
|
| 21 |
+
|
| 22 |
+
if HF_TOKEN: login(token=HF_TOKEN)
|
| 23 |
+
|
| 24 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 25 |
+
# MODEL ARCHITECTURE (T4/A100 Float16 Compatible)
|
| 26 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 27 |
+
class RMSNorm(nn.Module):
|
| 28 |
+
def __init__(self, d, eps=1e-6):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.w = nn.Parameter(torch.ones(d)); self.eps = eps
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
n = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
|
| 33 |
+
return (x.float() * n).to(x.dtype) * self.w.to(x.dtype)
|
| 34 |
+
|
| 35 |
+
class RoPE(nn.Module):
|
| 36 |
+
def __init__(self, dim, max_len=2048, base=500_000):
|
| 37 |
+
super().__init__()
|
| 38 |
+
inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 39 |
+
emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)
|
| 40 |
+
self.register_buffer("cos", emb.cos()[None, None].half())
|
| 41 |
+
self.register_buffer("sin", emb.sin()[None, None].half())
|
| 42 |
+
def forward(self, n): return self.cos[:, :, :n], self.sin[:, :, :n]
|
| 43 |
+
|
| 44 |
+
def rot(x):
|
| 45 |
+
a, b = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
|
| 46 |
+
return torch.cat([-b, a], dim=-1)
|
| 47 |
+
|
| 48 |
+
def rope(q, k, cos, sin): return (q*cos)+(rot(q)*sin), (k*cos)+(rot(k)*sin)
|
| 49 |
+
|
| 50 |
+
class Attn(nn.Module):
|
| 51 |
+
def __init__(self, nh=16, nkv=4, dm=2048):
|
| 52 |
+
super().__init__()
|
| 53 |
+
hd = dm // nh; self.nh = nh; self.nkv = nkv; self.hd = hd; self.rep = nh // nkv
|
| 54 |
+
self.q = nn.Linear(dm, nh*hd, bias=False)
|
| 55 |
+
self.k = nn.Linear(dm, nkv*hd, bias=False)
|
| 56 |
+
self.v = nn.Linear(dm, nkv*hd, bias=False)
|
| 57 |
+
self.o = nn.Linear(nh*hd, dm, bias=False)
|
| 58 |
+
self.pe = RoPE(hd)
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
B, T, _ = x.shape
|
| 61 |
+
q = self.q(x).view(B,T,self.nh,self.hd).transpose(1,2)
|
| 62 |
+
k = self.k(x).view(B,T,self.nkv,self.hd).transpose(1,2)
|
| 63 |
+
v = self.v(x).view(B,T,self.nkv,self.hd).transpose(1,2)
|
| 64 |
+
cos, sin = self.pe(T); q, k = rope(q, k, cos, sin)
|
| 65 |
+
k = k.repeat_interleave(self.rep, dim=1); v = v.repeat_interleave(self.rep, dim=1)
|
| 66 |
+
o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 67 |
+
return self.o(o.transpose(1,2).contiguous().view(B,T,-1))
|
| 68 |
+
|
| 69 |
+
class FFN(nn.Module):
|
| 70 |
+
def __init__(self, dm=2048, df=8192):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.g = nn.Linear(dm, df, bias=False)
|
| 73 |
+
self.u = nn.Linear(dm, df, bias=False)
|
| 74 |
+
self.d = nn.Linear(df, dm, bias=False)
|
| 75 |
+
def forward(self, x): return self.d(F.silu(self.g(x)) * self.u(x))
|
| 76 |
+
|
| 77 |
+
class Block(nn.Module):
|
| 78 |
+
def __init__(self, dm=2048, df=8192, nh=16, nkv=4):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.n1 = RMSNorm(dm); self.att = Attn(nh, nkv, dm)
|
| 81 |
+
self.n2 = RMSNorm(dm); self.ff = FFN(dm, df)
|
| 82 |
+
def forward(self, x):
|
| 83 |
+
x = x + self.att(self.n1(x)); x = x + self.ff(self.n2(x)); return x
|
| 84 |
+
|
| 85 |
+
class CodeSymb1B(nn.Module):
|
| 86 |
+
def __init__(self, vocab=50000):
|
| 87 |
+
super().__init__()
|
| 88 |
+
DM=2048; DF=8192; NL=16; NH=16; NKV=4
|
| 89 |
+
self.embed = nn.Embedding(vocab, DM)
|
| 90 |
+
self.blocks = nn.ModuleList([Block(DM,DF,NH,NKV) for _ in range(NL)])
|
| 91 |
+
self.norm = RMSNorm(DM)
|
| 92 |
+
self.head = nn.Linear(DM, vocab, bias=False)
|
| 93 |
+
def forward(self, tok):
|
| 94 |
+
x = self.embed(tok).to(torch.float16)
|
| 95 |
+
for b in self.blocks: x = b(x)
|
| 96 |
+
return self.head(self.norm(x))
|
| 97 |
+
|
| 98 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 99 |
+
# LOAD BASE MODEL INTO RAM ONCE
|
| 100 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 101 |
+
print("โณ Loading Tokenizer...")
|
| 102 |
+
tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)
|
| 103 |
+
sp = spm.SentencePieceProcessor(); sp.load(tok_path)
|
| 104 |
+
|
| 105 |
+
print("โณ Loading Base Model (240k steps)...")
|
| 106 |
+
model = CodeSymb1B(vocab=sp.get_piece_size())
|
| 107 |
+
base_ckpt = hf_hub_download(REPO_ID, "checkpoints/latest.pt", token=HF_TOKEN or None)
|
| 108 |
+
state = torch.load(base_ckpt, map_location="cpu", weights_only=False)
|
| 109 |
+
|
| 110 |
+
# Keep a pristine copy of the base weights in RAM so we can swap LoRAs infinitely!
|
| 111 |
+
BASE_WEIGHTS = {k: v for k, v in state.get("model", state).items() if not k.endswith((".pe.cos", ".pe.sin"))}
|
| 112 |
+
model.load_state_dict(BASE_WEIGHTS, strict=False)
|
| 113 |
+
|
| 114 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 115 |
+
model = model.to(device).half().eval()
|
| 116 |
+
CURRENT_LORA = "None"
|
| 117 |
+
print("โ
Base Model is LIVE!")
|
| 118 |
+
|
| 119 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 120 |
# DYNAMIC LORA HOT-SWAPPER
|
| 121 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
| 135 |
|
| 136 |
# 2. Download and fuse the requested LoRA!
|
| 137 |
try:
|
|
|
|
| 138 |
lora_ckpt = hf_hub_download(LORA_REPO, f"loras/{expert_name}/adapter.pt", token=HF_TOKEN or None)
|
| 139 |
lora_state = torch.load(lora_ckpt, map_location="cpu", weights_only=False)
|
| 140 |
|
| 141 |
+
scale = 200 / 100 # Alpha / Rank for our H100 LoRAs
|
| 142 |
with torch.no_grad():
|
| 143 |
for i, block in enumerate(model.blocks):
|
| 144 |
for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:
|
|
|
|
| 164 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 165 |
@spaces.GPU(duration=60)
|
| 166 |
def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
| 167 |
+
# ๐ฅ DYNAMICALLY SHAPE-SHIFT THE BRAIN!
|
| 168 |
switch_lora(expert_choice)
|
| 169 |
|
| 170 |
system_prompt = (
|
|
|
|
| 175 |
|
| 176 |
full_prompt = f"<|system|>\n{system_prompt}\n"
|
| 177 |
|
| 178 |
+
# Bulletproof Gradio 4+ History Parser!
|
| 179 |
for msg in history[-6:]: # Last 3 conversation turns
|
| 180 |
if isinstance(msg, dict):
|
| 181 |
role = "<|user|>" if msg.get("role") == "user" else "<|assistant|>"
|
|
|
|
| 184 |
role = "<|user|>" if msg.role == "user" else "<|assistant|>"
|
| 185 |
full_prompt += f"{role}\n{msg.content}\n"
|
| 186 |
else:
|
|
|
|
| 187 |
full_prompt += f"<|user|>\n{msg[0]}\n<|assistant|>\n{msg[1]}\n"
|
| 188 |
|
| 189 |
full_prompt += f"<|user|>\n{message}\n<|assistant|>\n"
|
|
|
|
| 236 |
return response
|
| 237 |
|
| 238 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 239 |
+
# GRADIO UI WITH EXPERT DROPDOWN!
|
| 240 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 241 |
with gr.Blocks(theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"), css="body { background: #060D1F !important; color: white !important; }") as demo:
|
| 242 |
gr.HTML("""
|
|
|
|
| 251 |
expert_dropdown = gr.Dropdown(
|
| 252 |
choices=[
|
| 253 |
"Base Model (No Expert)",
|
| 254 |
+
"python",
|
| 255 |
"javascript",
|
| 256 |
"cpp",
|
| 257 |
"react_jsx",
|
| 258 |
+
"hindi"
|
| 259 |
],
|
| 260 |
value="python",
|
| 261 |
label="๐ง Select CodeSymb Expert Brain",
|