File size: 7,659 Bytes
34825de
 
c27c4a3
 
 
 
 
34825de
c27c4a3
34825de
c27c4a3
 
 
 
 
 
 
 
 
34825de
c27c4a3
34825de
c27c4a3
 
 
 
 
34825de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c27c4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34825de
c27c4a3
34825de
 
c27c4a3
34825de
c27c4a3
 
 
 
 
 
 
 
34825de
 
 
 
c27c4a3
 
34825de
 
c27c4a3
 
 
 
 
 
34825de
 
c27c4a3
34825de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2e251b
 
 
 
 
 
 
 
 
 
34825de
 
 
c27c4a3
34825de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2e251b
34825de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2e251b
 
 
 
 
 
34825de
 
 
 
 
 
 
 
 
 
 
b2e251b
 
 
34825de
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import spaces  # Import before torch so ZeroGPU can initialize its CUDA emulation.

import json
import logging
import os
from pathlib import Path
from queue import Empty
from threading import Event, Thread

import gradio as gr
import torch
from huggingface_hub import hf_hub_download
from transformers import (
    AutoTokenizer,
    Qwen3_5ForConditionalGeneration,
    StoppingCriteria,
    TextIteratorStreamer,
)

APP_DIR = Path(__file__).resolve().parent
MODEL_ID = "mithulaartigala/Prompt-Resampler-2B-SFT-Alpha-8K-FP8"
MODEL_REVISION = "b5f0f8afe721d43329e84106fbb19c427cd7223a"
CONTEXT_LIMIT = 8192
MAX_PROMPT_LENGTH = 24_000
OPEN_THINK = "<think>"
CLOSE_THINK = "</think>"

os.environ.setdefault("TRANSFORMERS_DISABLE_DEEPGEMM_LINEAR", "1")
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=MODEL_REVISION)
system_prompt = Path(
    hf_hub_download(MODEL_ID, "default_system_prompt.md", revision=MODEL_REVISION)
).read_text(encoding="utf-8").strip()
model, loading = Qwen3_5ForConditionalGeneration.from_pretrained(
    MODEL_ID,
    revision=MODEL_REVISION,
    dtype=torch.bfloat16,
    attn_implementation="sdpa",
    use_safetensors=True,
    output_loading_info=True,
)
if loading["missing_keys"] or loading["mismatched_keys"]:
    raise RuntimeError(f"Incomplete checkpoint load: {loading}")
model.eval().to(device)
fp8_weights = sum(param.dtype == torch.float8_e4m3fn for param in model.parameters())
print(f"Loaded {fp8_weights} FP8 parameter tensors on {device}", flush=True)
eos_tokens = [
    tokenizer.convert_tokens_to_ids("<|endoftext|>"),
    tokenizer.convert_tokens_to_ids("<|im_end|>"),
]


class StopOnCancel(StoppingCriteria):
    def __init__(self, cancelled):
        self.cancelled = cancelled

    def __call__(self, input_ids, scores, **kwargs):
        return self.cancelled.is_set()


def split_output(text, reasoning_enabled):
    text = text.lstrip()
    if text.startswith(OPEN_THINK):
        text = text.removeprefix(OPEN_THINK).lstrip()
        reasoning_enabled = True
    if reasoning_enabled:
        reasoning, delimiter, answer = text.partition(CLOSE_THINK)
        return reasoning.strip(), answer.strip() if delimiter else ""
    return "", text.strip()


def updates(inputs, reasoning, limit):
    streamer = TextIteratorStreamer(
        tokenizer, skip_prompt=True, skip_special_tokens=True,
        clean_up_tokenization_spaces=False, timeout=1,
    )
    cancelled = Event()
    outcome = {}

    def run_model():
        try:
            with torch.inference_mode():
                tokens = model.generate(
                    **inputs,
                    streamer=streamer,
                    stopping_criteria=[StopOnCancel(cancelled)],
                    max_new_tokens=limit,
                    max_time=40,
                    eos_token_id=eos_tokens,
                    do_sample=False,
                )
            generated = tokens[0, inputs["input_ids"].shape[-1]:]
            outcome["limited"] = bool(len(generated) and generated[-1].item() not in eos_tokens)
        except Exception:
            logging.exception("Generation failed")
            outcome["error"] = "The model could not complete this request."
            streamer.end()

    worker = Thread(target=run_model, daemon=True)
    worker.start()
    raw_text = ""
    try:
        while True:
            try:
                chunk = next(streamer)
            except Empty:
                continue
            except StopIteration:
                break
            if chunk:
                raw_text += chunk
                thought, answer = split_output(raw_text, reasoning)
                yield {"kind": "update", "reasoning": thought if reasoning else "", "answer": answer}

        worker.join()
        thought, answer = split_output(raw_text, reasoning)
        if "error" in outcome:
            yield {"kind": "error", "message": outcome["error"]}
        elif not answer:
            message = (
                "The model reached the generation limit during reasoning."
                if thought and outcome["limited"]
                else "The model did not return a resampled prompt."
            )
            yield {"kind": "error", "message": message}
        else:
            yield {"kind": "done", "limited": outcome["limited"]}
    finally:
        cancelled.set()
        worker.join()


@spaces.GPU(duration=55)
def resample(payload: str):
    try:
        request = json.loads(payload) if isinstance(payload, str) else {}
    except json.JSONDecodeError:
        request = {}
    if not isinstance(request, dict):
        request = {}
    request_id = request.get("request_id", "")
    prompt = request.get("prompt", "")
    reasoning = request.get("reasoning", False)

    def encode(message):
        return json.dumps({"requestId": request_id, **message}, ensure_ascii=False)

    if not isinstance(prompt, str) or not prompt.strip() or type(reasoning) is not bool:
        yield encode({"kind": "error", "message": "Enter a prompt and choose a reasoning mode."})
        return
    if len(prompt) > MAX_PROMPT_LENGTH:
        yield encode({"kind": "error", "message": "Shorten the prompt to 24,000 characters or fewer."})
        return

    limit = 640 if reasoning else 384
    inputs = tokenizer.apply_chat_template(
        [{"role": "system", "content": system_prompt}, {"role": "user", "content": prompt.strip()}],
        tokenize=True,
        add_generation_prompt=True,
        enable_thinking=reasoning,
        return_dict=True,
        return_tensors="pt",
    )
    if inputs["input_ids"].shape[-1] + limit > CONTEXT_LIMIT:
        yield encode({"kind": "error", "message": "Shorten the prompt to leave room in the 8K context window."})
        return

    yield encode({"kind": "start"})
    for message in updates(inputs.to(model.device), reasoning, limit):
        yield encode(message)


with gr.Blocks(title="Prompt Resampler Mini", fill_width=True) as demo:
    workspace = gr.HTML(
        html_template=(APP_DIR / "templates/index.html").read_text(),
        css_template=(APP_DIR / "static/style.css").read_text(),
        js_on_load=(APP_DIR / "static/app.js").read_text(),
        elem_id="resampler-workspace",
        apply_default_css=False,
        container=False,
    )
    stream = gr.HTML(
        html_template="<span hidden></span>",
        js_on_load="""
        watch("value", () => {
          if (props.value) {
            window.dispatchEvent(new CustomEvent("resampler:update", { detail: JSON.parse(props.value) }));
          }
        });
        """,
        elem_id="resampler-stream",
        apply_default_css=False,
        container=False,
    )
    run = workspace.submit_prompt(
        resample,
        inputs=workspace,
        outputs=stream,
        js='() => [document.querySelector("#resampler-workspace form").dataset.request]',
        show_progress="hidden",
        api_visibility="undocumented",
    )
    run.failure(
        fn=None, js='() => window.dispatchEvent(new Event("resampler:failed"))',
        queue=False, api_visibility="private",
    )
    workspace.stop_prompt(fn=None, cancels=[run], queue=False, api_visibility="private")

if __name__ == "__main__":
    demo.queue(default_concurrency_limit=1, max_size=20).launch(
        css="""
        body, .gradio-container { background: #f3f4f3 !important; }
        .gradio-container, .gradio-container > .main, .gradio-container .html-container {
            padding: 0 !important;
        }
        .gradio-container footer, #resampler-stream { display: none !important; }
        """,
    )