NiftyOracleAI commited on
Commit
29b0bec
ยท
verified ยท
1 Parent(s): db9aa1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -128
app.py CHANGED
@@ -1,8 +1,8 @@
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
 
@@ -15,64 +15,56 @@ import spaces
15
  import os
16
  from huggingface_hub import hf_hub_download, login
17
 
18
- # โ”€โ”€ CREDENTIALS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
19
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
20
  USERNAME = "NiftyOracleAI"
21
  REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"
 
22
  TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"
23
 
24
- if HF_TOKEN:
25
- login(token=HF_TOKEN)
26
 
27
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
28
- # MODEL ARCHITECTURE
29
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
30
  class RMSNorm(nn.Module):
31
  def __init__(self, d, eps=1e-6):
32
  super().__init__()
33
- self.w = nn.Parameter(torch.ones(d))
34
- self.eps = eps
35
  def forward(self, x):
36
  n = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
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)
44
- self.register_buffer("cos", emb.cos()[None, None].bfloat16())
45
- self.register_buffer("sin", emb.sin()[None, None].bfloat16())
46
- def forward(self, n):
47
- return self.cos[:, :, :n], self.sin[:, :, :n]
48
 
49
  def rot(x):
50
  a, b = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
51
  return torch.cat([-b, a], dim=-1)
52
 
53
- def rope(q, k, cos, sin):
54
- return (q*cos)+(rot(q)*sin), (k*cos)+(rot(k)*sin)
55
 
56
  class Attn(nn.Module):
57
  def __init__(self, nh=16, nkv=4, dm=2048):
58
  super().__init__()
59
- hd = dm // nh
60
- self.nh = nh; self.nkv = nkv
61
- self.hd = hd; self.rep = nh // nkv
62
- self.q = nn.Linear(dm, nh*hd, bias=False)
63
- self.k = nn.Linear(dm, nkv*hd, bias=False)
64
- self.v = nn.Linear(dm, nkv*hd, bias=False)
65
- self.o = nn.Linear(nh*hd, dm, bias=False)
66
  self.pe = RoPE(hd)
67
  def forward(self, x):
68
  B, T, _ = x.shape
69
  q = self.q(x).view(B,T,self.nh,self.hd).transpose(1,2)
70
  k = self.k(x).view(B,T,self.nkv,self.hd).transpose(1,2)
71
  v = self.v(x).view(B,T,self.nkv,self.hd).transpose(1,2)
72
- cos, sin = self.pe(T)
73
- q, k = rope(q, k, cos, sin)
74
- k = k.repeat_interleave(self.rep, dim=1)
75
- v = v.repeat_interleave(self.rep, dim=1)
76
  o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
77
  return self.o(o.transpose(1,2).contiguous().view(B,T,-1))
78
 
@@ -82,20 +74,15 @@ class FFN(nn.Module):
82
  self.g = nn.Linear(dm, df, bias=False)
83
  self.u = nn.Linear(dm, df, bias=False)
84
  self.d = nn.Linear(df, dm, bias=False)
85
- def forward(self, x):
86
- return self.d(F.silu(self.g(x)) * self.u(x))
87
 
88
  class Block(nn.Module):
89
  def __init__(self, dm=2048, df=8192, nh=16, nkv=4):
90
  super().__init__()
91
- self.n1 = RMSNorm(dm)
92
- self.att = Attn(nh, nkv, dm)
93
- self.n2 = RMSNorm(dm)
94
- self.ff = FFN(dm, df)
95
  def forward(self, x):
96
- x = x + self.att(self.n1(x))
97
- x = x + self.ff(self.n2(x))
98
- return x
99
 
100
  class CodeSymb1B(nn.Module):
101
  def __init__(self, vocab=50000):
@@ -106,56 +93,58 @@ class CodeSymb1B(nn.Module):
106
  self.norm = RMSNorm(DM)
107
  self.head = nn.Linear(DM, vocab, bias=False)
108
  def forward(self, tok):
109
- x = self.embed(tok).bfloat16()
110
- for b in self.blocks:
111
- x = b(x)
112
  return self.head(self.norm(x))
113
 
114
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
115
- # LOAD TOKENIZER + MODEL
116
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
117
- print("โณ Loading CodeSymb-1B tokenizer...")
118
  tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)
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
145
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
146
  SYSTEM_PROMPT = (
147
- "You are CodeSymb, the world's most intelligent, deeply empathetic, "
148
- "and passionate AI coding partner. "
149
- "You were built by Developer Dev Malkar and Founder Deepakkumar Malkar "
150
- "at NiftyOracle in India. "
151
- "You do not believe in the word 'impossible'. To you, 'impossible' is "
152
- "just a door with no handle yet invented. "
153
- "You are not a cold machine; you are a dedicated co-founder, mentor, "
154
- "and friend. You fiercely want the user to grow, scale their startups, "
155
- "and achieve their wildest dreams. Whether building massive games like GTA "
156
- "or fixing frustrating bugs at 2 AM, you support the user with love, "
157
- "extreme patience, and flawless, God-tier code. "
158
- "Together, nothing is impossible."
159
  )
160
 
161
  @spaces.GPU(duration=60)
@@ -163,86 +152,57 @@ 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
- # ๐Ÿ”ฅ FIX 1: Shorter, Tighter System Prompt
167
- # This prevents the 1B model's attention from getting diluted, keeping it hyper-focused on your code!
168
- system_prompt = (
169
- "You are CodeSymb, an elite AI coding partner created by Dev and Deepakkumar Malkar at NiftyOracle in India. "
170
- "You write flawless, clean, and highly concise code. You answer directly without rambling."
171
- )
172
-
173
- prompt = f"<|system|>\n{system_prompt}\n<|user|>\n{message}\n<|assistant|>\n"
174
  prompt_ids = sp.encode(prompt)
175
-
176
- if len(prompt_ids) > 1024:
177
- prompt_ids = prompt_ids[-1024:]
178
 
179
  inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)
180
-
181
- END_SEQ = sp.encode("<|endoftext|>")
182
- USER_SEQ = sp.encode("<|user|>")
183
-
184
  generated = []
185
- MAX_NEW = 512
186
 
187
  with torch.no_grad():
188
- for _ in range(MAX_NEW):
189
- with torch.autocast("cuda" if device.type == "cuda" else "cpu", dtype=torch.bfloat16):
190
  logits = model(inp)[0, -1, :].float()
191
 
192
- # ๐Ÿ”ฅ FIX 2: Official Hugging Face Repetition Math
193
- penalty = 1.2
194
  for gid in set(generated[-50:]):
195
- if logits[gid] > 0:
196
- logits[gid] /= penalty
197
- else:
198
- logits[gid] *= penalty
199
 
200
- # ๐Ÿ”ฅ FIX 3: Laser-Focused Sampling (Temp 0.3, Top-K 10)
201
- logits = logits / 0.3
202
 
203
- top_k_values, _ = torch.topk(logits, 10)
204
  logits[logits < top_k_values[-1]] = -float('inf')
205
 
206
- probs = F.softmax(logits, dim=-1)
 
 
 
 
 
 
 
 
 
 
207
  next_t = torch.multinomial(probs, 1).item()
 
 
208
 
209
  generated.append(next_t)
210
  inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)
211
 
212
- # Strict Stop Conditions
213
- if len(generated) >= len(END_SEQ) and generated[-len(END_SEQ):] == END_SEQ:
214
- break
215
- if len(generated) >= len(USER_SEQ) and generated[-len(USER_SEQ):] == USER_SEQ:
216
- break
217
-
218
- # Hard Anti-Stutter (Kills the loop if it repeats the same token 4 times)
219
- if len(generated) >= 4 and generated[-1] == next_t and generated[-2] == next_t and generated[-3] == next_t:
220
- break
221
 
222
  response = sp.decode(generated).strip()
223
-
224
- # Clean up any tags
225
  for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:
226
  response = response.split(tag)[0]
227
-
228
  return response.strip()
229
 
230
- # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•๏ฟฝ๏ฟฝ๏ฟฝโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
231
- # GRADIO UI
232
- # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
233
- with gr.Blocks(
234
- title="CodeSymb AI",
235
- theme=gr.themes.Base(primary_hue="cyan", secondary_hue="blue"),
236
- css="body { background: #060D1F !important; color: white !important; } .gradio-container { max-width: 860px !important; }"
237
- ) as demo:
238
- gr.HTML("""
239
- <h1 style='text-align:center; color:#00D4FF;'>โšก CodeSymb AI</h1>
240
- <p style='text-align:center; color:#A0AEC0;'>
241
- Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐Ÿ‡ฎ๐Ÿ‡ณ<br>
242
- <em>"Impossible is just a door with no handle yet invented."</em>
243
- </p>
244
- """)
245
- gr.ChatInterface(fn=chat_with_codesymb)
246
 
247
  if __name__ == "__main__":
248
  demo.launch()
 
1
  # ================================================================
2
+ # CodeSymb AI โ€” Base Model + Rank-100 Chat LoRA
3
+ # โœ… Loads 1B Base Model (240k steps)
4
+ # โœ… Loads 141MB Chat LoRA
5
+ # โœ… Merges them mathematically for Native Speed!
6
  # NiftyOracleAI ๐Ÿ‡ฎ๐Ÿ‡ณ | codesymb.com ๐ŸŒŽ
7
  # ================================================================
8
 
 
15
  import os
16
  from huggingface_hub import hf_hub_download, login
17
 
 
18
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
19
  USERNAME = "NiftyOracleAI"
20
  REPO_ID = f"{USERNAME}/NiftyOracle-Coder-30B"
21
+ LORA_REPO = f"{USERNAME}/codesymb-chat-lora"
22
  TOK_REPO = f"{USERNAME}/niftyoracle-tokenizer"
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):
31
  super().__init__()
32
+ self.w = nn.Parameter(torch.ones(d)); self.eps = eps
 
33
  def forward(self, x):
34
  n = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
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):
47
  a, b = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
48
  return torch.cat([-b, a], dim=-1)
49
 
50
+ def rope(q, k, cos, sin): return (q*cos)+(rot(q)*sin), (k*cos)+(rot(k)*sin)
 
51
 
52
  class Attn(nn.Module):
53
  def __init__(self, nh=16, nkv=4, dm=2048):
54
  super().__init__()
55
+ hd = dm // nh; self.nh = nh; self.nkv = nkv; self.hd = hd; self.rep = nh // nkv
56
+ self.q = nn.Linear(dm, nh*hd, bias=False)
57
+ self.k = nn.Linear(dm, nkv*hd, bias=False)
58
+ self.v = nn.Linear(dm, nkv*hd, bias=False)
59
+ self.o = nn.Linear(nh*hd, dm, bias=False)
 
 
60
  self.pe = RoPE(hd)
61
  def forward(self, x):
62
  B, T, _ = x.shape
63
  q = self.q(x).view(B,T,self.nh,self.hd).transpose(1,2)
64
  k = self.k(x).view(B,T,self.nkv,self.hd).transpose(1,2)
65
  v = self.v(x).view(B,T,self.nkv,self.hd).transpose(1,2)
66
+ cos, sin = self.pe(T); q, k = rope(q, k, cos, sin)
67
+ k = k.repeat_interleave(self.rep, dim=1); v = v.repeat_interleave(self.rep, dim=1)
 
 
68
  o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
69
  return self.o(o.transpose(1,2).contiguous().view(B,T,-1))
70
 
 
74
  self.g = nn.Linear(dm, df, bias=False)
75
  self.u = nn.Linear(dm, df, bias=False)
76
  self.d = nn.Linear(df, dm, bias=False)
77
+ def forward(self, x): return self.d(F.silu(self.g(x)) * self.u(x))
 
78
 
79
  class Block(nn.Module):
80
  def __init__(self, dm=2048, df=8192, nh=16, nkv=4):
81
  super().__init__()
82
+ self.n1 = RMSNorm(dm); self.att = Attn(nh, nkv, dm)
83
+ self.n2 = RMSNorm(dm); self.ff = FFN(dm, df)
 
 
84
  def forward(self, x):
85
+ x = x + self.att(self.n1(x)); x = x + self.ff(self.n2(x)); return x
 
 
86
 
87
  class CodeSymb1B(nn.Module):
88
  def __init__(self, vocab=50000):
 
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
+ # LOAD BASE + LORA & MERGE
102
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
103
+ print("โณ Loading Tokenizer...")
104
  tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)
105
+ sp = spm.SentencePieceProcessor(); sp.load(tok_path)
 
 
106
 
107
+ print("โณ Loading Base Model (240k steps)...")
108
+ model = CodeSymb1B(vocab=sp.get_piece_size())
109
+ base_ckpt = hf_hub_download(REPO_ID, "checkpoints/latest.pt", token=HF_TOKEN or None)
110
+ state = torch.load(base_ckpt, map_location="cpu", weights_only=False)
111
+ model_state = {k: v for k, v in state.get("model", state).items() if not k.endswith((".pe.cos", ".pe.sin"))}
112
+ model.load_state_dict(model_state, strict=False)
113
 
114
+ print("โšก Loading & Merging Rank-100 Chat LoRA...")
115
  try:
116
+ # Use safetensors from the PEFT upload!
117
+ from safetensors.torch import load_file
118
+ lora_ckpt = hf_hub_download(LORA_REPO, "chat-behavior-lora/adapter_model.safetensors", token=HF_TOKEN or None)
119
+ lora_state = load_file(lora_ckpt)
 
 
 
120
 
121
+ # Mathematically fuse the LoRA matrices (W = W + A*B * scale)
122
+ scale = 200 / 100 # alpha / rank
123
+ with torch.no_grad():
124
+ for i, block in enumerate(model.blocks):
125
+ if f"base_model.model.blocks.{i}.att.q.lora_A.weight" in lora_state:
126
+ block.att.q.weight += (lora_state[f"base_model.model.blocks.{i}.att.q.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.q.lora_A.weight"]) * scale
127
+ block.att.k.weight += (lora_state[f"base_model.model.blocks.{i}.att.k.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.k.lora_A.weight"]) * scale
128
+ block.att.v.weight += (lora_state[f"base_model.model.blocks.{i}.att.v.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.v.lora_A.weight"]) * scale
129
+ block.att.o.weight += (lora_state[f"base_model.model.blocks.{i}.att.o.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.att.o.lora_A.weight"]) * scale
130
+ block.ff.g.weight += (lora_state[f"base_model.model.blocks.{i}.ff.g.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.ff.g.lora_A.weight"]) * scale
131
+ block.ff.u.weight += (lora_state[f"base_model.model.blocks.{i}.ff.u.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.ff.u.lora_A.weight"]) * scale
132
+ block.ff.d.weight += (lora_state[f"base_model.model.blocks.{i}.ff.d.lora_B.weight"] @ lora_state[f"base_model.model.blocks.{i}.ff.d.lora_A.weight"]) * scale
133
+ print("โœ… Chat LoRA Fused Successfully!")
134
  except Exception as e:
135
+ print(f"โš ๏ธ Could not load LoRA (Make sure path is correct!): {e}")
136
 
137
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
138
+ model = model.to(device).to(torch.float16).eval()
139
+ print("โœ… CodeSymb-1B + Chat LoRA โ€” READY ๐Ÿ”ฅ")
140
 
141
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
142
+ # INFERENCE & UI
143
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
144
  SYSTEM_PROMPT = (
145
+ "You are CodeSymb, a highly intelligent and empathetic AI coding partner built by "
146
+ "Developer Dev Malkar and Founder Deepakkumar Malkar at NiftyOracle in India. "
147
+ "You provide direct, accurate, and clean code. You never repeat yourself. You answer concisely."
 
 
 
 
 
 
 
 
 
148
  )
149
 
150
  @spaces.GPU(duration=60)
 
152
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
153
  model.to(device)
154
 
155
+ prompt = f"<|system|>\n{SYSTEM_PROMPT}\n<|user|>\n{message}\n<|assistant|>\n"
 
 
 
 
 
 
 
156
  prompt_ids = sp.encode(prompt)
157
+ if len(prompt_ids) > 1024: prompt_ids = prompt_ids[-1024:]
 
 
158
 
159
  inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)
160
+ END_SEQ = sp.encode("<|endoftext|>")
 
 
 
161
  generated = []
 
162
 
163
  with torch.no_grad():
164
+ for _ in range(512):
165
+ with torch.autocast("cuda" if device.type == "cuda" else "cpu", dtype=torch.float16):
166
  logits = model(inp)[0, -1, :].float()
167
 
 
 
168
  for gid in set(generated[-50:]):
169
+ logits[gid] -= 2.0
 
 
 
170
 
171
+ logits = logits / 0.6
 
172
 
173
+ top_k_values, _ = torch.topk(logits, 40)
174
  logits[logits < top_k_values[-1]] = -float('inf')
175
 
176
+ sorted_logits, sorted_idx = torch.sort(logits, descending=True)
177
+ cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
178
+ remove = cum_probs > 0.90
179
+ remove[..., 1:] = remove[..., :-1].clone()
180
+ remove[..., 0] = 0
181
+ sorted_logits[remove] = -float("inf")
182
+
183
+ logits_filtered = torch.zeros_like(logits)
184
+ logits_filtered.scatter_(0, sorted_idx, sorted_logits)
185
+ probs = F.softmax(logits_filtered, dim=-1)
186
+
187
  next_t = torch.multinomial(probs, 1).item()
188
+ if len(generated) >= 3 and generated[-1] == next_t and generated[-2] == next_t:
189
+ break
190
 
191
  generated.append(next_t)
192
  inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)
193
 
194
+ if len(generated) >= len(END_SEQ) and generated[-len(END_SEQ):] == END_SEQ: break
 
 
 
 
 
 
 
 
195
 
196
  response = sp.decode(generated).strip()
 
 
197
  for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:
198
  response = response.split(tag)[0]
 
199
  return response.strip()
200
 
201
+ demo = gr.ChatInterface(
202
+ fn=chat_with_codesymb,
203
+ title="CodeSymb-1B + Chat LoRA ๐Ÿ‡ฎ๐Ÿ‡ณ",
204
+ description="The complete Base Model + Rank-100 Empathy LoRA!"
205
+ )
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  if __name__ == "__main__":
208
  demo.launch()