File size: 5,376 Bytes
8f28364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Minimal Gradio wrapper for Qwen-Image-Edit — LOW-MEMORY VERSION
Optimized for 16GB RAM and modest GPUs (or CPU-only).
"""

import os
from typing import Optional

# --- Force CPU-only if needed (uncomment to disable GPU entirely) ---
os.environ["CUDA_VISIBLE_DEVICES"] = ""

import gradio as gr
import torch
from PIL import Image
from huggingface_hub import snapshot_download

# --- your project imports (as in the original script) ---
from hacked_models.scheduler import FlowMatchEulerDiscreteScheduler
from hacked_models.pipeline import QwenImageEditPipeline
from hacked_models.models import QwenImageTransformer2DModel
from hacked_models.utils import seed_everything

# -----------------------------
# Global state (LOW-MEM CONFIG)
# -----------------------------
_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
_DTYPE = torch.float32  # Use float32 for maximum compatibility
_PIPELINE: Optional[QwenImageEditPipeline] = None
_LOADED_MODEL_PATH: Optional[str] = None


def _load_pipeline(model_path: str) -> QwenImageEditPipeline:
    """Load model safely with low memory usage."""
    global _PIPELINE, _LOADED_MODEL_PATH
    if _PIPELINE is not None and _LOADED_MODEL_PATH == model_path:
        return _PIPELINE

    seed_everything(42)

    # Load scheduler
    scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
        os.path.join(model_path, "scheduler"), torch_dtype=_DTYPE
    )

    # Load transformer with CPU-first strategy
    transformer = QwenImageTransformer2DModel.from_pretrained(
        os.path.join(model_path, "transformer"),
        torch_dtype=_DTYPE,
        low_cpu_mem_usage=True,
        device_map="cpu",  # Critical: load to CPU first
    )

    # Load full pipeline
    pipe = QwenImageEditPipeline.from_pretrained(
        model_path,
        torch_dtype=_DTYPE,
        scheduler=scheduler,
        transformer=transformer,
        low_cpu_mem_usage=True,
        device_map="cpu",
    )

    pipe.set_progress_bar_config(disable=None)
    # Do NOT move to GPU here — do it dynamically in predict()
    _PIPELINE = pipe
    _LOADED_MODEL_PATH = model_path
    return pipe


def _build_grag_scale(cond_b: float, cond_delta: float, repeats: int = 10):
    """Reduced GRAG schedule for 512x512 resolution."""
    return [((256, 1.0, 1.0), (1024, cond_b, cond_delta))] * repeats


def predict(
    image: Image.Image,
    edit_prompt: str,
    cond_b: float,
    cond_delta: float,
    pipeline,
):
    if image is None or not edit_prompt:
        return None

    # Move to GPU only if available and needed
    if _DEVICE == "cuda":
        pipeline.to("cuda")

    try:
        # Downscale to 512x512 to save memory
        input_image = image.convert("RGB").resize((512, 512))

        inputs = {
            "image": input_image,
            "prompt": edit_prompt,
            "generator": torch.manual_seed(42),
            "true_cfg_scale": 4.0,
            "negative_prompt": " ",
            "num_inference_steps": 12,  # Reduced from 24
            "return_dict": False,
            "grag_scale": _build_grag_scale(cond_b, cond_delta, repeats=10),  # Reduced from 60
        }

        with torch.inference_mode():
            image_batch, x0_images, saved_outputs = pipeline(**inputs)

        result = image_batch[0]
    finally:
        # Always move back to CPU to free GPU memory
        if _DEVICE == "cuda":
            pipeline.to("cpu")
            torch.cuda.empty_cache()

    return result


# -----------------------------
# Model loading
# -----------------------------
model_dir = "Qwen-Image-Edit"
repo_id = "Qwen/Qwen-Image-Edit"

if not os.path.exists(model_dir) or not os.listdir(model_dir):
    # Use HF mirror for China users
    os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com")
    snapshot_download(repo_id=repo_id, local_dir=model_dir, local_dir_use_symlinks=False)
    print(f"Model downloaded to {model_dir}")
else:
    print(f"Model already exists at {model_dir}")

pipe = _load_pipeline(model_dir)


# -----------------------------
# Gradio UI
# -----------------------------
with gr.Blocks(title="Qwen Image Edit — Low-Mem Mode") as demo:
    gr.Markdown("# Qwen Image Edit — Low-Memory Mode\nUpload an image, enter your edit instruction, and set GRAG params.")

    with gr.Row():
        in_image = gr.Image(label="Input Image", type="pil")
        out_image = gr.Image(label="Edited Output", type="pil")

    edit_prompt = gr.Textbox(label="Edit Instruction", placeholder="e.g., Put sunglasses on her.")

    with gr.Row():
        cond_b = gr.Slider(label="cond_b", minimum=0.8, maximum=2.0, value=1.0, step=0.01)
        cond_delta = gr.Slider(label="cond_delta", minimum=0.8, maximum=2.0, value=1.0, step=0.01)

    run_btn = gr.Button("Run Edit")

    run_btn.click(
        fn=predict,
        inputs=[in_image, edit_prompt, cond_b, cond_delta, pipe],
        outputs=[out_image],
        api_name="run_edit",
    )

    gr.Markdown(
        """
**Low-Mem Optimizations Applied**
- Resolution: **512×512** (instead of 1024×1024)
- Inference steps: **12** (instead of 24)
- GRAG repeats: **10** (instead of 60)
- Precision: **float32** (max compatibility)
- Model loaded to **CPU first**, moved to GPU only during inference
- GPU memory freed immediately after generation
        """
    )

if __name__ == "__main__":
    demo.queue().launch(share=True)