ginipick commited on
Commit
b486d62
·
verified ·
1 Parent(s): 82fe1ba

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1533 -0
app.py ADDED
@@ -0,0 +1,1533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
64
+ clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
65
+ ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
66
+
67
+ # ---------------- NF4 ----------------
68
+
69
+ def functional_linear_4bits(x, weight, bias):
70
+ import bitsandbytes as bnb
71
+ out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
72
+ out = out.to(x)
73
+ return out
74
+
75
+ class ForgeParams4bit(Params4bit):
76
+ """Subclass to force re-quantization to GPU if needed."""
77
+ def to(self, *args, **kwargs):
78
+ import torch
79
+ device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
80
+ if device is not None and device.type == "cuda" and not self.bnb_quantized:
81
+ return self._quantize(device)
82
+ else:
83
+ n = ForgeParams4bit(
84
+ torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
85
+ requires_grad=self.requires_grad,
86
+ quant_state=self.quant_state,
87
+ compress_statistics=False,
88
+ blocksize=64,
89
+ quant_type=self.quant_type,
90
+ quant_storage=self.quant_storage,
91
+ bnb_quantized=self.bnb_quantized,
92
+ module=self.module
93
+ )
94
+ self.module.quant_state = n.quant_state
95
+ self.data = n.data
96
+ self.quant_state = n.quant_state
97
+ return n
98
+
99
+ class ForgeLoader4Bit(nn.Module):
100
+ def __init__(self, *, device, dtype, quant_type, **kwargs):
101
+ super().__init__()
102
+ self.dummy = nn.Parameter(torch.empty(1, device=device, dtype=dtype))
103
+ self.weight = None
104
+ self.quant_state = None
105
+ self.bias = None
106
+ self.quant_type = quant_type
107
+
108
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
109
+ super()._save_to_state_dict(destination, prefix, keep_vars)
110
+ from bitsandbytes.nn.modules import QuantState
111
+ quant_state = getattr(self.weight, "quant_state", None)
112
+ if quant_state is not None:
113
+ for k, v in quant_state.as_dict(packed=True).items():
114
+ destination[prefix + "weight." + k] = v if keep_vars else v.detach()
115
+ return
116
+
117
+ def _load_from_state_dict(
118
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
119
+ ):
120
+ from bitsandbytes.nn.modules import Params4bit
121
+ import torch
122
+
123
+ quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
124
+ if any('bitsandbytes' in k for k in quant_state_keys):
125
+ quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
126
+ self.weight = ForgeParams4bit.from_prequantized(
127
+ data=state_dict[prefix + 'weight'],
128
+ quantized_stats=quant_state_dict,
129
+ requires_grad=False,
130
+ device=torch.device('cuda'),
131
+ module=self
132
+ )
133
+ self.quant_state = self.weight.quant_state
134
+
135
+ if prefix + 'bias' in state_dict:
136
+ self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
137
+ del self.dummy
138
+ elif hasattr(self, 'dummy'):
139
+ if prefix + 'weight' in state_dict:
140
+ self.weight = ForgeParams4bit(
141
+ state_dict[prefix + 'weight'].to(self.dummy),
142
+ requires_grad=False,
143
+ compress_statistics=True,
144
+ quant_type=self.quant_type,
145
+ quant_storage=torch.uint8,
146
+ module=self,
147
+ )
148
+ self.quant_state = self.weight.quant_state
149
+
150
+ if prefix + 'bias' in state_dict:
151
+ self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
152
+
153
+ del self.dummy
154
+ else:
155
+ super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
156
+
157
+ class Linear(ForgeLoader4Bit):
158
+ def __init__(self, *args, device=None, dtype=None, **kwargs):
159
+ super().__init__(device=device, dtype=dtype, quant_type='nf4')
160
+
161
+ def forward(self, x):
162
+ self.weight.quant_state = self.quant_state
163
+ if self.bias is not None and self.bias.dtype != x.dtype:
164
+ self.bias.data = self.bias.data.to(x.dtype)
165
+ return functional_linear_4bits(x, self.weight, self.bias)
166
+
167
+ import torch.nn as nn
168
+ nn.Linear = Linear
169
+
170
+ # ---------------- Model ----------------
171
+
172
+ def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
173
+ q, k = apply_rope(q, k, pe)
174
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
175
+ x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
176
+ return x
177
+
178
+ def rope(pos, dim, theta):
179
+ import torch
180
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
181
+ omega = 1.0 / (theta ** scale)
182
+ out = pos.unsqueeze(-1) * omega.unsqueeze(0)
183
+ cos_out = torch.cos(out)
184
+ sin_out = torch.sin(out)
185
+ out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
186
+ b, n, d, _ = out.shape
187
+ out = out.view(b, n, d, 2, 2)
188
+ return out.float()
189
+
190
+ def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
191
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
192
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
193
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
194
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
195
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
196
+
197
+ class EmbedND(nn.Module):
198
+ def __init__(self, dim: int, theta: int, axes_dim: list[int]):
199
+ super().__init__()
200
+ self.dim = dim
201
+ self.theta = theta
202
+ self.axes_dim = axes_dim
203
+
204
+ def forward(self, ids: Tensor) -> Tensor:
205
+ import torch
206
+ n_axes = ids.shape[-1]
207
+ emb = torch.cat(
208
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
209
+ dim=-3,
210
+ )
211
+ return emb.unsqueeze(1)
212
+
213
+ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
214
+ import torch, math
215
+ t = time_factor * t
216
+ half = dim // 2
217
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
218
+ args = t[:, None].float() * freqs[None]
219
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
220
+ if dim % 2:
221
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
222
+ if torch.is_floating_point(t):
223
+ embedding = embedding.to(t)
224
+ return embedding
225
+
226
+ class MLPEmbedder(nn.Module):
227
+ def __init__(self, in_dim: int, hidden_dim: int):
228
+ super().__init__()
229
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
230
+ self.silu = nn.SiLU()
231
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
232
+
233
+ def forward(self, x: Tensor) -> Tensor:
234
+ return self.out_layer(self.silu(self.in_layer(x)))
235
+
236
+ class RMSNorm(torch.nn.Module):
237
+ def __init__(self, dim: int):
238
+ super().__init__()
239
+ self.scale = nn.Parameter(torch.ones(dim))
240
+
241
+ def forward(self, x: Tensor):
242
+ import torch
243
+ x_dtype = x.dtype
244
+ x = x.float()
245
+ rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
246
+ return (x * rrms).to(dtype=x_dtype) * self.scale
247
+
248
+ class QKNorm(torch.nn.Module):
249
+ def __init__(self, dim: int):
250
+ super().__init__()
251
+ self.query_norm = RMSNorm(dim)
252
+ self.key_norm = RMSNorm(dim)
253
+
254
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
255
+ q = self.query_norm(q)
256
+ k = self.key_norm(k)
257
+ return q.to(v), k.to(v)
258
+
259
+ class SelfAttention(nn.Module):
260
+ def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
261
+ super().__init__()
262
+ self.num_heads = num_heads
263
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
264
+ head_dim = dim // num_heads
265
+ self.norm = QKNorm(head_dim)
266
+ self.proj = nn.Linear(dim, dim)
267
+
268
+ def forward(self, x: Tensor, pe: Tensor) -> Tensor:
269
+ qkv = self.qkv(x)
270
+ B, L, _ = qkv.shape
271
+ qkv = qkv.view(B, L, 3, self.num_heads, -1)
272
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
273
+ q, k = self.norm(q, k, v)
274
+ x = attention(q, k, v, pe=pe)
275
+ x = self.proj(x)
276
+ return x
277
+
278
+ from dataclasses import dataclass
279
+
280
+ @dataclass
281
+ class ModulationOut:
282
+ shift: Tensor
283
+ scale: Tensor
284
+ gate: Tensor
285
+
286
+ class Modulation(nn.Module):
287
+ def __init__(self, dim: int, double: bool):
288
+ super().__init__()
289
+ self.is_double = double
290
+ self.multiplier = 6 if double else 3
291
+ self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
292
+
293
+ def forward(self, vec: Tensor):
294
+ out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
295
+ first = ModulationOut(*out[:3])
296
+ second = ModulationOut(*out[3:]) if self.is_double else None
297
+ return first, second
298
+
299
+ class DoubleStreamBlock(nn.Module):
300
+ def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
301
+ super().__init__()
302
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
303
+ self.num_heads = num_heads
304
+ self.hidden_size = hidden_size
305
+ self.img_mod = Modulation(hidden_size, double=True)
306
+ self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
307
+ self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
308
+ self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
309
+ self.img_mlp = nn.Sequential(
310
+ nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
311
+ nn.GELU(approximate="tanh"),
312
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
313
+ )
314
+ self.txt_mod = Modulation(hidden_size, double=True)
315
+ self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
316
+ self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
317
+ self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
318
+ self.txt_mlp = nn.Sequential(
319
+ nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
320
+ nn.GELU(approximate="tanh"),
321
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
322
+ )
323
+
324
+ def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
325
+ img_mod1, img_mod2 = self.img_mod(vec)
326
+ txt_mod1, txt_mod2 = self.txt_mod(vec)
327
+
328
+ # Image attention
329
+ img_modulated = self.img_norm1(img)
330
+ img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
331
+ img_qkv = self.img_attn.qkv(img_modulated)
332
+ B, L, _ = img_qkv.shape
333
+ H = self.num_heads
334
+ D = img_qkv.shape[-1] // (3 * H)
335
+ img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
336
+ img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
337
+
338
+ # Text attention
339
+ txt_modulated = self.txt_norm1(txt)
340
+ txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
341
+ txt_qkv = self.txt_attn.qkv(txt_modulated)
342
+ B, L, _ = txt_qkv.shape
343
+ txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
344
+ txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
345
+
346
+ # Combined attention
347
+ q = torch.cat((txt_q, img_q), dim=2)
348
+ k = torch.cat((txt_k, img_k), dim=2)
349
+ v = torch.cat((txt_v, img_v), dim=2)
350
+ attn = attention(q, k, v, pe=pe)
351
+ txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
352
+
353
+ # Img final
354
+ img = img + img_mod1.gate * self.img_attn.proj(img_attn)
355
+ img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
356
+
357
+ # Text final
358
+ txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
359
+ txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
360
+ return img, txt
361
+
362
+ class SingleStreamBlock(nn.Module):
363
+ def __init__(
364
+ self,
365
+ hidden_size: int,
366
+ num_heads: int,
367
+ mlp_ratio: float = 4.0,
368
+ qk_scale: float | None = None,
369
+ ):
370
+ super().__init__()
371
+ self.hidden_dim = hidden_size
372
+ self.num_heads = num_heads
373
+ head_dim = hidden_size // num_heads
374
+ self.scale = qk_scale or head_dim**-0.5
375
+ self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
376
+ self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
377
+ self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
378
+ self.norm = QKNorm(head_dim)
379
+ self.hidden_size = hidden_size
380
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
381
+ self.mlp_act = nn.GELU(approximate="tanh")
382
+ self.modulation = Modulation(hidden_size, double=False)
383
+
384
+ def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
385
+ mod, _ = self.modulation(vec)
386
+ x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
387
+ qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
388
+ qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
389
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
390
+ q, k = self.norm(q, k, v)
391
+ attn = attention(q, k, v, pe=pe)
392
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
393
+ return x + mod.gate * output
394
+
395
+ class LastLayer(nn.Module):
396
+ def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
397
+ super().__init__()
398
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
399
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
400
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
401
+
402
+ def forward(self, x: Tensor, vec: Tensor) -> Tensor:
403
+ shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
404
+ x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
405
+ x = self.linear(x)
406
+ return x
407
+
408
+ from dataclasses import dataclass, field
409
+
410
+ @dataclass
411
+ class FluxParams:
412
+ in_channels: int = 64
413
+ vec_in_dim: int = 768
414
+ context_in_dim: int = 4096
415
+ hidden_size: int = 3072
416
+ mlp_ratio: float = 4.0
417
+ num_heads: int = 24
418
+ depth: int = 19
419
+ depth_single_blocks: int = 38
420
+ axes_dim: list[int] = field(default_factory=lambda: [16, 56, 56])
421
+ theta: int = 10000
422
+ qkv_bias: bool = True
423
+ guidance_embed: bool = True
424
+
425
+ class Flux(nn.Module):
426
+ def __init__(self, params = FluxParams()):
427
+ super().__init__()
428
+ self.params = params
429
+ self.in_channels = params.in_channels
430
+ self.out_channels = self.in_channels
431
+ if params.hidden_size % params.num_heads != 0:
432
+ raise ValueError(
433
+ f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
434
+ )
435
+ pe_dim = params.hidden_size // params.num_heads
436
+ if sum(params.axes_dim) != pe_dim:
437
+ raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
438
+ self.hidden_size = params.hidden_size
439
+ self.num_heads = params.num_heads
440
+ self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
441
+ self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
442
+ self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
443
+ self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
444
+ self.guidance_in = (
445
+ MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
446
+ )
447
+ self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
448
+
449
+ self.double_blocks = nn.ModuleList(
450
+ [
451
+ DoubleStreamBlock(
452
+ self.hidden_size,
453
+ self.num_heads,
454
+ mlp_ratio=params.mlp_ratio,
455
+ qkv_bias=params.qkv_bias,
456
+ )
457
+ for _ in range(params.depth)
458
+ ]
459
+ )
460
+
461
+ self.single_blocks = nn.ModuleList(
462
+ [
463
+ SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
464
+ for _ in range(params.depth_single_blocks)
465
+ ]
466
+ )
467
+
468
+ self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
469
+
470
+ def forward(
471
+ self,
472
+ img: Tensor,
473
+ img_ids: Tensor,
474
+ txt: Tensor,
475
+ txt_ids: Tensor,
476
+ timesteps: Tensor,
477
+ y: Tensor,
478
+ guidance: Tensor | None = None,
479
+ ) -> Tensor:
480
+ if img.ndim != 3 or txt.ndim != 3:
481
+ raise ValueError("Input img and txt tensors must have 3 dimensions.")
482
+ img = self.img_in(img)
483
+ vec = self.time_in(timestep_embedding(timesteps, 256))
484
+ if self.params.guidance_embed:
485
+ if guidance is None:
486
+ raise ValueError("No guidance strength provided for guidance-distilled model.")
487
+ vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
488
+ vec = vec + self.vector_in(y)
489
+ txt = self.txt_in(txt)
490
+ ids = torch.cat((txt_ids, img_ids), dim=1)
491
+ pe = self.pe_embedder(ids)
492
+ for block in self.double_blocks:
493
+ img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
494
+ img = torch.cat((txt, img), 1)
495
+ for block in self.single_blocks:
496
+ img = block(img, vec=vec, pe=pe)
497
+ img = img[:, txt.shape[1] :, ...]
498
+ img = self.final_layer(img, vec)
499
+ return img
500
+
501
+ def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
502
+ import torch
503
+ bs, c, h, w = img.shape
504
+ if bs == 1 and not isinstance(prompt, str):
505
+ bs = len(prompt)
506
+ img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
507
+ if img.shape[0] == 1 and bs > 1:
508
+ img = repeat(img, "1 ... -> bs ...", bs=bs)
509
+ img_ids = torch.zeros(h // 2, w // 2, 3)
510
+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
511
+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
512
+ img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
513
+ if isinstance(prompt, str):
514
+ prompt = [prompt]
515
+ txt = t5(prompt)
516
+ if txt.shape[0] == 1 and bs > 1:
517
+ txt = repeat(txt, "1 ... -> bs ...", bs=bs)
518
+ txt_ids = torch.zeros(bs, txt.shape[1], 3)
519
+ vec = clip(prompt)
520
+ if vec.shape[0] == 1 and bs > 1:
521
+ vec = repeat(vec, "1 ... -> bs ...", bs=bs)
522
+ return {
523
+ "img": img,
524
+ "img_ids": img_ids.to(img.device),
525
+ "txt": txt.to(img.device),
526
+ "txt_ids": txt_ids.to(img.device),
527
+ "vec": vec.to(img.device),
528
+ }
529
+
530
+ def time_shift(mu: float, sigma: float, t: Tensor):
531
+ import math
532
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
533
+
534
+ def get_lin_function(
535
+ x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
536
+ ) -> Callable[[float], float]:
537
+ import math
538
+ m = (y2 - y1) / (x2 - x1)
539
+ b = y1 - m * x1
540
+ return lambda x: m * x + b
541
+
542
+ def get_schedule(
543
+ num_steps: int,
544
+ image_seq_len: int,
545
+ base_shift: float = 0.5,
546
+ max_shift: float = 1.15,
547
+ shift: bool = True,
548
+ ) -> list[float]:
549
+ import torch
550
+ import math
551
+ timesteps = torch.linspace(1, 0, num_steps + 1)
552
+ if shift:
553
+ mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
554
+ timesteps = time_shift(mu, 1.0, timesteps)
555
+ return timesteps.tolist()
556
+
557
+ def denoise(
558
+ model: Flux,
559
+ img: Tensor,
560
+ img_ids: Tensor,
561
+ txt: Tensor,
562
+ txt_ids: Tensor,
563
+ vec: Tensor,
564
+ timesteps: list[float],
565
+ guidance: float = 4.0,
566
+ ):
567
+ import torch
568
+ guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
569
+ for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
570
+ t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
571
+ pred = model(
572
+ img=img,
573
+ img_ids=img_ids,
574
+ txt=txt,
575
+ txt_ids=txt_ids,
576
+ y=vec,
577
+ timesteps=t_vec,
578
+ guidance=guidance_vec,
579
+ )
580
+ img = img + (t_prev - t_curr) * pred
581
+ return img
582
+
583
+ def unpack(x: Tensor, height: int, width: int) -> Tensor:
584
+ return rearrange(
585
+ x,
586
+ "b (h w) (c ph pw) -> b c (h ph) (w pw)",
587
+ h=math.ceil(height / 16),
588
+ w=math.ceil(width / 16),
589
+ ph=2,
590
+ pw=2,
591
+ )
592
+
593
+ @dataclass
594
+ class SamplingOptions:
595
+ prompt: str
596
+ width: int
597
+ height: int
598
+ guidance: float
599
+ seed: int | None
600
+
601
+ def get_image(image) -> torch.Tensor | None:
602
+ if image is None:
603
+ return None
604
+ image = Image.fromarray(image).convert("RGB")
605
+ transform = transforms.Compose([
606
+ transforms.ToTensor(),
607
+ transforms.Lambda(lambda x: 2.0 * x - 1.0),
608
+ ])
609
+ img: torch.Tensor = transform(image)
610
+ return img[None, ...]
611
+
612
+ # Load the NF4 quantized checkpoint
613
+ from huggingface_hub import hf_hub_download
614
+ from safetensors.torch import load_file
615
+
616
+ sd = load_file(hf_hub_download(repo_id="lllyasviel/flux1-dev-bnb-nf4", filename="flux1-dev-bnb-nf4-v2.safetensors"))
617
+ sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
618
+ model = Flux().to(dtype=torch.bfloat16, device=device)
619
+ result = model.load_state_dict(sd)
620
+ model_zero_init = False
621
+
622
+ # Remove @spaces.GPU decorator - we'll handle GPU allocation manually
623
+ # @spaces.GPU
624
+ @torch.no_grad()
625
+ def generate_image(
626
+ prompt, width, height, guidance, inference_steps, seed,
627
+ do_img2img, init_image, image2image_strength, resize_img,
628
+ progress=gr.Progress(track_tqdm=True),
629
+ ):
630
+ if seed == 0:
631
+ seed = int(random.random() * 1_000_000)
632
+
633
+ device = "cuda" if torch.cuda.is_available() else "cpu"
634
+ torch_device = torch.device(device)
635
+
636
+ global model, model_zero_init
637
+ if not model_zero_init:
638
+ model = model.to(torch_device)
639
+ model_zero_init = True
640
+
641
+ if do_img2img and init_image is not None:
642
+ init_image = get_image(init_image)
643
+ if resize_img:
644
+ init_image = torch.nn.functional.interpolate(init_image, (height, width))
645
+ else:
646
+ h, w = init_image.shape[-2:]
647
+ init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
648
+ height = init_image.shape[-2]
649
+ width = init_image.shape[-1]
650
+ init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
651
+ init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
652
+
653
+ generator = torch.Generator(device=device).manual_seed(seed)
654
+ x = torch.randn(
655
+ 1,
656
+ 16,
657
+ 2 * math.ceil(height / 16),
658
+ 2 * math.ceil(width / 16),
659
+ device=device,
660
+ dtype=torch.bfloat16,
661
+ generator=generator
662
+ )
663
+
664
+ timesteps = get_schedule(inference_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
665
+
666
+ if do_img2img and init_image is not None:
667
+ t_idx = int((1 - image2image_strength) * inference_steps)
668
+ t = timesteps[t_idx]
669
+ timesteps = timesteps[t_idx:]
670
+ x = t * x + (1.0 - t) * init_image.to(x.dtype)
671
+
672
+ inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
673
+ x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
674
+ x = unpack(x.float(), height, width)
675
+
676
+ with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
677
+ x = (x / ae.config.scaling_factor) + ae.config.shift_factor
678
+ x = ae.decode(x).sample
679
+
680
+ x = x.clamp(-1, 1)
681
+ x = rearrange(x[0], "c h w -> h w c")
682
+ img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
683
+ return img, seed
684
+
685
+ def create_demo():
686
+ with gr.Blocks(css=".gradio-container {background-color: #282828 !important;}") as demo:
687
+ gr.HTML(
688
+ """
689
+ <div style="text-align: center; margin: 0 auto;">
690
+ <h1 style="color: #ffffff; font-weight: 900;">
691
+ FluxLLama
692
+ </h1>
693
+ </div>
694
+ """
695
+ )
696
+
697
+ gr.HTML(
698
+ """
699
+ <div class='container' style='display:flex; justify-content:center; gap:12px;'>
700
+ <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
701
+ <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">
702
+ </a>
703
+
704
+ <a href="https://discord.gg/openfreeai" target="_blank">
705
+ <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">
706
+ </a>
707
+ </div>
708
+ """
709
+ )
710
+
711
+
712
+ with gr.Row():
713
+ with gr.Column():
714
+ prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")
715
+ width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=640)
716
+ height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=640)
717
+ guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
718
+ inference_steps = gr.Slider(
719
+ label="Inference steps",
720
+ minimum=1,
721
+ maximum=30,
722
+ step=1,
723
+ value=16,
724
+ )
725
+ seed = gr.Number(label="Seed", precision=-1)
726
+ do_img2img = gr.Checkbox(label="Image to Image", value=False)
727
+ init_image = gr.Image(label="Initial Image", visible=False)
728
+ image2image_strength = gr.Slider(
729
+ minimum=0.0,
730
+ maximum=1.0,
731
+ step=0.01,
732
+ label="Noising Strength",
733
+ value=0.8,
734
+ visible=False
735
+ )
736
+ resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
737
+ generate_button = gr.Button("Generate", variant="primary")
738
+ with gr.Column():
739
+ output_image = gr.Image(label="Result")
740
+ output_seed = gr.Text(label="Seed Used")
741
+
742
+ do_img2img.change(
743
+ fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
744
+ inputs=[do_img2img],
745
+ outputs=[init_image, image2image_strength, resize_img]
746
+ )
747
+
748
+ generate_button.click(
749
+ fn=generate_image,
750
+ inputs=[
751
+ prompt, width, height, guidance,
752
+ inference_steps, seed, do_img2img,
753
+ init_image, image2image_strength, resize_img
754
+ ],
755
+ outputs=[output_image, output_seed]
756
+ )
757
+ return demo
758
+
759
+ if __name__ == "__main__":
760
+ # Create the demo
761
+ demo = create_demo()
762
+ # Enable the queue to handle concurrency
763
+ demo.queue()
764
+ # Launch with show_api=False and share=True to avoid the "bool is not iterable" error
765
+ # and the "ValueError: When localhost is not accessible..." error.
766
+ # Remove mcp_server=True as it's not a valid parameter
767
+ demo.launch(show_api=False, share=True, server_name="0.0.0.0")import os
768
+ # Comment out spaces import to avoid the error
769
+ # import spaces
770
+
771
+ import time
772
+ import gradio as gr
773
+ import torch
774
+ from PIL import Image
775
+ from torchvision import transforms
776
+ from dataclasses import dataclass, field
777
+ import math
778
+ from typing import Callable
779
+
780
+ from tqdm import tqdm
781
+ import bitsandbytes as bnb
782
+ from bitsandbytes.nn.modules import Params4bit, QuantState
783
+
784
+ import torch
785
+ import random
786
+ from einops import rearrange, repeat
787
+ from diffusers import AutoencoderKL
788
+ from torch import Tensor, nn
789
+ from transformers import CLIPTextModel, CLIPTokenizer
790
+ from transformers import T5EncoderModel, T5Tokenizer
791
+
792
+ # ---------------- Encoders ----------------
793
+
794
+ class HFEmbedder(nn.Module):
795
+ def __init__(self, version: str, max_length: int, **hf_kwargs):
796
+ super().__init__()
797
+ self.is_clip = version.startswith("openai")
798
+ self.max_length = max_length
799
+ self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
800
+
801
+ if self.is_clip:
802
+ self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
803
+ self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
804
+ else:
805
+ self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
806
+ self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
807
+
808
+ self.hf_module = self.hf_module.eval().requires_grad_(False)
809
+
810
+ def forward(self, text: list[str]) -> Tensor:
811
+ batch_encoding = self.tokenizer(
812
+ text,
813
+ truncation=True,
814
+ max_length=self.max_length,
815
+ return_length=False,
816
+ return_overflowing_tokens=False,
817
+ padding="max_length",
818
+ return_tensors="pt",
819
+ )
820
+
821
+ outputs = self.hf_module(
822
+ input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
823
+ attention_mask=None,
824
+ output_hidden_states=False,
825
+ )
826
+ return outputs[self.output_key]
827
+
828
+ device = "cuda" if torch.cuda.is_available() else "cpu"
829
+ t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
830
+ clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
831
+ ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
832
+
833
+ # ---------------- NF4 ----------------
834
+
835
+ def functional_linear_4bits(x, weight, bias):
836
+ import bitsandbytes as bnb
837
+ out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
838
+ out = out.to(x)
839
+ return out
840
+
841
+ class ForgeParams4bit(Params4bit):
842
+ """Subclass to force re-quantization to GPU if needed."""
843
+ def to(self, *args, **kwargs):
844
+ import torch
845
+ device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
846
+ if device is not None and device.type == "cuda" and not self.bnb_quantized:
847
+ return self._quantize(device)
848
+ else:
849
+ n = ForgeParams4bit(
850
+ torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
851
+ requires_grad=self.requires_grad,
852
+ quant_state=self.quant_state,
853
+ compress_statistics=False,
854
+ blocksize=64,
855
+ quant_type=self.quant_type,
856
+ quant_storage=self.quant_storage,
857
+ bnb_quantized=self.bnb_quantized,
858
+ module=self.module
859
+ )
860
+ self.module.quant_state = n.quant_state
861
+ self.data = n.data
862
+ self.quant_state = n.quant_state
863
+ return n
864
+
865
+ class ForgeLoader4Bit(nn.Module):
866
+ def __init__(self, *, device, dtype, quant_type, **kwargs):
867
+ super().__init__()
868
+ self.dummy = nn.Parameter(torch.empty(1, device=device, dtype=dtype))
869
+ self.weight = None
870
+ self.quant_state = None
871
+ self.bias = None
872
+ self.quant_type = quant_type
873
+
874
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
875
+ super()._save_to_state_dict(destination, prefix, keep_vars)
876
+ from bitsandbytes.nn.modules import QuantState
877
+ quant_state = getattr(self.weight, "quant_state", None)
878
+ if quant_state is not None:
879
+ for k, v in quant_state.as_dict(packed=True).items():
880
+ destination[prefix + "weight." + k] = v if keep_vars else v.detach()
881
+ return
882
+
883
+ def _load_from_state_dict(
884
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
885
+ ):
886
+ from bitsandbytes.nn.modules import Params4bit
887
+ import torch
888
+
889
+ quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
890
+ if any('bitsandbytes' in k for k in quant_state_keys):
891
+ quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
892
+ self.weight = ForgeParams4bit.from_prequantized(
893
+ data=state_dict[prefix + 'weight'],
894
+ quantized_stats=quant_state_dict,
895
+ requires_grad=False,
896
+ device=torch.device('cuda'),
897
+ module=self
898
+ )
899
+ self.quant_state = self.weight.quant_state
900
+
901
+ if prefix + 'bias' in state_dict:
902
+ self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
903
+ del self.dummy
904
+ elif hasattr(self, 'dummy'):
905
+ if prefix + 'weight' in state_dict:
906
+ self.weight = ForgeParams4bit(
907
+ state_dict[prefix + 'weight'].to(self.dummy),
908
+ requires_grad=False,
909
+ compress_statistics=True,
910
+ quant_type=self.quant_type,
911
+ quant_storage=torch.uint8,
912
+ module=self,
913
+ )
914
+ self.quant_state = self.weight.quant_state
915
+
916
+ if prefix + 'bias' in state_dict:
917
+ self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
918
+
919
+ del self.dummy
920
+ else:
921
+ super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
922
+
923
+ class Linear(ForgeLoader4Bit):
924
+ def __init__(self, *args, device=None, dtype=None, **kwargs):
925
+ super().__init__(device=device, dtype=dtype, quant_type='nf4')
926
+
927
+ def forward(self, x):
928
+ self.weight.quant_state = self.quant_state
929
+ if self.bias is not None and self.bias.dtype != x.dtype:
930
+ self.bias.data = self.bias.data.to(x.dtype)
931
+ return functional_linear_4bits(x, self.weight, self.bias)
932
+
933
+ import torch.nn as nn
934
+ nn.Linear = Linear
935
+
936
+ # ---------------- Model ----------------
937
+
938
+ def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
939
+ q, k = apply_rope(q, k, pe)
940
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
941
+ x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
942
+ return x
943
+
944
+ def rope(pos, dim, theta):
945
+ import torch
946
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
947
+ omega = 1.0 / (theta ** scale)
948
+ out = pos.unsqueeze(-1) * omega.unsqueeze(0)
949
+ cos_out = torch.cos(out)
950
+ sin_out = torch.sin(out)
951
+ out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
952
+ b, n, d, _ = out.shape
953
+ out = out.view(b, n, d, 2, 2)
954
+ return out.float()
955
+
956
+ def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
957
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
958
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
959
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
960
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
961
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
962
+
963
+ class EmbedND(nn.Module):
964
+ def __init__(self, dim: int, theta: int, axes_dim: list[int]):
965
+ super().__init__()
966
+ self.dim = dim
967
+ self.theta = theta
968
+ self.axes_dim = axes_dim
969
+
970
+ def forward(self, ids: Tensor) -> Tensor:
971
+ import torch
972
+ n_axes = ids.shape[-1]
973
+ emb = torch.cat(
974
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
975
+ dim=-3,
976
+ )
977
+ return emb.unsqueeze(1)
978
+
979
+ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
980
+ import torch, math
981
+ t = time_factor * t
982
+ half = dim // 2
983
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
984
+ args = t[:, None].float() * freqs[None]
985
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
986
+ if dim % 2:
987
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
988
+ if torch.is_floating_point(t):
989
+ embedding = embedding.to(t)
990
+ return embedding
991
+
992
+ class MLPEmbedder(nn.Module):
993
+ def __init__(self, in_dim: int, hidden_dim: int):
994
+ super().__init__()
995
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
996
+ self.silu = nn.SiLU()
997
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
998
+
999
+ def forward(self, x: Tensor) -> Tensor:
1000
+ return self.out_layer(self.silu(self.in_layer(x)))
1001
+
1002
+ class RMSNorm(torch.nn.Module):
1003
+ def __init__(self, dim: int):
1004
+ super().__init__()
1005
+ self.scale = nn.Parameter(torch.ones(dim))
1006
+
1007
+ def forward(self, x: Tensor):
1008
+ import torch
1009
+ x_dtype = x.dtype
1010
+ x = x.float()
1011
+ rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
1012
+ return (x * rrms).to(dtype=x_dtype) * self.scale
1013
+
1014
+ class QKNorm(torch.nn.Module):
1015
+ def __init__(self, dim: int):
1016
+ super().__init__()
1017
+ self.query_norm = RMSNorm(dim)
1018
+ self.key_norm = RMSNorm(dim)
1019
+
1020
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
1021
+ q = self.query_norm(q)
1022
+ k = self.key_norm(k)
1023
+ return q.to(v), k.to(v)
1024
+
1025
+ class SelfAttention(nn.Module):
1026
+ def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
1027
+ super().__init__()
1028
+ self.num_heads = num_heads
1029
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
1030
+ head_dim = dim // num_heads
1031
+ self.norm = QKNorm(head_dim)
1032
+ self.proj = nn.Linear(dim, dim)
1033
+
1034
+ def forward(self, x: Tensor, pe: Tensor) -> Tensor:
1035
+ qkv = self.qkv(x)
1036
+ B, L, _ = qkv.shape
1037
+ qkv = qkv.view(B, L, 3, self.num_heads, -1)
1038
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
1039
+ q, k = self.norm(q, k, v)
1040
+ x = attention(q, k, v, pe=pe)
1041
+ x = self.proj(x)
1042
+ return x
1043
+
1044
+ from dataclasses import dataclass
1045
+
1046
+ @dataclass
1047
+ class ModulationOut:
1048
+ shift: Tensor
1049
+ scale: Tensor
1050
+ gate: Tensor
1051
+
1052
+ class Modulation(nn.Module):
1053
+ def __init__(self, dim: int, double: bool):
1054
+ super().__init__()
1055
+ self.is_double = double
1056
+ self.multiplier = 6 if double else 3
1057
+ self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
1058
+
1059
+ def forward(self, vec: Tensor):
1060
+ out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
1061
+ first = ModulationOut(*out[:3])
1062
+ second = ModulationOut(*out[3:]) if self.is_double else None
1063
+ return first, second
1064
+
1065
+ class DoubleStreamBlock(nn.Module):
1066
+ def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
1067
+ super().__init__()
1068
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
1069
+ self.num_heads = num_heads
1070
+ self.hidden_size = hidden_size
1071
+ self.img_mod = Modulation(hidden_size, double=True)
1072
+ self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1073
+ self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
1074
+ self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1075
+ self.img_mlp = nn.Sequential(
1076
+ nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
1077
+ nn.GELU(approximate="tanh"),
1078
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
1079
+ )
1080
+ self.txt_mod = Modulation(hidden_size, double=True)
1081
+ self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1082
+ self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
1083
+ self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1084
+ self.txt_mlp = nn.Sequential(
1085
+ nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
1086
+ nn.GELU(approximate="tanh"),
1087
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
1088
+ )
1089
+
1090
+ def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
1091
+ img_mod1, img_mod2 = self.img_mod(vec)
1092
+ txt_mod1, txt_mod2 = self.txt_mod(vec)
1093
+
1094
+ # Image attention
1095
+ img_modulated = self.img_norm1(img)
1096
+ img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
1097
+ img_qkv = self.img_attn.qkv(img_modulated)
1098
+ B, L, _ = img_qkv.shape
1099
+ H = self.num_heads
1100
+ D = img_qkv.shape[-1] // (3 * H)
1101
+ img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
1102
+ img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
1103
+
1104
+ # Text attention
1105
+ txt_modulated = self.txt_norm1(txt)
1106
+ txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
1107
+ txt_qkv = self.txt_attn.qkv(txt_modulated)
1108
+ B, L, _ = txt_qkv.shape
1109
+ txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
1110
+ txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
1111
+
1112
+ # Combined attention
1113
+ q = torch.cat((txt_q, img_q), dim=2)
1114
+ k = torch.cat((txt_k, img_k), dim=2)
1115
+ v = torch.cat((txt_v, img_v), dim=2)
1116
+ attn = attention(q, k, v, pe=pe)
1117
+ txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
1118
+
1119
+ # Img final
1120
+ img = img + img_mod1.gate * self.img_attn.proj(img_attn)
1121
+ img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
1122
+
1123
+ # Text final
1124
+ txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
1125
+ txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
1126
+ return img, txt
1127
+
1128
+ class SingleStreamBlock(nn.Module):
1129
+ def __init__(
1130
+ self,
1131
+ hidden_size: int,
1132
+ num_heads: int,
1133
+ mlp_ratio: float = 4.0,
1134
+ qk_scale: float | None = None,
1135
+ ):
1136
+ super().__init__()
1137
+ self.hidden_dim = hidden_size
1138
+ self.num_heads = num_heads
1139
+ head_dim = hidden_size // num_heads
1140
+ self.scale = qk_scale or head_dim**-0.5
1141
+ self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
1142
+ self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
1143
+ self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
1144
+ self.norm = QKNorm(head_dim)
1145
+ self.hidden_size = hidden_size
1146
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1147
+ self.mlp_act = nn.GELU(approximate="tanh")
1148
+ self.modulation = Modulation(hidden_size, double=False)
1149
+
1150
+ def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
1151
+ mod, _ = self.modulation(vec)
1152
+ x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
1153
+ qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
1154
+ qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
1155
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
1156
+ q, k = self.norm(q, k, v)
1157
+ attn = attention(q, k, v, pe=pe)
1158
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
1159
+ return x + mod.gate * output
1160
+
1161
+ class LastLayer(nn.Module):
1162
+ def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
1163
+ super().__init__()
1164
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1165
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
1166
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
1167
+
1168
+ def forward(self, x: Tensor, vec: Tensor) -> Tensor:
1169
+ shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
1170
+ x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
1171
+ x = self.linear(x)
1172
+ return x
1173
+
1174
+ from dataclasses import dataclass, field
1175
+
1176
+ @dataclass
1177
+ class FluxParams:
1178
+ in_channels: int = 64
1179
+ vec_in_dim: int = 768
1180
+ context_in_dim: int = 4096
1181
+ hidden_size: int = 3072
1182
+ mlp_ratio: float = 4.0
1183
+ num_heads: int = 24
1184
+ depth: int = 19
1185
+ depth_single_blocks: int = 38
1186
+ axes_dim: list[int] = field(default_factory=lambda: [16, 56, 56])
1187
+ theta: int = 10000
1188
+ qkv_bias: bool = True
1189
+ guidance_embed: bool = True
1190
+
1191
+ class Flux(nn.Module):
1192
+ def __init__(self, params = FluxParams()):
1193
+ super().__init__()
1194
+ self.params = params
1195
+ self.in_channels = params.in_channels
1196
+ self.out_channels = self.in_channels
1197
+ if params.hidden_size % params.num_heads != 0:
1198
+ raise ValueError(
1199
+ f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
1200
+ )
1201
+ pe_dim = params.hidden_size // params.num_heads
1202
+ if sum(params.axes_dim) != pe_dim:
1203
+ raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
1204
+ self.hidden_size = params.hidden_size
1205
+ self.num_heads = params.num_heads
1206
+ self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
1207
+ self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
1208
+ self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
1209
+ self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
1210
+ self.guidance_in = (
1211
+ MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
1212
+ )
1213
+ self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
1214
+
1215
+ self.double_blocks = nn.ModuleList(
1216
+ [
1217
+ DoubleStreamBlock(
1218
+ self.hidden_size,
1219
+ self.num_heads,
1220
+ mlp_ratio=params.mlp_ratio,
1221
+ qkv_bias=params.qkv_bias,
1222
+ )
1223
+ for _ in range(params.depth)
1224
+ ]
1225
+ )
1226
+
1227
+ self.single_blocks = nn.ModuleList(
1228
+ [
1229
+ SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
1230
+ for _ in range(params.depth_single_blocks)
1231
+ ]
1232
+ )
1233
+
1234
+ self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
1235
+
1236
+ def forward(
1237
+ self,
1238
+ img: Tensor,
1239
+ img_ids: Tensor,
1240
+ txt: Tensor,
1241
+ txt_ids: Tensor,
1242
+ timesteps: Tensor,
1243
+ y: Tensor,
1244
+ guidance: Tensor | None = None,
1245
+ ) -> Tensor:
1246
+ if img.ndim != 3 or txt.ndim != 3:
1247
+ raise ValueError("Input img and txt tensors must have 3 dimensions.")
1248
+ img = self.img_in(img)
1249
+ vec = self.time_in(timestep_embedding(timesteps, 256))
1250
+ if self.params.guidance_embed:
1251
+ if guidance is None:
1252
+ raise ValueError("No guidance strength provided for guidance-distilled model.")
1253
+ vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
1254
+ vec = vec + self.vector_in(y)
1255
+ txt = self.txt_in(txt)
1256
+ ids = torch.cat((txt_ids, img_ids), dim=1)
1257
+ pe = self.pe_embedder(ids)
1258
+ for block in self.double_blocks:
1259
+ img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
1260
+ img = torch.cat((txt, img), 1)
1261
+ for block in self.single_blocks:
1262
+ img = block(img, vec=vec, pe=pe)
1263
+ img = img[:, txt.shape[1] :, ...]
1264
+ img = self.final_layer(img, vec)
1265
+ return img
1266
+
1267
+ def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
1268
+ import torch
1269
+ bs, c, h, w = img.shape
1270
+ if bs == 1 and not isinstance(prompt, str):
1271
+ bs = len(prompt)
1272
+ img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
1273
+ if img.shape[0] == 1 and bs > 1:
1274
+ img = repeat(img, "1 ... -> bs ...", bs=bs)
1275
+ img_ids = torch.zeros(h // 2, w // 2, 3)
1276
+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
1277
+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
1278
+ img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
1279
+ if isinstance(prompt, str):
1280
+ prompt = [prompt]
1281
+ txt = t5(prompt)
1282
+ if txt.shape[0] == 1 and bs > 1:
1283
+ txt = repeat(txt, "1 ... -> bs ...", bs=bs)
1284
+ txt_ids = torch.zeros(bs, txt.shape[1], 3)
1285
+ vec = clip(prompt)
1286
+ if vec.shape[0] == 1 and bs > 1:
1287
+ vec = repeat(vec, "1 ... -> bs ...", bs=bs)
1288
+ return {
1289
+ "img": img,
1290
+ "img_ids": img_ids.to(img.device),
1291
+ "txt": txt.to(img.device),
1292
+ "txt_ids": txt_ids.to(img.device),
1293
+ "vec": vec.to(img.device),
1294
+ }
1295
+
1296
+ def time_shift(mu: float, sigma: float, t: Tensor):
1297
+ import math
1298
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
1299
+
1300
+ def get_lin_function(
1301
+ x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
1302
+ ) -> Callable[[float], float]:
1303
+ import math
1304
+ m = (y2 - y1) / (x2 - x1)
1305
+ b = y1 - m * x1
1306
+ return lambda x: m * x + b
1307
+
1308
+ def get_schedule(
1309
+ num_steps: int,
1310
+ image_seq_len: int,
1311
+ base_shift: float = 0.5,
1312
+ max_shift: float = 1.15,
1313
+ shift: bool = True,
1314
+ ) -> list[float]:
1315
+ import torch
1316
+ import math
1317
+ timesteps = torch.linspace(1, 0, num_steps + 1)
1318
+ if shift:
1319
+ mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
1320
+ timesteps = time_shift(mu, 1.0, timesteps)
1321
+ return timesteps.tolist()
1322
+
1323
+ def denoise(
1324
+ model: Flux,
1325
+ img: Tensor,
1326
+ img_ids: Tensor,
1327
+ txt: Tensor,
1328
+ txt_ids: Tensor,
1329
+ vec: Tensor,
1330
+ timesteps: list[float],
1331
+ guidance: float = 4.0,
1332
+ ):
1333
+ import torch
1334
+ guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
1335
+ for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
1336
+ t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
1337
+ pred = model(
1338
+ img=img,
1339
+ img_ids=img_ids,
1340
+ txt=txt,
1341
+ txt_ids=txt_ids,
1342
+ y=vec,
1343
+ timesteps=t_vec,
1344
+ guidance=guidance_vec,
1345
+ )
1346
+ img = img + (t_prev - t_curr) * pred
1347
+ return img
1348
+
1349
+ def unpack(x: Tensor, height: int, width: int) -> Tensor:
1350
+ return rearrange(
1351
+ x,
1352
+ "b (h w) (c ph pw) -> b c (h ph) (w pw)",
1353
+ h=math.ceil(height / 16),
1354
+ w=math.ceil(width / 16),
1355
+ ph=2,
1356
+ pw=2,
1357
+ )
1358
+
1359
+ @dataclass
1360
+ class SamplingOptions:
1361
+ prompt: str
1362
+ width: int
1363
+ height: int
1364
+ guidance: float
1365
+ seed: int | None
1366
+
1367
+ def get_image(image) -> torch.Tensor | None:
1368
+ if image is None:
1369
+ return None
1370
+ image = Image.fromarray(image).convert("RGB")
1371
+ transform = transforms.Compose([
1372
+ transforms.ToTensor(),
1373
+ transforms.Lambda(lambda x: 2.0 * x - 1.0),
1374
+ ])
1375
+ img: torch.Tensor = transform(image)
1376
+ return img[None, ...]
1377
+
1378
+ # Load the NF4 quantized checkpoint
1379
+ from huggingface_hub import hf_hub_download
1380
+ from safetensors.torch import load_file
1381
+
1382
+ sd = load_file(hf_hub_download(repo_id="lllyasviel/flux1-dev-bnb-nf4", filename="flux1-dev-bnb-nf4-v2.safetensors"))
1383
+ sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
1384
+ model = Flux().to(dtype=torch.bfloat16, device=device)
1385
+ result = model.load_state_dict(sd)
1386
+ model_zero_init = False
1387
+
1388
+ # Remove @spaces.GPU decorator - we'll handle GPU allocation manually
1389
+ # @spaces.GPU
1390
+ @torch.no_grad()
1391
+ def generate_image(
1392
+ prompt, width, height, guidance, inference_steps, seed,
1393
+ do_img2img, init_image, image2image_strength, resize_img,
1394
+ progress=gr.Progress(track_tqdm=True),
1395
+ ):
1396
+ if seed == 0:
1397
+ seed = int(random.random() * 1_000_000)
1398
+
1399
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1400
+ torch_device = torch.device(device)
1401
+
1402
+ global model, model_zero_init
1403
+ if not model_zero_init:
1404
+ model = model.to(torch_device)
1405
+ model_zero_init = True
1406
+
1407
+ if do_img2img and init_image is not None:
1408
+ init_image = get_image(init_image)
1409
+ if resize_img:
1410
+ init_image = torch.nn.functional.interpolate(init_image, (height, width))
1411
+ else:
1412
+ h, w = init_image.shape[-2:]
1413
+ init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
1414
+ height = init_image.shape[-2]
1415
+ width = init_image.shape[-1]
1416
+ init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
1417
+ init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
1418
+
1419
+ generator = torch.Generator(device=device).manual_seed(seed)
1420
+ x = torch.randn(
1421
+ 1,
1422
+ 16,
1423
+ 2 * math.ceil(height / 16),
1424
+ 2 * math.ceil(width / 16),
1425
+ device=device,
1426
+ dtype=torch.bfloat16,
1427
+ generator=generator
1428
+ )
1429
+
1430
+ timesteps = get_schedule(inference_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
1431
+
1432
+ if do_img2img and init_image is not None:
1433
+ t_idx = int((1 - image2image_strength) * inference_steps)
1434
+ t = timesteps[t_idx]
1435
+ timesteps = timesteps[t_idx:]
1436
+ x = t * x + (1.0 - t) * init_image.to(x.dtype)
1437
+
1438
+ inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
1439
+ x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
1440
+ x = unpack(x.float(), height, width)
1441
+
1442
+ with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
1443
+ x = (x / ae.config.scaling_factor) + ae.config.shift_factor
1444
+ x = ae.decode(x).sample
1445
+
1446
+ x = x.clamp(-1, 1)
1447
+ x = rearrange(x[0], "c h w -> h w c")
1448
+ img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
1449
+ return img, seed
1450
+
1451
+ def create_demo():
1452
+ with gr.Blocks(css=".gradio-container {background-color: #282828 !important;}") as demo:
1453
+ gr.HTML(
1454
+ """
1455
+ <div style="text-align: center; margin: 0 auto;">
1456
+ <h1 style="color: #ffffff; font-weight: 900;">
1457
+ FluxLLama
1458
+ </h1>
1459
+ </div>
1460
+ """
1461
+ )
1462
+
1463
+ gr.HTML(
1464
+ """
1465
+ <div class='container' style='display:flex; justify-content:center; gap:12px;'>
1466
+ <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
1467
+ <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">
1468
+ </a>
1469
+
1470
+ <a href="https://discord.gg/openfreeai" target="_blank">
1471
+ <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">
1472
+ </a>
1473
+ </div>
1474
+ """
1475
+ )
1476
+
1477
+
1478
+ with gr.Row():
1479
+ with gr.Column():
1480
+ prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")
1481
+ width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=640)
1482
+ height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=640)
1483
+ guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
1484
+ inference_steps = gr.Slider(
1485
+ label="Inference steps",
1486
+ minimum=1,
1487
+ maximum=30,
1488
+ step=1,
1489
+ value=16,
1490
+ )
1491
+ seed = gr.Number(label="Seed", precision=-1)
1492
+ do_img2img = gr.Checkbox(label="Image to Image", value=False)
1493
+ init_image = gr.Image(label="Initial Image", visible=False)
1494
+ image2image_strength = gr.Slider(
1495
+ minimum=0.0,
1496
+ maximum=1.0,
1497
+ step=0.01,
1498
+ label="Noising Strength",
1499
+ value=0.8,
1500
+ visible=False
1501
+ )
1502
+ resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
1503
+ generate_button = gr.Button("Generate", variant="primary")
1504
+ with gr.Column():
1505
+ output_image = gr.Image(label="Result")
1506
+ output_seed = gr.Text(label="Seed Used")
1507
+
1508
+ do_img2img.change(
1509
+ fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
1510
+ inputs=[do_img2img],
1511
+ outputs=[init_image, image2image_strength, resize_img]
1512
+ )
1513
+
1514
+ generate_button.click(
1515
+ fn=generate_image,
1516
+ inputs=[
1517
+ prompt, width, height, guidance,
1518
+ inference_steps, seed, do_img2img,
1519
+ init_image, image2image_strength, resize_img
1520
+ ],
1521
+ outputs=[output_image, output_seed]
1522
+ )
1523
+ return demo
1524
+
1525
+ if __name__ == "__main__":
1526
+ # Create the demo
1527
+ demo = create_demo()
1528
+ # Enable the queue to handle concurrency
1529
+ demo.queue()
1530
+ # Launch with show_api=False and share=True to avoid the "bool is not iterable" error
1531
+ # and the "ValueError: When localhost is not accessible..." error.
1532
+ # Remove mcp_server=True as it's not a valid parameter
1533
+ demo.launch(show_api=False, share=True, server_name="0.0.0.0")