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 = "" CLOSE_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="", 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; } """, )