Download server.py from kotorii1/exact2026-deploy: direct link, hf CLI and curl.
- Browser
- Download file 8.38 kB
-
https://huggingface.co/datasets/kotorii1/exact2026-deploy/resolve/main/server.py
- Command line
-
hf download hf://datasets/kotorii1/exact2026-deploy/server.py
-
curl -L -o server.py https://huggingface.co/datasets/kotorii1/exact2026-deploy/resolve/main/server.py
8.38 kB
| import os | |
| import json | |
| import io | |
| import re | |
| import sys | |
| import subprocess | |
| import uuid | |
| import logging | |
| from contextlib import redirect_stdout | |
| from fastapi import FastAPI, Request | |
| from vllm import AsyncLLMEngine, AsyncEngineArgs, SamplingParams | |
| from vllm.lora.request import LoRARequest | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # --- Configurations --- | |
| MODEL_PATH = os.getenv("MODEL_PATH", "Qwen/Qwen2.5-Coder-7B-Instruct") | |
| LOGIC_LORA_PATH = os.getenv("LOGIC_LORA_PATH", "/app/models/logic_lora") | |
| PHYSICS_LORA_PATH = os.getenv("PHYSICS_LORA_PATH", "/app/models/physics_lora") | |
| app = FastAPI(title="EXACT 2026 AI Solver API", description="Multi-LoRA Inference Server for EXACT 2026") | |
| logger.info(f"Loading Base Model: {MODEL_PATH}") | |
| # Initialize vLLM Engine with LoRA enabled | |
| engine_args = AsyncEngineArgs( | |
| model=MODEL_PATH, | |
| enable_lora=True, | |
| max_loras=2, | |
| max_lora_rank=64, # Matches standard LoRA training config | |
| trust_remote_code=True, | |
| gpu_memory_utilization=0.9 | |
| ) | |
| engine = AsyncLLMEngine.from_engine_args(engine_args) | |
| # Register LoRA Adapters | |
| logger.info("Registering LoRA Adapters...") | |
| try: | |
| logic_lora = LoRARequest("logic", 1, LOGIC_LORA_PATH) | |
| except Exception as e: | |
| logger.warning(f"Could not load logic lora from {LOGIC_LORA_PATH}: {e}") | |
| logic_lora = None | |
| try: | |
| physics_lora = LoRARequest("physics", 2, PHYSICS_LORA_PATH) | |
| except Exception as e: | |
| logger.warning(f"Could not load physics lora from {PHYSICS_LORA_PATH}: {e}") | |
| physics_lora = None | |
| # --- SFT Prompts --- | |
| LOGIC_SYS = "You are an expert logical reasoning AI assistant. You solve logic puzzles and educational queries using Z3 Theorem Prover.\nAlways follow this strict format:\n1. Wrap your natural language reasoning inside <thought>...</thought> tags.\n2. In your thought, explicitly identify the required premises and apply logical rules.\n3. Write the Z3 Python code in a ```python ... ``` block.\n4. You MUST use the pre-defined helper functions `check_property(solver, property)` for Yes/No/Uncertain queries, and `check_mcq(solver, options_dict)` for multiple-choice queries. Do not define these functions yourself." | |
| PHYSICS_SYS = "You are an expert AI physics tutor and programmer. You will be provided with a physics problem.\nYour task is to carefully analyze the problem and solve it step-by-step.\nFirst, explain your reasoning process wrapped within <reasoning> and </reasoning> tags.\nAfter your reasoning, provide a python script using the `sympy` library to calculate the exact final numerical answer.\nYour python code must print the final result in the format: print(f\"Answer: {float(result):.6g}\")." | |
| # --- Code Evaluators --- | |
| def extract_python_code(text): | |
| if "```python" in text: | |
| return text.split("```python")[1].split("```")[0].strip() | |
| elif "```" in text: | |
| return text.split("```")[1].split("```")[0].strip() | |
| return "" | |
| def execute_logic_code(code_str): | |
| def fix_parentheses(code): | |
| open_chars = "([{" | |
| close_chars = ")]}" | |
| mapping = {')': '(', ']': '[', '}': '{'} | |
| chars = list(code) | |
| stack = [] | |
| in_string = False | |
| string_char = None | |
| escape = False | |
| for i, c in enumerate(chars): | |
| if escape: | |
| escape = False | |
| continue | |
| if c == '\\\\': | |
| escape = True | |
| continue | |
| if c in ["'", '"']: | |
| if not in_string: | |
| in_string = True | |
| string_char = c | |
| elif string_char == c: | |
| in_string = False | |
| continue | |
| if in_string: | |
| continue | |
| if c in open_chars: | |
| stack.append((c, i)) | |
| elif c in close_chars: | |
| expected_open = mapping[c] | |
| match_idx = -1 | |
| for idx in range(len(stack) - 1, -1, -1): | |
| if stack[idx][0] == expected_open: | |
| match_idx = idx | |
| break | |
| if match_idx != -1: | |
| stack = stack[:match_idx] | |
| else: | |
| chars[i] = "" | |
| suffix = [] | |
| reverse_mapping = {'(': ')', '[': ']', '{': '}'} | |
| for c, _ in reversed(stack): | |
| suffix.append(reverse_mapping[c]) | |
| return "".join(chars) + "".join(suffix) | |
| code_str = fix_parentheses(code_str) | |
| code_str = re.sub(r'([A-Za-z0-9_]+)\\s*>>\\s*([A-Za-z0-9_]+)', r'Implies(\\1, \\2)', code_str) | |
| env_code = """ | |
| import z3 | |
| from z3 import * | |
| def check_property(solver, prop): | |
| solver.push() | |
| solver.add(z3.Not(prop)) | |
| is_always_true = (solver.check() == z3.unsat) | |
| solver.pop() | |
| solver.push() | |
| solver.add(prop) | |
| is_always_false = (solver.check() == z3.unsat) | |
| solver.pop() | |
| if is_always_true: | |
| return 'Yes' | |
| elif is_always_false: | |
| return 'No' | |
| else: | |
| return 'Unknown' | |
| def check_mcq(solver, options_dict): | |
| yes_opts = [] | |
| for label, prop in options_dict.items(): | |
| solver.push() | |
| solver.add(z3.Not(prop)) | |
| is_always_true = (solver.check() == z3.unsat) | |
| solver.pop() | |
| if is_always_true: | |
| yes_opts.append(label) | |
| if len(yes_opts) == 1: | |
| return yes_opts[0] | |
| no_opts = [] | |
| for label, prop in options_dict.items(): | |
| solver.push() | |
| solver.add(prop) | |
| is_always_false = (solver.check() == z3.unsat) | |
| solver.pop() | |
| if is_always_false: | |
| no_opts.append(label) | |
| if len(yes_opts) == 0 and len(no_opts) == 1: | |
| return no_opts[0] | |
| if len(yes_opts) > 1: | |
| return yes_opts[0] | |
| return 'Unknown' | |
| """ + "\\n" + code_str | |
| try: | |
| res = subprocess.run([sys.executable, "-c", env_code], capture_output=True, text=True, timeout=10) | |
| output = res.stdout.strip() | |
| m = re.search(r'Answer:\\s*(.*)', output, re.IGNORECASE) | |
| ans = m.group(1).strip() if m else "Error/Unknown" | |
| return ans | |
| except Exception as e: | |
| return "Error" | |
| def execute_physics_code(code_str): | |
| local_scope = {} | |
| out = '' | |
| try: | |
| f_io = io.StringIO() | |
| with redirect_stdout(f_io): | |
| exec(code_str, globals(), local_scope) | |
| out = f_io.getvalue() | |
| except Exception as e: | |
| return "Error" | |
| match = re.search(r'Answer:\\s*(.+)', out) | |
| if match: | |
| return match.group(1).strip() | |
| return "Error" | |
| # --- API Endpoint --- | |
| async def solve(request: Request): | |
| data = await request.json() | |
| req_id = data.get("id", str(uuid.uuid4())) | |
| is_logic = "premises-NL" in data | |
| if is_logic: | |
| lora_req = logic_lora | |
| user_prompt = "[Premises (Natural Language)]\\n" | |
| for i, p in enumerate(data.get("premises-NL", [])): | |
| user_prompt += f"{i+1}. {p}\\n" | |
| user_prompt += "\\n[Question]\\n" + data.get("questions", [""])[0] | |
| full_prompt = f"<|im_start|>system\n{LOGIC_SYS}<|im_end|>\n<|im_start|>user\n{user_prompt}<|im_end|>\n<|im_start|>assistant\n" | |
| else: | |
| lora_req = physics_lora | |
| user_prompt = data.get("question", "") | |
| full_prompt = f"<|im_start|>system\n{PHYSICS_SYS}<|im_end|>\n<|im_start|>user\n{user_prompt}<|im_end|>\n<|im_start|>assistant\n" | |
| # Inference Params | |
| sampling_params = SamplingParams(temperature=0.1, max_tokens=1500) | |
| # Generate (Streaming internally, await final output) | |
| results_generator = engine.generate(full_prompt, sampling_params, req_id, lora_request=lora_req) | |
| final_output = None | |
| async for request_output in results_generator: | |
| final_output = request_output | |
| text_out = final_output.outputs[0].text | |
| code = extract_python_code(text_out) | |
| if is_logic: | |
| predicted_answer = execute_logic_code(code) if code else "Error" | |
| else: | |
| predicted_answer = execute_physics_code(code) if code else "Error" | |
| return { | |
| "id": req_id, | |
| "type": "logic" if is_logic else "physics", | |
| "predicted_answer": predicted_answer, | |
| "generated_code": code, | |
| "raw_model_output": text_out | |
| } | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |