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