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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import spaces
|
| 3 |
+
import time
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import torch
|
| 6 |
+
import functools
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from diffusers import FluxPipeline, AutoencoderTiny, FluxKontextPipeline
|
| 10 |
+
from transformers import CLIPProcessor, CLIPModel, AutoModel
|
| 11 |
+
from transformers.models.clip.modeling_clip import _get_vector_norm
|
| 12 |
+
from nunchaku import NunchakuFluxTransformer2dModel
|
| 13 |
+
from nunchaku.utils import get_precision
|
| 14 |
+
from my_utils.group_inference import run_group_inference
|
| 15 |
+
from my_utils.default_values import apply_defaults
|
| 16 |
+
from diffusers.hooks import apply_group_offloading
|
| 17 |
+
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, FluxTransformer2DModel, FluxPipeline
|
| 18 |
+
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
|
| 22 |
+
pipe = FluxKontextPipeline.from_pretrained("black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")
|
| 23 |
+
pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=torch.bfloat16).to("cuda")
|
| 24 |
+
pipe.enable_model_cpu_offload()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=torch.bfloat16).to("cuda")
|
| 28 |
+
|
| 29 |
+
m_clip = CLIPModel.from_pretrained("multimodalart/clip-vit-base-patch32").to("cuda")
|
| 30 |
+
prep_clip = CLIPProcessor.from_pretrained("multimodalart/clip-vit-base-patch32")
|
| 31 |
+
dino_model = AutoModel.from_pretrained('facebook/dinov2-base').to("cuda")
|
| 32 |
+
|
| 33 |
+
# Get default args for flux-schnell
|
| 34 |
+
default_args = argparse.Namespace(
|
| 35 |
+
model_name="flux-kontext",
|
| 36 |
+
prompt=None,
|
| 37 |
+
starting_candidates=None,
|
| 38 |
+
output_group_size=None,
|
| 39 |
+
pruning_ratio=None,
|
| 40 |
+
lambda_score=None,
|
| 41 |
+
seed=None,
|
| 42 |
+
unary_term="clip_text_img",
|
| 43 |
+
binary_term="diversity_dino",
|
| 44 |
+
guidance_scale=None,
|
| 45 |
+
num_inference_steps=None,
|
| 46 |
+
height=512,
|
| 47 |
+
width=512,
|
| 48 |
+
)
|
| 49 |
+
default_args = apply_defaults(default_args)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Scoring functions
|
| 53 |
+
@torch.no_grad()
|
| 54 |
+
def unary_clip_text_img_score(l_images, target_caption, device="cuda"):
|
| 55 |
+
"""Compute CLIP text-image similarity scores."""
|
| 56 |
+
_img_std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).view(1, 3, 1, 1).to(device)
|
| 57 |
+
_img_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).view(1, 3, 1, 1).to(device)
|
| 58 |
+
|
| 59 |
+
b_images = torch.cat(l_images, dim=0)
|
| 60 |
+
b_images = F.interpolate(b_images, size=(224, 224), mode="bilinear", align_corners=False)
|
| 61 |
+
b_images = b_images * 0.5 + 0.5
|
| 62 |
+
b_images = (b_images - _img_mean) / _img_std
|
| 63 |
+
|
| 64 |
+
text_encoding = prep_clip.tokenizer(target_caption, return_tensors="pt", padding=True).to(device)
|
| 65 |
+
output = m_clip(pixel_values=b_images, **text_encoding).logits_per_image / m_clip.logit_scale.exp()
|
| 66 |
+
return output.view(-1).cpu().numpy()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@torch.no_grad()
|
| 70 |
+
def binary_dino_diversity_score(l_images, device="cuda"):
|
| 71 |
+
"""Compute pairwise diversity scores using DINO."""
|
| 72 |
+
b_images = torch.cat(l_images, dim=0)
|
| 73 |
+
_img_mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device)
|
| 74 |
+
_img_std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device)
|
| 75 |
+
|
| 76 |
+
b_images = F.interpolate(b_images, size=(256, 256), mode="bilinear", align_corners=False)
|
| 77 |
+
b_images = b_images * 0.5 + 0.5
|
| 78 |
+
b_images = (b_images - _img_mean) / _img_std
|
| 79 |
+
all_features = dino_model(pixel_values=b_images).last_hidden_state[:, 1:, :].cpu()
|
| 80 |
+
|
| 81 |
+
N = len(l_images)
|
| 82 |
+
score_matrix = np.zeros((N, N))
|
| 83 |
+
for i in range(N):
|
| 84 |
+
f1 = all_features[i]
|
| 85 |
+
for j in range(i+1, N):
|
| 86 |
+
f2 = all_features[j]
|
| 87 |
+
cos_sim = (1 - F.cosine_similarity(f1, f2, dim=1)).mean().item()
|
| 88 |
+
score_matrix[i, j] = cos_sim
|
| 89 |
+
return score_matrix
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@torch.no_grad()
|
| 93 |
+
def binary_dino_cls_score(l_images, device="cuda"):
|
| 94 |
+
"""Compute pairwise diversity scores using DINO CLS tokens."""
|
| 95 |
+
b_images = torch.cat(l_images, dim=0)
|
| 96 |
+
_img_mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device)
|
| 97 |
+
_img_std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device)
|
| 98 |
+
|
| 99 |
+
b_images = F.interpolate(b_images, size=(256, 256), mode="bilinear", align_corners=False)
|
| 100 |
+
b_images = b_images * 0.5 + 0.5
|
| 101 |
+
b_images = (b_images - _img_mean) / _img_std
|
| 102 |
+
all_features = dino_model(pixel_values=b_images).last_hidden_state[:, 0:1, :].cpu()
|
| 103 |
+
|
| 104 |
+
N = len(l_images)
|
| 105 |
+
score_matrix = np.zeros((N, N))
|
| 106 |
+
for i in range(N):
|
| 107 |
+
f1 = all_features[i]
|
| 108 |
+
for j in range(i+1, N):
|
| 109 |
+
f2 = all_features[j]
|
| 110 |
+
cos_sim = (1 - F.cosine_similarity(f1, f2, dim=1)).mean().item()
|
| 111 |
+
score_matrix[i, j] = cos_sim
|
| 112 |
+
return score_matrix
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@torch.no_grad()
|
| 116 |
+
def binary_clip_diversity_score(l_images, device="cuda"):
|
| 117 |
+
"""Compute pairwise diversity scores using CLIP."""
|
| 118 |
+
_img_std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).view(1, 3, 1, 1).to(device)
|
| 119 |
+
_img_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).view(1, 3, 1, 1).to(device)
|
| 120 |
+
|
| 121 |
+
b_images = torch.cat(l_images, dim=0)
|
| 122 |
+
b_images = F.interpolate(b_images, size=(224, 224), mode="bilinear", align_corners=False)
|
| 123 |
+
b_images = b_images * 0.5 + 0.5
|
| 124 |
+
b_images = (b_images - _img_mean) / _img_std
|
| 125 |
+
|
| 126 |
+
vision_outputs = m_clip.vision_model(
|
| 127 |
+
pixel_values=b_images,
|
| 128 |
+
output_attentions=False,
|
| 129 |
+
output_hidden_states=False,
|
| 130 |
+
interpolate_pos_encoding=False,
|
| 131 |
+
return_dict=True
|
| 132 |
+
)
|
| 133 |
+
image_embeds = m_clip.visual_projection(vision_outputs[1])
|
| 134 |
+
image_embeds = image_embeds / _get_vector_norm(image_embeds)
|
| 135 |
+
|
| 136 |
+
N = len(l_images)
|
| 137 |
+
score_matrix = np.zeros((N, N))
|
| 138 |
+
for i in range(N):
|
| 139 |
+
f1 = image_embeds[i]
|
| 140 |
+
for j in range(i+1, N):
|
| 141 |
+
f2 = image_embeds[j]
|
| 142 |
+
cos_sim = (1 - torch.dot(f1, f2)).item()
|
| 143 |
+
score_matrix[i, j] = cos_sim
|
| 144 |
+
return score_matrix
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def get_score_functions(unary_term, binary_term, prompt):
|
| 148 |
+
"""Get the appropriate scoring functions based on selected terms."""
|
| 149 |
+
# Unary score function (always CLIP for flux-schnell) - bind the prompt
|
| 150 |
+
unary_score_fn = functools.partial(unary_clip_text_img_score, target_caption=prompt, device="cuda")
|
| 151 |
+
# Binary score function
|
| 152 |
+
if binary_term == "diversity_dino":
|
| 153 |
+
binary_score_fn = functools.partial(binary_dino_diversity_score, device="cuda")
|
| 154 |
+
elif binary_term == "dino_cls_pairwise":
|
| 155 |
+
binary_score_fn = functools.partial(binary_dino_cls_score, device="cuda")
|
| 156 |
+
elif binary_term == "diversity_clip":
|
| 157 |
+
binary_score_fn = functools.partial(binary_clip_diversity_score, device="cuda")
|
| 158 |
+
else:
|
| 159 |
+
raise ValueError(f"Invalid binary term: {binary_term}")
|
| 160 |
+
|
| 161 |
+
return unary_score_fn, binary_score_fn
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@spaces.GPU(duration=200)
|
| 165 |
+
def generate_images(prompt, starting_candidates, output_group_size, pruning_ratio,
|
| 166 |
+
lambda_score, seed, unary_term, binary_term, input_image=None, progress=gr.Progress(track_tqdm=True)):
|
| 167 |
+
"""Generate images using group inference with progressive pruning."""
|
| 168 |
+
|
| 169 |
+
# Get scoring functions with prompt bound to unary function
|
| 170 |
+
unary_score_fn, binary_score_fn = get_score_functions(unary_term, binary_term, prompt)
|
| 171 |
+
|
| 172 |
+
# Create inference args
|
| 173 |
+
inference_args = {
|
| 174 |
+
"model_name": "flux-kontext",
|
| 175 |
+
"prompt": prompt,
|
| 176 |
+
"guidance_scale": default_args.guidance_scale,
|
| 177 |
+
"num_inference_steps": default_args.num_inference_steps,
|
| 178 |
+
"max_sequence_length": 256,
|
| 179 |
+
"height": default_args.height,
|
| 180 |
+
"width": default_args.width,
|
| 181 |
+
"unary_score_fn": unary_score_fn,
|
| 182 |
+
"binary_score_fn": binary_score_fn,
|
| 183 |
+
"output_group_size": output_group_size,
|
| 184 |
+
"pruning_ratio": pruning_ratio,
|
| 185 |
+
"lambda_score": lambda_score,
|
| 186 |
+
"l_generator": [torch.Generator("cpu").manual_seed(seed + i) for i in range(starting_candidates)],
|
| 187 |
+
"starting_candidates": starting_candidates,
|
| 188 |
+
"skip_first_cfg": True,
|
| 189 |
+
}
|
| 190 |
+
inference_args["input_image"] = input_image
|
| 191 |
+
print(f"pruning ratio is: {pruning_ratio}")
|
| 192 |
+
# Run group inference
|
| 193 |
+
t_start = time.time()
|
| 194 |
+
output_group = run_group_inference(pipe, **inference_args)
|
| 195 |
+
t_end = time.time()
|
| 196 |
+
print(f"Time taken for group inference: {t_end - t_start} seconds")
|
| 197 |
+
return output_group
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# Load custom CSS
|
| 201 |
+
css_path = os.path.join(os.path.dirname(__file__), "styles.css")
|
| 202 |
+
with open(css_path, "r") as f:
|
| 203 |
+
custom_css = f.read()
|
| 204 |
+
|
| 205 |
+
# JavaScript to force light mode
|
| 206 |
+
js_func = """
|
| 207 |
+
function refresh() {
|
| 208 |
+
const url = new URL(window.location);
|
| 209 |
+
if (url.searchParams.get('__theme') !== 'light') {
|
| 210 |
+
url.searchParams.set('__theme', 'light');
|
| 211 |
+
window.location.href = url.href;
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
# Create Gradio interface
|
| 217 |
+
with gr.Blocks(css=custom_css, js=js_func, theme=gr.themes.Soft(), elem_id="main-container") as demo:
|
| 218 |
+
|
| 219 |
+
# Title and header
|
| 220 |
+
gr.HTML(
|
| 221 |
+
"""
|
| 222 |
+
<div class="title_left">
|
| 223 |
+
<h1>Scaling Group Inference for Diverse and High-Quality Generation</h1>
|
| 224 |
+
<div class="author-container">
|
| 225 |
+
<div class="grid-item cmu"><a href="https://gauravparmar.com/">Gaurav Parmar</a></div>
|
| 226 |
+
<div class="grid-item snap"><a href="https://orpatashnik.github.io/">Or Patashnik</a></div>
|
| 227 |
+
<div class="grid-item snap"><a href="https://scholar.google.com/citations?user=uD79u6oAAAAJ&hl=en">Daniil Ostashev</a></div>
|
| 228 |
+
<div class="grid-item snap"><a href="https://wangkua1.github.io/">Kuan-Chieh (Jackson) Wang</a></div>
|
| 229 |
+
<div class="grid-item snap"><a href="https://kfiraberman.github.io/">Kfir Aberman</a></div>
|
| 230 |
+
</div>
|
| 231 |
+
<div class="author-container">
|
| 232 |
+
<div class="grid-item cmu"><a href="https://www.cs.cmu.edu/~srinivas/">Srinivasa Narasimhan</a></div>
|
| 233 |
+
<div class="grid-item cmu"><a href="https://www.cs.cmu.edu/~junyanz/">Jun-Yan Zhu</a></div>
|
| 234 |
+
</div>
|
| 235 |
+
<br>
|
| 236 |
+
<div class="affiliation-container">
|
| 237 |
+
<div class="grid-item cmu"> <p>Carnegie Mellon University</p></div>
|
| 238 |
+
<div class="grid-item snap"> <p>Snap Research</p></div>
|
| 239 |
+
</div>
|
| 240 |
+
|
| 241 |
+
<br>
|
| 242 |
+
<h2>DEMO: Text-to-Image Group Inference with FLUX.1-Schnell</h2>
|
| 243 |
+
</div>
|
| 244 |
+
"""
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
with gr.Row(scale=1):
|
| 248 |
+
with gr.Column(scale=1.0):
|
| 249 |
+
prompt_placeholder = "Cat is playing outside in nature."
|
| 250 |
+
prompt_default = "Cat is playing outside in nature."
|
| 251 |
+
prompt = gr.Textbox(label="Prompt", placeholder=prompt_placeholder, lines=4, value=prompt_default)
|
| 252 |
+
input_image = gr.Image(label="Input Image", type="pil", sources=["upload"])
|
| 253 |
+
|
| 254 |
+
with gr.Column(scale=1.0):
|
| 255 |
+
with gr.Row(elem_id="starting-candidates-row"):
|
| 256 |
+
gr.Text("Starting Candidates:", container=False, interactive=False, scale=5)
|
| 257 |
+
starting_candidates = gr.Number(value=default_args.starting_candidates, precision=0, container=False, show_label=False, scale=1)
|
| 258 |
+
|
| 259 |
+
with gr.Row(elem_id="output-group-size-row"):
|
| 260 |
+
gr.Text("Output Group Size:", container=False, interactive=False, scale=5)
|
| 261 |
+
output_group_size = gr.Number(value=default_args.output_group_size, precision=0, container=False, show_label=False, scale=1)
|
| 262 |
+
|
| 263 |
+
with gr.Column(scale=1.0):
|
| 264 |
+
with gr.Accordion("Advanced Options", open=False, elem_id="advanced-options-accordion"):
|
| 265 |
+
with gr.Row():
|
| 266 |
+
gr.Text("Pruning Ratio:", container=False, interactive=False, elem_id="pruning-ratio-label", scale=3)
|
| 267 |
+
pruning_ratio = gr.Number(value=default_args.pruning_ratio, precision=2, container=False, show_label=False, scale=1)
|
| 268 |
+
|
| 269 |
+
with gr.Row():
|
| 270 |
+
gr.Text("Lambda:", container=False, interactive=False, elem_id="lambda-label", scale=5)
|
| 271 |
+
lambda_score = gr.Number(value=default_args.lambda_score, precision=1, container=False, show_label=False, scale=1)
|
| 272 |
+
|
| 273 |
+
with gr.Row():
|
| 274 |
+
gr.Text("Seed:", container=False, interactive=False, elem_id="seed-label", scale=5)
|
| 275 |
+
seed = gr.Number(value=42, precision=0, container=False, show_label=False, scale=1)
|
| 276 |
+
|
| 277 |
+
with gr.Row():
|
| 278 |
+
gr.Text("Unary:", container=False, interactive=False, elem_id="unary-term-label", scale=2)
|
| 279 |
+
unary_term = gr.Dropdown(choices=["clip_text_img"], value=default_args.unary_term, container=False, show_label=False, scale=3)
|
| 280 |
+
|
| 281 |
+
with gr.Row():
|
| 282 |
+
gr.Text("Binary:", container=False, interactive=False, elem_id="binary-term-label", scale=2)
|
| 283 |
+
binary_term = gr.Dropdown(choices=["diversity_dino", "diversity_clip", "dino_cls_pairwise"], value=default_args.binary_term,
|
| 284 |
+
container=False, show_label=False, scale=3)
|
| 285 |
+
|
| 286 |
+
with gr.Row(scale=1):
|
| 287 |
+
generate_btn = gr.Button("Generate", variant="primary")
|
| 288 |
+
|
| 289 |
+
with gr.Row(scale=1):
|
| 290 |
+
output_gallery_group = gr.Gallery(label="Group Inference", show_label=True,elem_id="gallery", columns=4, height="auto")
|
| 291 |
+
|
| 292 |
+
generate_btn.click(
|
| 293 |
+
fn=generate_images,
|
| 294 |
+
inputs=[prompt, starting_candidates, output_group_size, pruning_ratio, lambda_score, seed, unary_term, binary_term, input_image],
|
| 295 |
+
outputs=[output_gallery_group]
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
demo.launch()
|