Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891027 unmodified lines3839404142434454 unmodified lines9910010110210310410518 unmodified lines1241251261271281291304 unmodified lines1351361371381391401411421431441451461471481 unmodified line15015115215315415515615715815916016116216316416516616711 unmodified lines1791801811821831841851861871881 unmodified line1901911921931941951963 unmodified lines2002012022032042052062075 unmodified lines2132142152162172182193 unmodified lines2232242252262272282292302312322332342352363 unmodified lines2402412422432442452462 unmodified lines2492502512522532542552562572582592602612 unmodified lines2642652662672682692702712722732742752762772782 unmodified lines28128228328428528628724 unmodified lines312313314315316317318319320321322323324325326327328329330331332333334# ================================================================# 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 ๐# ================================================================import gradio as gr27 unmodified linesreturn (x.float() * n).to(x.dtype) * self.w.to(x.dtype)class RoPE(nn.Module):def __init__(self, dim, max_len=2048, base=500_000):super().__init__()inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)54 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=418 unmodified linesprint(f"โ Tokenizer: {VOCAB:,} vocab")print("โณ Loading CodeSymb-1B model...")model = CodeSymb1B(vocab=VOCAB) # โ architecture built to match REAL vocab sizeckpt_found = Falselast_err = None4 unmodified linesckpt_path = hf_hub_download(REPO_ID, ckpt_name, token=HF_TOKEN or None)print(f"โฌ๏ธ Downloaded {ckpt_name} โ loading weights...")try:state = torch.load(ckpt_path, map_location="cpu") # โ NO mmapexcept Exception:state = torch.load(ckpt_path, map_location="cpu", weights_only=False)model_state = state.get("model", state)# โ RoPE buffers are rebuilt from config anyway โ never let them crash the loadmodel_state = {k: v for k, v in model_state.items()if not k.endswith((".pe.cos", ".pe.sin"))}model.load_state_dict(model_state, strict=False)model.load_state_dict(model_state, strict=False)step = state.get("step", 0)print(f"โ Loaded: {ckpt_name} (step {step:,})")1 unmodified linebreakexcept Exception as e:last_err = eprint(f" โ ๏ธ {ckpt_name} failed: {type(e).__name__}: {e}") # โ show REAL errorif not ckpt_found:raise RuntimeError(f"โ NO CHECKPOINT LOADED! Last error: {last_err}")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")1 unmodified linereturn 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):] == seq3 unmodified linesmodel.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 = 05 unmodified linesinp = 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|>")3 unmodified lineswith 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)cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)remove = cum_probs > 0.923 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]:2 unmodified linesprobs = 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:break2 unmodified linesresponse = 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 response2 unmodified lines# GRADIO UI# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(title="CodeSymb AI โ codesymb.com",theme=gr.themes.Base(primary_hue="blue", secondary_hue="indigo"),css="""body { background: #060D1F !important; }24 unmodified linesexamples=[["Hi! Who are you and what can you build?"],["Build me a Python FastAPI with JWT auth"],["Fix this error: AttributeError: 'NoneType' has no attribute 'split'"],["Explain async/await in simple Hindi"],["Write me a complete Android login screen in Kotlin"],["Build a 3D WebGPU game with Rust-WASM"],],retry_btn="๐ Retry",undo_btn="โฉ Undo",clear_btn="๐ Clear",)gr.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>""")if __name__ == "__main__":demo.launch()1234527 unmodified lines3334353637383954 unmodified lines94959697989918 unmodified lines1181191201211221231244 unmodified lines1291301311321331341351361371381391401411 unmodified line14314414514614714814915015115215315415515615715815911 unmodified lines1711721731741751761 unmodified line1781791801811821833 unmodified lines1871881891901911925 unmodified lines1981992002012022033 unmodified lines2072082092102112122132142152162173 unmodified lines2212222232242252262 unmodified lines2292302312322332342352362372 unmodified lines2402412422432442452462472482492502512522532 unmodified lines25625725825926026126224 unmodified lines287288289290291292293294295296# ================================================================# CodeSymb AI โ HuggingFace Space app.py (FIXED INDENTATION)# ================================================================import gradio as gr27 unmodified linesreturn (x.float() * n).to(x.dtype) * self.w.to(x.dtype)class RoPE(nn.Module):def __init__(self, dim, max_len=2048, base=500_000):super().__init__()inv = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))emb = torch.cat([torch.outer(torch.arange(max_len).float(), inv)] * 2, dim=-1)54 unmodified linesreturn xclass CodeSymb1B(nn.Module):def __init__(self, vocab=50000):super().__init__()DM=2048; DF=8192; NL=16; NH=16; NKV=418 unmodified linesprint(f"โ Tokenizer: {VOCAB:,} vocab")print("โณ Loading CodeSymb-1B model...")model = CodeSymb1B(vocab=VOCAB)ckpt_found = Falselast_err = None4 unmodified linesckpt_path = hf_hub_download(REPO_ID, ckpt_name, token=HF_TOKEN or None)print(f"โฌ๏ธ Downloaded {ckpt_name} โ loading weights...")try:state = torch.load(ckpt_path, map_location="cpu")except Exception:state = torch.load(ckpt_path, map_location="cpu", weights_only=False)model_state = state.get("model", state)model_state = {k: v for k, v in model_state.items() if not k.endswith((".pe.cos", ".pe.sin"))}model.load_state_dict(model_state, strict=False)step = state.get("step", 0)print(f"โ Loaded: {ckpt_name} (step {step:,})")1 unmodified linebreakexcept Exception as e:last_err = eprint(f" โ ๏ธ {ckpt_name} failed: {type(e).__name__}: {e}")if not ckpt_found:raise RuntimeError(f"โ NO CHECKPOINT LOADED! Last error: {last_err}")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# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโSYSTEM_PROMPT = ("You are CodeSymb, the world's most intelligent, deeply empathetic, "11 unmodified lines)def build_prompt(message: str, history: list) -> list: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")1 unmodified linereturn sp.encode("".join(parts))def tail_matches(generated: list, seq: list) -> bool:seq = list(seq)return len(generated) >= len(seq) and generated[-len(seq):] == seq3 unmodified linesmodel.to(device)prompt_ids = build_prompt(message, history)if len(prompt_ids) > 1024:user_seq = sp.encode("<|user|>")start = 05 unmodified linesinp = torch.tensor([prompt_ids], dtype=torch.long).to(device)END_SEQ = sp.encode("<|endoftext|>")USER_SEQ = sp.encode("<|user|>")SYS_SEQ = sp.encode("<|system|>")3 unmodified lineswith 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()logits = logits / 0.7sorted_logits, sorted_idx = torch.sort(logits, descending=True)cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)remove = cum_probs > 0.923 unmodified lineslogits_filtered = torch.zeros_like(logits)logits_filtered.scatter_(0, sorted_idx, sorted_logits)if generated:for gid in set(generated[-20:]):if 0 <= gid < logits_filtered.shape[0]:2 unmodified linesprobs = F.softmax(logits_filtered, dim=-1)next_t = torch.multinomial(probs, 1).item()if tail_matches(generated, END_SEQ) or tail_matches(generated, USER_SEQ) or tail_matches(generated, SYS_SEQ):breakif len(generated) > 2 and generated[-1] == generated[-2] == next_t:break2 unmodified linesresponse = sp.decode(generated).strip()for tag in ["<|user|>", "<|system|>", "<|assistant|>", "<|endoftext|>"]:response = response.split(tag)[0]response = response.strip()if not response:response = ("I'm CodeSymb! ๐ฅ\n""Built by Dev & Deepakkumar Malkar ๐ฎ๐ณ\n""Ask me anything about code!")return response2 unmodified lines# GRADIO UI# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Blocks(title="CodeSymb AI",theme=gr.themes.Base(primary_hue="blue", secondary_hue="indigo"),css="""body { background: #060D1F !important; }24 unmodified linesexamples=[["Hi! Who are you and what can you build?"],["Build me a Python FastAPI with JWT auth"],["Fix this error: AttributeError: 'NoneType'"],["Write me a complete Android login screen in Kotlin"],],)if __name__ == "__main__":demo.launch()
app.py+15-53