File size: 15,494 Bytes
34825de
 
890e83c
c27c4a3
 
 
 
 
890e83c
7fd52ed
890e83c
c9730d3
c27c4a3
34825de
c27c4a3
b225cf5
c27c4a3
 
 
 
 
 
c9730d3
c27c4a3
34825de
c27c4a3
34825de
aa05851
 
 
c27c4a3
 
7fd52ed
 
 
 
 
 
c27c4a3
34825de
 
b225cf5
 
 
 
 
34825de
b225cf5
 
34825de
 
 
 
 
 
 
 
 
b225cf5
 
 
 
 
34825de
 
 
 
 
 
 
c27c4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
890e83c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9730d3
890e83c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
959f8c5
890e83c
 
c9730d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
890e83c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03b69e4
 
890e83c
 
 
 
 
 
 
03b69e4
 
 
 
 
 
890e83c
c9730d3
 
03b69e4
890e83c
 
34825de
03b69e4
c27c4a3
34825de
c27c4a3
 
 
 
 
 
 
 
34825de
aa05851
03b69e4
 
34825de
aa05851
 
c27c4a3
34825de
 
c9730d3
c27c4a3
 
 
 
03b69e4
 
c27c4a3
 
34825de
 
890e83c
c27c4a3
34825de
 
 
 
 
 
 
 
c9730d3
890e83c
34825de
 
 
 
 
03b69e4
890e83c
 
 
 
 
03b69e4
890e83c
03b69e4
890e83c
 
 
 
 
c9730d3
890e83c
03b69e4
 
 
c9730d3
 
 
34825de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03b69e4
 
b2e251b
 
 
 
 
 
 
 
 
aa05851
34825de
 
03b69e4
34825de
 
 
 
 
 
 
 
03b69e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd52ed
 
03b69e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34825de
 
c9730d3
890e83c
03b69e4
 
 
 
7fd52ed
 
34825de
 
 
 
 
 
c2a7441
34825de
b2e251b
34825de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03b69e4
 
 
b2e251b
03b69e4
b2e251b
03b69e4
b2e251b
 
34825de
03b69e4
 
 
 
 
 
34825de
03b69e4
 
 
 
 
569eb28
34825de
 
 
c2a7441
aa05851
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
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"]


@spaces.GPU(duration=reserve_gpu)
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; }
        """,
    )