Spaces:
Runtime error
Runtime error
Tonic commited on
adds mcp server, ssrmode false , refactor the global variables
Browse files4 unmodified lines56789101112131415161721 unmodified lines39404142434445464748495051525354555657585960616263646522 unmodified lines88899091929320 unmodified lines1141151161171181191201211222 unmodified lines1251261271281291301315 unmodified lines1371381391401411421431441451461471481491501511 unmodified line1531541551561571581596 unmodified lines1661671681691701711721731741751761771781794 unmodified lines18418518618718818919022 unmodified lines2132142152164 unmodified linesimport torchimport jsonLEAN4_DEFAULT_HEADER = ("import Mathlib\n""import Aesop\n\n""set_option maxHeartbeats 0\n\n""open BigOperators Real Nat Topology Rat\n")title = "# ππ»ββοΈWelcome to πTonic's πππ¨π»βπ¬Moonshot Math"description = """21 unmodified linesπTeamTonicπ is always making cool demos! Join our active builder's π οΈcommunity π» [](https://discord.gg/qdfnvSPcqP) On π€Huggingface:[MultiTransformer](https://huggingface.co/MultiTransformer) On πGithub: [Tonic-AI](https://github.com/tonic-ai) & contribute toπ [MultiTonic](https://github.com/MultiTonic)π€Big thanks to Yuvi Sharma and all the folks at huggingface for the community grant π€"""# Build the initial system promptSYSTEM_PROMPT = "You are an expert in mathematics and Lean 4."# Helper to build a Lean4 code blockdef build_formal_block(formal_statement, informal_prefix=""):return (f"{LEAN4_DEFAULT_HEADER}\n"f"{informal_prefix}\n"f"{formal_statement}")# Helper to extract the first Lean4 code block from textdef extract_lean4_code(text):code_block = re.search(r"```lean4(.*?)(```|$)", text, re.DOTALL)if code_block:code = code_block.group(1)lines = [line for line in code.split('\n') if line.strip()]return '\n'.join(lines)return text.strip()# Example problemsunimath1 = """Goal:X : UUY : UU22 unmodified linesadditional_info_prompt = "/-Explain using mathematics-/\n"examples = [[unimath1, additional_info_prompt, 1234],[unimath2, additional_info_prompt, 1234],20 unmodified linestokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)# Set generation configmodel.generation_config = GenerationConfig.from_pretrained(model_name)# Ensure pad_token_id is an integer, not a listif isinstance(model.generation_config.eos_token_id, list):model.generation_config.pad_token_id = model.generation_config.eos_token_id[0]else:2 unmodified linesmodel.generation_config.temperature = 0.6model.generation_config.top_p = 0.95# Initialize chat history with system promptdef init_chat(formal_statement, informal_prefix):user_prompt = ("Think about and solve the following problem step by step in Lean 4.\n"5 unmodified lines{"role": "user", "content": user_prompt}]# Gradio chat handler@spaces.GPUdef chat_handler(user_message, informal_prefix, max_tokens, chat_history):# If chat_history is empty, initialize with system and first user messageif not chat_history or len(chat_history) < 2:chat_history = init_chat(user_message, informal_prefix)display_history = [("user", user_message)]else:# Append new user messagechat_history.append({"role": "user", "content": user_message})display_history = []for msg in chat_history:1 unmodified linedisplay_history.append(("user", msg["content"]))elif msg["role"] == "assistant":display_history.append(("assistant", msg["content"]))# Format prompt using chat templateprompt = tokenizer.apply_chat_template(chat_history, tokenize=False, add_generation_prompt=True)input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)attention_mask = torch.ones_like(input_ids)6 unmodified linestop_p=model.generation_config.top_p,)result = tokenizer.decode(outputs[0], skip_special_tokens=True)# Extract only the new assistant message (after the prompt)new_response = result[len(prompt):].strip()# Add assistant message to chat historychat_history.append({"role": "assistant", "content": new_response})display_history.append(("assistant", new_response))# Extract Lean4 codecode = extract_lean4_code(new_response)# Prepare outputoutput_data = {"model_input": prompt,"model_output": result,4 unmodified linesdef main():with gr.Blocks() as demo:# Title and Model Descriptiongr.Markdown("""# ππ»ββοΈWelcome to πTonic's πππ¨π»βπ¬Moonshot Math""")with gr.Row():with gr.Column():22 unmodified linesdemo.launch()if __name__ == "__main__":main()4 unmodified lines567891021 unmodified lines3233343536373839404142434445464722 unmodified lines70717273747576777879808182838485868788899020 unmodified lines1111121131141151161172 unmodified lines1201211221231241255 unmodified lines1311321331341351361371381391401411421 unmodified line1441451461471481496 unmodified lines1561571581591601611621631641654 unmodified lines17017117217317417522 unmodified lines1981992002014 unmodified linesimport torchimport jsontitle = "# ππ»ββοΈWelcome to πTonic's πππ¨π»βπ¬Moonshot Math"description = """21 unmodified linesπTeamTonicπ is always making cool demos! Join our active builder's π οΈcommunity π» [](https://discord.gg/qdfnvSPcqP) On π€Huggingface:[MultiTransformer](https://huggingface.co/MultiTransformer) On πGithub: [Tonic-AI](https://github.com/tonic-ai) & contribute toπ [MultiTonic](https://github.com/MultiTonic)π€Big thanks to Yuvi Sharma and all the folks at huggingface for the community grant π€"""SYSTEM_PROMPT = "You are an expert in mathematics and Lean 4."LEAN4_DEFAULT_HEADER = ("import Mathlib\n""import Aesop\n\n""set_option maxHeartbeats 0\n\n""open BigOperators Real Nat Topology Rat\n")unimath1 = """Goal:X : UUY : UU22 unmodified linesadditional_info_prompt = "/-Explain using mathematics-/\n"def build_formal_block(formal_statement, informal_prefix=""):return (f"{LEAN4_DEFAULT_HEADER}\n"f"{informal_prefix}\n"f"{formal_statement}")def extract_lean4_code(text):code_block = re.search(r"```lean4(.*?)(```|$)", text, re.DOTALL)if code_block:code = code_block.group(1)lines = [line for line in code.split('\n') if line.strip()]return '\n'.join(lines)return text.strip()examples = [[unimath1, additional_info_prompt, 1234],[unimath2, additional_info_prompt, 1234],20 unmodified linestokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)model.generation_config = GenerationConfig.from_pretrained(model_name)if isinstance(model.generation_config.eos_token_id, list):model.generation_config.pad_token_id = model.generation_config.eos_token_id[0]else:2 unmodified linesmodel.generation_config.temperature = 0.6model.generation_config.top_p = 0.95def init_chat(formal_statement, informal_prefix):user_prompt = ("Think about and solve the following problem step by step in Lean 4.\n"5 unmodified lines{"role": "user", "content": user_prompt}]@spaces.GPUdef chat_handler(user_message, informal_prefix, max_tokens, chat_history):if not chat_history or len(chat_history) < 2:chat_history = init_chat(user_message, informal_prefix)display_history = [("user", user_message)]else:chat_history.append({"role": "user", "content": user_message})display_history = []for msg in chat_history:1 unmodified linedisplay_history.append(("user", msg["content"]))elif msg["role"] == "assistant":display_history.append(("assistant", msg["content"]))prompt = tokenizer.apply_chat_template(chat_history, tokenize=False, add_generation_prompt=True)input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)attention_mask = torch.ones_like(input_ids)6 unmodified linestop_p=model.generation_config.top_p,)result = tokenizer.decode(outputs[0], skip_special_tokens=True)new_response = result[len(prompt):].strip()chat_history.append({"role": "assistant", "content": new_response})display_history.append(("assistant", new_response))code = extract_lean4_code(new_response)output_data = {"model_input": prompt,"model_output": result,4 unmodified linesdef main():with gr.Blocks() as demo:gr.Markdown("""# ππ»ββοΈWelcome to πTonic's πππ¨π»βπ¬Moonshot Math""")with gr.Row():with gr.Column():22 unmodified linesdemo.launch()if __name__ == "__main__":main(ssr_mode=False, mcp_server=True)
app.py+22-37