Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,50 +1,26 @@
|
|
| 1 |
import os
|
| 2 |
import spaces
|
|
|
|
| 3 |
import time
|
| 4 |
import gradio as gr
|
| 5 |
import torch
|
| 6 |
-
from torch import Tensor, nn
|
| 7 |
from PIL import Image
|
| 8 |
from torchvision import transforms
|
| 9 |
from dataclasses import dataclass
|
| 10 |
import math
|
| 11 |
from typing import Callable
|
| 12 |
-
|
| 13 |
from tqdm import tqdm
|
| 14 |
import bitsandbytes as bnb
|
| 15 |
from bitsandbytes.nn.modules import Params4bit, QuantState
|
| 16 |
-
from transformers import (
|
| 17 |
-
MarianTokenizer,
|
| 18 |
-
MarianMTModel,
|
| 19 |
-
CLIPTextModel, CLIPTokenizer,
|
| 20 |
-
T5EncoderModel, T5Tokenizer
|
| 21 |
-
)
|
| 22 |
-
from diffusers import AutoencoderKL
|
| 23 |
-
from huggingface_hub import hf_hub_download
|
| 24 |
-
from safetensors.torch import load_file
|
| 25 |
-
from einops import rearrange, repeat
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
trans_model = MarianMTModel.from_pretrained(
|
| 35 |
-
"Helsinki-NLP/opus-mt-ko-en",
|
| 36 |
-
from_tf=True, # TF 체크포인트라도 PyTorch 로드
|
| 37 |
-
torch_dtype=torch.float32,
|
| 38 |
-
).to(torch.device("cpu"))
|
| 39 |
-
|
| 40 |
-
def translate_ko_to_en(text: str, max_length: int = 512) -> str:
|
| 41 |
-
"""한글 → 영어 번역 (CPU)"""
|
| 42 |
-
batch = trans_tokenizer([text], return_tensors="pt", padding=True)
|
| 43 |
-
# 모델은 CPU에 있으므로 .to("cpu") 해줄 필요 없음
|
| 44 |
-
gen = trans_model.generate(
|
| 45 |
-
**batch, max_length=max_length
|
| 46 |
-
)
|
| 47 |
-
return trans_tokenizer.batch_decode(gen, skip_special_tokens=True)[0]
|
| 48 |
|
| 49 |
# ---------------- Encoders ----------------
|
| 50 |
|
|
@@ -56,19 +32,11 @@ class HFEmbedder(nn.Module):
|
|
| 56 |
self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
|
| 57 |
|
| 58 |
if self.is_clip:
|
| 59 |
-
self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(
|
| 60 |
-
|
| 61 |
-
)
|
| 62 |
-
self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(
|
| 63 |
-
version, **hf_kwargs
|
| 64 |
-
)
|
| 65 |
else:
|
| 66 |
-
self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(
|
| 67 |
-
|
| 68 |
-
)
|
| 69 |
-
self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(
|
| 70 |
-
version, **hf_kwargs
|
| 71 |
-
)
|
| 72 |
|
| 73 |
self.hf_module = self.hf_module.eval().requires_grad_(False)
|
| 74 |
|
|
@@ -77,9 +45,12 @@ class HFEmbedder(nn.Module):
|
|
| 77 |
text,
|
| 78 |
truncation=True,
|
| 79 |
max_length=self.max_length,
|
|
|
|
|
|
|
| 80 |
padding="max_length",
|
| 81 |
return_tensors="pt",
|
| 82 |
)
|
|
|
|
| 83 |
outputs = self.hf_module(
|
| 84 |
input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
|
| 85 |
attention_mask=None,
|
|
@@ -87,35 +58,24 @@ class HFEmbedder(nn.Module):
|
|
| 87 |
)
|
| 88 |
return outputs[self.output_key]
|
| 89 |
|
| 90 |
-
|
| 91 |
-
t5
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
clip = HFEmbedder(
|
| 97 |
-
"openai/clip-vit-large-patch14",
|
| 98 |
-
max_length=77,
|
| 99 |
-
torch_dtype=torch.bfloat16
|
| 100 |
-
).to(torch_device)
|
| 101 |
-
ae = AutoencoderKL.from_pretrained(
|
| 102 |
-
"black-forest-labs/FLUX.1-dev",
|
| 103 |
-
subfolder="vae",
|
| 104 |
-
torch_dtype=torch.bfloat16
|
| 105 |
-
).to(torch_device)
|
| 106 |
-
|
| 107 |
-
# ---------------- NF4 지원 코드 ----------------
|
| 108 |
|
| 109 |
def functional_linear_4bits(x, weight, bias):
|
| 110 |
-
out = bnb.matmul_4bit(
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
return out.to(x)
|
| 114 |
|
| 115 |
def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantState:
|
| 116 |
if state is None:
|
| 117 |
return None
|
|
|
|
| 118 |
device = device or state.absmax.device
|
|
|
|
| 119 |
state2 = (
|
| 120 |
QuantState(
|
| 121 |
absmax=state.state2.absmax.to(device),
|
|
@@ -128,6 +88,7 @@ def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantSta
|
|
| 128 |
if state.nested
|
| 129 |
else None
|
| 130 |
)
|
|
|
|
| 131 |
return QuantState(
|
| 132 |
absmax=state.absmax.to(device),
|
| 133 |
shape=state.shape,
|
|
@@ -141,26 +102,25 @@ def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantSta
|
|
| 141 |
|
| 142 |
class ForgeParams4bit(Params4bit):
|
| 143 |
def to(self, *args, **kwargs):
|
| 144 |
-
device, dtype, non_blocking,
|
| 145 |
if device is not None and device.type == "cuda" and not self.bnb_quantized:
|
| 146 |
return self._quantize(device)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
self, device=device, dtype=dtype, non_blocking=non_blocking
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
return new
|
| 164 |
|
| 165 |
class ForgeLoader4Bit(torch.nn.Module):
|
| 166 |
def __init__(self, *, device, dtype, quant_type, **kwargs):
|
|
@@ -171,154 +131,454 @@ class ForgeLoader4Bit(torch.nn.Module):
|
|
| 171 |
self.bias = None
|
| 172 |
self.quant_type = quant_type
|
| 173 |
|
| 174 |
-
def
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
for k in
|
| 187 |
-
|
| 188 |
-
}
|
| 189 |
-
if any("bitsandbytes" in k for k in qs_keys):
|
| 190 |
-
qs = {
|
| 191 |
-
k: state_dict[prefix + "weight." + k] for k in qs_keys
|
| 192 |
-
}
|
| 193 |
self.weight = ForgeParams4bit.from_prequantized(
|
| 194 |
-
data=state_dict[prefix +
|
| 195 |
-
quantized_stats=
|
| 196 |
requires_grad=False,
|
| 197 |
-
device=torch.device(
|
| 198 |
-
module=self
|
| 199 |
)
|
| 200 |
self.quant_state = self.weight.quant_state
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
del self.dummy
|
| 206 |
else:
|
| 207 |
-
super()._load_from_state_dict(
|
| 208 |
-
state_dict,
|
| 209 |
-
prefix,
|
| 210 |
-
local_metadata,
|
| 211 |
-
strict,
|
| 212 |
-
missing_keys,
|
| 213 |
-
unexpected_keys,
|
| 214 |
-
error_msgs,
|
| 215 |
-
)
|
| 216 |
|
| 217 |
class Linear(ForgeLoader4Bit):
|
| 218 |
def __init__(self, *args, device=None, dtype=None, **kwargs):
|
| 219 |
-
super().__init__(device=device, dtype=dtype, quant_type=
|
| 220 |
|
| 221 |
def forward(self, x):
|
| 222 |
self.weight.quant_state = self.quant_state
|
|
|
|
| 223 |
if self.bias is not None and self.bias.dtype != x.dtype:
|
| 224 |
self.bias.data = self.bias.data.to(x.dtype)
|
|
|
|
| 225 |
return functional_linear_4bits(x, self.weight, self.bias)
|
| 226 |
|
| 227 |
nn.Linear = Linear
|
| 228 |
|
| 229 |
-
# ----------------
|
| 230 |
|
| 231 |
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
|
| 232 |
-
# ... (생략 없이 원본 코드 그대로)
|
| 233 |
q, k = apply_rope(q, k, pe)
|
| 234 |
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
| 235 |
x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
|
| 236 |
return x
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
-
|
|
|
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
)
|
| 249 |
-
)
|
| 250 |
-
sd = {
|
| 251 |
-
k.replace("model.diffusion_model.", ""): v
|
| 252 |
-
for k, v in sd.items()
|
| 253 |
-
if "model.diffusion_model" in k
|
| 254 |
-
}
|
| 255 |
-
|
| 256 |
-
model = Flux().to(torch_device, dtype=torch.bfloat16)
|
| 257 |
-
model.load_state_dict(sd)
|
| 258 |
-
model_zero_init = False
|
| 259 |
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
[
|
| 268 |
-
transforms.ToTensor(),
|
| 269 |
-
transforms.Lambda(lambda x: 2.0 * x - 1.0),
|
| 270 |
-
]
|
| 271 |
-
)
|
| 272 |
-
return tfm(image)[None, ...]
|
| 273 |
|
| 274 |
-
def
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
return {
|
| 296 |
"img": img,
|
| 297 |
-
"img_ids": img_ids,
|
| 298 |
-
"txt": txt,
|
| 299 |
-
"txt_ids": txt_ids,
|
| 300 |
-
"vec": vec,
|
| 301 |
}
|
| 302 |
|
| 303 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
timesteps = torch.linspace(1, 0, num_steps + 1)
|
| 305 |
if shift:
|
| 306 |
-
mu = (
|
| 307 |
-
|
| 308 |
-
)
|
| 309 |
-
timesteps = timesteps.exp().div((1 / timesteps - 1) ** 1 + mu)
|
| 310 |
return timesteps.tolist()
|
| 311 |
|
| 312 |
-
def denoise(
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
| 322 |
pred = model(
|
| 323 |
img=img,
|
| 324 |
img_ids=img_ids,
|
|
@@ -331,155 +591,152 @@ def denoise(model, img, img_ids, txt, txt_ids, vec, timesteps, guidance):
|
|
| 331 |
img = img + (t_prev - t_curr) * pred
|
| 332 |
return img
|
| 333 |
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
|
| 336 |
@spaces.GPU
|
| 337 |
@torch.no_grad()
|
| 338 |
def generate_image(
|
| 339 |
-
prompt,
|
| 340 |
-
|
| 341 |
-
height,
|
| 342 |
-
guidance,
|
| 343 |
-
inference_steps,
|
| 344 |
-
seed,
|
| 345 |
-
do_img2img,
|
| 346 |
-
init_image,
|
| 347 |
-
image2image_strength,
|
| 348 |
-
resize_img,
|
| 349 |
progress=gr.Progress(track_tqdm=True),
|
| 350 |
):
|
| 351 |
-
# 한글 감지 시 CPU 번역기 사용
|
| 352 |
-
if any("\u3131" <= c <= "\u318E" or "\uAC00" <= c <= "\uD7A3" for c in prompt):
|
| 353 |
-
prompt = translate_ko_to_en(prompt)
|
| 354 |
-
|
| 355 |
if seed == 0:
|
| 356 |
-
seed = random.
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
| 359 |
if not model_zero_init:
|
| 360 |
model = model.to(torch_device)
|
| 361 |
model_zero_init = True
|
| 362 |
-
|
| 363 |
if do_img2img and init_image is not None:
|
| 364 |
-
|
| 365 |
if resize_img:
|
| 366 |
-
|
| 367 |
-
init_img, (height, width)
|
| 368 |
-
)
|
| 369 |
else:
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
height
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
).
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
) * ae.config.scaling_factor
|
| 379 |
-
else:
|
| 380 |
-
init_img = None
|
| 381 |
-
|
| 382 |
-
generator = torch.Generator(device=str(torch_device)).manual_seed(seed)
|
| 383 |
x = torch.randn(
|
| 384 |
1,
|
| 385 |
16,
|
| 386 |
2 * math.ceil(height / 16),
|
| 387 |
2 * math.ceil(width / 16),
|
| 388 |
-
device=
|
| 389 |
dtype=torch.bfloat16,
|
| 390 |
-
generator=generator
|
| 391 |
-
)
|
| 392 |
-
timesteps = get_schedule(
|
| 393 |
-
inference_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True
|
| 394 |
)
|
| 395 |
-
|
| 396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
t = timesteps[t_idx]
|
| 398 |
timesteps = timesteps[t_idx:]
|
| 399 |
-
x = t * x + (1 - t) *
|
| 400 |
|
| 401 |
-
inp = prepare(t5, clip, x, prompt)
|
| 402 |
x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
|
| 403 |
-
|
| 404 |
-
x = rearrange(
|
| 405 |
-
x[:, inp["txt"].shape[1] :, ...].float(),
|
| 406 |
-
"b (h w) (c ph pw) -> b c (h ph) (w pw)",
|
| 407 |
-
h=math.ceil(height / 16),
|
| 408 |
-
w=math.ceil(width / 16),
|
| 409 |
-
ph=2,
|
| 410 |
-
pw=2,
|
| 411 |
-
)
|
| 412 |
with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
|
| 413 |
x = (x / ae.config.scaling_factor) + ae.config.shift_factor
|
| 414 |
x = ae.decode(x).sample
|
| 415 |
-
|
| 416 |
x = x.clamp(-1, 1)
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
.cpu()
|
| 420 |
-
.byte()
|
| 421 |
-
.numpy()
|
| 422 |
-
)
|
| 423 |
-
|
| 424 |
return img, seed
|
| 425 |
|
| 426 |
-
css = """
|
| 427 |
-
footer {
|
| 428 |
-
visibility: hidden;
|
| 429 |
-
}
|
| 430 |
-
"""
|
| 431 |
-
|
| 432 |
def create_demo():
|
| 433 |
-
with gr.Blocks(
|
| 434 |
-
gr.
|
| 435 |
-
"
|
| 436 |
-
"
|
| 437 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
)
|
| 439 |
with gr.Row():
|
| 440 |
with gr.Column():
|
| 441 |
-
prompt = gr.Textbox(
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
)
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
init_img = gr.Image(label="Input Image", visible=False)
|
| 452 |
-
strength = gr.Slider(
|
| 453 |
-
0.0, 1.0, 0.01, label="Noising strength", value=0.8, visible=False
|
| 454 |
)
|
| 455 |
-
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
with gr.Column():
|
| 458 |
-
|
| 459 |
-
|
| 460 |
|
| 461 |
-
|
| 462 |
-
fn=lambda x: [gr.update(visible=x)
|
| 463 |
-
inputs=[
|
| 464 |
-
outputs=[
|
| 465 |
)
|
| 466 |
-
|
|
|
|
| 467 |
fn=generate_image,
|
| 468 |
-
inputs=[
|
| 469 |
-
|
| 470 |
-
width,
|
| 471 |
-
height,
|
| 472 |
-
guidance,
|
| 473 |
-
steps,
|
| 474 |
-
seed,
|
| 475 |
-
do_i2i,
|
| 476 |
-
init_img,
|
| 477 |
-
strength,
|
| 478 |
-
resize,
|
| 479 |
-
],
|
| 480 |
-
outputs=[out_img, out_seed],
|
| 481 |
)
|
| 482 |
return demo
|
| 483 |
|
| 484 |
if __name__ == "__main__":
|
| 485 |
-
create_demo()
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import spaces
|
| 3 |
+
|
| 4 |
import time
|
| 5 |
import gradio as gr
|
| 6 |
import torch
|
|
|
|
| 7 |
from PIL import Image
|
| 8 |
from torchvision import transforms
|
| 9 |
from dataclasses import dataclass
|
| 10 |
import math
|
| 11 |
from typing import Callable
|
| 12 |
+
|
| 13 |
from tqdm import tqdm
|
| 14 |
import bitsandbytes as bnb
|
| 15 |
from bitsandbytes.nn.modules import Params4bit, QuantState
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
import torch
|
| 18 |
+
import random
|
| 19 |
+
from einops import rearrange, repeat
|
| 20 |
+
from diffusers import AutoencoderKL
|
| 21 |
+
from torch import Tensor, nn
|
| 22 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 23 |
+
from transformers import T5EncoderModel, T5Tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# ---------------- Encoders ----------------
|
| 26 |
|
|
|
|
| 32 |
self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
|
| 33 |
|
| 34 |
if self.is_clip:
|
| 35 |
+
self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
|
| 36 |
+
self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
else:
|
| 38 |
+
self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
|
| 39 |
+
self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
self.hf_module = self.hf_module.eval().requires_grad_(False)
|
| 42 |
|
|
|
|
| 45 |
text,
|
| 46 |
truncation=True,
|
| 47 |
max_length=self.max_length,
|
| 48 |
+
return_length=False,
|
| 49 |
+
return_overflowing_tokens=False,
|
| 50 |
padding="max_length",
|
| 51 |
return_tensors="pt",
|
| 52 |
)
|
| 53 |
+
|
| 54 |
outputs = self.hf_module(
|
| 55 |
input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
|
| 56 |
attention_mask=None,
|
|
|
|
| 58 |
)
|
| 59 |
return outputs[self.output_key]
|
| 60 |
|
| 61 |
+
device = "cuda"
|
| 62 |
+
t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
|
| 63 |
+
clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
|
| 64 |
+
ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
|
| 65 |
+
|
| 66 |
+
# ---------------- NF4 ----------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
def functional_linear_4bits(x, weight, bias):
|
| 69 |
+
out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
|
| 70 |
+
out = out.to(x)
|
| 71 |
+
return out
|
|
|
|
| 72 |
|
| 73 |
def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantState:
|
| 74 |
if state is None:
|
| 75 |
return None
|
| 76 |
+
|
| 77 |
device = device or state.absmax.device
|
| 78 |
+
|
| 79 |
state2 = (
|
| 80 |
QuantState(
|
| 81 |
absmax=state.state2.absmax.to(device),
|
|
|
|
| 88 |
if state.nested
|
| 89 |
else None
|
| 90 |
)
|
| 91 |
+
|
| 92 |
return QuantState(
|
| 93 |
absmax=state.absmax.to(device),
|
| 94 |
shape=state.shape,
|
|
|
|
| 102 |
|
| 103 |
class ForgeParams4bit(Params4bit):
|
| 104 |
def to(self, *args, **kwargs):
|
| 105 |
+
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
|
| 106 |
if device is not None and device.type == "cuda" and not self.bnb_quantized:
|
| 107 |
return self._quantize(device)
|
| 108 |
+
else:
|
| 109 |
+
n = ForgeParams4bit(
|
| 110 |
+
torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
|
| 111 |
+
requires_grad=self.requires_grad,
|
| 112 |
+
quant_state=copy_quant_state(self.quant_state, device),
|
| 113 |
+
compress_statistics=False,
|
| 114 |
+
blocksize=64,
|
| 115 |
+
quant_type=self.quant_type,
|
| 116 |
+
quant_storage=self.quant_storage,
|
| 117 |
+
bnb_quantized=self.bnb_quantized,
|
| 118 |
+
module=self.module
|
| 119 |
+
)
|
| 120 |
+
self.module.quant_state = n.quant_state
|
| 121 |
+
self.data = n.data
|
| 122 |
+
self.quant_state = n.quant_state
|
| 123 |
+
return n
|
|
|
|
| 124 |
|
| 125 |
class ForgeLoader4Bit(torch.nn.Module):
|
| 126 |
def __init__(self, *, device, dtype, quant_type, **kwargs):
|
|
|
|
| 131 |
self.bias = None
|
| 132 |
self.quant_type = quant_type
|
| 133 |
|
| 134 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 135 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 136 |
+
quant_state = getattr(self.weight, "quant_state", None)
|
| 137 |
+
if quant_state is not None:
|
| 138 |
+
for k, v in quant_state.as_dict(packed=True).items():
|
| 139 |
+
destination[prefix + "weight." + k] = v if keep_vars else v.detach()
|
| 140 |
+
return
|
| 141 |
+
|
| 142 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
|
| 143 |
+
quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
|
| 144 |
+
|
| 145 |
+
if any('bitsandbytes' in k for k in quant_state_keys):
|
| 146 |
+
quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
|
| 147 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
self.weight = ForgeParams4bit.from_prequantized(
|
| 149 |
+
data=state_dict[prefix + 'weight'],
|
| 150 |
+
quantized_stats=quant_state_dict,
|
| 151 |
requires_grad=False,
|
| 152 |
+
device=torch.device('cuda'),
|
| 153 |
+
module=self
|
| 154 |
)
|
| 155 |
self.quant_state = self.weight.quant_state
|
| 156 |
+
|
| 157 |
+
if prefix + 'bias' in state_dict:
|
| 158 |
+
self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
|
| 159 |
+
|
| 160 |
+
del self.dummy
|
| 161 |
+
elif hasattr(self, 'dummy'):
|
| 162 |
+
if prefix + 'weight' in state_dict:
|
| 163 |
+
self.weight = ForgeParams4bit(
|
| 164 |
+
state_dict[prefix + 'weight'].to(self.dummy),
|
| 165 |
+
requires_grad=False,
|
| 166 |
+
compress_statistics=True,
|
| 167 |
+
quant_type=self.quant_type,
|
| 168 |
+
quant_storage=torch.uint8,
|
| 169 |
+
module=self,
|
| 170 |
)
|
| 171 |
+
self.quant_state = self.weight.quant_state
|
| 172 |
+
|
| 173 |
+
if prefix + 'bias' in state_dict:
|
| 174 |
+
self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
|
| 175 |
+
|
| 176 |
del self.dummy
|
| 177 |
else:
|
| 178 |
+
super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
class Linear(ForgeLoader4Bit):
|
| 181 |
def __init__(self, *args, device=None, dtype=None, **kwargs):
|
| 182 |
+
super().__init__(device=device, dtype=dtype, quant_type='nf4')
|
| 183 |
|
| 184 |
def forward(self, x):
|
| 185 |
self.weight.quant_state = self.quant_state
|
| 186 |
+
|
| 187 |
if self.bias is not None and self.bias.dtype != x.dtype:
|
| 188 |
self.bias.data = self.bias.data.to(x.dtype)
|
| 189 |
+
|
| 190 |
return functional_linear_4bits(x, self.weight, self.bias)
|
| 191 |
|
| 192 |
nn.Linear = Linear
|
| 193 |
|
| 194 |
+
# ---------------- Model ----------------
|
| 195 |
|
| 196 |
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
|
|
|
|
| 197 |
q, k = apply_rope(q, k, pe)
|
| 198 |
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
| 199 |
x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
|
| 200 |
return x
|
| 201 |
|
| 202 |
+
def rope(pos, dim, theta):
|
| 203 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
| 204 |
+
omega = 1.0 / (theta ** scale)
|
| 205 |
+
out = pos.unsqueeze(-1) * omega.unsqueeze(0)
|
| 206 |
+
cos_out = torch.cos(out)
|
| 207 |
+
sin_out = torch.sin(out)
|
| 208 |
+
out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
|
| 209 |
+
b, n, d, _ = out.shape
|
| 210 |
+
out = out.view(b, n, d, 2, 2)
|
| 211 |
+
return out.float()
|
| 212 |
+
|
| 213 |
+
def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
| 214 |
+
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
|
| 215 |
+
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
|
| 216 |
+
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
|
| 217 |
+
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
|
| 218 |
+
return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
|
| 219 |
+
|
| 220 |
+
class EmbedND(nn.Module):
|
| 221 |
+
def __init__(self, dim: int, theta: int, axes_dim: list[int]):
|
| 222 |
+
super().__init__()
|
| 223 |
+
self.dim = dim
|
| 224 |
+
self.theta = theta
|
| 225 |
+
self.axes_dim = axes_dim
|
| 226 |
+
|
| 227 |
+
def forward(self, ids: Tensor) -> Tensor:
|
| 228 |
+
n_axes = ids.shape[-1]
|
| 229 |
+
emb = torch.cat(
|
| 230 |
+
[rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
|
| 231 |
+
dim=-3,
|
| 232 |
+
)
|
| 233 |
+
return emb.unsqueeze(1)
|
| 234 |
+
|
| 235 |
+
def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
|
| 236 |
+
t = time_factor * t
|
| 237 |
+
half = dim // 2
|
| 238 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
|
| 239 |
+
args = t[:, None].float() * freqs[None]
|
| 240 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 241 |
+
if dim % 2:
|
| 242 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 243 |
+
if torch.is_floating_point(t):
|
| 244 |
+
embedding = embedding.to(t)
|
| 245 |
+
return embedding
|
| 246 |
+
|
| 247 |
+
class MLPEmbedder(nn.Module):
|
| 248 |
+
def __init__(self, in_dim: int, hidden_dim: int):
|
| 249 |
+
super().__init__()
|
| 250 |
+
self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
|
| 251 |
+
self.silu = nn.SiLU()
|
| 252 |
+
self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
| 253 |
|
| 254 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 255 |
+
return self.out_layer(self.silu(self.in_layer(x)))
|
| 256 |
|
| 257 |
+
class RMSNorm(torch.nn.Module):
|
| 258 |
+
def __init__(self, dim: int):
|
| 259 |
+
super().__init__()
|
| 260 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
+
def forward(self, x: Tensor):
|
| 263 |
+
x_dtype = x.dtype
|
| 264 |
+
x = x.float()
|
| 265 |
+
rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
|
| 266 |
+
return (x * rrms).to(dtype=x_dtype) * self.scale
|
| 267 |
|
| 268 |
+
class QKNorm(torch.nn.Module):
|
| 269 |
+
def __init__(self, dim: int):
|
| 270 |
+
super().__init__()
|
| 271 |
+
self.query_norm = RMSNorm(dim)
|
| 272 |
+
self.key_norm = RMSNorm(dim)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
|
| 275 |
+
q = self.query_norm(q)
|
| 276 |
+
k = self.key_norm(k)
|
| 277 |
+
return q.to(v), k.to(v)
|
| 278 |
+
|
| 279 |
+
class SelfAttention(nn.Module):
|
| 280 |
+
def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
|
| 281 |
+
super().__init__()
|
| 282 |
+
self.num_heads = num_heads
|
| 283 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 284 |
+
head_dim = dim // num_heads
|
| 285 |
+
self.norm = QKNorm(head_dim)
|
| 286 |
+
self.proj = nn.Linear(dim, dim)
|
| 287 |
+
|
| 288 |
+
def forward(self, x: Tensor, pe: Tensor) -> Tensor:
|
| 289 |
+
qkv = self.qkv(x)
|
| 290 |
+
B, L, _ = qkv.shape
|
| 291 |
+
qkv = qkv.view(B, L, 3, self.num_heads, -1)
|
| 292 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
| 293 |
+
q, k = self.norm(q, k, v)
|
| 294 |
+
x = attention(q, k, v, pe=pe)
|
| 295 |
+
x = self.proj(x)
|
| 296 |
+
return x
|
| 297 |
+
|
| 298 |
+
@dataclass
|
| 299 |
+
class ModulationOut:
|
| 300 |
+
shift: Tensor
|
| 301 |
+
scale: Tensor
|
| 302 |
+
gate: Tensor
|
| 303 |
+
|
| 304 |
+
class Modulation(nn.Module):
|
| 305 |
+
def __init__(self, dim: int, double: bool):
|
| 306 |
+
super().__init__()
|
| 307 |
+
self.is_double = double
|
| 308 |
+
self.multiplier = 6 if double else 3
|
| 309 |
+
self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
|
| 310 |
+
|
| 311 |
+
def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
|
| 312 |
+
out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
|
| 313 |
+
return (
|
| 314 |
+
ModulationOut(*out[:3]),
|
| 315 |
+
ModulationOut(*out[3:]) if self.is_double else None,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
class DoubleStreamBlock(nn.Module):
|
| 319 |
+
def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
|
| 320 |
+
super().__init__()
|
| 321 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 322 |
+
self.num_heads = num_heads
|
| 323 |
+
self.hidden_size = hidden_size
|
| 324 |
+
self.img_mod = Modulation(hidden_size, double=True)
|
| 325 |
+
self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 326 |
+
self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
| 327 |
+
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 328 |
+
self.img_mlp = nn.Sequential(
|
| 329 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
| 330 |
+
nn.GELU(approximate="tanh"),
|
| 331 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
| 332 |
+
)
|
| 333 |
+
self.txt_mod = Modulation(hidden_size, double=True)
|
| 334 |
+
self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 335 |
+
self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
| 336 |
+
self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 337 |
+
self.txt_mlp = nn.Sequential(
|
| 338 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
| 339 |
+
nn.GELU(approximate="tanh"),
|
| 340 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
|
| 344 |
+
img_mod1, img_mod2 = self.img_mod(vec)
|
| 345 |
+
txt_mod1, txt_mod2 = self.txt_mod(vec)
|
| 346 |
+
|
| 347 |
+
# Image attention
|
| 348 |
+
img_modulated = self.img_norm1(img)
|
| 349 |
+
img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
|
| 350 |
+
img_qkv = self.img_attn.qkv(img_modulated)
|
| 351 |
+
B, L, _ = img_qkv.shape
|
| 352 |
+
H = self.num_heads
|
| 353 |
+
D = img_qkv.shape[-1] // (3 * H)
|
| 354 |
+
img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
| 355 |
+
img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
|
| 356 |
+
|
| 357 |
+
# Text attention
|
| 358 |
+
txt_modulated = self.txt_norm1(txt)
|
| 359 |
+
txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
|
| 360 |
+
txt_qkv = self.txt_attn.qkv(txt_modulated)
|
| 361 |
+
B, L, _ = txt_qkv.shape
|
| 362 |
+
txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
| 363 |
+
txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
|
| 364 |
+
|
| 365 |
+
# Combined attention
|
| 366 |
+
q = torch.cat((txt_q, img_q), dim=2)
|
| 367 |
+
k = torch.cat((txt_k, img_k), dim=2)
|
| 368 |
+
v = torch.cat((txt_v, img_v), dim=2)
|
| 369 |
+
attn = attention(q, k, v, pe=pe)
|
| 370 |
+
txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
|
| 371 |
+
|
| 372 |
+
# Img final
|
| 373 |
+
img = img + img_mod1.gate * self.img_attn.proj(img_attn)
|
| 374 |
+
img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
|
| 375 |
+
|
| 376 |
+
# Text final
|
| 377 |
+
txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
|
| 378 |
+
txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
|
| 379 |
+
return img, txt
|
| 380 |
+
|
| 381 |
+
class SingleStreamBlock(nn.Module):
|
| 382 |
+
def __init__(
|
| 383 |
+
self,
|
| 384 |
+
hidden_size: int,
|
| 385 |
+
num_heads: int,
|
| 386 |
+
mlp_ratio: float = 4.0,
|
| 387 |
+
qk_scale: float | None = None,
|
| 388 |
+
):
|
| 389 |
+
super().__init__()
|
| 390 |
+
self.hidden_dim = hidden_size
|
| 391 |
+
self.num_heads = num_heads
|
| 392 |
+
head_dim = hidden_size // num_heads
|
| 393 |
+
self.scale = qk_scale or head_dim**-0.5
|
| 394 |
+
self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 395 |
+
self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
|
| 396 |
+
self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
|
| 397 |
+
self.norm = QKNorm(head_dim)
|
| 398 |
+
self.hidden_size = hidden_size
|
| 399 |
+
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 400 |
+
self.mlp_act = nn.GELU(approximate="tanh")
|
| 401 |
+
self.modulation = Modulation(hidden_size, double=False)
|
| 402 |
+
|
| 403 |
+
def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
|
| 404 |
+
mod, _ = self.modulation(vec)
|
| 405 |
+
x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
|
| 406 |
+
qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
|
| 407 |
+
qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
|
| 408 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
| 409 |
+
q, k = self.norm(q, k, v)
|
| 410 |
+
attn = attention(q, k, v, pe=pe)
|
| 411 |
+
output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
|
| 412 |
+
return x + mod.gate * output
|
| 413 |
+
|
| 414 |
+
class LastLayer(nn.Module):
|
| 415 |
+
def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
|
| 416 |
+
super().__init__()
|
| 417 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 418 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
| 419 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
|
| 420 |
+
|
| 421 |
+
def forward(self, x: Tensor, vec: Tensor) -> Tensor:
|
| 422 |
+
shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
|
| 423 |
+
x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
|
| 424 |
+
x = self.linear(x)
|
| 425 |
+
return x
|
| 426 |
+
|
| 427 |
+
@dataclass
|
| 428 |
+
class FluxParams:
|
| 429 |
+
in_channels: int = 64
|
| 430 |
+
vec_in_dim: int = 768
|
| 431 |
+
context_in_dim: int = 4096
|
| 432 |
+
hidden_size: int = 3072
|
| 433 |
+
mlp_ratio: float = 4.0
|
| 434 |
+
num_heads: int = 24
|
| 435 |
+
depth: int = 19
|
| 436 |
+
depth_single_blocks: int = 38
|
| 437 |
+
axes_dim: list = [16, 56, 56]
|
| 438 |
+
theta: int = 10000
|
| 439 |
+
qkv_bias: bool = True
|
| 440 |
+
guidance_embed: bool = True
|
| 441 |
+
|
| 442 |
+
class Flux(nn.Module):
|
| 443 |
+
def __init__(self, params = FluxParams()):
|
| 444 |
+
super().__init__()
|
| 445 |
+
self.params = params
|
| 446 |
+
self.in_channels = params.in_channels
|
| 447 |
+
self.out_channels = self.in_channels
|
| 448 |
+
if params.hidden_size % params.num_heads != 0:
|
| 449 |
+
raise ValueError(
|
| 450 |
+
f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
|
| 451 |
+
)
|
| 452 |
+
pe_dim = params.hidden_size // params.num_heads
|
| 453 |
+
if sum(params.axes_dim) != pe_dim:
|
| 454 |
+
raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
|
| 455 |
+
self.hidden_size = params.hidden_size
|
| 456 |
+
self.num_heads = params.num_heads
|
| 457 |
+
self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
|
| 458 |
+
self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
|
| 459 |
+
self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
|
| 460 |
+
self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
|
| 461 |
+
self.guidance_in = (
|
| 462 |
+
MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
|
| 463 |
+
)
|
| 464 |
+
self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
|
| 465 |
+
|
| 466 |
+
self.double_blocks = nn.ModuleList(
|
| 467 |
+
[
|
| 468 |
+
DoubleStreamBlock(
|
| 469 |
+
self.hidden_size,
|
| 470 |
+
self.num_heads,
|
| 471 |
+
mlp_ratio=params.mlp_ratio,
|
| 472 |
+
qkv_bias=params.qkv_bias,
|
| 473 |
+
)
|
| 474 |
+
for _ in range(params.depth)
|
| 475 |
+
]
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
self.single_blocks = nn.ModuleList(
|
| 479 |
+
[
|
| 480 |
+
SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
|
| 481 |
+
for _ in range(params.depth_single_blocks)
|
| 482 |
+
]
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
|
| 486 |
|
| 487 |
+
def forward(
|
| 488 |
+
self,
|
| 489 |
+
img: Tensor,
|
| 490 |
+
img_ids: Tensor,
|
| 491 |
+
txt: Tensor,
|
| 492 |
+
txt_ids: Tensor,
|
| 493 |
+
timesteps: Tensor,
|
| 494 |
+
y: Tensor,
|
| 495 |
+
guidance: Tensor | None = None,
|
| 496 |
+
) -> Tensor:
|
| 497 |
+
if img.ndim != 3 or txt.ndim != 3:
|
| 498 |
+
raise ValueError("Input img and txt tensors must have 3 dimensions.")
|
| 499 |
+
img = self.img_in(img)
|
| 500 |
+
vec = self.time_in(timestep_embedding(timesteps, 256))
|
| 501 |
+
if self.params.guidance_embed:
|
| 502 |
+
if guidance is None:
|
| 503 |
+
raise ValueError("No guidance strength provided for guidance-distilled model.")
|
| 504 |
+
vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
|
| 505 |
+
vec = vec + self.vector_in(y)
|
| 506 |
+
txt = self.txt_in(txt)
|
| 507 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
| 508 |
+
pe = self.pe_embedder(ids)
|
| 509 |
+
for block in self.double_blocks:
|
| 510 |
+
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
|
| 511 |
+
img = torch.cat((txt, img), 1)
|
| 512 |
+
for block in self.single_blocks:
|
| 513 |
+
img = block(img, vec=vec, pe=pe)
|
| 514 |
+
img = img[:, txt.shape[1] :, ...]
|
| 515 |
+
img = self.final_layer(img, vec)
|
| 516 |
+
return img
|
| 517 |
+
|
| 518 |
+
def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
|
| 519 |
+
bs, c, h, w = img.shape
|
| 520 |
+
if bs == 1 and not isinstance(prompt, str):
|
| 521 |
+
bs = len(prompt)
|
| 522 |
+
img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
|
| 523 |
+
if img.shape[0] == 1 and bs > 1:
|
| 524 |
+
img = repeat(img, "1 ... -> bs ...", bs=bs)
|
| 525 |
+
img_ids = torch.zeros(h // 2, w // 2, 3)
|
| 526 |
+
img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
|
| 527 |
+
img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
|
| 528 |
+
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
|
| 529 |
+
if isinstance(prompt, str):
|
| 530 |
+
prompt = [prompt]
|
| 531 |
+
txt = t5(prompt)
|
| 532 |
+
if txt.shape[0] == 1 and bs > 1:
|
| 533 |
+
txt = repeat(txt, "1 ... -> bs ...", bs=bs)
|
| 534 |
+
txt_ids = torch.zeros(bs, txt.shape[1], 3)
|
| 535 |
+
vec = clip(prompt)
|
| 536 |
+
if vec.shape[0] == 1 and bs > 1:
|
| 537 |
+
vec = repeat(vec, "1 ... -> bs ...", bs=bs)
|
| 538 |
return {
|
| 539 |
"img": img,
|
| 540 |
+
"img_ids": img_ids.to(img.device),
|
| 541 |
+
"txt": txt.to(img.device),
|
| 542 |
+
"txt_ids": txt_ids.to(img.device),
|
| 543 |
+
"vec": vec.to(img.device),
|
| 544 |
}
|
| 545 |
|
| 546 |
+
def time_shift(mu: float, sigma: float, t: Tensor):
|
| 547 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 548 |
+
|
| 549 |
+
def get_lin_function(
|
| 550 |
+
x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
|
| 551 |
+
) -> Callable[[float], float]:
|
| 552 |
+
m = (y2 - y1) / (x2 - x1)
|
| 553 |
+
b = y1 - m * x1
|
| 554 |
+
return lambda x: m * x + b
|
| 555 |
+
|
| 556 |
+
def get_schedule(
|
| 557 |
+
num_steps: int,
|
| 558 |
+
image_seq_len: int,
|
| 559 |
+
base_shift: float = 0.5,
|
| 560 |
+
max_shift: float = 1.15,
|
| 561 |
+
shift: bool = True,
|
| 562 |
+
) -> list[float]:
|
| 563 |
timesteps = torch.linspace(1, 0, num_steps + 1)
|
| 564 |
if shift:
|
| 565 |
+
mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
|
| 566 |
+
timesteps = time_shift(mu, 1.0, timesteps)
|
|
|
|
|
|
|
| 567 |
return timesteps.tolist()
|
| 568 |
|
| 569 |
+
def denoise(
|
| 570 |
+
model: Flux,
|
| 571 |
+
img: Tensor,
|
| 572 |
+
img_ids: Tensor,
|
| 573 |
+
txt: Tensor,
|
| 574 |
+
txt_ids: Tensor,
|
| 575 |
+
vec: Tensor,
|
| 576 |
+
timesteps: list[float],
|
| 577 |
+
guidance: float = 4.0,
|
| 578 |
+
):
|
| 579 |
+
guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
|
| 580 |
+
for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
|
| 581 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
| 582 |
pred = model(
|
| 583 |
img=img,
|
| 584 |
img_ids=img_ids,
|
|
|
|
| 591 |
img = img + (t_prev - t_curr) * pred
|
| 592 |
return img
|
| 593 |
|
| 594 |
+
def unpack(x: Tensor, height: int, width: int) -> Tensor:
|
| 595 |
+
return rearrange(
|
| 596 |
+
x,
|
| 597 |
+
"b (h w) (c ph pw) -> b c (h ph) (w pw)",
|
| 598 |
+
h=math.ceil(height / 16),
|
| 599 |
+
w=math.ceil(width / 16),
|
| 600 |
+
ph=2,
|
| 601 |
+
pw=2,
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
@dataclass
|
| 605 |
+
class SamplingOptions:
|
| 606 |
+
prompt: str
|
| 607 |
+
width: int
|
| 608 |
+
height: int
|
| 609 |
+
guidance: float
|
| 610 |
+
seed: int | None
|
| 611 |
+
|
| 612 |
+
def get_image(image) -> torch.Tensor | None:
|
| 613 |
+
if image is None:
|
| 614 |
+
return None
|
| 615 |
+
image = Image.fromarray(image).convert("RGB")
|
| 616 |
+
transform = transforms.Compose([
|
| 617 |
+
transforms.ToTensor(),
|
| 618 |
+
transforms.Lambda(lambda x: 2.0 * x - 1.0),
|
| 619 |
+
])
|
| 620 |
+
img: torch.Tensor = transform(image)
|
| 621 |
+
return img[None, ...]
|
| 622 |
+
|
| 623 |
+
from huggingface_hub import hf_hub_download
|
| 624 |
+
from safetensors.torch import load_file
|
| 625 |
+
|
| 626 |
+
sd = load_file(hf_hub_download(repo_id="lllyasviel/flux1-dev-bnb-nf4", filename="flux1-dev-bnb-nf4-v2.safetensors"))
|
| 627 |
+
sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
|
| 628 |
+
model = Flux().to(dtype=torch.bfloat16, device="cuda")
|
| 629 |
+
result = model.load_state_dict(sd)
|
| 630 |
+
model_zero_init = False
|
| 631 |
|
| 632 |
@spaces.GPU
|
| 633 |
@torch.no_grad()
|
| 634 |
def generate_image(
|
| 635 |
+
prompt, width, height, guidance, inference_steps, seed,
|
| 636 |
+
do_img2img, init_image, image2image_strength, resize_img,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 637 |
progress=gr.Progress(track_tqdm=True),
|
| 638 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
if seed == 0:
|
| 640 |
+
seed = int(random.random() * 1000000)
|
| 641 |
+
|
| 642 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 643 |
+
torch_device = torch.device(device)
|
| 644 |
+
|
| 645 |
+
global model, model_zero_init
|
| 646 |
if not model_zero_init:
|
| 647 |
model = model.to(torch_device)
|
| 648 |
model_zero_init = True
|
| 649 |
+
|
| 650 |
if do_img2img and init_image is not None:
|
| 651 |
+
init_image = get_image(init_image)
|
| 652 |
if resize_img:
|
| 653 |
+
init_image = torch.nn.functional.interpolate(init_image, (height, width))
|
|
|
|
|
|
|
| 654 |
else:
|
| 655 |
+
h, w = init_image.shape[-2:]
|
| 656 |
+
init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
|
| 657 |
+
height = init_image.shape[-2]
|
| 658 |
+
width = init_image.shape[-1]
|
| 659 |
+
init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
|
| 660 |
+
init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
|
| 661 |
+
|
| 662 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 663 |
x = torch.randn(
|
| 664 |
1,
|
| 665 |
16,
|
| 666 |
2 * math.ceil(height / 16),
|
| 667 |
2 * math.ceil(width / 16),
|
| 668 |
+
device=device,
|
| 669 |
dtype=torch.bfloat16,
|
| 670 |
+
generator=generator
|
|
|
|
|
|
|
|
|
|
| 671 |
)
|
| 672 |
+
|
| 673 |
+
num_steps = inference_steps
|
| 674 |
+
timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
|
| 675 |
+
|
| 676 |
+
if do_img2img and init_image is not None:
|
| 677 |
+
t_idx = int((1 - image2image_strength) * num_steps)
|
| 678 |
t = timesteps[t_idx]
|
| 679 |
timesteps = timesteps[t_idx:]
|
| 680 |
+
x = t * x + (1.0 - t) * init_image.to(x.dtype)
|
| 681 |
|
| 682 |
+
inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
|
| 683 |
x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
|
| 684 |
+
x = unpack(x.float(), height, width)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
|
| 686 |
x = (x / ae.config.scaling_factor) + ae.config.shift_factor
|
| 687 |
x = ae.decode(x).sample
|
|
|
|
| 688 |
x = x.clamp(-1, 1)
|
| 689 |
+
x = rearrange(x[0], "c h w -> h w c")
|
| 690 |
+
img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 691 |
return img, seed
|
| 692 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
def create_demo():
|
| 694 |
+
with gr.Blocks(css=".gradio-container {background-color: #282828 !important;}") as demo:
|
| 695 |
+
gr.HTML(
|
| 696 |
+
"""
|
| 697 |
+
<div style="text-align: center; margin: 0 auto;">
|
| 698 |
+
<h1 style="color: #ffffff; font-weight: 900;">
|
| 699 |
+
FluxLLama
|
| 700 |
+
</h1>
|
| 701 |
+
</div>
|
| 702 |
+
"""
|
| 703 |
)
|
| 704 |
with gr.Row():
|
| 705 |
with gr.Column():
|
| 706 |
+
prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")
|
| 707 |
+
width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=640)
|
| 708 |
+
height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=640)
|
| 709 |
+
guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
|
| 710 |
+
inference_steps = gr.Slider(
|
| 711 |
+
label="Inference steps",
|
| 712 |
+
minimum=1,
|
| 713 |
+
maximum=30,
|
| 714 |
+
step=1,
|
| 715 |
+
value=16,
|
|
|
|
|
|
|
|
|
|
| 716 |
)
|
| 717 |
+
seed = gr.Number(label="Seed", precision=-1)
|
| 718 |
+
do_img2img = gr.Checkbox(label="Image to Image", value=False)
|
| 719 |
+
init_image = gr.Image(label="Initial Image", visible=False)
|
| 720 |
+
image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising Strength", value=0.8, visible=False)
|
| 721 |
+
resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
|
| 722 |
+
generate_button = gr.Button("Generate", variant="primary")
|
| 723 |
with gr.Column():
|
| 724 |
+
output_image = gr.Image(label="Result")
|
| 725 |
+
output_seed = gr.Text(label="Seed Used")
|
| 726 |
|
| 727 |
+
do_img2img.change(
|
| 728 |
+
fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
|
| 729 |
+
inputs=[do_img2img],
|
| 730 |
+
outputs=[init_image, image2image_strength, resize_img]
|
| 731 |
)
|
| 732 |
+
|
| 733 |
+
generate_button.click(
|
| 734 |
fn=generate_image,
|
| 735 |
+
inputs=[prompt, width, height, guidance, inference_steps, seed, do_img2img, init_image, image2image_strength, resize_img],
|
| 736 |
+
outputs=[output_image, output_seed]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
)
|
| 738 |
return demo
|
| 739 |
|
| 740 |
if __name__ == "__main__":
|
| 741 |
+
demo = create_demo()
|
| 742 |
+
demo.launch()
|