File size: 13,233 Bytes
a9be9e3
9f871fc
 
 
 
 
 
 
 
 
a9be9e3
9f871fc
a9be9e3
9f871fc
 
a9be9e3
 
 
 
 
2aab1f8
a9be9e3
9f871fc
 
 
 
 
 
 
a9be9e3
9f871fc
 
 
 
 
a9be9e3
9f871fc
 
 
 
 
 
 
f30e319
9f871fc
 
 
 
 
a9be9e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f871fc
 
 
a9be9e3
 
 
 
 
 
 
9f871fc
2aab1f8
a9be9e3
 
 
9f871fc
 
a9be9e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f871fc
 
57ead13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9be9e3
 
 
 
 
 
9f871fc
 
 
a9be9e3
 
9f871fc
a9be9e3
 
 
 
9f871fc
 
a9be9e3
 
 
 
 
 
9f871fc
 
57ead13
9f871fc
 
 
 
a9be9e3
 
9f871fc
 
 
 
 
a9be9e3
9f871fc
 
 
 
 
 
 
 
a9be9e3
 
9f871fc
 
 
 
 
 
 
 
 
 
 
57ead13
a9be9e3
 
9f871fc
 
290cc53
9f871fc
a9be9e3
 
 
 
290cc53
a9be9e3
9f871fc
a9be9e3
 
 
 
 
 
9f871fc
 
a9be9e3
 
 
 
 
9f871fc
 
 
 
a9be9e3
 
 
 
 
 
 
 
 
 
 
 
9f871fc
a9be9e3
 
 
 
 
 
 
9f871fc
 
 
 
 
 
 
 
a9be9e3
9f871fc
 
a9be9e3
9f871fc
a9be9e3
 
 
 
9f871fc
 
 
 
 
 
 
 
 
 
a9be9e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f871fc
 
 
 
 
 
 
a9be9e3
9f871fc
 
 
 
d85f9f5
9f871fc
a9be9e3
 
 
 
9f871fc
 
 
 
 
 
 
 
 
f30e319
9f871fc
 
 
 
 
 
700ea0b
9f871fc
 
 
358285a
a9be9e3
 
 
 
 
 
 
 
 
9f871fc
 
 
 
a9be9e3
 
 
 
 
 
9f871fc
 
a9be9e3
 
9f871fc
 
 
 
a9be9e3
 
9f871fc
 
 
 
 
a9be9e3
9f871fc
 
 
a9be9e3
9f871fc
 
a9be9e3
9f871fc
 
 
a9be9e3
 
9f871fc
 
 
 
 
 
700ea0b
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
406
407
408
409
410
411
412
"""Dynamic quantized LLM playground for Hugging Face ZeroGPU Spaces."""

from __future__ import annotations

import logging
import os
from typing import Any

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

# ZeroGPU must be imported before torch or a library that may initialize CUDA.
import spaces
import torch  # noqa: F401  # imported after spaces by design
import gradio as gr

from backend_router import (
    BACKEND_AUTO,
    BACKEND_CHOICES,
    BackendRouterError,
    ModelInspection,
)
from model_manager import ModelCache, ModelRuntime, validate_model_id


logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)

DEFAULT_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
cache = ModelCache()
runtime = ModelRuntime(cache)


def _short_error(prefix: str, exc: Exception) -> str:
    LOGGER.exception("%s", prefix)
    detail = str(exc).strip().splitlines()[0] if str(exc).strip() else exc.__class__.__name__
    return f"Error: {prefix} {detail[:320]}"


def _safe_generation_settings(
    max_new_tokens: Any,
    temperature: Any,
    top_p: Any,
) -> tuple[int, float, float]:
    tokens = max(1, min(8192, int(max_new_tokens or 256)))
    temp = max(0.0, min(2.0, float(temperature or 0.7)))
    nucleus = max(0.05, min(1.0, float(top_p or 0.95)))
    return tokens, temp, nucleus


def _dropdown_update(inspection: ModelInspection | None) -> Any:
    choices = inspection.gguf_files if inspection else []
    value = inspection.default_gguf if inspection else None
    return gr.update(choices=choices, value=value)


def _inspection_markdown(
    inspection: ModelInspection | None,
    backend: str | None = None,
    selected_file: str | None = None,
) -> str:
    if inspection is None:
        return "**Detected format:** not inspected yet  \n**Backend:** Auto"
    return inspection.markdown(backend, selected_file)


def inspect_model(model_id: str) -> tuple[str, Any, str, str]:
    """Inspect repository metadata and list GGUF choices without downloading weights."""

    try:
        model_id = validate_model_id(model_id)
        inspection = cache.inspect_remote(model_id)
        selected = inspection.default_gguf
        status = f"Inspected `{model_id}` on CPU."
        if inspection.gguf_files:
            status += " Select a GGUF file, then click Download."
        else:
            status += " No GGUF file was found; Auto will use Transformers."
        return (
            status,
            _dropdown_update(inspection),
            _inspection_markdown(inspection, selected_file=selected),
            cache.describe(model_id, selected),
        )
    except Exception as exc:
        return (
            _short_error("Could not inspect the repository:", exc),
            _dropdown_update(None),
            _inspection_markdown(None),
            cache.describe(model_id),
        )


def download_model(
    model_id: str,
    backend_choice: str,
    gguf_file: str | None,
) -> tuple[str, Any, str, str]:
    """Download a standard snapshot or exactly one selected GGUF on CPU."""

    try:
        model_id = validate_model_id(model_id)
        inspection = cache.inspect_remote(model_id)
        selected = (gguf_file or inspection.default_gguf or "").strip()
        backend = cache.router.resolve_backend(inspection, backend_choice, selected or None)

        if backend == "llama.cpp":
            path = cache.download_gguf(model_id, selected)
            status = f"Downloaded one GGUF file on CPU: `{selected}`"
            cache_status = cache.describe(model_id, selected)
            return (
                status,
                _dropdown_update(inspection),
                _inspection_markdown(inspection, backend, selected),
                cache_status,
            )

        path = cache.download(model_id)
        return (
            f"Downloaded Transformers files on CPU: `{model_id}`",
            _dropdown_update(inspection),
            _inspection_markdown(inspection, backend),
            f"Disk cache: snapshot ready (`{path.name}`).",
        )
    except Exception as exc:
        return (
            _short_error("Could not download the model:", exc),
            _dropdown_update(None),
            _inspection_markdown(None),
            cache.describe(model_id, gguf_file),
        )



def _chat_gpu_duration(
    message: str,
    history: list[Any] | None,
    model_id: str,
    backend_choice: str,
    gguf_file: str | None,
    system_prompt: str,
    max_new_tokens: Any,
    temperature: Any,
    top_p: Any,
) -> int:
    """Reserve only the GPU time a text request is likely to need.

    ZeroGPU checks the declared duration against the visitor's remaining quota
    before the call starts, so a large fixed reservation wastes Free-tier quota.
    Keep ordinary short chats cheap while allowing longer 2K-token generations.
    """
    try:
        tokens = max(1, min(2048, int(max_new_tokens or 256)))
    except (TypeError, ValueError):
        tokens = 256

    # 256 tokens -> 38s, 1024 -> 62s, 2048 -> 94s.
    # Clamp below 120s so Free-tier calls stay well inside the daily 300s budget.
    return max(30, min(120, 30 + (tokens + 31) // 32))


@spaces.GPU(duration=120)
def load_model_on_gpu(
    model_id: str,
    backend_choice: str,
    gguf_file: str | None,
) -> tuple[str, str, str, str]:
    """Load one selected model on ZeroGPU using the routed backend."""

    try:
        model_id = validate_model_id(model_id)
        target = runtime.ensure_loaded(model_id, backend_choice, gguf_file)
        selected = target.selected_file
        return (
            f"Loaded on ZeroGPU: `{model_id}` via `{target.backend}`",
            runtime.active_label(),
            _inspection_markdown(target.inspection, target.backend, selected),
            cache.describe(model_id, selected),
        )
    except Exception as exc:
        return (
            _short_error("Could not load the model:", exc),
            "No model loaded",
            _inspection_markdown(None),
            cache.describe(model_id, gguf_file),
        )


@spaces.GPU(duration=_chat_gpu_duration)
def chat_with_model(
    message: str,
    history: list[Any] | None,
    model_id: str,
    backend_choice: str,
    gguf_file: str | None,
    system_prompt: str,
    max_new_tokens: Any,
    temperature: Any,
    top_p: Any,
) -> str:
    """Generate a reply through the active Transformers or llama.cpp runtime."""

    try:
        model_id = validate_model_id(model_id)
        tokens, temp, nucleus = _safe_generation_settings(
            max_new_tokens, temperature, top_p
        )
        return runtime.generate(
            model_id=model_id,
            requested_backend=backend_choice,
            selected_file=gguf_file,
            message=message,
            history=history,
            system_prompt=system_prompt,
            max_new_tokens=tokens,
            temperature=temp,
            top_p=nucleus,
        )
    except Exception as exc:
        return _short_error("Could not generate a reply:", exc)


@spaces.GPU(duration=15)
def unload_model_on_gpu(model_id: str) -> tuple[str, str, str, str]:
    """Unload the active runtime and release RAM/VRAM."""

    try:
        active_file = runtime.active_selected_file
        runtime.unload()
        return (
            "Unloaded; RAM/VRAM cleanup requested.",
            "No model loaded",
            "**Detected format:** none active  \n**Backend:** none",
            cache.describe(model_id, active_file),
        )
    except Exception as exc:
        return (
            _short_error("Could not unload the model:", exc),
            "Unknown",
            _inspection_markdown(None),
            cache.describe(model_id),
        )


def delete_model_from_disk(
    model_id: str,
    gguf_file: str | None,
) -> tuple[str, str, str, str, Any]:
    """Remove all cached revisions/files for the selected model on CPU."""

    try:
        model_id = validate_model_id(model_id)
        deleted = cache.delete(model_id)
        status = (
            f"Deleted from disk: `{model_id}`"
            if deleted
            else f"No cached files found for `{model_id}`"
        )
        return (
            status,
            "No model loaded",
            "**Detected format:** none active  \n**Backend:** none",
            cache.describe(model_id),
            _dropdown_update(None),
        )
    except Exception as exc:
        return (
            _short_error("Could not delete the model cache:", exc),
            "Unknown",
            _inspection_markdown(None),
            cache.describe(model_id, gguf_file),
            _dropdown_update(None),
        )


CSS = """
#app-container { max-width: 1180px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""


with gr.Blocks(title="Quantized LLM ZeroGPU Playground", css=CSS) as demo:
    gr.Markdown(
        """
        # Quantized LLM ZeroGPU Playground

        Download and test one Hugging Face LLM at a time. **Auto** routes
        standard Transformers checkpoints to Transformers and GGUF files to
        the CUDA-enabled llama.cpp backend. GGUF repositories are inspected
        first so you can select only the Q4/Q5/Q8 (or newer) quant you want.
        """
    )

    with gr.Row():
        model_id = gr.Textbox(
            label="Hugging Face model ID",
            value=DEFAULT_MODEL_ID,
            placeholder="namespace/model-name",
            scale=4,
        )
        backend_choice = gr.Radio(
            label="Backend",
            choices=BACKEND_CHOICES,
            value=BACKEND_AUTO,
            scale=2,
        )

    with gr.Row():
        inspect_button = gr.Button("Inspect / list GGUF", variant="secondary")
        gguf_file = gr.Dropdown(
            label="GGUF quant file (choose one)",
            choices=[],
            value=None,
            allow_custom_value=False,
            interactive=True,
            scale=4,
        )

    with gr.Row():
        download_button = gr.Button("Download", variant="secondary", scale=1)
        load_button = gr.Button("Load", variant="primary", scale=1)
        unload_button = gr.Button("Unload", variant="secondary", scale=1)
        delete_button = gr.Button("Delete from disk", variant="stop", scale=1)

    with gr.Row():
        current_model = gr.Textbox(
            label="Active model / backend",
            value="No model loaded",
            interactive=False,
            scale=1,
        )
        cache_status = gr.Markdown("Disk cache: no model selected.")

    status = gr.Markdown("Status: inspect a repository, then Download and Load it.")
    format_backend = gr.Markdown(
        "**Detected format:** not inspected yet  \n**Backend:** Auto"
    )

    with gr.Accordion("Generation settings", open=True):
        system_prompt = gr.Textbox(
            label="System prompt",
            value="You are a helpful assistant.",
            lines=2,
        )
        with gr.Row():
            max_new_tokens = gr.Slider(
                label="Max new tokens", minimum=1, maximum=8192, value=256, step=1
            )
            temperature = gr.Slider(
                label="Temperature", minimum=0, maximum=2, value=0.7, step=0.05
            )
            top_p = gr.Slider(label="Top-p", minimum=0.05, maximum=1, value=0.95, step=0.05)

    chatbot = gr.Chatbot(type="messages", height=520, allow_tags=False)
    gr.ChatInterface(
        fn=chat_with_model,
        chatbot=chatbot,
        type="messages",
        additional_inputs=[
            model_id,
            backend_choice,
            gguf_file,
            system_prompt,
            max_new_tokens,
            temperature,
            top_p,
        ],
        textbox=gr.Textbox(placeholder="Write a message…", container=False),
        api_name="chat",
    )

    inspect_button.click(
        fn=inspect_model,
        inputs=[model_id],
        outputs=[status, gguf_file, format_backend, cache_status],
        api_name="inspect",
    )
    download_button.click(
        fn=download_model,
        inputs=[model_id, backend_choice, gguf_file],
        outputs=[status, gguf_file, format_backend, cache_status],
        api_name="download",
    )
    load_button.click(
        fn=load_model_on_gpu,
        inputs=[model_id, backend_choice, gguf_file],
        outputs=[status, current_model, format_backend, cache_status],
        api_name="load",
    )
    unload_button.click(
        fn=unload_model_on_gpu,
        inputs=[model_id],
        outputs=[status, current_model, format_backend, cache_status],
        api_name="unload",
    )
    delete_event = delete_button.click(
        # Release a possibly active GPU copy before deleting its CPU cache.
        fn=unload_model_on_gpu,
        inputs=[model_id],
        outputs=[status, current_model, format_backend, cache_status],
    )
    delete_event.then(
        fn=delete_model_from_disk,
        inputs=[model_id, gguf_file],
        outputs=[status, current_model, format_backend, cache_status, gguf_file],
        api_name="delete_from_disk",
    )


if __name__ == "__main__":
    demo.queue(default_concurrency_limit=1)
    demo.launch(mcp_server=True)