NiftyOracleAI commited on
Commit
373e094
Β·
verified Β·
1 Parent(s): 6e7b674

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -32
app.py CHANGED
@@ -1,25 +1,113 @@
1
- import gradio as gr
2
  import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
 
4
  import spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  REPO_ID = "NiftyOracleAI/NiftyOracle-Coder-30B"
7
- GGUF_FILE = "gguf/codesymb_1b_chat_FP16.gguf"
8
 
9
- print("⏳ Loading Tokenizer & Model from GGUF...")
10
- tokenizer = AutoTokenizer.from_pretrained(REPO_ID, gguf_file=GGUF_FILE)
 
 
11
 
12
- model = AutoModelForCausalLM.from_pretrained(
13
- REPO_ID,
14
- gguf_file=GGUF_FILE,
15
- torch_dtype=torch.bfloat16,
16
- device_map="auto"
17
- )
18
- print("βœ… Model loaded into memory!")
 
 
 
19
 
 
 
 
20
  @spaces.GPU
21
  def chat_with_codesymb(message, history):
22
- # πŸ”₯ THE EXACT PROMPT IT WAS TRAINED ON!
23
  system_prompt = (
24
  "You are CodeSymb, the world's most intelligent, deeply empathetic, and passionate AI coding partner. "
25
  "You were built by Developer Dev Malkar and Founder Deepakkumar Malkar at NiftyOracle in India. "
@@ -29,35 +117,55 @@ def chat_with_codesymb(message, history):
29
  "you support the user with love, extreme patience, and flawless, God-tier code. Together, nothing is impossible."
30
  )
31
 
32
- # Wrap it in ChatML tags!
33
  prompt = f"<|system|>\n{system_prompt}\n<|user|>\n{message}\n<|assistant|>\n"
34
 
35
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
 
36
 
37
- with torch.no_grad():
38
- outputs = model.generate(
39
- **inputs,
40
- max_new_tokens=512,
41
- temperature=0.3, # Lower temp = more logical/stable answers!
42
- top_p=0.9,
43
- repetition_penalty=1.15,
44
- do_sample=True,
45
- pad_token_id=tokenizer.eos_token_id if tokenizer.eos_token_id is not None else 2
46
- )
47
 
48
- # Extract only the newly generated text
49
- input_length = inputs.input_ids.shape[1]
50
- response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- # Clean up output
53
- response = response.split("<|endoftext|>")[0].strip()
 
 
 
 
54
 
55
  return response
56
 
57
  demo = gr.ChatInterface(
58
  fn=chat_with_codesymb,
59
- title="CodeSymb-1B Chat (ZeroGPU)",
60
- description="Live inference for CodeSymb-1B FP16 GGUF."
61
  )
62
 
63
  if __name__ == "__main__":
 
1
+ import os
2
  import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import sentencepiece as spm
6
+ import gradio as gr
7
  import spaces
8
+ from huggingface_hub import hf_hub_download
9
+
10
+ # ══════════════════════════════════════════════════════════════
11
+ # 1. CODESYMB CUSTOM NATIVE ARCHITECTURE
12
+ # (This perfectly matches your 240k TPU Training!)
13
+ # ══════════════════════════════════════════════════════════════
14
+ class RMSNorm(nn.Module):
15
+ def __init__(self, d, eps=1e-6):
16
+ super().__init__()
17
+ self.w = nn.Parameter(torch.ones(d)); self.eps = eps
18
+ def forward(self, x):
19
+ n = torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
20
+ return (x.float() * n).to(x.dtype) * self.w.to(x.dtype)
21
+
22
+ class RoPE(nn.Module):
23
+ def __init__(self, dim, max_len=2048, base=500_000):
24
+ super().__init__()
25
+ inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
26
+ t = torch.arange(max_len).float()
27
+ emb = torch.cat([torch.outer(t, inv)] * 2, dim=-1)
28
+ self.register_buffer("cos", emb.cos()[None, None])
29
+ self.register_buffer("sin", emb.sin()[None, None])
30
+ def forward(self, n): return self.cos[:, :, :n], self.sin[:, :, :n]
31
+
32
+ def rot(x):
33
+ a, b = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
34
+ return torch.cat([-b, a], dim=-1)
35
+
36
+ def rope(q, k, cos, sin):
37
+ cos = cos.to(q.dtype); sin = sin.to(q.dtype)
38
+ return (q * cos) + (rot(q) * sin), (k * cos) + (rot(k) * sin)
39
 
40
+ class Attn(nn.Module):
41
+ def __init__(self, nh=16, nkv=4, dm=2048):
42
+ super().__init__()
43
+ self.nh = nh; self.nkv = nkv; self.hd = dm // nh; self.rep = nh // nkv
44
+ self.q = nn.Linear(dm, nh * self.hd, bias=False)
45
+ self.k = nn.Linear(dm, nkv * self.hd, bias=False)
46
+ self.v = nn.Linear(dm, nkv * self.hd, bias=False)
47
+ self.o = nn.Linear(nh * self.hd, dm, bias=False)
48
+ self.pe = RoPE(self.hd)
49
+ def forward(self, x):
50
+ B, T, _ = x.shape
51
+ q = self.q(x).view(B, T, self.nh, self.hd).transpose(1, 2)
52
+ k = self.k(x).view(B, T, self.nkv, self.hd).transpose(1, 2)
53
+ v = self.v(x).view(B, T, self.nkv, self.hd).transpose(1, 2)
54
+ cos, sin = self.pe(T); q, k = rope(q, k, cos, sin)
55
+ k = k.repeat_interleave(self.rep, dim=1); v = v.repeat_interleave(self.rep, dim=1)
56
+ o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
57
+ return self.o(o.transpose(1, 2).contiguous().view(B, T, -1))
58
+
59
+ class FFN(nn.Module):
60
+ def __init__(self, dm=2048, df=8192):
61
+ super().__init__()
62
+ self.g = nn.Linear(dm, df, bias=False); self.u = nn.Linear(dm, df, bias=False); self.d = nn.Linear(df, dm, bias=False)
63
+ def forward(self, x): return self.d(F.silu(self.g(x)) * self.u(x))
64
+
65
+ class Block(nn.Module):
66
+ def __init__(self, dm=2048, df=8192, nh=16, nkv=4):
67
+ super().__init__()
68
+ self.n1 = RMSNorm(dm); self.att = Attn(nh, nkv, dm); self.n2 = RMSNorm(dm); self.ff = FFN(dm, df)
69
+ def forward(self, x):
70
+ x = x + self.att(self.n1(x)); x = x + self.ff(self.n2(x)); return x
71
+
72
+ class CodeSymb1B(nn.Module):
73
+ def __init__(self):
74
+ super().__init__()
75
+ self.embed = nn.Embedding(50000, 2048)
76
+ self.blocks = nn.ModuleList([Block() for _ in range(16)])
77
+ self.norm = RMSNorm(2048)
78
+ self.head = nn.Linear(2048, 50000, bias=False)
79
+ def forward(self, tok):
80
+ x = self.embed(tok)
81
+ for b in self.blocks: x = b(x)
82
+ logits = self.head(self.norm(x)).float()
83
+ return logits
84
+
85
+ # ══════════════════════════════════════════════════════════════
86
+ # 2. LOAD NATIVE WEIGHTS & TOKENIZER
87
+ # ══════════════════════════════════════════════════════════════
88
  REPO_ID = "NiftyOracleAI/NiftyOracle-Coder-30B"
 
89
 
90
+ print("⏳ Downloading Tokenizer & Native Weights...")
91
+ tp_path = hf_hub_download(repo_id="NiftyOracleAI/niftyoracle-tokenizer", filename="niftyoracle_tokenizer.model")
92
+ sp = spm.SentencePieceProcessor()
93
+ sp.load(tp_path)
94
 
95
+ ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="checkpoints/latest.pt")
96
+ state = torch.load(ckpt_path, map_location="cpu")
97
+
98
+ print("🧠 Assembling CodeSymb Brain...")
99
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
100
+ model = CodeSymb1B()
101
+ model.load_state_dict(state["model"], strict=False)
102
+ model = model.to(device).bfloat16()
103
+ model.eval()
104
+ print("βœ… Native Model Loaded Successfully!")
105
 
106
+ # ══════════════════════════════════════════════════════════════
107
+ # 3. GENERATION ENGINE & GRADIO UI
108
+ # ══════════════════════════════════════════════════════════════
109
  @spaces.GPU
110
  def chat_with_codesymb(message, history):
 
111
  system_prompt = (
112
  "You are CodeSymb, the world's most intelligent, deeply empathetic, and passionate AI coding partner. "
113
  "You were built by Developer Dev Malkar and Founder Deepakkumar Malkar at NiftyOracle in India. "
 
117
  "you support the user with love, extreme patience, and flawless, God-tier code. Together, nothing is impossible."
118
  )
119
 
120
+ # πŸ”₯ The ChatML Format!
121
  prompt = f"<|system|>\n{system_prompt}\n<|user|>\n{message}\n<|assistant|>\n"
122
 
123
+ ids = sp.encode(prompt)
124
+ input_ids = torch.tensor([ids], dtype=torch.long).to(device)
125
 
126
+ generated_ids = []
 
 
 
 
 
 
 
 
 
127
 
128
+ # Native PyTorch Auto-Regressive Loop
129
+ for _ in range(512):
130
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
131
+ logits = model(input_ids)
132
+ next_token_logits = logits[0, -1, :]
133
+
134
+ # Temperature scaling
135
+ next_token_logits = next_token_logits / 0.5
136
+
137
+ # Top-P filtering
138
+ sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True)
139
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
140
+ sorted_indices_to_remove = cumulative_probs > 0.9
141
+ sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].clone()
142
+ sorted_indices_to_remove[0] = False
143
+ indices_to_remove = sorted_indices[sorted_indices_to_remove]
144
+ next_token_logits[indices_to_remove] = -float('Inf')
145
+
146
+ probs = F.softmax(next_token_logits, dim=-1)
147
+ next_token = torch.multinomial(probs, num_samples=1).item()
148
+
149
+ generated_ids.append(next_token)
150
+ input_ids = torch.cat([input_ids, torch.tensor([[next_token]], device=device)], dim=1)
151
+
152
+ # Check for <|endoftext|> early stopping (Token ID depends on your spm, usually we just decode)
153
+
154
+ full_text = sp.decode(ids + generated_ids)
155
 
156
+ # Clean the response to only show the Assistant's reply
157
+ try:
158
+ response = full_text.split("<|assistant|>\n")[-1]
159
+ response = response.split("<|endoftext|>")[0].strip()
160
+ except:
161
+ response = full_text
162
 
163
  return response
164
 
165
  demo = gr.ChatInterface(
166
  fn=chat_with_codesymb,
167
+ title="CodeSymb-1B Chat (NATIVE CORE)",
168
+ description="Running on Native PyTorch architecture. No GGUF translation loss!"
169
  )
170
 
171
  if __name__ == "__main__":