File size: 5,444 Bytes
13e1f35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""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)


@spaces.GPU(duration=_vl_duration)
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)


@spaces.GPU(duration=_vl_duration)
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)


@spaces.GPU(duration=_prove_duration)
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]