NiftyOracleAI commited on
Commit
cc66355
ยท
verified ยท
1 Parent(s): b512b82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -113
app.py CHANGED
@@ -1,5 +1,9 @@
1
  # ================================================================
2
- # CodeSymb AI โ€” HuggingFace Space app.py (FIXED INDENTATION)
 
 
 
 
3
  # ================================================================
4
 
5
  import gradio as gr
@@ -21,7 +25,7 @@ if HF_TOKEN:
21
  login(token=HF_TOKEN)
22
 
23
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
24
- # MODEL ARCHITECTURE (must match training exactly)
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=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)
@@ -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
- ckpt_found = False
124
- last_err = None
125
- for ckpt_name in ["checkpoints/sft_latest.pt",
126
- "checkpoints/latest.pt",
127
- "checkpoints/sft_chat_latest.pt"]:
128
- try:
129
- ckpt_path = hf_hub_download(REPO_ID, ckpt_name, token=HF_TOKEN or None)
130
- print(f"โฌ‡๏ธ Downloaded {ckpt_name} โ€” loading weights...")
131
- try:
132
- state = torch.load(ckpt_path, map_location="cpu")
133
- except Exception:
134
- state = torch.load(ckpt_path, map_location="cpu", weights_only=False)
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
- n_params = sum(p.numel() for p in model.parameters())
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
- prompt_ids = build_prompt(message, history)
190
- if len(prompt_ids) > 1024:
191
- user_seq = sp.encode("<|user|>")
192
- start = 0
193
- for i in range(len(prompt_ids) - 6, 0, -1):
194
- if prompt_ids[i:i+len(user_seq)] == list(user_seq):
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
- MAX_NEW = 512
207
-
208
  with torch.no_grad():
209
- for _ in range(MAX_NEW):
210
  with torch.autocast("cuda" if device.type == "cuda" else "cpu", dtype=torch.bfloat16):
211
  logits = model(inp)[0, -1, :].float()
212
 
213
- logits = logits / 0.7
 
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.92
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
- if generated:
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
- if not response:
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="blue", secondary_hue="indigo"),
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 class='subtitle'>
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()