File size: 10,361 Bytes
2b7c58b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f2aea2
 
 
 
 
 
 
 
 
2b7c58b
7f2aea2
2b7c58b
 
 
 
 
 
 
 
 
 
 
 
 
7f2aea2
2b7c58b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MV Studio image engine: FLUX 3 Image Klein (distilled) on ZeroGPU.

Keyframes for music-video shots and album art. Takes a final caption (the studio upsamples it with the
brain engine first, using the FLUX upsampler's own system prompts) plus up to 10 reference images, so a
character's front/left/right/back photos lock identity. Model loading follows black-forest-labs/flux-3-image-klein.
"""

import glob
import os
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
_wheel = glob.glob(os.path.join(HERE, "diffusers-*.whl"))
if _wheel:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-deps", "--no-cache-dir", _wheel[0]])

import spaces  # noqa: E402  (must come before torch)
import json  # noqa: E402
import random  # noqa: E402
import tempfile  # noqa: E402
import time  # noqa: E402
from pathlib import Path  # noqa: E402

import gradio as gr  # noqa: E402
import numpy as np  # noqa: E402
import safetensors.torch  # noqa: E402
import torch  # noqa: E402
from huggingface_hub import hf_hub_download, snapshot_download  # noqa: E402
from PIL import Image  # noqa: E402
from spaces.config import Config as SPACES_CONFIG  # noqa: E402
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration  # noqa: E402

from diffusers import AutoencoderKLFlux2, Flux3Transformer2DModel  # noqa: E402
from diffusers.modular_pipelines import Flux3DistilledAutoBlocks  # noqa: E402
from vae_convert import convert_flux2_vae_checkpoint_to_diffusers  # noqa: E402

dtype = torch.bfloat16
token = os.environ.get("HF_TOKEN")
REPO = os.environ.get("FLUX_REPO", "black-forest-labs/flux-3-image-klein")

MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 4096
MAX_REF_PIXELS = 1024 * 1024
MAX_REFS = 10
RESOLUTIONS = {"1K": 1024, "2K": 2048, "4K": 4096}
ASPECTS = {"1:1": 1.0, "4:3": 4 / 3, "3:4": 3 / 4, "3:2": 3 / 2, "2:3": 2 / 3, "16:9": 16 / 9, "9:16": 9 / 16}

print("[boot] text encoder…", flush=True)
text_encoder = Qwen3VLForConditionalGeneration.from_pretrained(REPO, subfolder="text_encoder", dtype=dtype, token=token)
processor = AutoProcessor.from_pretrained(REPO, subfolder="text_encoder", token=token)

print("[boot] VAE…", flush=True)
vae = AutoencoderKLFlux2()
_ae = safetensors.torch.load_file(hf_hub_download(REPO, "ae.safetensors", token=token))
vae.load_state_dict(convert_flux2_vae_checkpoint_to_diffusers(_ae, vae.config), strict=True)
vae.to(torch.float32).eval()
# Decode in 2048 px tiles above 2048 px: a 4K decode in one piece runs out of memory on ZeroGPU.
vae.use_tiling = True
vae.tile_sample_min_size = 2048
vae.tile_latent_min_size = 2048 // (2 ** (len(vae.config.block_out_channels) - 1))
del _ae

print("[boot] distilled transformer…", flush=True)
transformer = Flux3Transformer2DModel.from_single_file(
    f"https://huggingface.co/{REPO}/blob/main/model.safetensors",
    config=os.path.join(HERE, "configs", "distilled"),
    subfolder="transformer",
    torch_dtype=dtype,
    token=token,
)
for name in Flux3Transformer2DModel._keep_in_fp32_modules:
    for module_name, module in transformer.named_modules():
        if module_name.split(".")[-1] == name:
            module.to(torch.float32)

pipe = Flux3DistilledAutoBlocks().init_pipeline()
pipe.update_components(text_encoder=text_encoder, tokenizer=processor, vae=vae, transformer=transformer)
pipe.to("cuda")


def _load_aoti():
    """Ahead-of-time compiled blocks from the official Space, when this torch matches; eager otherwise."""
    from spaces.zero.torch.aoti import aoti_load_from_package_dir

    repo = "diffusers-internal-dev/f3-small-image-distilled-aoti-sm120"
    config = json.loads(Path(hf_hub_download(repo, "config.json", token=token)).read_text())
    if config.get("torch") != torch.__version__:
        raise RuntimeError(f"built for torch {config.get('torch')}, runtime has {torch.__version__}")
    package_dir = Path(snapshot_download(repo, allow_patterns="package/*", token=token)) / "package"

    def blocks(name):
        stack = transformer.get_submodule(name)
        return list(stack) if isinstance(stack, torch.nn.ModuleList) else [stack]

    names = list(config["stacks"])
    for name in names:
        for block in blocks(name):
            block.attn.norm_q.to(torch.bfloat16)
            block.attn.norm_k.to(torch.bfloat16)
    eager = {name: [block.forward for block in blocks(name)] for name in names}
    aoti_load_from_package_dir(transformer, package_dir)
    for name in names:
        for block, eager_forward in zip(blocks(name), eager[name]):
            compiled = block.forward

            def forward(*args, _c=compiled, _e=eager_forward, **kwargs):
                try:
                    return _c(*args, **kwargs)
                except Exception as e:
                    print(f"[aoti] eager fallback: {e!r}", flush=True)
                    return _e(*args, **kwargs)

            block.forward = forward


try:
    _load_aoti()
    print("[boot] AOTI loaded", flush=True)
except Exception as e:
    print(f"[boot] AOTI unavailable, running eager: {e!r}", flush=True)
print("[boot] ready", flush=True)


def dims(aspect: str, resolution: str) -> tuple[int, int]:
    ratio = ASPECTS.get(aspect, 1.0)
    side = RESOLUTIONS.get(resolution, 2048)
    h = (side * side / ratio) ** 0.5
    w = h * ratio
    scale = min(1.0, MAX_IMAGE_SIZE / max(w, h))
    return (max(256, round(w * scale / 16) * 16), max(256, round(h * scale / 16) * 16))


def fit_reference(img: Image.Image) -> Image.Image:
    img = img.convert("RGB")
    pixels = img.width * img.height
    if pixels <= MAX_REF_PIXELS:
        return img
    scale = (MAX_REF_PIXELS / pixels) ** 0.5
    return img.resize((max(16, round(img.width * scale)), max(16, round(img.height * scale))), Image.LANCZOS)


def load_refs(files) -> list[Image.Image]:
    paths = [f if isinstance(f, str) else getattr(f, "name", None) or f.get("path") for f in (files or [])]
    return [fit_reference(Image.open(p)) for p in paths[:MAX_REFS] if p]


def _tokens(width, height, refs):
    tokens = width * height / 256 + 512
    for img in refs:
        tokens += min(img.width * img.height, MAX_REF_PIXELS) / 256
    return tokens


# GPU-second estimates from the official Space's timings (large = half RTX Pro 6000, xlarge = full, 2x quota).
def _duration_large(caption, refs, width, height, seed, steps):
    return int(min(max(15 + steps * 0.5 * (_tokens(width, height, refs) / 4608) ** 1.5, 20), 300))


def _duration_xlarge(caption, refs, width, height, seed, steps):
    return int(min(max(20 + 1.3 * steps * 8.4 * (_tokens(width, height, refs) / 66048) ** 1.5, 30), 300))


def _run(caption, refs, width, height, seed, steps):
    t0 = time.time()
    kwargs = dict(prompt=caption, height=height, width=width, num_inference_steps=steps,
                  generator=torch.Generator().manual_seed(seed), output="images")
    if refs:
        kwargs["image"] = refs
    image = pipe(**kwargs)[0]
    print(f"[timing] {width}x{height} refs={len(refs)} steps={steps} gen_s={time.time() - t0:.1f} "
          f"peak_gb={torch.cuda.max_memory_allocated() / 2**30:.1f}", flush=True)
    return image


@spaces.GPU(duration=_duration_large)
def _gpu_large(caption, refs, width, height, seed, steps):
    return _run(caption, refs, width, height, seed, steps)


@spaces.GPU(duration=_duration_xlarge, size="xlarge")
def _gpu_xlarge(caption, refs, width, height, seed, steps):
    return _run(caption, refs, width, height, seed, steps)



ENGINE_KEY = os.environ.get("ENGINE_KEY", "")


def _guard(request):
    """Only the owner's studio may run jobs: it sends the shared ENGINE_KEY in a header."""
    if ENGINE_KEY and (request is None or request.headers.get("x-mv-key") != ENGINE_KEY):
        raise gr.Error("This is a private engine.")

def generate(caption: str, references=None, aspect: str = "1:1", resolution: str = "2K",
             seed: int = -1, steps: int = 16, request: gr.Request = None):
    """Generate one image from a full scene caption and optional reference images (identity lock).

    Args:
        caption: the full, already-upsampled scene caption. Refer to references as "the first image", ...
        references: up to 10 image files (e.g. a character's front, left, right and back photos).
        aspect: one of 1:1, 4:3, 3:4, 3:2, 2:3, 16:9, 9:16.
        resolution: 1K, 2K or 4K (4K runs on a full GPU and costs 2x quota).
        seed: -1 for random.
        steps: denoising steps (distilled checkpoint is trained for 4-16).

    Returns:
        (image file path, seed used)
    """
    _guard(request)
    if not (caption or "").strip():
        raise gr.Error("Caption is empty.")
    refs = load_refs(references)
    width, height = dims(aspect, resolution)
    seed = random.randint(0, MAX_SEED) if int(seed) < 0 else int(seed)
    steps = max(1, min(int(steps), 16))
    gpu = _gpu_large
    if SPACES_CONFIG.zero_gpu and _duration_large(caption, refs, width, height, seed, steps) >= 300:
        gpu = _gpu_xlarge
    image = gpu(caption.strip(), refs, width, height, seed, steps)
    out = Path(tempfile.mkdtemp()) / f"img_{seed}.png"
    image.save(out)
    return str(out), seed


with gr.Blocks(title="MV Studio · image engine") as demo:
    gr.Markdown("### MV Studio image engine · FLUX 3 Image Klein\nBackend for the studio. Captions should be full scene descriptions.")
    with gr.Row():
        with gr.Column():
            caption = gr.Textbox(label="Caption", lines=5)
            references = gr.File(label="Reference images (≤10)", file_count="multiple", file_types=["image"])
            with gr.Row():
                aspect = gr.Dropdown(list(ASPECTS), value="1:1", label="Aspect")
                resolution = gr.Radio(list(RESOLUTIONS), value="2K", label="Resolution")
            with gr.Row():
                seed = gr.Number(value=-1, precision=0, label="Seed (-1 random)")
                steps = gr.Slider(4, 16, value=16, step=1, label="Steps")
            run = gr.Button("Generate", variant="primary")
        with gr.Column():
            out_image = gr.Image(label="Result", type="filepath")
            out_seed = gr.Number(label="Seed used", precision=0)
    run.click(generate, [caption, references, aspect, resolution, seed, steps], [out_image, out_seed], api_name="generate")

demo.queue(max_size=16).launch(show_error=True)