Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
| 1 |
# ================================================================
|
| 2 |
-
# CodeSymb AI โ HuggingFace Space app.py (FIXED
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
# ================================================================
|
| 4 |
|
| 5 |
import gradio as gr
|
|
@@ -21,7 +25,7 @@ if HF_TOKEN:
|
|
| 21 |
login(token=HF_TOKEN)
|
| 22 |
|
| 23 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 24 |
-
# MODEL ARCHITECTURE
|
| 25 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 26 |
class RMSNorm(nn.Module):
|
| 27 |
def __init__(self, d, eps=1e-6):
|
|
@@ -33,7 +37,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=
|
| 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)
|
|
@@ -115,42 +119,26 @@ tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOK
|
|
| 115 |
sp = spm.SentencePieceProcessor()
|
| 116 |
sp.load(tok_path)
|
| 117 |
VOCAB = sp.get_piece_size()
|
| 118 |
-
print(f"โ
Tokenizer: {VOCAB:,} vocab")
|
| 119 |
|
| 120 |
print("โณ Loading CodeSymb-1B model...")
|
| 121 |
model = CodeSymb1B(vocab=VOCAB)
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
model_state = state.get("model", state)
|
| 137 |
-
model_state = {k: v for k, v in model_state.items() if not k.endswith((".pe.cos", ".pe.sin"))}
|
| 138 |
-
|
| 139 |
-
model.load_state_dict(model_state, strict=False)
|
| 140 |
-
step = state.get("step", 0)
|
| 141 |
-
print(f"โ
Loaded: {ckpt_name} (step {step:,})")
|
| 142 |
-
ckpt_found = True
|
| 143 |
-
break
|
| 144 |
-
except Exception as e:
|
| 145 |
-
last_err = e
|
| 146 |
-
print(f" โ ๏ธ {ckpt_name} failed: {type(e).__name__}: {e}")
|
| 147 |
-
|
| 148 |
-
if not ckpt_found:
|
| 149 |
-
raise RuntimeError(f"โ NO CHECKPOINT LOADED! Last error: {last_err}")
|
| 150 |
|
| 151 |
model.eval()
|
| 152 |
-
|
| 153 |
-
print(f"โ
CodeSymb-1B: {n_params/1e9:.2f}B params โ READY ๐ฅ")
|
| 154 |
|
| 155 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 156 |
# SYSTEM PROMPT
|
|
@@ -170,127 +158,81 @@ SYSTEM_PROMPT = (
|
|
| 170 |
"Together, nothing is impossible."
|
| 171 |
)
|
| 172 |
|
| 173 |
-
def build_prompt(message: str, history: list) -> list:
|
| 174 |
-
parts = ["<|system|>\n" + SYSTEM_PROMPT + "\n"]
|
| 175 |
-
for user_msg, asst_msg in history[-4:]:
|
| 176 |
-
parts.append(f"<|user|>\n{user_msg}\n<|assistant|>\n{asst_msg}\n")
|
| 177 |
-
parts.append(f"<|user|>\n{message}\n<|assistant|>\n")
|
| 178 |
-
return sp.encode("".join(parts))
|
| 179 |
-
|
| 180 |
-
def tail_matches(generated: list, seq: list) -> bool:
|
| 181 |
-
seq = list(seq)
|
| 182 |
-
return len(generated) >= len(seq) and generated[-len(seq):] == seq
|
| 183 |
-
|
| 184 |
@spaces.GPU(duration=60)
|
| 185 |
def chat_with_codesymb(message: str, history: list) -> str:
|
| 186 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 187 |
model.to(device)
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
start = i
|
| 196 |
-
break
|
| 197 |
-
prompt_ids = prompt_ids[start:][-1024:]
|
| 198 |
-
|
| 199 |
inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)
|
| 200 |
|
| 201 |
-
END_SEQ = sp.encode("<|endoftext|>")
|
| 202 |
-
USER_SEQ = sp.encode("<|user|>")
|
| 203 |
-
SYS_SEQ = sp.encode("<|system|>")
|
| 204 |
-
|
| 205 |
generated = []
|
| 206 |
-
|
| 207 |
-
|
| 208 |
with torch.no_grad():
|
| 209 |
-
for _ in range(
|
| 210 |
with torch.autocast("cuda" if device.type == "cuda" else "cpu", dtype=torch.bfloat16):
|
| 211 |
logits = model(inp)[0, -1, :].float()
|
| 212 |
|
| 213 |
-
|
|
|
|
| 214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
sorted_logits, sorted_idx = torch.sort(logits, descending=True)
|
| 216 |
cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 217 |
-
remove = cum_probs > 0.
|
| 218 |
remove[..., 1:] = remove[..., :-1].clone()
|
| 219 |
remove[..., 0] = 0
|
| 220 |
sorted_logits[remove] = -float("inf")
|
|
|
|
| 221 |
logits_filtered = torch.zeros_like(logits)
|
| 222 |
logits_filtered.scatter_(0, sorted_idx, sorted_logits)
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
for gid in set(generated[-20:]):
|
| 226 |
-
if 0 <= gid < logits_filtered.shape[0]:
|
| 227 |
-
logits_filtered[gid] /= 1.3
|
| 228 |
-
|
| 229 |
-
probs = F.softmax(logits_filtered, dim=-1)
|
| 230 |
next_t = torch.multinomial(probs, 1).item()
|
| 231 |
-
|
| 232 |
-
if tail_matches(generated, END_SEQ) or tail_matches(generated, USER_SEQ) or tail_matches(generated, SYS_SEQ):
|
| 233 |
-
break
|
| 234 |
-
|
| 235 |
-
if len(generated) > 2 and generated[-1] == generated[-2] == next_t:
|
| 236 |
-
break
|
| 237 |
-
|
| 238 |
generated.append(next_t)
|
| 239 |
inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
response = sp.decode(generated).strip()
|
| 242 |
|
|
|
|
| 243 |
for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:
|
| 244 |
response = response.split(tag)[0]
|
| 245 |
-
response = response.strip()
|
| 246 |
|
| 247 |
-
|
| 248 |
-
response = (
|
| 249 |
-
"I'm CodeSymb! ๐ฅ\n"
|
| 250 |
-
"Built by Dev & Deepakkumar Malkar ๐ฎ๐ณ\n"
|
| 251 |
-
"Ask me anything about code!"
|
| 252 |
-
)
|
| 253 |
-
return response
|
| 254 |
|
| 255 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 256 |
# GRADIO UI
|
| 257 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 258 |
with gr.Blocks(
|
| 259 |
title="CodeSymb AI",
|
| 260 |
-
theme=gr.themes.Base(primary_hue="
|
| 261 |
-
css=""
|
| 262 |
-
body { background: #060D1F !important; }
|
| 263 |
-
.gradio-container { max-width: 860px !important; }
|
| 264 |
-
h1 {
|
| 265 |
-
text-align: center;
|
| 266 |
-
background: linear-gradient(135deg, #00D4FF, #A855F7);
|
| 267 |
-
-webkit-background-clip: text;
|
| 268 |
-
-webkit-text-fill-color: transparent;
|
| 269 |
-
font-size: 2.5em !important;
|
| 270 |
-
font-weight: 900 !important;
|
| 271 |
-
}
|
| 272 |
-
.subtitle { text-align: center; color: #A0AEC0; margin-bottom: 20px; font-size: 1.1em; }
|
| 273 |
-
""",
|
| 274 |
) as demo:
|
| 275 |
-
|
| 276 |
gr.HTML("""
|
| 277 |
-
<h1>โก CodeSymb AI</h1>
|
| 278 |
-
<p
|
| 279 |
-
World's Most Powerful Coding AI ๐<br>
|
| 280 |
Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br>
|
| 281 |
<em>"Impossible is just a door with no handle yet invented."</em>
|
| 282 |
</p>
|
| 283 |
""")
|
| 284 |
-
|
| 285 |
-
gr.ChatInterface(
|
| 286 |
-
fn=chat_with_codesymb,
|
| 287 |
-
examples=[
|
| 288 |
-
["Hi! Who are you and what can you build?"],
|
| 289 |
-
["Build me a Python FastAPI with JWT auth"],
|
| 290 |
-
["Fix this error: AttributeError: 'NoneType'"],
|
| 291 |
-
["Write me a complete Android login screen in Kotlin"],
|
| 292 |
-
],
|
| 293 |
-
)
|
| 294 |
|
| 295 |
if __name__ == "__main__":
|
| 296 |
demo.launch()
|
|
|
|
| 1 |
# ================================================================
|
| 2 |
+
# CodeSymb AI โ HuggingFace Space app.py (FIXED MATH!)
|
| 3 |
+
# โ
Indentation Fixed
|
| 4 |
+
# โ
Negative Logit Penalty Fixed
|
| 5 |
+
# โ
Direct Checkpoint Loading
|
| 6 |
+
# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐
|
| 7 |
# ================================================================
|
| 8 |
|
| 9 |
import gradio as gr
|
|
|
|
| 25 |
login(token=HF_TOKEN)
|
| 26 |
|
| 27 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 28 |
+
# MODEL ARCHITECTURE
|
| 29 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 30 |
class RMSNorm(nn.Module):
|
| 31 |
def __init__(self, d, eps=1e-6):
|
|
|
|
| 37 |
return (x.float() * n).to(x.dtype) * self.w.to(x.dtype)
|
| 38 |
|
| 39 |
class RoPE(nn.Module):
|
| 40 |
+
def __init__(self, dim, max_len=4096, base=500_000):
|
| 41 |
super().__init__()
|
| 42 |
inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 43 |
emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)
|
|
|
|
| 119 |
sp = spm.SentencePieceProcessor()
|
| 120 |
sp.load(tok_path)
|
| 121 |
VOCAB = sp.get_piece_size()
|
|
|
|
| 122 |
|
| 123 |
print("โณ Loading CodeSymb-1B model...")
|
| 124 |
model = CodeSymb1B(vocab=VOCAB)
|
| 125 |
|
| 126 |
+
try:
|
| 127 |
+
ckpt_path = hf_hub_download(REPO_ID, "checkpoints/latest.pt", token=HF_TOKEN or None)
|
| 128 |
+
print(f"โฌ๏ธ Downloaded latest.pt โ loading weights...")
|
| 129 |
+
state = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 130 |
+
model_state = state.get("model", state)
|
| 131 |
+
|
| 132 |
+
# Safely strip RoPE buffers
|
| 133 |
+
model_state = {k: v for k, v in model_state.items() if not k.endswith((".pe.cos", ".pe.sin"))}
|
| 134 |
+
|
| 135 |
+
model.load_state_dict(model_state, strict=False)
|
| 136 |
+
print(f"โ
Loaded: Checkpoint Step {state.get('step', 'Unknown')}")
|
| 137 |
+
except Exception as e:
|
| 138 |
+
raise RuntimeError(f"โ NO CHECKPOINT LOADED! Last error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
model.eval()
|
| 141 |
+
print(f"โ
CodeSymb-1B โ READY ๐ฅ")
|
|
|
|
| 142 |
|
| 143 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 144 |
# SYSTEM PROMPT
|
|
|
|
| 158 |
"Together, nothing is impossible."
|
| 159 |
)
|
| 160 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
@spaces.GPU(duration=60)
|
| 162 |
def chat_with_codesymb(message: str, history: list) -> str:
|
| 163 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 164 |
model.to(device)
|
| 165 |
|
| 166 |
+
# Clean ChatML construction
|
| 167 |
+
prompt = f"<|system|>\n{SYSTEM_PROMPT}\n<|user|>\n{message}\n<|assistant|>\n"
|
| 168 |
+
prompt_ids = sp.encode(prompt)
|
| 169 |
+
|
| 170 |
+
# Cap prompt size
|
| 171 |
+
if len(prompt_ids) > 1024: prompt_ids = prompt_ids[-1024:]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
generated = []
|
| 175 |
+
|
|
|
|
| 176 |
with torch.no_grad():
|
| 177 |
+
for _ in range(512):
|
| 178 |
with torch.autocast("cuda" if device.type == "cuda" else "cpu", dtype=torch.bfloat16):
|
| 179 |
logits = model(inp)[0, -1, :].float()
|
| 180 |
|
| 181 |
+
# Temp scaling
|
| 182 |
+
logits = logits / 0.5
|
| 183 |
|
| 184 |
+
# ๐ฅ THE MATHEMATICALLY CORRECT REPETITION PENALTY ๐ฅ
|
| 185 |
+
for gid in set(generated[-30:]):
|
| 186 |
+
if logits[gid] > 0:
|
| 187 |
+
logits[gid] /= 1.2
|
| 188 |
+
else:
|
| 189 |
+
logits[gid] *= 1.2 # Multiply negatives to shrink probability!
|
| 190 |
+
|
| 191 |
+
# Top-p sampling
|
| 192 |
sorted_logits, sorted_idx = torch.sort(logits, descending=True)
|
| 193 |
cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 194 |
+
remove = cum_probs > 0.90
|
| 195 |
remove[..., 1:] = remove[..., :-1].clone()
|
| 196 |
remove[..., 0] = 0
|
| 197 |
sorted_logits[remove] = -float("inf")
|
| 198 |
+
|
| 199 |
logits_filtered = torch.zeros_like(logits)
|
| 200 |
logits_filtered.scatter_(0, sorted_idx, sorted_logits)
|
| 201 |
+
probs = F.softmax(logits_filtered, dim=-1)
|
| 202 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
next_t = torch.multinomial(probs, 1).item()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
generated.append(next_t)
|
| 205 |
inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)
|
| 206 |
+
|
| 207 |
+
# Fast early stopping check
|
| 208 |
+
decoded_so_far = sp.decode(generated)
|
| 209 |
+
if "<|endoftext|>" in decoded_so_far or "<|user|>" in decoded_so_far:
|
| 210 |
+
break
|
| 211 |
|
| 212 |
response = sp.decode(generated).strip()
|
| 213 |
|
| 214 |
+
# Strip tags
|
| 215 |
for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:
|
| 216 |
response = response.split(tag)[0]
|
|
|
|
| 217 |
|
| 218 |
+
return response.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 221 |
# GRADIO UI
|
| 222 |
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 223 |
with gr.Blocks(
|
| 224 |
title="CodeSymb AI",
|
| 225 |
+
theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"),
|
| 226 |
+
css="body { background: #060D1F !important; color: white !important; } .gradio-container { max-width: 860px !important; }"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
) as demo:
|
|
|
|
| 228 |
gr.HTML("""
|
| 229 |
+
<h1 style='text-align:center; color:#00D4FF;'>โก CodeSymb AI</h1>
|
| 230 |
+
<p style='text-align:center; color:#A0AEC0;'>
|
|
|
|
| 231 |
Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br>
|
| 232 |
<em>"Impossible is just a door with no handle yet invented."</em>
|
| 233 |
</p>
|
| 234 |
""")
|
| 235 |
+
gr.ChatInterface(fn=chat_with_codesymb)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
if __name__ == "__main__":
|
| 238 |
demo.launch()
|