Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678916 unmodified lines262728293031323366 unmodified lines1001011021031041051061071081091101111121131 unmodified line11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816911 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382395 unmodified lines2452462472482492502512521 unmodified line2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842851 unmodified line2872882892902912922932942952962972982993001 unmodified line30230330430530630730830931031131231331431531631731831932032132232332432532632710 unmodified lines338339340341342343344345346347348349350351352# ================================================================# CodeSymb AI โ HuggingFace Space app.py (FIXED!)# Loads .pt checkpoint directly โ NO GGUF issues!# Works on ZeroGPU Spaces (A100 80GB)## REPLACE your current app.py with this!# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐# ================================================================16 unmodified lineslogin(token=HF_TOKEN)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# EXACT SAME MODEL ARCHITECTURE AS TRAINING# (This is why .pt loading works perfectly!)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass RMSNorm(nn.Module):def __init__(self, d, eps=1e-6):66 unmodified linesreturn xclass CodeSymb1B(nn.Module):"""CodeSymb 1B | NiftyOracleAI ๐ฎ๐ | codesymb.com"""def __init__(self):super().__init__()DM=2048; DF=8192; NL=16; NH=16; NKV=4; V=50000self.embed = nn.Embedding(V, DM)self.blocks = nn.ModuleList([Block(DM,DF,NH,NKV) for _ in range(NL)])self.norm = RMSNorm(DM)self.head = nn.Linear(DM, V, bias=False)def forward(self, tok):x = self.embed(tok).bfloat16()for b in self.blocks:1 unmodified linereturn self.head(self.norm(x))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# LOAD MODEL + TOKENIZER (happens once at startup)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โณ Loading CodeSymb-1B tokenizer...")tok_path = hf_hub_download(TOK_REPO,"niftyoracle_tokenizer.model",token=HF_TOKEN or None,)sp = spm.SentencePieceProcessor()sp.load(tok_path)VOCAB = sp.get_piece_size()print(f"โ Tokenizer: {VOCAB:,} vocab")# Special token IDs โ encode themSYS_TOKEN = sp.encode("<|system|>")USER_TOKEN = sp.encode("<|user|>")ASST_TOKEN = sp.encode("<|assistant|>")END_TOKEN = sp.encode("<|endoftext|>")print("โณ Loading CodeSymb-1B model...")model = CodeSymb1B()# Try SFT checkpoint first, fall back to basefor ckpt_name in ["checkpoints/sft_latest.pt","checkpoints/latest.pt","checkpoints/sft_chat_latest.pt"]:try:ckpt_path = hf_hub_download(REPO_ID, ckpt_name, token=HF_TOKEN or None)state = torch.load(ckpt_path, map_location="cpu")model_state = state.get("model", state)model.load_state_dict(model_state, strict=False)step = state.get("step", 0)loss = state.get("loss", 0)print(f"โ Loaded: {ckpt_name}")print(f" Step: {step:,} | Loss: {loss:.4f}")breakexcept Exception as e:print(f" Not found: {ckpt_name} ({e})")model.eval()n_params = sum(p.numel() for p in model.parameters())print(f"โ CodeSymb-1B: {n_params/1e9:.2f}B params")print("โ Model ready! ๐ฅ")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# THE EMPATHY SYSTEM PROMPT# (Same as what was trained on!)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโSYSTEM_PROMPT = ("You are CodeSymb, the world's most intelligent, deeply empathetic, "11 unmodified lines)def build_prompt(message: str, history: list) -> list:"""Build token IDs for the complete conversation"""ids = []# System promptids += SYS_TOKENids += sp.encode("\n" + SYSTEM_PROMPT + "\n")# History (previous turns)for user_msg, asst_msg in history[-4:]: # Last 4 turnsids += USER_TOKENids += sp.encode("\n" + str(user_msg) + "\n")ids += ASST_TOKENids += sp.encode("\n" + str(asst_msg) + "\n")# Current messageids += USER_TOKENids += sp.encode("\n" + message + "\n")ids += ASST_TOKENids += sp.encode("\n")return ids@spaces.GPU(duration=60)def chat_with_codesymb(message: str, history: list) -> str:"""Generate response from CodeSymb-1B.Loads model to GPU just for this call (ZeroGPU!)"""device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)# Build prompt tokensprompt_ids = build_prompt(message, history)# Trim if too long (max 1024 input tokens)if len(prompt_ids) > 1024:prompt_ids = prompt_ids[-1024:]inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)# โโ GENERATION โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโgenerated = []MAX_NEW = 512END_IDS = set(END_TOKEN + ASST_TOKEN[:1] + USER_TOKEN[:1])with torch.no_grad():for _ in range(MAX_NEW):with torch.autocast("cuda" if device.type=="cuda" else "cpu",dtype=torch.bfloat16):logits = model(inp)[0, -1, :] # [vocab]# Temperature + top-p samplinglogits = logits / 0.7 # temperature# Top-p (nucleus) samplingsorted_logits, sorted_idx = torch.sort(logits, descending=True)5 unmodified lineslogits_filtered = torch.zeros_like(logits)logits_filtered.scatter_(0, sorted_idx, sorted_logits)# Repetition penaltyif len(generated) > 0:for gid in set(generated[-20:]):if 0 <= gid < logits_filtered.shape[0]:logits_filtered[gid] /= 1.31 unmodified lineprobs = F.softmax(logits_filtered, dim=-1)next_t = torch.multinomial(probs, 1).item()# Stop conditionsif next_t in END_IDS:breakif len(generated) > 20 and next_t == generated[-1] == generated[-2]:break # Stop repetitiongenerated.append(next_t)new_tok = torch.tensor([[next_t]], dtype=torch.long).to(device)inp = torch.cat([inp, new_tok], dim=1)# Decoderesponse = sp.decode(generated).strip()# Clean up any leaked tagsfor tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:response = response.split(tag)[0]response = response.strip()if not response:response = ("I'm CodeSymb, your coding partner! ๐ฅ\n""Built by Deepakkumar Malkar at NiftyOracle ๐ฎ๐\n""Ask me anything about code!")return response# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ1 unmodified line# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(title="CodeSymb AI โ codesymb.com",theme=gr.themes.Base(primary_hue="blue",secondary_hue="indigo",),css="""body { background: #060D1F !important; }.gradio-container { max-width: 860px !important; }h1 {text-align: center;background: linear-gradient(135deg, #00D4FF, #A855F7);-webkit-background-clip: text;1 unmodified linefont-size: 2.5em !important;font-weight: 900 !important;}.subtitle {text-align: center;color: #A0AEC0;margin-bottom: 20px;font-size: 1.1em;}""") as demo:gr.HTML("""<h1>โก CodeSymb AI</h1><p class='subtitle'>World's Most Powerful Coding AI ๐<br>Built by <strong>Deepakkumar Malkar</strong>at NiftyOracle ๐ฎ๐<br><em>"Impossible is just a door with no handle yet invented."</em></p>""")chatbot = gr.ChatInterface(fn=chat_with_codesymb,examples=[["Hi! Who are you and what can you build?"],10 unmodified linesgr.HTML("""<div style='text-align:center;padding:20px;color:#4A5568;font-size:13px'><strong>CodeSymb-1B</strong> | 1.08B params | Loss: 1.17 |Trained on TPU v5e-8 | 240,000 steps<br><a href='https://codesymb.com' style='color:#1D6FEB'>codesymb.com</a> ๐ |<a href='https://huggingface.co/NiftyOracleAI'style='color:#1D6FEB'>HuggingFace</a></div>""")12345678916 unmodified lines2627282930313266 unmodified lines991001011021031041051061071081091101111121 unmodified line11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615711 unmodified lines1691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232245 unmodified lines2302312322332342352362371 unmodified line2392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692701 unmodified line2722732742752762772782792802812821 unmodified line28428528628728828929029129229329429529629729829930030130230310 unmodified lines314315316317318319320321322# ================================================================# CodeSymb AI โ HuggingFace Space app.py (FINAL v2.0)# โ Single-string tokenization (matches training exactly)# โ Full-sequence stop tags (no more "<" premature death)# โ Vocab size verification# โ Hard fail if no checkpoint (no silent random model)# NiftyOracleAI ๐ฎ๐ณ | codesymb.com ๐# ================================================================16 unmodified lineslogin(token=HF_TOKEN)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# MODEL ARCHITECTURE (must match training exactly)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass RMSNorm(nn.Module):def __init__(self, d, eps=1e-6):66 unmodified linesreturn xclass CodeSymb1B(nn.Module):"""CodeSymb 1B | NiftyOracleAI ๐ฎ๐ณ | codesymb.com"""def __init__(self, vocab=50000):super().__init__()DM=2048; DF=8192; NL=16; NH=16; NKV=4self.embed = nn.Embedding(vocab, DM)self.blocks = nn.ModuleList([Block(DM,DF,NH,NKV) for _ in range(NL)])self.norm = RMSNorm(DM)self.head = nn.Linear(DM, vocab, bias=False)def forward(self, tok):x = self.embed(tok).bfloat16()for b in self.blocks:1 unmodified linereturn self.head(self.norm(x))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# LOAD TOKENIZER + MODEL# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("โณ Loading CodeSymb-1B tokenizer...")tok_path = hf_hub_download(TOK_REPO, "niftyoracle_tokenizer.model", token=HF_TOKEN or None)sp = spm.SentencePieceProcessor()sp.load(tok_path)VOCAB = sp.get_piece_size()print(f"โ Tokenizer: {VOCAB:,} vocab")print("โณ Loading CodeSymb-1B model...")model = CodeSymb1B(vocab=VOCAB) # โ architecture built to match REAL vocab sizeckpt_found = Falsefor ckpt_name in ["checkpoints/sft_latest.pt","checkpoints/latest.pt","checkpoints/sft_chat_latest.pt"]:try:ckpt_path = hf_hub_download(REPO_ID, ckpt_name, token=HF_TOKEN or None)state = torch.load(ckpt_path, map_location="cpu", mmap=True)model_state = state.get("model", state)model.load_state_dict(model_state, strict=False)step = state.get("step", 0)print(f"โ Loaded: {ckpt_name} (step {step:,})")ckpt_found = Truebreakexcept Exception as e:print(f" Not found: {ckpt_name}")# โ HARD FAIL โ never serve a random-weight model silentlyif not ckpt_found:raise RuntimeError("โ NO CHECKPOINT FOUND on HF! Fix repo before deploying!")model.eval()n_params = sum(p.numel() for p in model.parameters())print(f"โ CodeSymb-1B: {n_params/1e9:.2f}B params โ READY ๐ฅ")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# SYSTEM PROMPT (byte-identical to SFT training data)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโSYSTEM_PROMPT = ("You are CodeSymb, the world's most intelligent, deeply empathetic, "11 unmodified lines)def build_prompt(message: str, history: list) -> list:"""โ Build ONE string exactly like training did, encode ONCE.SentencePiece is not concatenative โ never encode pieces separately!"""parts = ["<|system|>\n" + SYSTEM_PROMPT + "\n"]for user_msg, asst_msg in history[-4:]:parts.append(f"<|user|>\n{user_msg}\n<|assistant|>\n{asst_msg}\n")parts.append(f"<|user|>\n{message}\n<|assistant|>\n")return sp.encode("".join(parts))def tail_matches(generated: list, seq: list) -> bool:"""โ Only stop on COMPLETE tag sequence โ a lone '<' won't kill generation"""seq = list(seq)return len(generated) >= len(seq) and generated[-len(seq):] == seq@spaces.GPU(duration=60)def chat_with_codesymb(message: str, history: list) -> str:device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)prompt_ids = build_prompt(message, history)# โ Trim safely: if too long, keep from a <|user|> boundary, never mid-tagif len(prompt_ids) > 1024:user_seq = sp.encode("<|user|>")start = 0for i in range(len(prompt_ids) - 6, 0, -1):if prompt_ids[i:i+len(user_seq)] == list(user_seq):start = ibreakprompt_ids = prompt_ids[start:][-1024:]inp = torch.tensor([prompt_ids], dtype=torch.long).to(device)# โ Stop sequences (complete multi-piece tags, not single pieces)END_SEQ = sp.encode("<|endoftext|>")USER_SEQ = sp.encode("<|user|>")SYS_SEQ = sp.encode("<|system|>")generated = []MAX_NEW = 512with torch.no_grad():for _ in range(MAX_NEW):with torch.autocast("cuda" if device.type == "cuda" else "cpu",dtype=torch.bfloat16):logits = model(inp)[0, -1, :].float()# Temperaturelogits = logits / 0.7# Top-p (nucleus) samplingsorted_logits, sorted_idx = torch.sort(logits, descending=True)5 unmodified lineslogits_filtered = torch.zeros_like(logits)logits_filtered.scatter_(0, sorted_idx, sorted_logits)# Repetition penalty (last 20 tokens)if generated:for gid in set(generated[-20:]):if 0 <= gid < logits_filtered.shape[0]:logits_filtered[gid] /= 1.31 unmodified lineprobs = F.softmax(logits_filtered, dim=-1)next_t = torch.multinomial(probs, 1).item()# โ Stop ONLY on complete turn-ending tagsif tail_matches(generated, END_SEQ) or \tail_matches(generated, USER_SEQ) or \tail_matches(generated, SYS_SEQ):break# Anti-loop: same token 3x in a rowif len(generated) > 2 and generated[-1] == generated[-2] == next_t:breakgenerated.append(next_t)inp = torch.cat([inp, torch.tensor([[next_t]], device=device)], dim=1)response = sp.decode(generated).strip()# Strip any leaked tagsfor tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:response = response.split(tag)[0]response = response.strip()if not response:response = ("I'm CodeSymb, your coding partner! ๐ฅ\n""Built by Deepakkumar Malkar at NiftyOracle ๐ฎ๐ณ\n""Ask me anything about code!")return response# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ1 unmodified line# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(title="CodeSymb AI โ codesymb.com",theme=gr.themes.Base(primary_hue="blue", secondary_hue="indigo"),css="""body { background: #060D1F !important; }.gradio-container { max-width: 860px !important; }h1 {text-align: center;background: linear-gradient(135deg, #00D4FF, #A855F7);-webkit-background-clip: text;1 unmodified linefont-size: 2.5em !important;font-weight: 900 !important;}.subtitle { text-align: center; color: #A0AEC0; margin-bottom: 20px; font-size: 1.1em; }""",) as demo:gr.HTML("""<h1>โก CodeSymb AI</h1><p class='subtitle'>World's Most Powerful Coding AI ๐<br>Built by <strong>Deepakkumar Malkar</strong> at NiftyOracle ๐ฎ๐ณ<br><em>"Impossible is just a door with no handle yet invented."</em></p>""")gr.ChatInterface(fn=chat_with_codesymb,examples=[["Hi! Who are you and what can you build?"],10 unmodified linesgr.HTML("""<div style='text-align:center;padding:20px;color:#4A5568;font-size:13px'><strong>CodeSymb-1B</strong> | 1.08B params | NiftyOracle ๐ฎ๐ณ<br><a href='https://codesymb.com' style='color:#1D6FEB'>codesymb.com</a> ๐ |<a href='https://huggingface.co/NiftyOracleAI' style='color:#1D6FEB'>HuggingFace</a></div>""")
app.py+79-109