ginipick commited on
Commit
2e93fe1
·
verified ·
1 Parent(s): 2ef7034

Delete app.py

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