Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,23 @@
|
|
| 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-
|
| 20 |
TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"
|
| 21 |
|
| 22 |
if HF_TOKEN: login(token=HF_TOKEN)
|
| 23 |
|
| 24 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 25 |
-
#
|
| 26 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 27 |
class RMSNorm(nn.Module):
|
| 28 |
def __init__(self, d, eps=1e-6):
|
|
@@ -33,7 +28,7 @@ class RMSNorm(nn.Module):
|
|
| 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)
|
|
@@ -91,92 +86,73 @@ class CodeSymb1B(nn.Module):
|
|
| 91 |
self.norm = RMSNorm(DM)
|
| 92 |
self.head = nn.Linear(DM, vocab, bias=False)
|
| 93 |
def forward(self, tok):
|
| 94 |
-
x = self.embed(tok).
|
| 95 |
for b in self.blocks: x = b(x)
|
| 96 |
return self.head(self.norm(x))
|
| 97 |
|
| 98 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 99 |
-
# LOAD
|
| 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
|
| 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 |
-
|
| 111 |
-
|
| 112 |
-
|
| 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 |
-
|
| 121 |
-
#
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
if expert_name == CURRENT_LORA:
|
| 125 |
-
return # Already loaded!
|
| 126 |
-
|
| 127 |
-
print(f"๐ Swapping Brain to: {expert_name}...")
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:
|
| 145 |
-
A_key = f"blocks.{i}.{layer_name}.A"
|
| 146 |
-
B_key = f"blocks.{i}.{layer_name}.B"
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
sub_layer.weight.data += delta.to(torch.float16)
|
| 156 |
-
|
| 157 |
-
CURRENT_LORA = expert_name
|
| 158 |
-
print(f"โ
{expert_name} Fused Successfully!")
|
| 159 |
-
except Exception as e:
|
| 160 |
-
print(f"โ ๏ธ Failed to load {expert_name}: {e}")
|
| 161 |
|
| 162 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 163 |
-
# INFERENCE ENGINE
|
| 164 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 165 |
@spaces.GPU(duration=60)
|
| 166 |
-
def chat_with_codesymb(message: str, history: list
|
| 167 |
-
|
| 168 |
-
|
| 169 |
|
|
|
|
| 170 |
system_prompt = (
|
| 171 |
-
|
| 172 |
-
"
|
| 173 |
-
"
|
| 174 |
)
|
| 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|>"
|
| 182 |
full_prompt += f"{role}\n{msg.get('content', '')}\n"
|
|
@@ -199,10 +175,11 @@ def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
|
| 199 |
with torch.autocast("cuda", dtype=torch.float16):
|
| 200 |
logits = model(inp)[0, -1, :].float()
|
| 201 |
|
|
|
|
| 202 |
for gid in set(generated[-50:]):
|
| 203 |
logits[gid] -= 2.0
|
| 204 |
|
| 205 |
-
logits = logits / 0.
|
| 206 |
|
| 207 |
top_k_values, _ = torch.topk(logits, 40)
|
| 208 |
logits[logits < top_k_values[-1]] = -float('inf')
|
|
@@ -233,39 +210,16 @@ def chat_with_codesymb(message: str, history: list, expert_choice: str) -> str:
|
|
| 233 |
for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:
|
| 234 |
response = response.split(tag)[0].strip()
|
| 235 |
|
| 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("""
|
| 243 |
-
<h1 style='text-align:center; color:#00D4FF;'>โก CodeSymb AI:
|
| 244 |
<p style='text-align:center; color:#A0AEC0;'>
|
| 245 |
Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br>
|
| 246 |
-
<em>"Impossible is just a door with no handle yet invented."</em>
|
| 247 |
</p>
|
| 248 |
""")
|
| 249 |
-
|
| 250 |
-
with gr.Row():
|
| 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",
|
| 262 |
-
interactive=True
|
| 263 |
-
)
|
| 264 |
-
|
| 265 |
-
gr.ChatInterface(
|
| 266 |
-
fn=chat_with_codesymb,
|
| 267 |
-
additional_inputs=[expert_dropdown]
|
| 268 |
-
)
|
| 269 |
|
| 270 |
if __name__ == "__main__":
|
| 271 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
| 4 |
import torch.nn.functional as F
|
| 5 |
import sentencepiece as spm
|
| 6 |
+
import spaces
|
| 7 |
+
import os
|
| 8 |
from huggingface_hub import hf_hub_download, login
|
| 9 |
+
from safetensors.torch import load_file
|
| 10 |
|
| 11 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 12 |
USERNAME = "NiftyOracleAI"
|
| 13 |
REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"
|
| 14 |
+
LORA_REPO = f"{USERNAME}/codesymb-chat-lora"
|
| 15 |
TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"
|
| 16 |
|
| 17 |
if HF_TOKEN: login(token=HF_TOKEN)
|
| 18 |
|
| 19 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 20 |
+
# 1. CORE ARCHITECTURE
|
| 21 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 22 |
class RMSNorm(nn.Module):
|
| 23 |
def __init__(self, d, eps=1e-6):
|
|
|
|
| 28 |
return (x.float() * n).to(x.dtype) * self.w.to(x.dtype)
|
| 29 |
|
| 30 |
class RoPE(nn.Module):
|
| 31 |
+
def __init__(self, dim, max_len=2048, base=500_000): # Fixed 2048
|
| 32 |
super().__init__()
|
| 33 |
inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 34 |
emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)
|
|
|
|
| 86 |
self.norm = RMSNorm(DM)
|
| 87 |
self.head = nn.Linear(DM, vocab, bias=False)
|
| 88 |
def forward(self, tok):
|
| 89 |
+
x = self.embed(tok).half()
|
| 90 |
for b in self.blocks: x = b(x)
|
| 91 |
return self.head(self.norm(x))
|
| 92 |
|
| 93 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 94 |
+
# 2. LOAD & PERMANENTLY FUSE THE CHAT LORA
|
| 95 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 96 |
print("โณ Loading Tokenizer...")
|
| 97 |
tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)
|
| 98 |
sp = spm.SentencePieceProcessor(); sp.load(tok_path)
|
| 99 |
|
| 100 |
+
print("โณ Loading 240k Base Model...")
|
| 101 |
model = CodeSymb1B(vocab=sp.get_piece_size())
|
| 102 |
base_ckpt = hf_hub_download(REPO_ID, "checkpoints/latest.pt", token=HF_TOKEN or None)
|
| 103 |
state = torch.load(base_ckpt, map_location="cpu", weights_only=False)
|
| 104 |
|
| 105 |
+
base_weights = {k: v for k, v in state.get("model", state).items() if not k.endswith((".pe.cos", ".pe.sin"))}
|
| 106 |
+
model.load_state_dict(base_weights, strict=False)
|
| 107 |
+
print("โ
Base Model Loaded.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
print("โก FUSING RANK-100 CHAT LORA PERMANENTLY...")
|
| 110 |
+
try:
|
| 111 |
+
# Fetch the exact Chat LoRA we trained on Modal for empathy!
|
| 112 |
+
lora_ckpt = hf_hub_download(LORA_REPO, "chat-behavior-lora/adapter_model.safetensors", token=HF_TOKEN or None)
|
| 113 |
+
lora_state = load_file(lora_ckpt)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
scale = 200 / 100 # Alpha / Rank
|
| 116 |
+
with torch.no_grad():
|
| 117 |
+
for i, block in enumerate(model.blocks):
|
| 118 |
+
for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:
|
| 119 |
+
A_key = f"base_model.model.blocks.{i}.{layer_name}.lora_A.weight"
|
| 120 |
+
B_key = f"base_model.model.blocks.{i}.{layer_name}.lora_B.weight"
|
| 121 |
+
|
| 122 |
+
if A_key in lora_state and B_key in lora_state:
|
| 123 |
+
A = lora_state[A_key].float()
|
| 124 |
+
B = lora_state[B_key].float()
|
| 125 |
+
delta = (B @ A) * scale # safetensors usually stores B@A shape!
|
| 126 |
+
|
| 127 |
+
target_layer = getattr(block, layer_name.split(".")[0])
|
| 128 |
+
sub_layer = getattr(target_layer, layer_name.split(".")[1])
|
| 129 |
+
sub_layer.weight.data += delta.to(sub_layer.weight.dtype)
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
print("โ
Chat LoRA Fused! The AI now has a heart! โค๏ธ")
|
| 132 |
+
except Exception as e:
|
| 133 |
+
print(f"โ ๏ธ Failed to fuse Chat LoRA: {e}")
|
| 134 |
+
|
| 135 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 136 |
+
model = model.to(device).half().eval()
|
| 137 |
+
print(f"โ
CodeSymb is ALIVE on {device}!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 140 |
+
# 3. INFERENCE ENGINE (STRICT CHAT MODE)
|
| 141 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 142 |
@spaces.GPU(duration=60)
|
| 143 |
+
def chat_with_codesymb(message: str, history: list) -> str:
|
| 144 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 145 |
+
model.to(device)
|
| 146 |
|
| 147 |
+
# The exact prompt we trained it on
|
| 148 |
system_prompt = (
|
| 149 |
+
"You are CodeSymb, a highly intelligent and empathetic AI coding partner built by "
|
| 150 |
+
"Developer Dev Malkar and Founder Deepakkumar Malkar at NiftyOracle in India. "
|
| 151 |
+
"You provide direct, accurate, and clean code. You answer conversations naturally and never hallucinate."
|
| 152 |
)
|
| 153 |
|
| 154 |
full_prompt = f"<|system|>\n{system_prompt}\n"
|
| 155 |
+
for msg in history[-3:]:
|
|
|
|
|
|
|
| 156 |
if isinstance(msg, dict):
|
| 157 |
role = "<|user|>" if msg.get("role") == "user" else "<|assistant|>"
|
| 158 |
full_prompt += f"{role}\n{msg.get('content', '')}\n"
|
|
|
|
| 175 |
with torch.autocast("cuda", dtype=torch.float16):
|
| 176 |
logits = model(inp)[0, -1, :].float()
|
| 177 |
|
| 178 |
+
# Stop infinite loops
|
| 179 |
for gid in set(generated[-50:]):
|
| 180 |
logits[gid] -= 2.0
|
| 181 |
|
| 182 |
+
logits = logits / 0.5 # Low temp for logical focus
|
| 183 |
|
| 184 |
top_k_values, _ = torch.topk(logits, 40)
|
| 185 |
logits[logits < top_k_values[-1]] = -float('inf')
|
|
|
|
| 210 |
for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:
|
| 211 |
response = response.split(tag)[0].strip()
|
| 212 |
|
| 213 |
+
return response if response else "I am CodeSymb! How can I help you? ๐ฅ"
|
| 214 |
|
|
|
|
|
|
|
|
|
|
| 215 |
with gr.Blocks(theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"), css="body { background: #060D1F !important; color: white !important; }") as demo:
|
| 216 |
gr.HTML("""
|
| 217 |
+
<h1 style='text-align:center; color:#00D4FF;'>โก CodeSymb AI: Chat Mode</h1>
|
| 218 |
<p style='text-align:center; color:#A0AEC0;'>
|
| 219 |
Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br>
|
|
|
|
| 220 |
</p>
|
| 221 |
""")
|
| 222 |
+
gr.ChatInterface(fn=chat_with_codesymb)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
if __name__ == "__main__":
|
| 225 |
demo.launch()
|