Spaces:
Running on Zero
Running on Zero
Download app.py from mithulaartigala/Prompt-Resampler-Mini: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/spaces/mithulaartigala/Prompt-Resampler-Mini/resolve/main/app.py
- Command line
-
hf download hf://spaces/mithulaartigala/Prompt-Resampler-Mini/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mithulaartigala/Prompt-Resampler-Mini/resolve/main/app.py
15.5 kB
| import spaces # Import before torch so ZeroGPU can initialize its CUDA emulation. | |
| import importlib | |
| import json | |
| import logging | |
| import os | |
| from pathlib import Path | |
| from queue import Empty | |
| import sys | |
| from tempfile import TemporaryDirectory | |
| from threading import Event, Lock, Thread | |
| from time import perf_counter | |
| import gradio as gr | |
| import torch | |
| from huggingface_hub import snapshot_download | |
| from transformers import ( | |
| AutoTokenizer, | |
| Qwen3_5ForConditionalGeneration, | |
| StoppingCriteria, | |
| TextIteratorStreamer, | |
| ) | |
| from transformers.models.qwen3_5 import modeling_qwen3_5 | |
| APP_DIR = Path(__file__).resolve().parent | |
| MODEL_ID = "mithulaartigala/Prompt-Resampler-2B-SFT-Alpha-8K-FP8" | |
| MODEL_REVISION = "b5f0f8afe721d43329e84106fbb19c427cd7223a" | |
| CONTEXT_LIMIT = 24 * 1024 | |
| MAX_INPUT_TOKENS = 8 * 1024 | |
| MAX_OUTPUT_TOKENS = CONTEXT_LIMIT - MAX_INPUT_TOKENS | |
| OPEN_THINK = "<think>" | |
| CLOSE_THINK = "</think>" | |
| COLD_GPU_DURATION_SECONDS = 90 | |
| # ZeroGPU workers share the Space's filesystem. Keep this marker scoped to the | |
| # current app process so each deployment budgets for first-use kernel setup. | |
| runtime_dir = TemporaryDirectory(prefix="resampler-") | |
| gpu_ready = Path(runtime_dir.name) / "gpu-ready" | |
| os.environ.setdefault("TRANSFORMERS_DISABLE_DEEPGEMM_LINEAR", "1") | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| checkpoint_started = perf_counter() | |
| # The Space builder seeds the default Hub cache via preload_from_hub. | |
| weights_dir = Path(snapshot_download(MODEL_ID, revision=MODEL_REVISION, local_files_only=True)) | |
| tokenizer = AutoTokenizer.from_pretrained(weights_dir, local_files_only=True) | |
| system_prompt = (weights_dir / "default_system_prompt.md").read_text(encoding="utf-8").strip() | |
| model, loading = Qwen3_5ForConditionalGeneration.from_pretrained( | |
| weights_dir, | |
| local_files_only=True, | |
| 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 from the preloaded checkpoint on {device} " | |
| f"in {perf_counter() - checkpoint_started:.2f}s", | |
| 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() | |
| _fast_gpu_kernels_enabled = False | |
| _fast_gpu_kernels_lock = Lock() | |
| def enable_fast_kernels(): | |
| with _fast_gpu_kernels_lock: | |
| return _enable_fast_kernels() | |
| def _enable_fast_kernels(): | |
| global _fast_gpu_kernels_enabled | |
| if _fast_gpu_kernels_enabled: | |
| return True | |
| # Transformers and FLA are imported while ZeroGPU is staging the CPU-side | |
| # app. FLA probes Triton's active device at import time, so reload it only | |
| # after this request has acquired its GPU. | |
| for module_name in tuple(sys.modules): | |
| if module_name == "fla" or module_name.startswith("fla."): | |
| del sys.modules[module_name] | |
| try: | |
| hardware = importlib.import_module("fla.utils.hardware") | |
| backend = hardware.get_available_device() | |
| if backend != "cuda": | |
| logging.warning( | |
| "FLA Triton backend is %s inside ZeroGPU inference; retaining Transformers fallback kernels.", | |
| backend, | |
| ) | |
| return False | |
| convolution = importlib.import_module("fla.modules.causal_conv1d") | |
| gated_delta = importlib.import_module("fla.ops.gated_delta_rule") | |
| causal_conv1d = convolution.causal_conv1d | |
| causal_conv1d_update = convolution.causal_conv1d_update | |
| chunk_gated_delta_rule = gated_delta.chunk_gated_delta_rule | |
| fused_recurrent_gated_delta_rule = gated_delta.fused_recurrent_gated_delta_rule | |
| except Exception: | |
| logging.exception("Could not initialize FLA GPU kernels; retaining Transformers fallback kernels.") | |
| return False | |
| def prefill(hidden_states, weight, bias=None, activation=None, **kwargs): | |
| output, _ = causal_conv1d( | |
| hidden_states.transpose(1, 2), weight=weight, bias=bias, activation=activation, | |
| cu_seqlens=kwargs.get("cu_seq_lens_q"), | |
| ) | |
| return output.transpose(1, 2) | |
| def decode(hidden_states, conv_state, weight, bias=None, activation=None): | |
| output, _ = causal_conv1d_update( | |
| hidden_states.transpose(1, 2), conv_state, weight=weight, bias=bias, activation=activation, | |
| ) | |
| return output.transpose(1, 2) | |
| modeling_qwen3_5.causal_conv1d_fn = prefill | |
| modeling_qwen3_5.causal_conv1d_update = decode | |
| modeling_qwen3_5.torch_chunk_gated_delta_rule = chunk_gated_delta_rule | |
| modeling_qwen3_5.torch_recurrent_gated_delta_rule = fused_recurrent_gated_delta_rule | |
| gpu_name = torch.cuda.get_device_name(0) | |
| capability = torch.cuda.get_device_capability(0) | |
| print( | |
| "ZeroGPU fast kernels enabled " | |
| f"(gpu={gpu_name}, sm={capability[0]}.{capability[1]}, triton={backend}/{hardware.get_device_arch()}, " | |
| f"prefill={chunk_gated_delta_rule.__module__}, decode={fused_recurrent_gated_delta_rule.__module__})", | |
| flush=True, | |
| ) | |
| _fast_gpu_kernels_enabled = True | |
| return True | |
| class TimingTextIteratorStreamer(TextIteratorStreamer): | |
| def __init__(self, *args, timing, started, **kwargs): | |
| self.timing = timing | |
| self.started = started | |
| self.first_generated_token_at = None | |
| super().__init__(*args, **kwargs) | |
| def put(self, value): | |
| if self.first_generated_token_at is None and not self.next_tokens_are_prompt: | |
| self.first_generated_token_at = perf_counter() | |
| print( | |
| f"ZeroGPU first token request={self.timing['request_id']!r} " | |
| f"generation_ttft={self.first_generated_token_at - self.started:.2f}s " | |
| f"server_ttft={self.first_generated_token_at - self.timing['received_at']:.2f}s", | |
| flush=True, | |
| ) | |
| super().put(value) | |
| def updates(inputs, reasoning, remake, timing, deadline): | |
| started = perf_counter() | |
| streamer = TimingTextIteratorStreamer( | |
| tokenizer, skip_prompt=True, skip_special_tokens=True, | |
| clean_up_tokenization_spaces=False, timeout=1, timing=timing, started=started, | |
| ) | |
| cancelled = Event() | |
| outcome = {} | |
| def run_model(): | |
| try: | |
| with torch.inference_mode(): | |
| tokens = model.generate( | |
| **inputs, | |
| streamer=streamer, | |
| stopping_criteria=[StopOnCancel(cancelled)], | |
| max_new_tokens=MAX_OUTPUT_TOKENS, | |
| max_time=max(0, deadline - perf_counter()), | |
| disable_compile=True, | |
| eos_token_id=eos_tokens, | |
| do_sample=remake, | |
| **({"temperature": 0.75, "top_p": 0.9} if remake else {}), | |
| ) | |
| generated = tokens[0, inputs["input_ids"].shape[-1]:] | |
| outcome["limited"] = bool(len(generated) and generated[-1].item() not in eos_tokens) | |
| outcome["output_tokens"] = len(generated) | |
| except Exception: | |
| logging.exception("Generation failed") | |
| outcome["error"] = "The model could not complete this request." | |
| streamer.end() | |
| finally: | |
| outcome["finished_at"] = perf_counter() | |
| worker = Thread(target=run_model, daemon=True) | |
| worker.start() | |
| raw_text = "" | |
| first_text_at = None | |
| try: | |
| while True: | |
| try: | |
| chunk = next(streamer) | |
| except Empty: | |
| continue | |
| except StopIteration: | |
| break | |
| if chunk: | |
| if not raw_text: | |
| first_text_at = perf_counter() | |
| raw_text += chunk | |
| thought, answer = split_output(raw_text, reasoning) | |
| yield {"kind": "update", "reasoning": thought if reasoning else "", "answer": answer} | |
| worker.join() | |
| finished = outcome["finished_at"] | |
| output_tokens = outcome.get("output_tokens", 0) | |
| first_token_at = streamer.first_generated_token_at | |
| first_token_after = first_token_at - started if first_token_at is not None else None | |
| first_text_after = first_text_at - started if first_text_at is not None else None | |
| decode_seconds = finished - first_token_at if first_token_at is not None else 0 | |
| decode_tps = (output_tokens - 1) / decode_seconds if output_tokens > 1 and decode_seconds > 0 else 0 | |
| first_text_timing = f"{first_text_after:.2f}s" if first_text_after is not None else "unavailable" | |
| generation_timing = ( | |
| f"first_token={first_token_after:.2f}s, first_text={first_text_timing}, " | |
| f"decode={decode_tps:.1f} tok/s" | |
| if first_token_after is not None | |
| else "first_token=unavailable" | |
| ) | |
| print( | |
| f"Generation finished in {finished - started:.2f}s " | |
| f"(request={timing['request_id']!r}, {generation_timing}, " | |
| f"server_total={finished - timing['received_at']:.2f}s, " | |
| f"input_tokens={inputs['input_ids'].shape[-1]}, output_tokens={output_tokens}, " | |
| f"thinking={reasoning})", | |
| flush=True, | |
| ) | |
| 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() | |
| def prepare_request(payload: str): | |
| received_at = perf_counter() | |
| 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) | |
| remake = request.get("remake") is True | |
| if not isinstance(prompt, str) or not prompt.strip() or type(reasoning) is not bool: | |
| raise gr.Error("Enter a prompt and choose a reasoning mode.") | |
| 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", | |
| ) | |
| input_tokens = inputs["input_ids"].shape[-1] | |
| if input_tokens > MAX_INPUT_TOKENS: | |
| raise gr.Error("Shorten the prompt. The 8,192-token input limit includes the system prompt and chat formatting.") | |
| # Long prompts can yield long answers, and Thinking adds generated tokens. | |
| if input_tokens <= 1024: | |
| duration = 30 if reasoning else 20 | |
| elif input_tokens <= 4096: | |
| duration = 60 if reasoning else 40 | |
| else: | |
| duration = 90 if reasoning else 60 | |
| return { | |
| "inputs": inputs, "reasoning": reasoning, "remake": remake, | |
| "request_id": request_id, "duration": duration, "received_at": received_at, | |
| "prepared_at": perf_counter(), | |
| } | |
| def reserve_gpu(prepared): | |
| prepared["scheduling_at"] = perf_counter() | |
| if not gpu_ready.exists(): | |
| prepared["duration"] = COLD_GPU_DURATION_SECONDS | |
| return prepared["duration"] | |
| def resample(prepared): | |
| gpu_started = perf_counter() | |
| request_id = prepared["request_id"] | |
| scheduling_at = prepared.get("scheduling_at", prepared["prepared_at"]) | |
| def encode(message): | |
| return json.dumps({"requestId": request_id, **message}, ensure_ascii=False) | |
| print( | |
| f"ZeroGPU entered request={request_id!r} reservation={prepared['duration']}s " | |
| f"prepare={prepared['prepared_at'] - prepared['received_at']:.2f}s " | |
| f"gradio_wait={scheduling_at - prepared['prepared_at']:.2f}s " | |
| f"gpu_wait_and_worker={gpu_started - scheduling_at:.2f}s", | |
| flush=True, | |
| ) | |
| yield encode({"kind": "start"}) | |
| if model.device.type == "cuda": | |
| enable_fast_kernels() | |
| deadline = gpu_started + prepared["duration"] - 2 | |
| for message in updates( | |
| prepared["inputs"].to(model.device), prepared["reasoning"], prepared["remake"], prepared, deadline, | |
| ): | |
| if message["kind"] == "done" and not gpu_ready.exists(): | |
| gpu_ready.touch() | |
| 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, | |
| ) | |
| prepared = gr.State() | |
| prepare = workspace.submit_prompt( | |
| prepare_request, | |
| inputs=workspace, | |
| outputs=prepared, | |
| js='() => [document.querySelector("#resampler-workspace form").dataset.request]', | |
| queue=False, | |
| show_progress="hidden", | |
| api_visibility="undocumented", | |
| ) | |
| run = prepare.success( | |
| resample, | |
| inputs=prepared, | |
| outputs=stream, | |
| show_progress="hidden", | |
| api_visibility="undocumented", | |
| ) | |
| for event in (prepare, run): | |
| event.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: #f5f5f5 !important; } | |
| .gradio-container, .gradio-container > .main, .gradio-container .html-container { | |
| padding: 0 !important; | |
| } | |
| .gradio-container footer, #resampler-stream { display: none !important; } | |
| """, | |
| ) | |