ginipick commited on
Commit
8398621
·
verified ·
1 Parent(s): 374614c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -837
app.py CHANGED
@@ -1,854 +1,166 @@
 
 
 
1
  import os
2
- import sys
3
-
4
- # Disable bitsandbytes triton integration to avoid conflicts
5
- os.environ["BITSANDBYTES_NOWELCOME"] = "1"
6
- os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
7
-
8
- # Try to handle spaces import gracefully
9
- try:
10
- import spaces
11
- SPACES_AVAILABLE = True
12
- except Exception as e:
13
- print(f"Warning: Could not import spaces: {e}")
14
- SPACES_AVAILABLE = False
15
- # Create a dummy decorator if spaces is not available
16
- class spaces:
17
- @staticmethod
18
- def GPU(duration=None):
19
- def decorator(func):
20
- return func
21
- return decorator
22
-
23
  import time
24
- import gradio as gr
25
  import torch
26
- from PIL import Image
27
- from torchvision import transforms
28
- from dataclasses import dataclass, field
29
- import math
30
- from typing import Callable
31
-
32
- from tqdm import tqdm
33
- import random
34
- from einops import rearrange, repeat
35
- from diffusers import AutoencoderKL
36
- from torch import Tensor, nn
37
- from transformers import CLIPTextModel, CLIPTokenizer
38
- from transformers import T5EncoderModel, T5Tokenizer
39
-
40
- # Import bitsandbytes after spaces to avoid conflicts
41
- try:
42
- import bitsandbytes as bnb
43
- from bitsandbytes.nn.modules import Params4bit, QuantState
44
- BNB_AVAILABLE = True
45
- except Exception as e:
46
- print(f"Warning: Could not import bitsandbytes: {e}")
47
- BNB_AVAILABLE = False
48
-
49
- # Store original Linear class before any modifications
50
- original_linear = nn.Linear
51
-
52
- # Disable BNB for now due to compatibility issues
53
- BNB_AVAILABLE = False
54
- print("Note: BitsAndBytes quantization disabled for compatibility")
55
-
56
- # ---------------- Encoders ----------------
57
-
58
- class HFEmbedder(nn.Module):
59
- def __init__(self, version: str, max_length: int, **hf_kwargs):
60
- super().__init__()
61
- self.is_clip = version.startswith("openai")
62
- self.max_length = max_length
63
- self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
64
-
65
- if self.is_clip:
66
- self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
67
- self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
68
- else:
69
- self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
70
- self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
71
-
72
- self.hf_module = self.hf_module.eval().requires_grad_(False)
73
-
74
- def forward(self, text: list[str]) -> Tensor:
75
- batch_encoding = self.tokenizer(
76
- text,
77
- truncation=True,
78
- max_length=self.max_length,
79
- return_length=False,
80
- return_overflowing_tokens=False,
81
- padding="max_length",
82
- return_tensors="pt",
83
- )
84
-
85
- outputs = self.hf_module(
86
- input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
87
- attention_mask=None,
88
- output_hidden_states=False,
89
  )
90
- return outputs[self.output_key]
91
-
92
- # Initialize models without GPU decorator first
93
- t5 = None
94
- clip = None
95
- ae = None
96
- model = None
97
- model_initialized = False
98
-
99
- def initialize_models():
100
- global t5, clip, ae, model, model_initialized
101
- if not model_initialized:
102
- print("Initializing models...")
103
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
104
 
105
- # Load standard models
106
- print("Loading T5 encoder...")
107
- t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
108
- t5 = t5.to(device)
 
 
 
 
 
109
 
110
- print("Loading CLIP encoder...")
111
- clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
112
- clip = clip.to(device)
113
 
114
- print("Loading VAE...")
115
- ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
116
- ae = ae.to(device)
117
 
118
- print("Loading Flux model...")
119
- from huggingface_hub import hf_hub_download
120
- from safetensors.torch import load_file
 
121
 
122
- try:
123
- # Try to load from a standard Flux checkpoint
124
- # First, let's try the schnell version which might be smaller
125
- print("Attempting to load Flux model weights...")
126
- model = Flux()
127
-
128
- # Try loading from black-forest-labs directly
129
- try:
130
- # Note: You might need to authenticate with HuggingFace for this
131
- sd = load_file(hf_hub_download(repo_id="black-forest-labs/FLUX.1-schnell", filename="flux1-schnell.safetensors"))
132
- # Adjust state dict keys if needed
133
- model.load_state_dict(sd, strict=False)
134
- print("Loaded Flux schnell model successfully!")
135
- except Exception as e1:
136
- print(f"Could not load Flux schnell: {e1}")
137
-
138
- # Try the dev version
139
- try:
140
- sd = load_file(hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="flux1-dev.safetensors"))
141
- model.load_state_dict(sd, strict=False)
142
- print("Loaded Flux dev model successfully!")
143
- except Exception as e2:
144
- print(f"Could not load Flux dev: {e2}")
145
-
146
- # If no pretrained weights are available, warn the user
147
- print("\n" + "="*50)
148
- print("WARNING: Could not load pretrained Flux weights!")
149
- print("The model will use random initialization.")
150
- print("For proper results, you need to:")
151
- print("1. Authenticate with HuggingFace: huggingface-cli login")
152
- print("2. Accept the Flux model license agreement")
153
- print("3. Or use a publicly available Flux checkpoint")
154
- print("="*50 + "\n")
155
-
156
- model = model.to(dtype=torch.bfloat16, device=device)
157
-
158
- except Exception as e:
159
- print(f"Error initializing Flux model: {e}")
160
- # Continue with random initialization for now
161
- model = Flux().to(dtype=torch.bfloat16, device=device)
162
 
163
- model_initialized = True
164
- print("Models initialized successfully!")
165
-
166
- # ---------------- NF4 ----------------
167
-
168
- if BNB_AVAILABLE:
169
- def functional_linear_4bits(x, weight, bias):
170
- import bitsandbytes as bnb
171
- out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
172
- out = out.to(x)
173
- return out
174
-
175
- class ForgeParams4bit(Params4bit):
176
- """Subclass to force re-quantization to GPU if needed."""
177
- def to(self, *args, **kwargs):
178
- import torch
179
- device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
180
- if device is not None and device.type == "cuda" and not self.bnb_quantized:
181
- return self._quantize(device)
182
- else:
183
- n = ForgeParams4bit(
184
- torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
185
- requires_grad=self.requires_grad,
186
- quant_state=self.quant_state,
187
- compress_statistics=False,
188
- blocksize=64,
189
- quant_type=self.quant_type,
190
- quant_storage=self.quant_storage,
191
- bnb_quantized=self.bnb_quantized,
192
- module=self.module
193
- )
194
- self.module.quant_state = n.quant_state
195
- self.data = n.data
196
- self.quant_state = n.quant_state
197
- return n
198
-
199
- class ForgeLoader4Bit(nn.Module):
200
- def __init__(self, *, device, dtype, quant_type, **kwargs):
201
- super().__init__()
202
- self.dummy = nn.Parameter(torch.empty(1, device=device, dtype=dtype))
203
- self.weight = None
204
- self.quant_state = None
205
- self.bias = None
206
- self.quant_type = quant_type
207
-
208
- def _save_to_state_dict(self, destination, prefix, keep_vars):
209
- super()._save_to_state_dict(destination, prefix, keep_vars)
210
- from bitsandbytes.nn.modules import QuantState
211
- quant_state = getattr(self.weight, "quant_state", None)
212
- if quant_state is not None:
213
- for k, v in quant_state.as_dict(packed=True).items():
214
- destination[prefix + "weight." + k] = v if keep_vars else v.detach()
215
- return
216
-
217
- def _load_from_state_dict(
218
- self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
219
- ):
220
- from bitsandbytes.nn.modules import Params4bit
221
- import torch
222
-
223
- quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
224
- if any('bitsandbytes' in k for k in quant_state_keys):
225
- quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
226
- self.weight = ForgeParams4bit.from_prequantized(
227
- data=state_dict[prefix + 'weight'],
228
- quantized_stats=quant_state_dict,
229
- requires_grad=False,
230
- device=torch.device('cuda'),
231
- module=self
232
- )
233
- self.quant_state = self.weight.quant_state
234
-
235
- if prefix + 'bias' in state_dict:
236
- self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
237
- del self.dummy
238
- elif hasattr(self, 'dummy'):
239
- if prefix + 'weight' in state_dict:
240
- self.weight = ForgeParams4bit(
241
- state_dict[prefix + 'weight'].to(self.dummy),
242
- requires_grad=False,
243
- compress_statistics=True,
244
- quant_type=self.quant_type,
245
- quant_storage=torch.uint8,
246
- module=self,
247
- )
248
- self.quant_state = self.weight.quant_state
249
-
250
- if prefix + 'bias' in state_dict:
251
- self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
252
-
253
- del self.dummy
254
- else:
255
- super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
256
-
257
- class Linear(ForgeLoader4Bit):
258
- def __init__(self, *args, device=None, dtype=None, **kwargs):
259
- super().__init__(device=device, dtype=dtype, quant_type='nf4')
260
-
261
- def forward(self, x):
262
- self.weight.quant_state = self.quant_state
263
- if self.bias is not None and self.bias.dtype != x.dtype:
264
- self.bias.data = self.bias.data.to(x.dtype)
265
- return functional_linear_4bits(x, self.weight, self.bias)
266
-
267
- # Don't override Linear globally - we'll only use it for Flux model
268
- pass
269
- else:
270
- print("Warning: BitsAndBytes not available, using standard Linear layers")
271
-
272
- # ---------------- Model ----------------
273
-
274
- def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
275
- q, k = apply_rope(q, k, pe)
276
- x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
277
- x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
278
- return x
279
-
280
- def rope(pos, dim, theta):
281
- import torch
282
- scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
283
- omega = 1.0 / (theta ** scale)
284
- out = pos.unsqueeze(-1) * omega.unsqueeze(0)
285
- cos_out = torch.cos(out)
286
- sin_out = torch.sin(out)
287
- out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
288
- b, n, d, _ = out.shape
289
- out = out.view(b, n, d, 2, 2)
290
- return out.float()
291
-
292
- def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
293
- xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
294
- xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
295
- xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
296
- xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
297
- return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
298
-
299
- class EmbedND(nn.Module):
300
- def __init__(self, dim: int, theta: int, axes_dim: list[int]):
301
- super().__init__()
302
- self.dim = dim
303
- self.theta = theta
304
- self.axes_dim = axes_dim
305
-
306
- def forward(self, ids: Tensor) -> Tensor:
307
- import torch
308
- n_axes = ids.shape[-1]
309
- emb = torch.cat(
310
- [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
311
- dim=-3,
312
- )
313
- return emb.unsqueeze(1)
314
-
315
- def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
316
- import torch, math
317
- t = time_factor * t
318
- half = dim // 2
319
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
320
- args = t[:, None].float() * freqs[None]
321
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
322
- if dim % 2:
323
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
324
- if torch.is_floating_point(t):
325
- embedding = embedding.to(t)
326
- return embedding
327
-
328
- class MLPEmbedder(nn.Module):
329
- def __init__(self, in_dim: int, hidden_dim: int):
330
- super().__init__()
331
- self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
332
- self.silu = nn.SiLU()
333
- self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
334
-
335
- def forward(self, x: Tensor) -> Tensor:
336
- return self.out_layer(self.silu(self.in_layer(x)))
337
-
338
- class RMSNorm(torch.nn.Module):
339
- def __init__(self, dim: int):
340
- super().__init__()
341
- self.scale = nn.Parameter(torch.ones(dim))
342
-
343
- def forward(self, x: Tensor):
344
- import torch
345
- x_dtype = x.dtype
346
- x = x.float()
347
- rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
348
- return (x * rrms).to(dtype=x_dtype) * self.scale
349
-
350
- class QKNorm(torch.nn.Module):
351
- def __init__(self, dim: int):
352
- super().__init__()
353
- self.query_norm = RMSNorm(dim)
354
- self.key_norm = RMSNorm(dim)
355
-
356
- def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
357
- q = self.query_norm(q)
358
- k = self.key_norm(k)
359
- return q.to(v), k.to(v)
360
-
361
- class SelfAttention(nn.Module):
362
- def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
363
- super().__init__()
364
- self.num_heads = num_heads
365
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
366
- head_dim = dim // num_heads
367
- self.norm = QKNorm(head_dim)
368
- self.proj = nn.Linear(dim, dim)
369
-
370
- def forward(self, x: Tensor, pe: Tensor) -> Tensor:
371
- qkv = self.qkv(x)
372
- B, L, _ = qkv.shape
373
- qkv = qkv.view(B, L, 3, self.num_heads, -1)
374
- q, k, v = qkv.permute(2, 0, 3, 1, 4)
375
- q, k = self.norm(q, k, v)
376
- x = attention(q, k, v, pe=pe)
377
- x = self.proj(x)
378
- return x
379
-
380
- from dataclasses import dataclass
381
-
382
- @dataclass
383
- class ModulationOut:
384
- shift: Tensor
385
- scale: Tensor
386
- gate: Tensor
387
-
388
- class Modulation(nn.Module):
389
- def __init__(self, dim: int, double: bool):
390
- super().__init__()
391
- self.is_double = double
392
- self.multiplier = 6 if double else 3
393
- self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
394
-
395
- def forward(self, vec: Tensor):
396
- out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
397
- first = ModulationOut(*out[:3])
398
- second = ModulationOut(*out[3:]) if self.is_double else None
399
- return first, second
400
-
401
- class DoubleStreamBlock(nn.Module):
402
- def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
403
- super().__init__()
404
- mlp_hidden_dim = int(hidden_size * mlp_ratio)
405
- self.num_heads = num_heads
406
- self.hidden_size = hidden_size
407
- self.img_mod = Modulation(hidden_size, double=True)
408
- self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
409
- self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
410
- self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
411
- self.img_mlp = nn.Sequential(
412
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
413
- nn.GELU(approximate="tanh"),
414
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
415
- )
416
- self.txt_mod = Modulation(hidden_size, double=True)
417
- self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
418
- self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
419
- self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
420
- self.txt_mlp = nn.Sequential(
421
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
422
- nn.GELU(approximate="tanh"),
423
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
424
- )
425
-
426
- def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
427
- img_mod1, img_mod2 = self.img_mod(vec)
428
- txt_mod1, txt_mod2 = self.txt_mod(vec)
429
-
430
- # Image attention
431
- img_modulated = self.img_norm1(img)
432
- img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
433
- img_qkv = self.img_attn.qkv(img_modulated)
434
- B, L, _ = img_qkv.shape
435
- H = self.num_heads
436
- D = img_qkv.shape[-1] // (3 * H)
437
- img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
438
- img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
439
-
440
- # Text attention
441
- txt_modulated = self.txt_norm1(txt)
442
- txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
443
- txt_qkv = self.txt_attn.qkv(txt_modulated)
444
- B, L, _ = txt_qkv.shape
445
- txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
446
- txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
447
-
448
- # Combined attention
449
- q = torch.cat((txt_q, img_q), dim=2)
450
- k = torch.cat((txt_k, img_k), dim=2)
451
- v = torch.cat((txt_v, img_v), dim=2)
452
- attn = attention(q, k, v, pe=pe)
453
- txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
454
-
455
- # Img final
456
- img = img + img_mod1.gate * self.img_attn.proj(img_attn)
457
- img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
458
-
459
- # Text final
460
- txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
461
- txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
462
- return img, txt
463
-
464
- class SingleStreamBlock(nn.Module):
465
- def __init__(
466
- self,
467
- hidden_size: int,
468
- num_heads: int,
469
- mlp_ratio: float = 4.0,
470
- qk_scale: float | None = None,
471
- ):
472
- super().__init__()
473
- self.hidden_dim = hidden_size
474
- self.num_heads = num_heads
475
- head_dim = hidden_size // num_heads
476
- self.scale = qk_scale or head_dim**-0.5
477
- self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
478
- self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
479
- self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
480
- self.norm = QKNorm(head_dim)
481
- self.hidden_size = hidden_size
482
- self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
483
- self.mlp_act = nn.GELU(approximate="tanh")
484
- self.modulation = Modulation(hidden_size, double=False)
485
-
486
- def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
487
- mod, _ = self.modulation(vec)
488
- x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
489
- qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
490
- qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
491
- q, k, v = qkv.permute(2, 0, 3, 1, 4)
492
- q, k = self.norm(q, k, v)
493
- attn = attention(q, k, v, pe=pe)
494
- output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
495
- return x + mod.gate * output
496
-
497
- class LastLayer(nn.Module):
498
- def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
499
- super().__init__()
500
- self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
501
- self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
502
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
503
-
504
- def forward(self, x: Tensor, vec: Tensor) -> Tensor:
505
- shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
506
- x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
507
- x = self.linear(x)
508
- return x
509
-
510
- from dataclasses import dataclass, field
511
-
512
- @dataclass
513
- class FluxParams:
514
- in_channels: int = 64
515
- vec_in_dim: int = 768
516
- context_in_dim: int = 4096
517
- hidden_size: int = 3072
518
- mlp_ratio: float = 4.0
519
- num_heads: int = 24
520
- depth: int = 19
521
- depth_single_blocks: int = 38
522
- axes_dim: list[int] = field(default_factory=lambda: [16, 56, 56])
523
- theta: int = 10000
524
- qkv_bias: bool = True
525
- guidance_embed: bool = True
526
-
527
- class Flux(nn.Module):
528
- def __init__(self, params = FluxParams()):
529
- super().__init__()
530
- self.params = params
531
- self.in_channels = params.in_channels
532
- self.out_channels = self.in_channels
533
- if params.hidden_size % params.num_heads != 0:
534
- raise ValueError(
535
- f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
536
- )
537
- pe_dim = params.hidden_size // params.num_heads
538
- if sum(params.axes_dim) != pe_dim:
539
- raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
540
- self.hidden_size = params.hidden_size
541
- self.num_heads = params.num_heads
542
- self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
543
- self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
544
- self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
545
- self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
546
- self.guidance_in = (
547
- MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
548
- )
549
- self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
550
-
551
- self.double_blocks = nn.ModuleList(
552
- [
553
- DoubleStreamBlock(
554
- self.hidden_size,
555
- self.num_heads,
556
- mlp_ratio=params.mlp_ratio,
557
- qkv_bias=params.qkv_bias,
558
- )
559
- for _ in range(params.depth)
560
- ]
561
- )
562
-
563
- self.single_blocks = nn.ModuleList(
564
- [
565
- SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
566
- for _ in range(params.depth_single_blocks)
567
- ]
568
- )
569
-
570
- self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
571
-
572
- def forward(
573
- self,
574
- img: Tensor,
575
- img_ids: Tensor,
576
- txt: Tensor,
577
- txt_ids: Tensor,
578
- timesteps: Tensor,
579
- y: Tensor,
580
- guidance: Tensor | None = None,
581
- ) -> Tensor:
582
- if img.ndim != 3 or txt.ndim != 3:
583
- raise ValueError("Input img and txt tensors must have 3 dimensions.")
584
- img = self.img_in(img)
585
- vec = self.time_in(timestep_embedding(timesteps, 256))
586
- if self.params.guidance_embed:
587
- if guidance is None:
588
- raise ValueError("No guidance strength provided for guidance-distilled model.")
589
- vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
590
- vec = vec + self.vector_in(y)
591
- txt = self.txt_in(txt)
592
- ids = torch.cat((txt_ids, img_ids), dim=1)
593
- pe = self.pe_embedder(ids)
594
- for block in self.double_blocks:
595
- img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
596
- img = torch.cat((txt, img), 1)
597
- for block in self.single_blocks:
598
- img = block(img, vec=vec, pe=pe)
599
- img = img[:, txt.shape[1] :, ...]
600
- img = self.final_layer(img, vec)
601
- return img
602
-
603
- def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
604
- import torch
605
- bs, c, h, w = img.shape
606
- if bs == 1 and not isinstance(prompt, str):
607
- bs = len(prompt)
608
- img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
609
- if img.shape[0] == 1 and bs > 1:
610
- img = repeat(img, "1 ... -> bs ...", bs=bs)
611
- img_ids = torch.zeros(h // 2, w // 2, 3)
612
- img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
613
- img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
614
- img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
615
- if isinstance(prompt, str):
616
- prompt = [prompt]
617
- txt = t5(prompt)
618
- if txt.shape[0] == 1 and bs > 1:
619
- txt = repeat(txt, "1 ... -> bs ...", bs=bs)
620
- txt_ids = torch.zeros(bs, txt.shape[1], 3)
621
- vec = clip(prompt)
622
- if vec.shape[0] == 1 and bs > 1:
623
- vec = repeat(vec, "1 ... -> bs ...", bs=bs)
624
- return {
625
- "img": img,
626
- "img_ids": img_ids.to(img.device),
627
- "txt": txt.to(img.device),
628
- "txt_ids": txt_ids.to(img.device),
629
- "vec": vec.to(img.device),
630
- }
631
-
632
- def time_shift(mu: float, sigma: float, t: Tensor):
633
- import math
634
- return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
635
-
636
- def get_lin_function(
637
- x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
638
- ) -> Callable[[float], float]:
639
- import math
640
- m = (y2 - y1) / (x2 - x1)
641
- b = y1 - m * x1
642
- return lambda x: m * x + b
643
-
644
- def get_schedule(
645
- num_steps: int,
646
- image_seq_len: int,
647
- base_shift: float = 0.5,
648
- max_shift: float = 1.15,
649
- shift: bool = True,
650
- ) -> list[float]:
651
- import torch
652
- import math
653
- timesteps = torch.linspace(1, 0, num_steps + 1)
654
- if shift:
655
- mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
656
- timesteps = time_shift(mu, 1.0, timesteps)
657
- return timesteps.tolist()
658
-
659
- def denoise(
660
- model: Flux,
661
- img: Tensor,
662
- img_ids: Tensor,
663
- txt: Tensor,
664
- txt_ids: Tensor,
665
- vec: Tensor,
666
- timesteps: list[float],
667
- guidance: float = 4.0,
668
- ):
669
- import torch
670
- guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
671
- for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
672
- t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
673
- pred = model(
674
- img=img,
675
- img_ids=img_ids,
676
- txt=txt,
677
- txt_ids=txt_ids,
678
- y=vec,
679
- timesteps=t_vec,
680
- guidance=guidance_vec,
681
- )
682
- img = img + (t_prev - t_curr) * pred
683
- return img
684
-
685
- def unpack(x: Tensor, height: int, width: int) -> Tensor:
686
- return rearrange(
687
- x,
688
- "b (h w) (c ph pw) -> b c (h ph) (w pw)",
689
- h=math.ceil(height / 16),
690
- w=math.ceil(width / 16),
691
- ph=2,
692
- pw=2,
693
  )
694
-
695
- @dataclass
696
- class SamplingOptions:
697
- prompt: str
698
- width: int
699
- height: int
700
- guidance: float
701
- seed: int | None
702
-
703
- def get_image(image) -> torch.Tensor | None:
704
- if image is None:
705
- return None
706
- image = Image.fromarray(image).convert("RGB")
707
- transform = transforms.Compose([
708
- transforms.ToTensor(),
709
- transforms.Lambda(lambda x: 2.0 * x - 1.0),
710
- ])
711
- img: torch.Tensor = transform(image)
712
- return img[None, ...]
713
-
714
- @spaces.GPU(duration=120)
715
- @torch.no_grad()
716
- def generate_image(
717
- prompt, width, height, guidance, inference_steps, seed,
718
- do_img2img, init_image, image2image_strength, resize_img,
719
- progress=gr.Progress(track_tqdm=True),
720
- ):
721
- # Initialize models on first run
722
- initialize_models()
723
 
724
- if seed == 0:
725
- seed = int(random.random() * 1_000_000)
726
-
727
- device = "cuda" if torch.cuda.is_available() else "cpu"
728
- torch_device = torch.device(device)
729
-
730
- if do_img2img and init_image is not None:
731
- init_image = get_image(init_image)
732
- if resize_img:
733
- init_image = torch.nn.functional.interpolate(init_image, (height, width))
734
- else:
735
- h, w = init_image.shape[-2:]
736
- init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
737
- height = init_image.shape[-2]
738
- width = init_image.shape[-1]
739
- init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
740
- init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
741
-
742
- generator = torch.Generator(device=device).manual_seed(seed)
743
- x = torch.randn(
744
- 1,
745
- 16,
746
- 2 * math.ceil(height / 16),
747
- 2 * math.ceil(width / 16),
748
- device=device,
749
- dtype=torch.bfloat16,
750
- generator=generator
751
  )
752
-
753
- timesteps = get_schedule(inference_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
754
-
755
- if do_img2img and init_image is not None:
756
- t_idx = int((1 - image2image_strength) * inference_steps)
757
- t = timesteps[t_idx]
758
- timesteps = timesteps[t_idx:]
759
- x = t * x + (1.0 - t) * init_image.to(x.dtype)
760
-
761
- inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
762
- x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
763
- x = unpack(x.float(), height, width)
764
-
765
- with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
766
- x = (x / ae.config.scaling_factor) + ae.config.shift_factor
767
- x = ae.decode(x).sample
768
-
769
- x = x.clamp(-1, 1)
770
- x = rearrange(x[0], "c h w -> h w c")
771
- img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
772
- return img, seed
773
-
774
- def create_demo():
775
- with gr.Blocks(css=".gradio-container {background-color: #282828 !important;}") as demo:
776
- gr.HTML(
777
- """
778
- <div style="text-align: center; margin: 0 auto;">
779
- <h1 style="color: #ffffff; font-weight: 900;">
780
- FluxLLama
781
- </h1>
782
- </div>
783
- """
784
- )
785
-
786
- gr.HTML(
787
- """
788
- <div class='container' style='display:flex; justify-content:center; gap:12px;'>
789
- <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
790
- <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">
791
- </a>
792
 
793
- <a href="https://discord.gg/openfreeai" target="_blank">
794
- <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">
795
- </a>
796
- </div>
797
- """
 
798
  )
799
-
800
-
801
- with gr.Row():
802
- with gr.Column():
803
- prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")
804
- width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=640)
805
- height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=640)
806
- guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
807
- inference_steps = gr.Slider(
808
- label="Inference steps",
809
- minimum=1,
810
- maximum=30,
811
- step=1,
812
- value=16,
813
- )
814
- seed = gr.Number(label="Seed", precision=-1)
815
- do_img2img = gr.Checkbox(label="Image to Image", value=False)
816
- init_image = gr.Image(label="Initial Image", visible=False)
817
- image2image_strength = gr.Slider(
818
- minimum=0.0,
819
- maximum=1.0,
820
- step=0.01,
821
- label="Noising Strength",
822
- value=0.8,
823
- visible=False
824
- )
825
- resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
826
- generate_button = gr.Button("Generate", variant="primary")
827
- with gr.Column():
828
- output_image = gr.Image(label="Result")
829
- output_seed = gr.Text(label="Seed Used")
830
-
831
- do_img2img.change(
832
- fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
833
- inputs=[do_img2img],
834
- outputs=[init_image, image2image_strength, resize_img]
835
- )
836
-
837
- generate_button.click(
838
- fn=generate_image,
839
- inputs=[
840
- prompt, width, height, guidance,
841
- inference_steps, seed, do_img2img,
842
- init_image, image2image_strength, resize_img
843
- ],
844
- outputs=[output_image, output_seed]
845
- )
846
- return demo
847
 
848
  if __name__ == "__main__":
849
- # Create the demo
850
- demo = create_demo()
851
- # Enable the queue to handle concurrency
852
- demo.queue()
853
- # Launch with appropriate settings
854
- demo.launch(show_api=False, share=True)
 
1
+ import spaces
2
+ import gradio as gr
3
+ import random
4
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import time
 
6
  import torch
7
+ from diffusers import FluxPipeline
8
+
9
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
+ print(f"Using device: {DEVICE}")
11
+
12
+ DEFAULT_HEIGHT = 1024
13
+ DEFAULT_WIDTH = 1024
14
+ DEFAULT_GUIDANCE_SCALE = 3.5
15
+ DEFAULT_NUM_INFERENCE_STEPS = 15
16
+ DEFAULT_MAX_SEQUENCE_LENGTH = 512
17
+ HF_TOKEN = os.environ.get("HF_ACCESS_TOKEN")
18
+
19
+ # Cache for the pipeline
20
+ CACHED_PIPE = None
21
+
22
+ def load_bnb_4bit_pipeline():
23
+ """Load the 4-bit quantized pipeline"""
24
+ global CACHED_PIPE
25
+ if CACHED_PIPE is not None:
26
+ return CACHED_PIPE
27
+
28
+ print("Loading 4-bit BNB pipeline...")
29
+ MODEL_ID = "derekl35/FLUX.1-dev-nf4"
30
+
31
+ start_time = time.time()
32
+ try:
33
+ pipe = FluxPipeline.from_pretrained(
34
+ MODEL_ID,
35
+ torch_dtype=torch.bfloat16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  )
37
+ pipe.enable_model_cpu_offload()
38
+ end_time = time.time()
39
+ mem_reserved = torch.cuda.memory_reserved(0)/1024**3 if DEVICE == "cuda" else 0
40
+ print(f"4-bit BNB pipeline loaded in {end_time - start_time:.2f}s. Memory reserved: {mem_reserved:.2f} GB")
41
+ CACHED_PIPE = pipe
42
+ return pipe
43
+ except Exception as e:
44
+ print(f"Error loading 4-bit BNB pipeline: {e}")
45
+ raise
46
+
47
+ @spaces.GPU(duration=240)
48
+ def generate_image(prompt, progress=gr.Progress(track_tqdm=True)):
49
+ """Generate image using 4-bit quantized model"""
50
+ if not prompt:
51
+ return None, "Please enter a prompt."
52
+
53
+ progress(0.2, desc="Loading 4-bit quantized model...")
54
+
55
+ try:
56
+ # Load the 4-bit pipeline
57
+ pipe = load_bnb_4bit_pipeline()
58
 
59
+ # Set up generation parameters
60
+ pipe_kwargs = {
61
+ "prompt": prompt,
62
+ "height": DEFAULT_HEIGHT,
63
+ "width": DEFAULT_WIDTH,
64
+ "guidance_scale": DEFAULT_GUIDANCE_SCALE,
65
+ "num_inference_steps": DEFAULT_NUM_INFERENCE_STEPS,
66
+ "max_sequence_length": DEFAULT_MAX_SEQUENCE_LENGTH,
67
+ }
68
 
69
+ # Generate seed
70
+ seed = random.getrandbits(64)
71
+ print(f"Using seed: {seed}")
72
 
73
+ progress(0.5, desc="Generating image...")
 
 
74
 
75
+ # Generate image
76
+ gen_start_time = time.time()
77
+ image = pipe(**pipe_kwargs, generator=torch.manual_seed(seed)).images[0]
78
+ gen_end_time = time.time()
79
 
80
+ print(f"Image generated in {gen_end_time - gen_start_time:.2f} seconds")
81
+ mem_reserved = torch.cuda.memory_reserved(0)/1024**3 if DEVICE == "cuda" else 0
82
+ print(f"Memory reserved: {mem_reserved:.2f} GB")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ return image, f"Generation complete! (Seed: {seed})"
85
+
86
+ except Exception as e:
87
+ print(f"Error during generation: {e}")
88
+ return None, f"Error: {e}"
89
+
90
+ # Create Gradio interface
91
+ with gr.Blocks(title="FLUXllama", theme=gr.themes.Soft()) as demo:
92
+ gr.HTML(
93
+ """
94
+ <div style='text-align: center; margin-bottom: 20px;'>
95
+ <h1>FLUXllama</h1>
96
+ <p>FLUX.1-dev 4-bit Quantized Version</p>
97
+ </div>
98
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ gr.HTML(
102
+ """
103
+ <div class='container' style='display:flex; justify-content:center; gap:12px; margin-bottom: 20px;'>
104
+ <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
105
+ <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">
106
+ </a>
107
+
108
+ <a href="https://discord.gg/openfreeai" target="_blank">
109
+ <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">
110
+ </a>
111
+ </div>
112
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
+ with gr.Row():
116
+ prompt_input = gr.Textbox(
117
+ label="Enter your prompt",
118
+ placeholder="e.g., A photorealistic portrait of an astronaut on Mars",
119
+ lines=2,
120
+ scale=4
121
  )
122
+ generate_button = gr.Button("Generate", variant="primary", scale=1)
123
+
124
+ output_image = gr.Image(
125
+ label="Generated Image (4-bit Quantized)",
126
+ type="pil",
127
+ height=600
128
+ )
129
+
130
+ status_text = gr.Textbox(
131
+ label="Status",
132
+ interactive=False,
133
+ lines=1
134
+ )
135
+
136
+ # Connect components
137
+ generate_button.click(
138
+ fn=generate_image,
139
+ inputs=[prompt_input],
140
+ outputs=[output_image, status_text]
141
+ )
142
+
143
+ # Enter key to submit
144
+ prompt_input.submit(
145
+ fn=generate_image,
146
+ inputs=[prompt_input],
147
+ outputs=[output_image, status_text]
148
+ )
149
+
150
+ # Example prompts
151
+ gr.Examples(
152
+ examples=[
153
+ "A photorealistic portrait of an astronaut on Mars",
154
+ "Water-color painting of a cat wearing sunglasses",
155
+ "Neo-tokyo cyberpunk cityscape at night, rain-soaked streets, 8K",
156
+ "A majestic dragon flying over a medieval castle at sunset",
157
+ "Abstract art representing the concept of time and space",
158
+ "Detailed oil painting of a steampunk clockwork city",
159
+ "Underwater scene with bioluminescent creatures in deep ocean",
160
+ "Japanese garden in autumn with falling maple leaves"
161
+ ],
162
+ inputs=prompt_input
163
+ )
 
 
 
 
 
 
164
 
165
  if __name__ == "__main__":
166
+ demo.launch(share=True)