NiftyOracleAI commited on
Commit
34a299c
ยท
verified ยท
1 Parent(s): 75fa51d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -99
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-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):
@@ -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).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
- # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
122
- def switch_lora(expert_name):
123
- global CURRENT_LORA
124
- if expert_name == CURRENT_LORA:
125
- return # Already loaded!
126
-
127
- print(f"๐Ÿ”„ Swapping Brain to: {expert_name}...")
128
 
129
- # 1. Reset model to pristine Base Weights
130
- model.load_state_dict(BASE_WEIGHTS, strict=False)
131
-
132
- if expert_name == "Base Model (No Expert)":
133
- CURRENT_LORA = expert_name
134
- return
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"]:
145
- A_key = f"blocks.{i}.{layer_name}.A"
146
- B_key = f"blocks.{i}.{layer_name}.B"
147
 
148
- if A_key in lora_state and B_key in lora_state:
149
- A = lora_state[A_key].float().to(device)
150
- B = lora_state[B_key].float().to(device)
151
- delta = (A @ B).T * scale
152
-
153
- target_layer = getattr(block, layer_name.split(".")[0])
154
- sub_layer = getattr(target_layer, layer_name.split(".")[1])
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, expert_choice: str) -> str:
167
- # ๐Ÿ”ฅ DYNAMICALLY SHAPE-SHIFT THE BRAIN!
168
- switch_lora(expert_choice)
169
 
 
170
  system_prompt = (
171
- f"You are CodeSymb, acting as the {expert_choice}. You are deeply empathetic, "
172
- "passionate, and highly intelligent. Built by Dev Malkar and Founder Deepakkumar Malkar "
173
- "at NiftyOracle India. Provide flawless code and do not hallucinate."
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.6
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: Expert Swarm</h1>
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()