Spaces:
Running on Zero
Running on Zero
Download models.py from Angshul/lean-proof-checker: direct link, hf CLI and curl.
- Browser
- Download file 5.44 kB
-
https://huggingface.co/spaces/Angshul/lean-proof-checker/resolve/main/models.py
- Command line
-
hf download hf://spaces/Angshul/lean-proof-checker/models.py
-
curl -L -o models.py https://huggingface.co/spaces/Angshul/lean-proof-checker/resolve/main/models.py
5.44 kB
| """The two open models, run on ZeroGPU. | |
| - Qwen3-VL-8B-Thinking: reads PDF pages, writes the Lean skeleton, back-translates statements. | |
| It is a reasoning model: it thinks first, then answers; only the answer is returned. | |
| - DeepSeek-Prover-V2-7B: proves individual proof steps (sampled in batches). | |
| Both are placed on `cuda` at import time, as ZeroGPU requires; a real GPU is attached only | |
| while a @spaces.GPU function runs, and that time counts against the caller's daily quota. | |
| """ | |
| import os | |
| import spaces | |
| import torch | |
| from transformers import (AutoModelForCausalLM, AutoProcessor, AutoTokenizer, | |
| Qwen3VLForConditionalGeneration) | |
| VL_ID = os.environ.get("VL_MODEL", "Qwen/Qwen3-VL-8B-Thinking") | |
| PROVER_ID = os.environ.get("PROVER_MODEL", "deepseek-ai/DeepSeek-Prover-V2-7B") | |
| vl_processor = AutoProcessor.from_pretrained(VL_ID) | |
| vl_model = Qwen3VLForConditionalGeneration.from_pretrained(VL_ID, dtype=torch.bfloat16).to("cuda").eval() | |
| pr_tokenizer = AutoTokenizer.from_pretrained(PROVER_ID) | |
| pr_model = AutoModelForCausalLM.from_pretrained(PROVER_ID, dtype=torch.bfloat16).to("cuda").eval() | |
| FORCE_ANSWER = ("\n\nConsidering the limited time, I have to give the final answer now " | |
| "based on the thinking so far.\n</think>\n\n") | |
| def _vl_generate(messages, think_tokens, answer_tokens, temperature): | |
| """Thinking budget: let the model think for up to `think_tokens`. If it has not closed its | |
| thinking by then, close it for the model and generate up to `answer_tokens` of answer. | |
| Returns the answer only (no thinking).""" | |
| inputs = vl_processor.apply_chat_template( | |
| messages, tokenize=True, add_generation_prompt=True, | |
| return_dict=True, return_tensors="pt").to(vl_model.device) | |
| # Qwen recommends sampling (not greedy) for thinking models | |
| kw = {"do_sample": True, "temperature": max(temperature, 0.1), "top_p": 0.95, "top_k": 20} | |
| prompt_len = inputs["input_ids"].shape[1] | |
| with torch.inference_mode(): | |
| out = vl_model.generate(**inputs, max_new_tokens=think_tokens + answer_tokens, **kw) | |
| new = out[0, prompt_len:] | |
| text = vl_processor.tokenizer.decode(new, skip_special_tokens=True) | |
| if "</think>" in text: | |
| answer = text.split("</think>")[-1].strip() | |
| if answer: | |
| return answer | |
| elif len(new) < think_tokens + answer_tokens: # stopped by itself: non-thinking model | |
| return text.replace("<think>", "").strip() | |
| # Still thinking (or closed with nothing after): keep at most `think_tokens` of thinking, | |
| # close it, and ask for the answer. | |
| think = new[:think_tokens] | |
| forced = vl_processor.tokenizer(FORCE_ANSWER, add_special_tokens=False, | |
| return_tensors="pt").input_ids.to(vl_model.device) | |
| ids = torch.cat([inputs["input_ids"], think.unsqueeze(0), forced], dim=1) | |
| seq_shape = tuple(inputs["input_ids"].shape) | |
| inputs2 = {k: v for k, v in inputs.items() | |
| if not (torch.is_tensor(v) and tuple(v.shape[:2]) == seq_shape)} | |
| inputs2["input_ids"] = ids | |
| inputs2["attention_mask"] = torch.ones_like(ids) | |
| with torch.inference_mode(): | |
| out2 = vl_model.generate(**inputs2, max_new_tokens=answer_tokens, **kw) | |
| answer = vl_processor.tokenizer.decode(out2[0, ids.shape[1]:], skip_special_tokens=True) | |
| return answer.split("</think>")[-1].strip() | |
| def _vl_duration(*args, think_tokens=3000, answer_tokens=3000, **kwargs): | |
| # ~40 tokens/s on the ZeroGPU slice; worst case is think + answer, then answer again | |
| return int(30 + (think_tokens + 2 * answer_tokens) * 0.025) | |
| def read_pages(images, system, instruction, think_tokens=3000, answer_tokens=5000): | |
| """images: list of PIL images (one per page).""" | |
| content = [{"type": "image", "image": im} for im in images] | |
| content.append({"type": "text", "text": instruction}) | |
| messages = [{"role": "system", "content": [{"type": "text", "text": system}]}, | |
| {"role": "user", "content": content}] | |
| return _vl_generate(messages, think_tokens, answer_tokens, 0.6) | |
| def chat(system, user, think_tokens=3000, answer_tokens=3000, temperature=0.6): | |
| messages = [{"role": "system", "content": [{"type": "text", "text": system}]}, | |
| {"role": "user", "content": [{"type": "text", "text": user}]}] | |
| return _vl_generate(messages, think_tokens, answer_tokens, temperature) | |
| def _prove_duration(prompt, n=8, max_new_tokens=1024, temperature=1.0): | |
| return int(40 + max_new_tokens * 0.05) | |
| def prove(prompt, n=8, max_new_tokens=1024, temperature=1.0): | |
| """n sampled completions of the prover for one prompt.""" | |
| inputs = pr_tokenizer.apply_chat_template( | |
| [{"role": "user", "content": prompt}], tokenize=True, add_generation_prompt=True, | |
| return_dict=True, return_tensors="pt").to(pr_model.device) | |
| pad = pr_tokenizer.pad_token_id if pr_tokenizer.pad_token_id is not None else pr_tokenizer.eos_token_id | |
| with torch.inference_mode(): | |
| out = pr_model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=True, | |
| temperature=temperature, top_p=0.95, | |
| num_return_sequences=n, pad_token_id=pad) | |
| start = inputs["input_ids"].shape[1] | |
| return [pr_tokenizer.decode(o[start:], skip_special_tokens=True) for o in out] | |