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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
if os.environ.get("SPACES_ZERO_GPU") is not None:
|
| 3 |
+
import spaces
|
| 4 |
+
else:
|
| 5 |
+
class spaces:
|
| 6 |
+
@staticmethod
|
| 7 |
+
def GPU(func):
|
| 8 |
+
def wrapper(*args, **kwargs):
|
| 9 |
+
return func(*args, **kwargs)
|
| 10 |
+
return wrapper
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
import argparse
|
| 16 |
+
import torch
|
| 17 |
+
import torchvision
|
| 18 |
+
from os import path
|
| 19 |
+
from PIL import Image
|
| 20 |
+
import numpy as np
|
| 21 |
+
import spaces
|
| 22 |
+
import copy
|
| 23 |
+
import random
|
| 24 |
+
import time
|
| 25 |
+
from torchvision import transforms
|
| 26 |
+
from dataclasses import dataclass
|
| 27 |
+
|
| 28 |
+
import math
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 31 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 32 |
+
from diffusers import DiffusionPipeline, AutoencoderTiny, AutoPipelineForImage2Image
|
| 33 |
+
from diffusers.models.transformers import FluxTransformer2DModel
|
| 34 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 35 |
+
import safetensors.torch
|
| 36 |
+
from safetensors.torch import load_file
|
| 37 |
+
import random
|
| 38 |
+
from tqdm import tqdm
|
| 39 |
+
from einops import rearrange, repeat
|
| 40 |
+
from torch import Tensor, nn
|
| 41 |
+
from pipeline import FluxWithCFGPipeline
|
| 42 |
+
from transformers import CLIPModel, CLIPProcessor, CLIPTextModel, CLIPTokenizer, CLIPConfig, T5EncoderModel, T5Tokenizer
|
| 43 |
+
import gc
|
| 44 |
+
import warnings
|
| 45 |
+
model_path = snapshot_download(repo_id="Kijai/OpenFLUX-comfy")
|
| 46 |
+
cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
|
| 47 |
+
os.environ["TRANSFORMERS_CACHE"] = cache_path
|
| 48 |
+
os.environ["HF_HUB_CACHE"] = cache_path
|
| 49 |
+
os.environ["HF_HOME"] = cache_path
|
| 50 |
+
|
| 51 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 52 |
+
|
| 53 |
+
#torch.backends.cuda.matmul.allow_tf32 = True
|
| 54 |
+
|
| 55 |
+
# Load LoRAs from JSON file
|
| 56 |
+
with open('loras.json', 'r') as f:
|
| 57 |
+
loras = json.load(f)
|
| 58 |
+
|
| 59 |
+
dtype = torch.bfloat16
|
| 60 |
+
|
| 61 |
+
#clipmodel = 'norm'
|
| 62 |
+
#if clipmodel == "long":
|
| 63 |
+
# model_id = "zer0int/LongCLIP-GmP-ViT-L-14"
|
| 64 |
+
# config = CLIPConfig.from_pretrained(model_id)
|
| 65 |
+
# maxtokens = 77
|
| 66 |
+
#if clipmodel == "norm":
|
| 67 |
+
# model_id = "zer0int/CLIP-GmP-ViT-L-14"
|
| 68 |
+
# config = CLIPConfig.from_pretrained(model_id)
|
| 69 |
+
# maxtokens = 77
|
| 70 |
+
#clip_model = CLIPModel.from_pretrained(model_id, torch_dtype=torch.bfloat16, config=config, ignore_mismatched_sizes=True).to("cuda")
|
| 71 |
+
#clip_processor = CLIPProcessor.from_pretrained(model_id, padding="max_length", max_length=maxtokens, ignore_mismatched_sizes=True, return_tensors="pt", truncation=True)
|
| 72 |
+
|
| 73 |
+
#pipe.tokenizer = clip_processor.tokenizer
|
| 74 |
+
#pipe.text_encoder = clip_model.text_model
|
| 75 |
+
#pipe.tokenizer_max_length = maxtokens
|
| 76 |
+
#pipe.text_encoder.dtype = torch.bfloat16
|
| 77 |
+
|
| 78 |
+
class HFEmbedder(nn.Module):
|
| 79 |
+
def __init__(self, version: str, max_length: int, **hf_kwargs):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.is_clip = version.startswith("openai")
|
| 82 |
+
self.max_length = max_length
|
| 83 |
+
self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
|
| 84 |
+
|
| 85 |
+
if self.is_clip:
|
| 86 |
+
self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
|
| 87 |
+
self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
|
| 88 |
+
else:
|
| 89 |
+
self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
|
| 90 |
+
self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
|
| 91 |
+
|
| 92 |
+
self.hf_module = self.hf_module.eval().requires_grad_(False)
|
| 93 |
+
|
| 94 |
+
def forward(self, text: list[str]) -> Tensor:
|
| 95 |
+
batch_encoding = self.tokenizer(
|
| 96 |
+
text,
|
| 97 |
+
truncation=True,
|
| 98 |
+
max_length=self.max_length,
|
| 99 |
+
return_length=False,
|
| 100 |
+
return_overflowing_tokens=False,
|
| 101 |
+
padding="max_length",
|
| 102 |
+
return_tensors="pt",
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
outputs = self.hf_module(
|
| 106 |
+
input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
|
| 107 |
+
attention_mask=None,
|
| 108 |
+
output_hidden_states=False,
|
| 109 |
+
)
|
| 110 |
+
return outputs[self.output_key]
|
| 111 |
+
|
| 112 |
+
device = "cuda"
|
| 113 |
+
t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
|
| 114 |
+
clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
|
| 115 |
+
ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
|
| 116 |
+
# quantize(t5, weights=qfloat8)
|
| 117 |
+
# freeze(t5)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ---------------- Model ----------------
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
|
| 124 |
+
q, k = apply_rope(q, k, pe)
|
| 125 |
+
|
| 126 |
+
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
| 127 |
+
# x = rearrange(x, "B H L D -> B L (H D)")
|
| 128 |
+
x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
|
| 129 |
+
|
| 130 |
+
return x
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def rope(pos, dim, theta):
|
| 134 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
| 135 |
+
omega = 1.0 / (theta ** scale)
|
| 136 |
+
|
| 137 |
+
# out = torch.einsum("...n,d->...nd", pos, omega)
|
| 138 |
+
out = pos.unsqueeze(-1) * omega.unsqueeze(0)
|
| 139 |
+
|
| 140 |
+
cos_out = torch.cos(out)
|
| 141 |
+
sin_out = torch.sin(out)
|
| 142 |
+
out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
|
| 143 |
+
|
| 144 |
+
# out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
|
| 145 |
+
b, n, d, _ = out.shape
|
| 146 |
+
out = out.view(b, n, d, 2, 2)
|
| 147 |
+
|
| 148 |
+
return out.float()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
| 152 |
+
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
|
| 153 |
+
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
|
| 154 |
+
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
|
| 155 |
+
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
|
| 156 |
+
return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class EmbedND(nn.Module):
|
| 160 |
+
def __init__(self, dim: int, theta: int, axes_dim: list[int]):
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.dim = dim
|
| 163 |
+
self.theta = theta
|
| 164 |
+
self.axes_dim = axes_dim
|
| 165 |
+
|
| 166 |
+
def forward(self, ids: Tensor) -> Tensor:
|
| 167 |
+
n_axes = ids.shape[-1]
|
| 168 |
+
emb = torch.cat(
|
| 169 |
+
[rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
|
| 170 |
+
dim=-3,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
return emb.unsqueeze(1)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
|
| 177 |
+
"""
|
| 178 |
+
Create sinusoidal timestep embeddings.
|
| 179 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
| 180 |
+
These may be fractional.
|
| 181 |
+
:param dim: the dimension of the output.
|
| 182 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 183 |
+
:return: an (N, D) Tensor of positional embeddings.
|
| 184 |
+
"""
|
| 185 |
+
t = time_factor * t
|
| 186 |
+
half = dim // 2
|
| 187 |
+
|
| 188 |
+
# Do not block CUDA steam, but having about 1e-4 differences with Flux official codes:
|
| 189 |
+
# freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half)
|
| 190 |
+
|
| 191 |
+
# Block CUDA steam, but consistent with official codes:
|
| 192 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
|
| 193 |
+
|
| 194 |
+
args = t[:, None].float() * freqs[None]
|
| 195 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 196 |
+
if dim % 2:
|
| 197 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 198 |
+
if torch.is_floating_point(t):
|
| 199 |
+
embedding = embedding.to(t)
|
| 200 |
+
return embedding
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class MLPEmbedder(nn.Module):
|
| 204 |
+
def __init__(self, in_dim: int, hidden_dim: int):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
|
| 207 |
+
self.silu = nn.SiLU()
|
| 208 |
+
self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
| 209 |
+
|
| 210 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 211 |
+
return self.out_layer(self.silu(self.in_layer(x)))
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class RMSNorm(torch.nn.Module):
|
| 215 |
+
def __init__(self, dim: int):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
| 218 |
+
|
| 219 |
+
def forward(self, x: Tensor):
|
| 220 |
+
x_dtype = x.dtype
|
| 221 |
+
x = x.float()
|
| 222 |
+
rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
|
| 223 |
+
return (x * rrms).to(dtype=x_dtype) * self.scale
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class QKNorm(torch.nn.Module):
|
| 227 |
+
def __init__(self, dim: int):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.query_norm = RMSNorm(dim)
|
| 230 |
+
self.key_norm = RMSNorm(dim)
|
| 231 |
+
|
| 232 |
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
|
| 233 |
+
q = self.query_norm(q)
|
| 234 |
+
k = self.key_norm(k)
|
| 235 |
+
return q.to(v), k.to(v)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class SelfAttention(nn.Module):
|
| 239 |
+
def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
|
| 240 |
+
super().__init__()
|
| 241 |
+
self.num_heads = num_heads
|
| 242 |
+
head_dim = dim // num_heads
|
| 243 |
+
|
| 244 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 245 |
+
self.norm = QKNorm(head_dim)
|
| 246 |
+
self.proj = nn.Linear(dim, dim)
|
| 247 |
+
|
| 248 |
+
def forward(self, x: Tensor, pe: Tensor) -> Tensor:
|
| 249 |
+
qkv = self.qkv(x)
|
| 250 |
+
# q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
| 251 |
+
B, L, _ = qkv.shape
|
| 252 |
+
qkv = qkv.view(B, L, 3, self.num_heads, -1)
|
| 253 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
| 254 |
+
q, k = self.norm(q, k, v)
|
| 255 |
+
x = attention(q, k, v, pe=pe)
|
| 256 |
+
x = self.proj(x)
|
| 257 |
+
return x
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@dataclass
|
| 261 |
+
class ModulationOut:
|
| 262 |
+
shift: Tensor
|
| 263 |
+
scale: Tensor
|
| 264 |
+
gate: Tensor
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class Modulation(nn.Module):
|
| 268 |
+
def __init__(self, dim: int, double: bool):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.is_double = double
|
| 271 |
+
self.multiplier = 6 if double else 3
|
| 272 |
+
self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
|
| 273 |
+
|
| 274 |
+
def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
|
| 275 |
+
out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
|
| 276 |
+
|
| 277 |
+
return (
|
| 278 |
+
ModulationOut(*out[:3]),
|
| 279 |
+
ModulationOut(*out[3:]) if self.is_double else None,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class DoubleStreamBlock(nn.Module):
|
| 284 |
+
def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
|
| 285 |
+
super().__init__()
|
| 286 |
+
|
| 287 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 288 |
+
self.num_heads = num_heads
|
| 289 |
+
self.hidden_size = hidden_size
|
| 290 |
+
self.img_mod = Modulation(hidden_size, double=True)
|
| 291 |
+
self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 292 |
+
self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
| 293 |
+
|
| 294 |
+
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 295 |
+
self.img_mlp = nn.Sequential(
|
| 296 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
| 297 |
+
nn.GELU(approximate="tanh"),
|
| 298 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
self.txt_mod = Modulation(hidden_size, double=True)
|
| 302 |
+
self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 303 |
+
self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
| 304 |
+
|
| 305 |
+
self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 306 |
+
self.txt_mlp = nn.Sequential(
|
| 307 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
| 308 |
+
nn.GELU(approximate="tanh"),
|
| 309 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
|
| 313 |
+
img_mod1, img_mod2 = self.img_mod(vec)
|
| 314 |
+
txt_mod1, txt_mod2 = self.txt_mod(vec)
|
| 315 |
+
|
| 316 |
+
# prepare image for attention
|
| 317 |
+
img_modulated = self.img_norm1(img)
|
| 318 |
+
img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
|
| 319 |
+
img_qkv = self.img_attn.qkv(img_modulated)
|
| 320 |
+
# img_q, img_k, img_v = rearrange(img_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
| 321 |
+
B, L, _ = img_qkv.shape
|
| 322 |
+
H = self.num_heads
|
| 323 |
+
D = img_qkv.shape[-1] // (3 * H)
|
| 324 |
+
img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
| 325 |
+
img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
|
| 326 |
+
|
| 327 |
+
# prepare txt for attention
|
| 328 |
+
txt_modulated = self.txt_norm1(txt)
|
| 329 |
+
txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
|
| 330 |
+
txt_qkv = self.txt_attn.qkv(txt_modulated)
|
| 331 |
+
# txt_q, txt_k, txt_v = rearrange(txt_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
| 332 |
+
B, L, _ = txt_qkv.shape
|
| 333 |
+
txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
| 334 |
+
txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
|
| 335 |
+
|
| 336 |
+
# run actual attention
|
| 337 |
+
q = torch.cat((txt_q, img_q), dim=2)
|
| 338 |
+
k = torch.cat((txt_k, img_k), dim=2)
|
| 339 |
+
v = torch.cat((txt_v, img_v), dim=2)
|
| 340 |
+
|
| 341 |
+
attn = attention(q, k, v, pe=pe)
|
| 342 |
+
txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
|
| 343 |
+
|
| 344 |
+
# calculate the img bloks
|
| 345 |
+
img = img + img_mod1.gate * self.img_attn.proj(img_attn)
|
| 346 |
+
img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
|
| 347 |
+
|
| 348 |
+
# calculate the txt bloks
|
| 349 |
+
txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
|
| 350 |
+
txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
|
| 351 |
+
return img, txt
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
class SingleStreamBlock(nn.Module):
|
| 355 |
+
"""
|
| 356 |
+
A DiT block with parallel linear layers as described in
|
| 357 |
+
https://arxiv.org/abs/2302.05442 and adapted modulation interface.
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
def __init__(
|
| 361 |
+
self,
|
| 362 |
+
hidden_size: int,
|
| 363 |
+
num_heads: int,
|
| 364 |
+
mlp_ratio: float = 4.0,
|
| 365 |
+
qk_scale: float | None = None,
|
| 366 |
+
):
|
| 367 |
+
super().__init__()
|
| 368 |
+
self.hidden_dim = hidden_size
|
| 369 |
+
self.num_heads = num_heads
|
| 370 |
+
head_dim = hidden_size // num_heads
|
| 371 |
+
self.scale = qk_scale or head_dim**-0.5
|
| 372 |
+
|
| 373 |
+
self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 374 |
+
# qkv and mlp_in
|
| 375 |
+
self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
|
| 376 |
+
# proj and mlp_out
|
| 377 |
+
self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
|
| 378 |
+
|
| 379 |
+
self.norm = QKNorm(head_dim)
|
| 380 |
+
|
| 381 |
+
self.hidden_size = hidden_size
|
| 382 |
+
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 383 |
+
|
| 384 |
+
self.mlp_act = nn.GELU(approximate="tanh")
|
| 385 |
+
self.modulation = Modulation(hidden_size, double=False)
|
| 386 |
+
|
| 387 |
+
def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
|
| 388 |
+
mod, _ = self.modulation(vec)
|
| 389 |
+
x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
|
| 390 |
+
qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
|
| 391 |
+
|
| 392 |
+
# q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
| 393 |
+
qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
|
| 394 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
| 395 |
+
q, k = self.norm(q, k, v)
|
| 396 |
+
|
| 397 |
+
# compute attention
|
| 398 |
+
attn = attention(q, k, v, pe=pe)
|
| 399 |
+
# compute activation in mlp stream, cat again and run second linear layer
|
| 400 |
+
output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
|
| 401 |
+
return x + mod.gate * output
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class LastLayer(nn.Module):
|
| 405 |
+
def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
|
| 406 |
+
super().__init__()
|
| 407 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
| 408 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
| 409 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
|
| 410 |
+
|
| 411 |
+
def forward(self, x: Tensor, vec: Tensor) -> Tensor:
|
| 412 |
+
shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
|
| 413 |
+
x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
|
| 414 |
+
x = self.linear(x)
|
| 415 |
+
return x
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class FluxParams:
|
| 419 |
+
in_channels: int = 64
|
| 420 |
+
vec_in_dim: int = 768
|
| 421 |
+
context_in_dim: int = 4096
|
| 422 |
+
hidden_size: int = 3072
|
| 423 |
+
mlp_ratio: float = 4.0
|
| 424 |
+
num_heads: int = 24
|
| 425 |
+
depth: int = 19
|
| 426 |
+
depth_single_blocks: int = 38
|
| 427 |
+
axes_dim: list = [16, 56, 56]
|
| 428 |
+
theta: int = 10_000
|
| 429 |
+
qkv_bias: bool = True
|
| 430 |
+
guidance_embed: bool = True
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class Flux(nn.Module):
|
| 434 |
+
"""
|
| 435 |
+
Transformer model for flow matching on sequences.
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
def __init__(self, params = FluxParams()):
|
| 439 |
+
super().__init__()
|
| 440 |
+
|
| 441 |
+
self.params = params
|
| 442 |
+
self.in_channels = params.in_channels
|
| 443 |
+
self.out_channels = self.in_channels
|
| 444 |
+
if params.hidden_size % params.num_heads != 0:
|
| 445 |
+
raise ValueError(
|
| 446 |
+
f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
|
| 447 |
+
)
|
| 448 |
+
pe_dim = params.hidden_size // params.num_heads
|
| 449 |
+
if sum(params.axes_dim) != pe_dim:
|
| 450 |
+
raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
|
| 451 |
+
self.hidden_size = params.hidden_size
|
| 452 |
+
self.num_heads = params.num_heads
|
| 453 |
+
self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
|
| 454 |
+
self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
|
| 455 |
+
self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
|
| 456 |
+
self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
|
| 457 |
+
# self.guidance_in = (
|
| 458 |
+
# MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
|
| 459 |
+
# )
|
| 460 |
+
self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
|
| 461 |
+
|
| 462 |
+
self.double_blocks = nn.ModuleList(
|
| 463 |
+
[
|
| 464 |
+
DoubleStreamBlock(
|
| 465 |
+
self.hidden_size,
|
| 466 |
+
self.num_heads,
|
| 467 |
+
mlp_ratio=params.mlp_ratio,
|
| 468 |
+
qkv_bias=params.qkv_bias,
|
| 469 |
+
)
|
| 470 |
+
for _ in range(params.depth)
|
| 471 |
+
]
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
self.single_blocks = nn.ModuleList(
|
| 475 |
+
[
|
| 476 |
+
SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
|
| 477 |
+
for _ in range(params.depth_single_blocks)
|
| 478 |
+
]
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
|
| 482 |
+
|
| 483 |
+
def forward(
|
| 484 |
+
self,
|
| 485 |
+
img: Tensor,
|
| 486 |
+
img_ids: Tensor,
|
| 487 |
+
txt: Tensor,
|
| 488 |
+
txt_ids: Tensor,
|
| 489 |
+
timesteps: Tensor,
|
| 490 |
+
y: Tensor,
|
| 491 |
+
guidance: Tensor | None = None,
|
| 492 |
+
use_guidance_vec = True,
|
| 493 |
+
) -> Tensor:
|
| 494 |
+
if img.ndim != 3 or txt.ndim != 3:
|
| 495 |
+
raise ValueError("Input img and txt tensors must have 3 dimensions.")
|
| 496 |
+
|
| 497 |
+
# running on sequences img
|
| 498 |
+
img = self.img_in(img)
|
| 499 |
+
vec = self.time_in(timestep_embedding(timesteps, 256))
|
| 500 |
+
# if self.params.guidance_embed and use_guidance_vec:
|
| 501 |
+
# if guidance is None:
|
| 502 |
+
# raise ValueError("Didn't get guidance strength for guidance distilled model.")
|
| 503 |
+
# vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
|
| 504 |
+
vec = vec + self.vector_in(y)
|
| 505 |
+
txt = self.txt_in(txt)
|
| 506 |
+
|
| 507 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
| 508 |
+
pe = self.pe_embedder(ids)
|
| 509 |
+
|
| 510 |
+
for block in self.double_blocks:
|
| 511 |
+
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
|
| 512 |
+
|
| 513 |
+
img = torch.cat((txt, img), 1)
|
| 514 |
+
for block in self.single_blocks:
|
| 515 |
+
img = block(img, vec=vec, pe=pe)
|
| 516 |
+
img = img[:, txt.shape[1] :, ...]
|
| 517 |
+
|
| 518 |
+
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
|
| 519 |
+
return img
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
|
| 523 |
+
bs, c, h, w = img.shape
|
| 524 |
+
if bs == 1 and not isinstance(prompt, str):
|
| 525 |
+
bs = len(prompt)
|
| 526 |
+
|
| 527 |
+
img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
|
| 528 |
+
if img.shape[0] == 1 and bs > 1:
|
| 529 |
+
img = repeat(img, "1 ... -> bs ...", bs=bs)
|
| 530 |
+
|
| 531 |
+
img_ids = torch.zeros(h // 2, w // 2, 3)
|
| 532 |
+
img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
|
| 533 |
+
img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
|
| 534 |
+
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
|
| 535 |
+
|
| 536 |
+
if isinstance(prompt, str):
|
| 537 |
+
prompt = [prompt]
|
| 538 |
+
txt = t5(prompt)
|
| 539 |
+
if txt.shape[0] == 1 and bs > 1:
|
| 540 |
+
txt = repeat(txt, "1 ... -> bs ...", bs=bs)
|
| 541 |
+
txt_ids = torch.zeros(bs, txt.shape[1], 3)
|
| 542 |
+
|
| 543 |
+
vec = clip(prompt)
|
| 544 |
+
if vec.shape[0] == 1 and bs > 1:
|
| 545 |
+
vec = repeat(vec, "1 ... -> bs ...", bs=bs)
|
| 546 |
+
|
| 547 |
+
return {
|
| 548 |
+
"img": img,
|
| 549 |
+
"img_ids": img_ids.to(img.device),
|
| 550 |
+
"txt": txt.to(img.device),
|
| 551 |
+
"txt_ids": txt_ids.to(img.device),
|
| 552 |
+
"vec": vec.to(img.device),
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def time_shift(mu: float, sigma: float, t: Tensor):
|
| 557 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def get_lin_function(
|
| 561 |
+
x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
|
| 562 |
+
) -> Callable[[float], float]:
|
| 563 |
+
m = (y2 - y1) / (x2 - x1)
|
| 564 |
+
b = y1 - m * x1
|
| 565 |
+
return lambda x: m * x + b
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def get_schedule(
|
| 569 |
+
num_steps: int,
|
| 570 |
+
image_seq_len: int,
|
| 571 |
+
base_shift: float = 0.5,
|
| 572 |
+
max_shift: float = 1.15,
|
| 573 |
+
shift: bool = True,
|
| 574 |
+
) -> list[float]:
|
| 575 |
+
# extra step for zero
|
| 576 |
+
timesteps = torch.linspace(1, 0, num_steps + 1)
|
| 577 |
+
|
| 578 |
+
# shifting the schedule to favor high timesteps for higher signal images
|
| 579 |
+
if shift:
|
| 580 |
+
# eastimate mu based on linear estimation between two points
|
| 581 |
+
mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
|
| 582 |
+
timesteps = time_shift(mu, 1.0, timesteps)
|
| 583 |
+
|
| 584 |
+
return timesteps.tolist()
|
| 585 |
+
|
| 586 |
+
@property
|
| 587 |
+
def joint_attention_kwargs(self):
|
| 588 |
+
return self._joint_attention_kwargs
|
| 589 |
+
|
| 590 |
+
def denoise(
|
| 591 |
+
model: Flux,
|
| 592 |
+
# model input
|
| 593 |
+
img: Tensor,
|
| 594 |
+
img_ids: Tensor,
|
| 595 |
+
txt: Tensor,
|
| 596 |
+
txt_ids: Tensor,
|
| 597 |
+
vec: Tensor,
|
| 598 |
+
# sampling parameters
|
| 599 |
+
timesteps: list[float],
|
| 600 |
+
guidance: float = 4.0,
|
| 601 |
+
use_cfg_guidance = False,
|
| 602 |
+
):
|
| 603 |
+
# this is ignored for schnell
|
| 604 |
+
guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
|
| 605 |
+
for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:])):
|
| 606 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
| 607 |
+
|
| 608 |
+
if use_cfg_guidance:
|
| 609 |
+
half_x = img[:len(img)//2]
|
| 610 |
+
img = torch.cat([half_x, half_x], dim=0)
|
| 611 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
| 612 |
+
|
| 613 |
+
pred = model(
|
| 614 |
+
img=img,
|
| 615 |
+
img_ids=img_ids,
|
| 616 |
+
txt=txt,
|
| 617 |
+
txt_ids=txt_ids,
|
| 618 |
+
y=vec,
|
| 619 |
+
timesteps=t_vec,
|
| 620 |
+
guidance=guidance_vec,
|
| 621 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 622 |
+
use_guidance_vec=not use_cfg_guidance,
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
if use_cfg_guidance:
|
| 626 |
+
uncond, cond = pred.chunk(2, dim=0)
|
| 627 |
+
model_output = uncond + guidance * (cond - uncond)
|
| 628 |
+
pred = torch.cat([model_output, model_output], dim=0)
|
| 629 |
+
|
| 630 |
+
img = img + (t_prev - t_curr) * pred
|
| 631 |
+
|
| 632 |
+
return img
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def unpack(x: Tensor, height: int, width: int) -> Tensor:
|
| 636 |
+
return rearrange(
|
| 637 |
+
x,
|
| 638 |
+
"b (h w) (c ph pw) -> b c (h ph) (w pw)",
|
| 639 |
+
h=math.ceil(height / 16),
|
| 640 |
+
w=math.ceil(width / 16),
|
| 641 |
+
ph=2,
|
| 642 |
+
pw=2,
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
@dataclass
|
| 646 |
+
class SamplingOptions:
|
| 647 |
+
prompt: str
|
| 648 |
+
width: int
|
| 649 |
+
height: int
|
| 650 |
+
guidance: float
|
| 651 |
+
seed: int | None
|
| 652 |
+
joint_attention_kwargs: InitVar[Dict[str, Any]] | None
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def get_image(image) -> torch.Tensor | None:
|
| 656 |
+
if image is None:
|
| 657 |
+
return None
|
| 658 |
+
image = Image.fromarray(image).convert("RGB")
|
| 659 |
+
|
| 660 |
+
transform = transforms.Compose([
|
| 661 |
+
transforms.ToTensor(),
|
| 662 |
+
transforms.Lambda(lambda x: 2.0 * x - 1.0),
|
| 663 |
+
])
|
| 664 |
+
img: torch.Tensor = transform(image)
|
| 665 |
+
return img[None, ...]
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
# ---------------- Demo ----------------
|
| 669 |
+
|
| 670 |
+
class EmptyInitWrapper(torch.overrides.TorchFunctionMode):
|
| 671 |
+
def __init__(self, device=None):
|
| 672 |
+
self.device = device
|
| 673 |
+
|
| 674 |
+
def __torch_function__(self, func, types, args=(), kwargs=None):
|
| 675 |
+
kwargs = kwargs or {}
|
| 676 |
+
if getattr(func, "__module__", None) == "torch.nn.init":
|
| 677 |
+
if "tensor" in kwargs:
|
| 678 |
+
return kwargs["tensor"]
|
| 679 |
+
else:
|
| 680 |
+
return args[0]
|
| 681 |
+
if (
|
| 682 |
+
self.device is not None
|
| 683 |
+
and func in torch.utils._device._device_constructors()
|
| 684 |
+
and kwargs.get("device") is None
|
| 685 |
+
):
|
| 686 |
+
kwargs["device"] = self.device
|
| 687 |
+
return func(*args, **kwargs)
|
| 688 |
+
|
| 689 |
+
with EmptyInitWrapper():
|
| 690 |
+
model = Flux().to(dtype=torch.bfloat16, device="cuda")
|
| 691 |
+
|
| 692 |
+
sd = load_file(f"{model_path}/OpenFlux-fp8_e4m3fn.safetensors")
|
| 693 |
+
sd = {k.replace("model.", ""): v for k, v in sd.items()}
|
| 694 |
+
result = model.load_state_dict(sd)
|
| 695 |
+
|
| 696 |
+
@torch.cuda.empty_cache()
|
| 697 |
+
|
| 698 |
+
@spaces.GPU(duration=70)
|
| 699 |
+
@torch.no_grad()
|
| 700 |
+
def generate_image(
|
| 701 |
+
prompt, neg_prompt, num_steps, width, height, guidance, seed,
|
| 702 |
+
do_img2img, init_image, image2image_strength, resize_img, lora_scale,
|
| 703 |
+
progress=gr.Progress(track_tqdm=True),
|
| 704 |
+
):
|
| 705 |
+
if seed == 0:
|
| 706 |
+
seed = int(random.random() * 1000000)
|
| 707 |
+
|
| 708 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 709 |
+
torch_device = torch.device(device)
|
| 710 |
+
|
| 711 |
+
lora_scale = (self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None)
|
| 712 |
+
|
| 713 |
+
if do_img2img and init_image is not None:
|
| 714 |
+
init_image = get_image(init_image)
|
| 715 |
+
if resize_img:
|
| 716 |
+
init_image = torch.nn.functional.interpolate(init_image, (height, width))
|
| 717 |
+
else:
|
| 718 |
+
h, w = init_image.shape[-2:]
|
| 719 |
+
init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
|
| 720 |
+
height = init_image.shape[-2]
|
| 721 |
+
width = init_image.shape[-1]
|
| 722 |
+
init_image = ae.encode(init_image.to(torch_device)).latent_dist.sample()
|
| 723 |
+
init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
|
| 724 |
+
|
| 725 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 726 |
+
x = torch.randn(1, 16, 2 * math.ceil(height / 16), 2 * math.ceil(width / 16), device=device, dtype=torch.bfloat16, generator=generator)
|
| 727 |
+
|
| 728 |
+
with calculateDuration("Generating image"):
|
| 729 |
+
# Generate image
|
| 730 |
+
image = pipe(
|
| 731 |
+
prompt=f"{prompt} {trigger_word}",
|
| 732 |
+
neg_prompt=negative_prompt,
|
| 733 |
+
num_steps=steps,
|
| 734 |
+
guidance=cfg_scale,
|
| 735 |
+
width=width,
|
| 736 |
+
height=height,
|
| 737 |
+
generator=generator,
|
| 738 |
+
do_img2img=img2img,
|
| 739 |
+
init_image=upload_image,
|
| 740 |
+
image2image_strength=image2image_strength,
|
| 741 |
+
resize_img=resize_img,
|
| 742 |
+
joint_attention_kwargs={"scale": lora_scale},
|
| 743 |
+
).images[0]
|
| 744 |
+
return image
|
| 745 |
+
|
| 746 |
+
# num_steps = 28
|
| 747 |
+
timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
|
| 748 |
+
|
| 749 |
+
if do_img2img and init_image is not None:
|
| 750 |
+
t_idx = int((1 - image2image_strength) * num_steps)
|
| 751 |
+
t = timesteps[t_idx]
|
| 752 |
+
timesteps = timesteps[t_idx:]
|
| 753 |
+
x = t * x + (1.0 - t) * init_image.to(x.dtype)
|
| 754 |
+
|
| 755 |
+
inp = prepare(t5=t5, clip=clip, img=x, prompt=[neg_prompt, prompt])
|
| 756 |
+
x = denoise(model, **inp, timesteps=timesteps, guidance=guidance, use_cfg_guidance=True, lora_scale=)
|
| 757 |
+
|
| 758 |
+
# with profile(activities=[ProfilerActivity.CPU],record_shapes=True,profile_memory=True) as prof:
|
| 759 |
+
# print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=20))
|
| 760 |
+
|
| 761 |
+
x = unpack(x.float(), height, width)
|
| 762 |
+
with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
|
| 763 |
+
x = x = (x / ae.config.scaling_factor) + ae.config.shift_factor
|
| 764 |
+
x = ae.decode(x).sample
|
| 765 |
+
|
| 766 |
+
x = x.clamp(-1, 1)
|
| 767 |
+
x = rearrange(x[0], "c h w -> h w c")
|
| 768 |
+
img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
|
| 769 |
+
|
| 770 |
+
return img, seed
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
@torch.cuda.empty_cache()
|
| 774 |
+
|
| 775 |
+
class calculateDuration:
|
| 776 |
+
def __init__(self, activity_name=""):
|
| 777 |
+
self.activity_name = activity_name
|
| 778 |
+
|
| 779 |
+
def __enter__(self):
|
| 780 |
+
self.start_time = time.time()
|
| 781 |
+
return self
|
| 782 |
+
|
| 783 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 784 |
+
self.end_time = time.time()
|
| 785 |
+
self.elapsed_time = self.end_time - self.start_time
|
| 786 |
+
if self.activity_name:
|
| 787 |
+
print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
|
| 788 |
+
else:
|
| 789 |
+
print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def update_selection(evt: gr.SelectData, width, height):
|
| 793 |
+
selected_lora = loras[evt.index]
|
| 794 |
+
new_placeholder = f"Type a prompt for {selected_lora['title']}"
|
| 795 |
+
lora_repo = selected_lora["repo"]
|
| 796 |
+
updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
|
| 797 |
+
if "aspect" in selected_lora:
|
| 798 |
+
if selected_lora["aspect"] == "portrait":
|
| 799 |
+
width = 768
|
| 800 |
+
height = 1024
|
| 801 |
+
elif selected_lora["aspect"] == "landscape":
|
| 802 |
+
width = 1024
|
| 803 |
+
height = 768
|
| 804 |
+
return (
|
| 805 |
+
gr.update(placeholder=new_placeholder),
|
| 806 |
+
updated_text,
|
| 807 |
+
evt.index,
|
| 808 |
+
width,
|
| 809 |
+
height,
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, negative_prompt, lora_scale, progress=gr.Progress(track_tqdm=True)):
|
| 813 |
+
if negative_prompt == "":
|
| 814 |
+
negative_prompt = None
|
| 815 |
+
if selected_index is None:
|
| 816 |
+
raise gr.Error("You must select a LoRA before proceeding.")
|
| 817 |
+
|
| 818 |
+
selected_lora = loras[selected_index]
|
| 819 |
+
lora_path = selected_lora["repo"]
|
| 820 |
+
trigger_word = selected_lora["trigger_word"]
|
| 821 |
+
|
| 822 |
+
# Load LoRA weights
|
| 823 |
+
with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
|
| 824 |
+
if "weights" in selected_lora:
|
| 825 |
+
pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
|
| 826 |
+
else:
|
| 827 |
+
pipe.load_lora_weights(lora_path)
|
| 828 |
+
|
| 829 |
+
# Set random seed for reproducibility
|
| 830 |
+
with calculateDuration("Randomizing seed"):
|
| 831 |
+
if randomize_seed:
|
| 832 |
+
seed = random.randint(0, 2**32-1)
|
| 833 |
+
|
| 834 |
+
image = generate_image(prompt, trigger_word, steps, seed, cfg_scale, width, height, negative_prompt, lora_scale, progress)
|
| 835 |
+
pipe.to("cpu")
|
| 836 |
+
pipe.unload_lora_weights()
|
| 837 |
+
return image, seed
|
| 838 |
+
|
| 839 |
+
run_lora.zerogpu = True
|
| 840 |
+
|
| 841 |
+
css = '''
|
| 842 |
+
#gen_btn{height: 100%}
|
| 843 |
+
#title{text-align: center}
|
| 844 |
+
#title h1{font-size: 3em; display:inline-flex; align-items:center}
|
| 845 |
+
#title img{width: 100px; margin-right: 0.5em}
|
| 846 |
+
#gallery .grid-wrap{height: 10vh}
|
| 847 |
+
'''
|
| 848 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=css) as app:
|
| 849 |
+
title = gr.HTML(
|
| 850 |
+
"""<h1><img src="https://huggingface.co/AlekseyCalvin/HSTklimbimOPENfluxLora/resolve/main/acs62iv.png" alt="LoRA">OpenFlux LoRAsoon®</h1>""",
|
| 851 |
+
elem_id="title",
|
| 852 |
+
)
|
| 853 |
+
# Info blob stating what the app is running
|
| 854 |
+
info_blob = gr.HTML(
|
| 855 |
+
"""<div id="info_blob"> SOON®'s curated LoRa Gallery & Art Manufactory Space.|Runs on Ostris' OpenFLUX.1 model + fast-gen LoRA & Zer0int's fine-tuned CLIP-GmP-ViT-L-14*! (*'normal' 77 tokens)| Largely stocked w/our trained LoRAs: Historic Color, Silver Age Poets, Sots Art, more!|</div>"""
|
| 856 |
+
)
|
| 857 |
+
# Info blob stating what the app is running
|
| 858 |
+
info_blob = gr.HTML(
|
| 859 |
+
"""<div id="info_blob"> *Auto-planting of prompts with a choice LoRA trigger errors out in this space over flaws yet unclear. In its stead, we pose numbered LoRA-box rows & a matched token cheat-sheet: ungainly & free. So, prephrase your prompts w/: 1-2. HST style autochrome |3. RCA style Communist poster |4. SOTS art |5. HST Austin Osman Spare style |6. Vladimir Mayakovsky |7-8. Marina Tsvetaeva Tsvetaeva_02.CR2 |9. Anna Akhmatova |10. Osip Mandelshtam |11-12. Alexander Blok |13. Blok_02.CR2 |14. LEN Lenin |15. Leon Trotsky |16. Rosa Fluxemburg |17. HST Peterhof photo |18-19. HST |20. HST portrait |21. HST |22. HST 80s Perestroika-era Soviet photo |23-30. HST |31. How2Draw a__ |32. propaganda poster |33. TOK hybrid photo of__ with cartoon of__ |34. 2004 IMG_1099.CR2 photo |35. unexpected photo of |36. flmft |37. 80s yearbook photo |38. TOK portra |39. pficonics |40. retrofuturism |41. wh3r3sw4ld0 |42. amateur photo |43. crisp |44-45. IMG_1099.CR2 |46. FilmFotos |47. ff-collage |48. HST |49-50. AOS |51. cover </div>"""
|
| 860 |
+
)
|
| 861 |
+
selected_index = gr.State(None)
|
| 862 |
+
with gr.Row():
|
| 863 |
+
with gr.Column(scale=3):
|
| 864 |
+
prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Select LoRa/Style & type prompt!")
|
| 865 |
+
with gr.Row():
|
| 866 |
+
with gr.Column(scale=3):
|
| 867 |
+
negative_prompt = gr.Textbox(label="Negative Prompt", lines=1, placeholder="List unwanted conditions, open-fluxedly!")
|
| 868 |
+
with gr.Column(scale=1, elem_id="gen_column"):
|
| 869 |
+
generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
|
| 870 |
+
with gr.Row():
|
| 871 |
+
with gr.Column(scale=3):
|
| 872 |
+
selected_info = gr.Markdown("")
|
| 873 |
+
gallery = gr.Gallery(
|
| 874 |
+
[(item["image"], item["title"]) for item in loras],
|
| 875 |
+
label="LoRA Inventory",
|
| 876 |
+
allow_preview=False,
|
| 877 |
+
columns=3,
|
| 878 |
+
elem_id="gallery"
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
with gr.Column(scale=4):
|
| 882 |
+
result = gr.Image(label="Generated Image")
|
| 883 |
+
|
| 884 |
+
with gr.Row():
|
| 885 |
+
with gr.Accordion("Advanced Settings", open=True):
|
| 886 |
+
with gr.Column():
|
| 887 |
+
with gr.Row():
|
| 888 |
+
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=1, value=3)
|
| 889 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=6)
|
| 890 |
+
|
| 891 |
+
with gr.Row():
|
| 892 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=768)
|
| 893 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=768)
|
| 894 |
+
|
| 895 |
+
with gr.Row():
|
| 896 |
+
randomize_seed = gr.Checkbox(True, label="Randomize seed")
|
| 897 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=2**32-1, step=1, value=0, randomize=True)
|
| 898 |
+
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=1, step=0.01, value=0.95)
|
| 899 |
+
|
| 900 |
+
gallery.select(
|
| 901 |
+
update_selection,
|
| 902 |
+
inputs=[width, height],
|
| 903 |
+
outputs=[prompt, selected_info, selected_index, width, height]
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
gr.on(
|
| 907 |
+
triggers=[generate_button.click, prompt.submit],
|
| 908 |
+
fn=run_lora,
|
| 909 |
+
inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, negative_prompt, lora_scale],
|
| 910 |
+
outputs=[result, seed]
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 914 |
+
app.queue(default_concurrency_limit=2).launch(show_error=True)
|
| 915 |
+
app.launch()
|