Spaces:
Runtime error

File size: 5,402 Bytes
44482d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Real inference only. No stock-encoder fallback and no simulated outputs."""
import base64
import io
import secrets
import time

from config import (
    BASE_REPO, BASE_REVISION, ENCODER_REPO, ENCODER_REVISION,
    ENCODER_SUBFOLDER, GPU_RATE_USD_SECOND, MODEL_ID,
)


def download_models():
    from huggingface_hub import snapshot_download

    # Download the gated encoder first, so access failures avoid the large base download.
    encoder = snapshot_download(
        ENCODER_REPO, revision=ENCODER_REVISION,
        allow_patterns=[f"{ENCODER_SUBFOLDER}/*"],
    )
    base = snapshot_download(
        BASE_REPO, revision=BASE_REVISION,
        allow_patterns=["model_index.json", "scheduler/*", "tokenizer/*", "transformer/*", "vae/*", "LICENSE.md"],
    )
    return base, encoder


class Engine:
    def __init__(self):
        import torch
        from diffusers import Flux2KleinPipeline
        from transformers import Qwen3ForCausalLM

        start = time.perf_counter()
        # ZeroGPU emulates CUDA at startup; actual inference runs only in @spaces.GPU.
        base, encoder = download_models()
        text_encoder, info = Qwen3ForCausalLM.from_pretrained(
            encoder, subfolder=ENCODER_SUBFOLDER, torch_dtype=torch.bfloat16,
            local_files_only=True, use_safetensors=True, output_loading_info=True,
        )
        if any(info.get(k) for k in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")):
            counts = ", ".join(f"{k}={len(info.get(k) or [])}" for k in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs"))
            raise RuntimeError(
                f"Encoder state dictionary did not load exactly ({counts}). "
                "Inspect checkpoint key prefixes against Qwen3ForCausalLM before attempting an explicit conversion. "
                "This is a compatibility failure, not evidence of corrupted weights; no fallback was loaded."
            )
        self.pipe = Flux2KleinPipeline.from_pretrained(
            base, text_encoder=text_encoder, torch_dtype=torch.bfloat16,
            local_files_only=True, use_safetensors=True,
        ).to("cuda")
        if self.pipe.text_encoder is not text_encoder or not self.pipe.config.is_distilled:
            raise RuntimeError("Unexpected pipeline composition")
        self.pipe.vae.enable_slicing()
        self.pipe.set_progress_bar_config(disable=True)
        self.load_seconds = time.perf_counter() - start

    def generate(self, payload, references):
        import torch
        from PIL import Image

        prompt = payload["prompt"]
        # The upstream pipeline truncates silently. Reject instead of changing the prompt.
        tokens = self.pipe.tokenizer.apply_chat_template(
            [{"role": "user", "content": prompt}], tokenize=True,
            add_generation_prompt=True, enable_thinking=False,
        )
        if len(tokens) > 512:
            return {"error": {"status": 400, "message": "Prompt exceeds the model's 512-token context including its native template."}}
        images = [Image.open(io.BytesIO(b)).convert("RGB") for b in references]
        seed = payload["seed"] if payload["seed"] is not None else secrets.randbelow(2**32)
        torch.cuda.reset_peak_memory_stats()
        torch.cuda.synchronize()
        start = time.perf_counter()
        data = []
        try:
            with torch.inference_mode():
                # Sequential outputs bound VRAM independently of n.
                for i in range(payload["n"]):
                    output = self.pipe(
                        prompt=prompt, image=images or None,
                        width=payload["width"], height=payload["height"],
                        num_inference_steps=payload["steps"], guidance_scale=1.0,
                        generator=torch.Generator("cuda").manual_seed(seed + i),
                        max_sequence_length=512,
                    ).images[0]
                    buf = io.BytesIO()
                    fmt = payload["output_format"]
                    output.save(buf, format={"png": "PNG", "jpeg": "JPEG", "webp": "WEBP"}[fmt])
                    data.append({"b64_json": base64.b64encode(buf.getvalue()).decode(), "seed": seed + i})
            torch.cuda.synchronize()
        except torch.cuda.OutOfMemoryError:
            torch.cuda.empty_cache()
            return {"error": {"status": 503, "message": "GPU memory exhausted. Reduce dimensions or reference count."}}
        elapsed = time.perf_counter() - start
        return {
            "created": int(time.time()), "model": MODEL_ID, "data": data,
            "metrics": {
                "inference_seconds": elapsed,
                "model_load_seconds": self.load_seconds,
                "peak_allocated_gib": torch.cuda.max_memory_allocated() / 2**30,
                "peak_reserved_gib": torch.cuda.max_memory_reserved() / 2**30,
                "gpu": torch.cuda.get_device_name(),
                "estimated_inference_gpu_usd": elapsed * GPU_RATE_USD_SECOND,
                "hosting": "Hugging Face ZeroGPU free quota; no paid fallback",
            },
            "provenance": {
                "base": BASE_REPO, "base_revision": BASE_REVISION,
                "text_encoder": ENCODER_REPO, "text_encoder_revision": ENCODER_REVISION,
                "text_encoder_subfolder": ENCODER_SUBFOLDER,
            },
        }