Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
|
@@ -11,13 +18,13 @@ from safetensors.torch import load_file
|
|
| 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 |
-
#
|
| 21 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 22 |
class RMSNorm(nn.Module):
|
| 23 |
def __init__(self, d, eps=1e-6):
|
|
@@ -28,12 +35,12 @@ class RMSNorm(nn.Module):
|
|
| 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):
|
| 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)
|
| 35 |
-
self.register_buffer("cos", emb.cos()[None, None].
|
| 36 |
-
self.register_buffer("sin", emb.sin()[None, None].
|
| 37 |
def forward(self, n): return self.cos[:, :, :n], self.sin[:, :, :n]
|
| 38 |
|
| 39 |
def rot(x):
|
|
@@ -86,12 +93,12 @@ class CodeSymb1B(nn.Module):
|
|
| 86 |
self.norm = RMSNorm(DM)
|
| 87 |
self.head = nn.Linear(DM, vocab, bias=False)
|
| 88 |
def forward(self, tok):
|
| 89 |
-
x = self.embed(tok).
|
| 90 |
for b in self.blocks: x = b(x)
|
| 91 |
return self.head(self.norm(x))
|
| 92 |
|
| 93 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 94 |
-
#
|
| 95 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 96 |
print("โณ Loading Tokenizer...")
|
| 97 |
tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)
|
|
@@ -106,29 +113,35 @@ base_weights = {k: v for k, v in state.get("model", state).items() if not k.ends
|
|
| 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 |
-
#
|
| 112 |
-
lora_ckpt = hf_hub_download(LORA_REPO, "
|
| 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 |
-
|
|
|
|
|
|
|
| 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
|
| 132 |
except Exception as e:
|
| 133 |
print(f"โ ๏ธ Failed to fuse Chat LoRA: {e}")
|
| 134 |
|
|
@@ -137,14 +150,13 @@ model = model.to(device).half().eval()
|
|
| 137 |
print(f"โ
CodeSymb is ALIVE on {device}!")
|
| 138 |
|
| 139 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 140 |
-
# 3. INFERENCE ENGINE
|
| 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. "
|
|
@@ -175,11 +187,11 @@ def chat_with_codesymb(message: str, history: list) -> str:
|
|
| 175 |
with torch.autocast("cuda", dtype=torch.float16):
|
| 176 |
logits = model(inp)[0, -1, :].float()
|
| 177 |
|
| 178 |
-
#
|
| 179 |
for gid in set(generated[-50:]):
|
| 180 |
logits[gid] -= 2.0
|
| 181 |
|
| 182 |
-
logits = logits / 0.5 #
|
| 183 |
|
| 184 |
top_k_values, _ = torch.topk(logits, 40)
|
| 185 |
logits[logits < top_k_values[-1]] = -float('inf')
|
|
|
|
| 1 |
+
# ================================================================
|
| 2 |
+
# CodeSymb AI โ HuggingFace Space app.py
|
| 3 |
+
# โ
EXACT URL FIX: codesymb-chat-lora/chat_lora_latest
|
| 4 |
+
# โ
Safetensors PEFT Matrix Fusion
|
| 5 |
+
# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐
|
| 6 |
+
# ================================================================
|
| 7 |
+
|
| 8 |
import gradio as gr
|
| 9 |
import torch
|
| 10 |
import torch.nn as nn
|
|
|
|
| 18 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 19 |
USERNAME = "NiftyOracleAI"
|
| 20 |
REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"
|
|
|
|
| 21 |
TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"
|
| 22 |
+
LORA_REPO = f"{USERNAME}/codesymb-chat-lora" # ๐ฅ MATCHES YOUR EXACT URL!
|
| 23 |
|
| 24 |
if HF_TOKEN: login(token=HF_TOKEN)
|
| 25 |
|
| 26 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 27 |
+
# MODEL ARCHITECTURE
|
| 28 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 29 |
class RMSNorm(nn.Module):
|
| 30 |
def __init__(self, d, eps=1e-6):
|
|
|
|
| 35 |
return (x.float() * n).to(x.dtype) * self.w.to(x.dtype)
|
| 36 |
|
| 37 |
class RoPE(nn.Module):
|
| 38 |
+
def __init__(self, dim, max_len=2048, base=500_000):
|
| 39 |
super().__init__()
|
| 40 |
inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 41 |
emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)
|
| 42 |
+
self.register_buffer("cos", emb.cos()[None, None].to(torch.float16))
|
| 43 |
+
self.register_buffer("sin", emb.sin()[None, None].to(torch.float16))
|
| 44 |
def forward(self, n): return self.cos[:, :, :n], self.sin[:, :, :n]
|
| 45 |
|
| 46 |
def rot(x):
|
|
|
|
| 93 |
self.norm = RMSNorm(DM)
|
| 94 |
self.head = nn.Linear(DM, vocab, bias=False)
|
| 95 |
def forward(self, tok):
|
| 96 |
+
x = self.embed(tok).to(torch.float16)
|
| 97 |
for b in self.blocks: x = b(x)
|
| 98 |
return self.head(self.norm(x))
|
| 99 |
|
| 100 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 101 |
+
# 1. LOAD BASE MODEL
|
| 102 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 103 |
print("โณ Loading Tokenizer...")
|
| 104 |
tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)
|
|
|
|
| 113 |
model.load_state_dict(base_weights, strict=False)
|
| 114 |
print("โ
Base Model Loaded.")
|
| 115 |
|
| 116 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 117 |
+
# 2. LOAD & FUSE THE EXACT CHAT LORA YOU PROVIDED
|
| 118 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 119 |
print("โก FUSING RANK-100 CHAT LORA PERMANENTLY...")
|
| 120 |
try:
|
| 121 |
+
# ๐ฅ PULLING YOUR EXACT URL!
|
| 122 |
+
lora_ckpt = hf_hub_download(LORA_REPO, "chat_lora_latest/adapter_model.safetensors", token=HF_TOKEN or None)
|
| 123 |
lora_state = load_file(lora_ckpt)
|
| 124 |
|
| 125 |
+
scale = 200 / 100 # Alpha 200 / Rank 100 = 2.0
|
| 126 |
with torch.no_grad():
|
| 127 |
for i, block in enumerate(model.blocks):
|
| 128 |
for layer_name in ["att.q", "att.k", "att.v", "att.o", "ff.g", "ff.u", "ff.d"]:
|
| 129 |
+
# PEFT standard safetensors keys
|
| 130 |
A_key = f"base_model.model.blocks.{i}.{layer_name}.lora_A.weight"
|
| 131 |
B_key = f"base_model.model.blocks.{i}.{layer_name}.lora_B.weight"
|
| 132 |
|
| 133 |
if A_key in lora_state and B_key in lora_state:
|
| 134 |
+
A = lora_state[A_key].float() # [rank, in_features]
|
| 135 |
+
B = lora_state[B_key].float() # [out_features, rank]
|
| 136 |
+
|
| 137 |
+
# PEFT Matrix Fusion: W_new = W_old + (B @ A) * scale
|
| 138 |
+
delta = (B @ A) * scale
|
| 139 |
|
| 140 |
target_layer = getattr(block, layer_name.split(".")[0])
|
| 141 |
sub_layer = getattr(target_layer, layer_name.split(".")[1])
|
| 142 |
sub_layer.weight.data += delta.to(sub_layer.weight.dtype)
|
| 143 |
|
| 144 |
+
print("โ
Chat LoRA Fused! The AI now has its Empathy overrides active! โค๏ธ")
|
| 145 |
except Exception as e:
|
| 146 |
print(f"โ ๏ธ Failed to fuse Chat LoRA: {e}")
|
| 147 |
|
|
|
|
| 150 |
print(f"โ
CodeSymb is ALIVE on {device}!")
|
| 151 |
|
| 152 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 153 |
+
# 3. INFERENCE ENGINE
|
| 154 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 155 |
@spaces.GPU(duration=60)
|
| 156 |
def chat_with_codesymb(message: str, history: list) -> str:
|
| 157 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 158 |
model.to(device)
|
| 159 |
|
|
|
|
| 160 |
system_prompt = (
|
| 161 |
"You are CodeSymb, a highly intelligent and empathetic AI coding partner built by "
|
| 162 |
"Developer Dev Malkar and Founder Deepakkumar Malkar at NiftyOracle in India. "
|
|
|
|
| 187 |
with torch.autocast("cuda", dtype=torch.float16):
|
| 188 |
logits = model(inp)[0, -1, :].float()
|
| 189 |
|
| 190 |
+
# Anti-Stutter / Repetition Penalty
|
| 191 |
for gid in set(generated[-50:]):
|
| 192 |
logits[gid] -= 2.0
|
| 193 |
|
| 194 |
+
logits = logits / 0.5 # Focus Mode
|
| 195 |
|
| 196 |
top_k_values, _ = torch.topk(logits, 40)
|
| 197 |
logits[logits < top_k_values[-1]] = -float('inf')
|