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+
from torchvision import transforms
|
4 |
+
from dataclasses import dataclass
|
5 |
+
import math
|
6 |
+
from typing import Callable
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
from tqdm import tqdm
|
11 |
+
from einops import rearrange, repeat
|
12 |
+
from diffusers import AutoencoderKL
|
13 |
+
from torch import Tensor, nn
|
14 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokenizer
|
15 |
+
from safetensors.torch import load_file
|
16 |
+
|
17 |
+
# ---------------- Encoders ----------------
|
18 |
+
|
19 |
+
class HFEmbedder(nn.Module):
|
20 |
+
def __init__(self, version: str, max_length: int, **hf_kwargs):
|
21 |
+
super().__init__()
|
22 |
+
self.is_clip = version.startswith("openai")
|
23 |
+
self.max_length = max_length
|
24 |
+
self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
|
25 |
+
|
26 |
+
if self.is_clip:
|
27 |
+
self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
|
28 |
+
self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
|
29 |
+
else:
|
30 |
+
self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
|
31 |
+
self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
|
32 |
+
|
33 |
+
self.hf_module = self.hf_module.eval().requires_grad_(False)
|
34 |
+
|
35 |
+
def forward(self, text: list[str]) -> Tensor:
|
36 |
+
batch_encoding = self.tokenizer(
|
37 |
+
text,
|
38 |
+
truncation=True,
|
39 |
+
max_length=self.max_length,
|
40 |
+
return_length=False,
|
41 |
+
return_overflowing_tokens=False,
|
42 |
+
padding="max_length",
|
43 |
+
return_tensors="pt",
|
44 |
+
)
|
45 |
+
|
46 |
+
outputs = self.hf_module(
|
47 |
+
input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
|
48 |
+
attention_mask=None,
|
49 |
+
output_hidden_states=False,
|
50 |
+
)
|
51 |
+
return outputs[self.output_key]
|
52 |
+
|
53 |
+
|
54 |
+
device = "cuda"
|
55 |
+
t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
|
56 |
+
clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
|
57 |
+
ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
|
58 |
+
# quantize(t5, weights=qfloat8)
|
59 |
+
# freeze(t5)
|
60 |
+
|
61 |
+
|
62 |
+
# ---------------- Model ----------------
|
63 |
+
|
64 |
+
|
65 |
+
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
|
66 |
+
q, k = apply_rope(q, k, pe)
|
67 |
+
|
68 |
+
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
69 |
+
# x = rearrange(x, "B H L D -> B L (H D)")
|
70 |
+
x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
|
71 |
+
|
72 |
+
return x
|
73 |
+
|
74 |
+
|
75 |
+
def rope(pos, dim, theta):
|
76 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
77 |
+
omega = 1.0 / (theta ** scale)
|
78 |
+
|
79 |
+
# out = torch.einsum("...n,d->...nd", pos, omega)
|
80 |
+
out = pos.unsqueeze(-1) * omega.unsqueeze(0)
|
81 |
+
|
82 |
+
cos_out = torch.cos(out)
|
83 |
+
sin_out = torch.sin(out)
|
84 |
+
out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
|
85 |
+
|
86 |
+
# out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
|
87 |
+
b, n, d, _ = out.shape
|
88 |
+
out = out.view(b, n, d, 2, 2)
|
89 |
+
|
90 |
+
return out.float()
|
91 |
+
|
92 |
+
|
93 |
+
def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
94 |
+
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
|
95 |
+
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
|
96 |
+
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
|
97 |
+
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
|
98 |
+
return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
|
99 |
+
|
100 |
+
|
101 |
+
class EmbedND(nn.Module):
|
102 |
+
def __init__(self, dim: int, theta: int, axes_dim: list[int]):
|
103 |
+
super().__init__()
|
104 |
+
self.dim = dim
|
105 |
+
self.theta = theta
|
106 |
+
self.axes_dim = axes_dim
|
107 |
+
|
108 |
+
def forward(self, ids: Tensor) -> Tensor:
|
109 |
+
n_axes = ids.shape[-1]
|
110 |
+
emb = torch.cat(
|
111 |
+
[rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
|
112 |
+
dim=-3,
|
113 |
+
)
|
114 |
+
|
115 |
+
return emb.unsqueeze(1)
|
116 |
+
|
117 |
+
|
118 |
+
def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
|
119 |
+
"""
|
120 |
+
Create sinusoidal timestep embeddings.
|
121 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
122 |
+
These may be fractional.
|
123 |
+
:param dim: the dimension of the output.
|
124 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
125 |
+
:return: an (N, D) Tensor of positional embeddings.
|
126 |
+
"""
|
127 |
+
t = time_factor * t
|
128 |
+
half = dim // 2
|
129 |
+
|
130 |
+
# Do not block CUDA steam, but having about 1e-4 differences with Flux official codes:
|
131 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half)
|
132 |
+
|
133 |
+
# Block CUDA steam, but consistent with official codes:
|
134 |
+
# freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
|
135 |
+
|
136 |
+
args = t[:, None].float() * freqs[None]
|
137 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
138 |
+
if dim % 2:
|
139 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
140 |
+
if torch.is_floating_point(t):
|
141 |
+
embedding = embedding.to(t)
|
142 |
+
return embedding
|
143 |
+
|
144 |
+
|
145 |
+
class MLPEmbedder(nn.Module):
|
146 |
+
def __init__(self, in_dim: int, hidden_dim: int):
|
147 |
+
super().__init__()
|
148 |
+
self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
|
149 |
+
self.silu = nn.SiLU()
|
150 |
+
self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
151 |
+
|
152 |
+
def forward(self, x: Tensor) -> Tensor:
|
153 |
+
return self.out_layer(self.silu(self.in_layer(x)))
|
154 |
+
|
155 |
+
|
156 |
+
class RMSNorm(torch.nn.Module):
|
157 |
+
def __init__(self, dim: int):
|
158 |
+
super().__init__()
|
159 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
160 |
+
|
161 |
+
def forward(self, x: Tensor):
|
162 |
+
x_dtype = x.dtype
|
163 |
+
x = x.float()
|
164 |
+
rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
|
165 |
+
return (x * rrms).to(dtype=x_dtype) * self.scale
|
166 |
+
|
167 |
+
|
168 |
+
class QKNorm(torch.nn.Module):
|
169 |
+
def __init__(self, dim: int):
|
170 |
+
super().__init__()
|
171 |
+
self.query_norm = RMSNorm(dim)
|
172 |
+
self.key_norm = RMSNorm(dim)
|
173 |
+
|
174 |
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
|
175 |
+
q = self.query_norm(q)
|
176 |
+
k = self.key_norm(k)
|
177 |
+
return q.to(v), k.to(v)
|
178 |
+
|
179 |
+
|
180 |
+
class SelfAttention(nn.Module):
|
181 |
+
def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
|
182 |
+
super().__init__()
|
183 |
+
self.num_heads = num_heads
|
184 |
+
head_dim = dim // num_heads
|
185 |
+
|
186 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
187 |
+
self.norm = QKNorm(head_dim)
|
188 |
+
self.proj = nn.Linear(dim, dim)
|
189 |
+
|
190 |
+
def forward(self, x: Tensor, pe: Tensor) -> Tensor:
|
191 |
+
qkv = self.qkv(x)
|
192 |
+
# q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
193 |
+
B, L, _ = qkv.shape
|
194 |
+
qkv = qkv.view(B, L, 3, self.num_heads, -1)
|
195 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
196 |
+
q, k = self.norm(q, k, v)
|
197 |
+
x = attention(q, k, v, pe=pe)
|
198 |
+
x = self.proj(x)
|
199 |
+
return x
|
200 |
+
|
201 |
+
|
202 |
+
@dataclass
|
203 |
+
class ModulationOut:
|
204 |
+
shift: Tensor
|
205 |
+
scale: Tensor
|
206 |
+
gate: Tensor
|
207 |
+
|
208 |
+
|
209 |
+
class Modulation(nn.Module):
|
210 |
+
def __init__(self, dim: int, double: bool):
|
211 |
+
super().__init__()
|
212 |
+
self.is_double = double
|
213 |
+
self.multiplier = 6 if double else 3
|
214 |
+
self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
|
215 |
+
|
216 |
+
def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
|
217 |
+
out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
|
218 |
+
|
219 |
+
return (
|
220 |
+
ModulationOut(*out[:3]),
|
221 |
+
ModulationOut(*out[3:]) if self.is_double else None,
|
222 |
+
)
|
223 |
+
|
224 |
+
|
225 |
+
class DoubleStreamBlock(nn.Module):
|
226 |
+
def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
|
227 |
+
super().__init__()
|
228 |
+
|
229 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
230 |
+
self.num_heads = num_heads
|
231 |
+
self.hidden_size = hidden_size
|
232 |
+
self.img_mod = Modulation(hidden_size, double=True)
|
233 |
+
self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
234 |
+
self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
235 |
+
|
236 |
+
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
237 |
+
self.img_mlp = nn.Sequential(
|
238 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
239 |
+
nn.GELU(approximate="tanh"),
|
240 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
241 |
+
)
|
242 |
+
|
243 |
+
self.txt_mod = Modulation(hidden_size, double=True)
|
244 |
+
self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
245 |
+
self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
246 |
+
|
247 |
+
self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
248 |
+
self.txt_mlp = nn.Sequential(
|
249 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
250 |
+
nn.GELU(approximate="tanh"),
|
251 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
252 |
+
)
|
253 |
+
|
254 |
+
def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
|
255 |
+
img_mod1, img_mod2 = self.img_mod(vec)
|
256 |
+
txt_mod1, txt_mod2 = self.txt_mod(vec)
|
257 |
+
|
258 |
+
# prepare image for attention
|
259 |
+
img_modulated = self.img_norm1(img)
|
260 |
+
img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
|
261 |
+
img_qkv = self.img_attn.qkv(img_modulated)
|
262 |
+
# img_q, img_k, img_v = rearrange(img_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
263 |
+
B, L, _ = img_qkv.shape
|
264 |
+
H = self.num_heads
|
265 |
+
D = img_qkv.shape[-1] // (3 * H)
|
266 |
+
img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
267 |
+
img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
|
268 |
+
|
269 |
+
# prepare txt for attention
|
270 |
+
txt_modulated = self.txt_norm1(txt)
|
271 |
+
txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
|
272 |
+
txt_qkv = self.txt_attn.qkv(txt_modulated)
|
273 |
+
# txt_q, txt_k, txt_v = rearrange(txt_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
274 |
+
B, L, _ = txt_qkv.shape
|
275 |
+
txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
276 |
+
txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
|
277 |
+
|
278 |
+
# run actual attention
|
279 |
+
q = torch.cat((txt_q, img_q), dim=2)
|
280 |
+
k = torch.cat((txt_k, img_k), dim=2)
|
281 |
+
v = torch.cat((txt_v, img_v), dim=2)
|
282 |
+
|
283 |
+
attn = attention(q, k, v, pe=pe)
|
284 |
+
txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
|
285 |
+
|
286 |
+
# calculate the img bloks
|
287 |
+
img = img + img_mod1.gate * self.img_attn.proj(img_attn)
|
288 |
+
img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
|
289 |
+
|
290 |
+
# calculate the txt bloks
|
291 |
+
txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
|
292 |
+
txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
|
293 |
+
return img, txt
|
294 |
+
|
295 |
+
|
296 |
+
class SingleStreamBlock(nn.Module):
|
297 |
+
"""
|
298 |
+
A DiT block with parallel linear layers as described in
|
299 |
+
https://arxiv.org/abs/2302.05442 and adapted modulation interface.
|
300 |
+
"""
|
301 |
+
|
302 |
+
def __init__(
|
303 |
+
self,
|
304 |
+
hidden_size: int,
|
305 |
+
num_heads: int,
|
306 |
+
mlp_ratio: float = 4.0,
|
307 |
+
qk_scale: float | None = None,
|
308 |
+
):
|
309 |
+
super().__init__()
|
310 |
+
self.hidden_dim = hidden_size
|
311 |
+
self.num_heads = num_heads
|
312 |
+
head_dim = hidden_size // num_heads
|
313 |
+
self.scale = qk_scale or head_dim**-0.5
|
314 |
+
|
315 |
+
self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
316 |
+
# qkv and mlp_in
|
317 |
+
self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
|
318 |
+
# proj and mlp_out
|
319 |
+
self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
|
320 |
+
|
321 |
+
self.norm = QKNorm(head_dim)
|
322 |
+
|
323 |
+
self.hidden_size = hidden_size
|
324 |
+
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
325 |
+
|
326 |
+
self.mlp_act = nn.GELU(approximate="tanh")
|
327 |
+
self.modulation = Modulation(hidden_size, double=False)
|
328 |
+
|
329 |
+
def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
|
330 |
+
mod, _ = self.modulation(vec)
|
331 |
+
x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
|
332 |
+
qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
|
333 |
+
|
334 |
+
# q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
335 |
+
qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
|
336 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
337 |
+
q, k = self.norm(q, k, v)
|
338 |
+
|
339 |
+
# compute attention
|
340 |
+
attn = attention(q, k, v, pe=pe)
|
341 |
+
# compute activation in mlp stream, cat again and run second linear layer
|
342 |
+
output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
|
343 |
+
return x + mod.gate * output
|
344 |
+
|
345 |
+
|
346 |
+
class LastLayer(nn.Module):
|
347 |
+
def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
|
348 |
+
super().__init__()
|
349 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
350 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
351 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
|
352 |
+
|
353 |
+
def forward(self, x: Tensor, vec: Tensor) -> Tensor:
|
354 |
+
shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
|
355 |
+
x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
|
356 |
+
x = self.linear(x)
|
357 |
+
return x
|
358 |
+
|
359 |
+
|
360 |
+
class FluxParams:
|
361 |
+
in_channels: int = 64
|
362 |
+
vec_in_dim: int = 768
|
363 |
+
context_in_dim: int = 4096
|
364 |
+
hidden_size: int = 3072
|
365 |
+
mlp_ratio: float = 4.0
|
366 |
+
num_heads: int = 24
|
367 |
+
depth: int = 19
|
368 |
+
depth_single_blocks: int = 38
|
369 |
+
axes_dim: list = [16, 56, 56]
|
370 |
+
theta: int = 10_000
|
371 |
+
qkv_bias: bool = True
|
372 |
+
guidance_embed: bool = True
|
373 |
+
|
374 |
+
|
375 |
+
class Flux(nn.Module):
|
376 |
+
"""
|
377 |
+
Transformer model for flow matching on sequences.
|
378 |
+
"""
|
379 |
+
|
380 |
+
def __init__(self, params = FluxParams()):
|
381 |
+
super().__init__()
|
382 |
+
|
383 |
+
self.params = params
|
384 |
+
self.in_channels = params.in_channels
|
385 |
+
self.out_channels = self.in_channels
|
386 |
+
if params.hidden_size % params.num_heads != 0:
|
387 |
+
raise ValueError(
|
388 |
+
f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
|
389 |
+
)
|
390 |
+
pe_dim = params.hidden_size // params.num_heads
|
391 |
+
if sum(params.axes_dim) != pe_dim:
|
392 |
+
raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
|
393 |
+
self.hidden_size = params.hidden_size
|
394 |
+
self.num_heads = params.num_heads
|
395 |
+
self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
|
396 |
+
self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
|
397 |
+
self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
|
398 |
+
self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
|
399 |
+
# self.guidance_in = (
|
400 |
+
# MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
|
401 |
+
# )
|
402 |
+
self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
|
403 |
+
|
404 |
+
self.double_blocks = nn.ModuleList(
|
405 |
+
[
|
406 |
+
DoubleStreamBlock(
|
407 |
+
self.hidden_size,
|
408 |
+
self.num_heads,
|
409 |
+
mlp_ratio=params.mlp_ratio,
|
410 |
+
qkv_bias=params.qkv_bias,
|
411 |
+
)
|
412 |
+
for _ in range(params.depth)
|
413 |
+
]
|
414 |
+
)
|
415 |
+
|
416 |
+
self.single_blocks = nn.ModuleList(
|
417 |
+
[
|
418 |
+
SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
|
419 |
+
for _ in range(params.depth_single_blocks)
|
420 |
+
]
|
421 |
+
)
|
422 |
+
|
423 |
+
self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
|
424 |
+
|
425 |
+
def forward(
|
426 |
+
self,
|
427 |
+
img: Tensor,
|
428 |
+
img_ids: Tensor,
|
429 |
+
txt: Tensor,
|
430 |
+
txt_ids: Tensor,
|
431 |
+
timesteps: Tensor,
|
432 |
+
y: Tensor,
|
433 |
+
guidance: Tensor | None = None,
|
434 |
+
use_guidance_vec = True,
|
435 |
+
) -> Tensor:
|
436 |
+
if img.ndim != 3 or txt.ndim != 3:
|
437 |
+
raise ValueError("Input img and txt tensors must have 3 dimensions.")
|
438 |
+
|
439 |
+
# running on sequences img
|
440 |
+
img = self.img_in(img)
|
441 |
+
vec = self.time_in(timestep_embedding(timesteps, 256))
|
442 |
+
# if self.params.guidance_embed and use_guidance_vec:
|
443 |
+
# if guidance is None:
|
444 |
+
# raise ValueError("Didn't get guidance strength for guidance distilled model.")
|
445 |
+
# vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
|
446 |
+
vec = vec + self.vector_in(y)
|
447 |
+
txt = self.txt_in(txt)
|
448 |
+
|
449 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
450 |
+
pe = self.pe_embedder(ids)
|
451 |
+
|
452 |
+
for block in self.double_blocks:
|
453 |
+
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
|
454 |
+
|
455 |
+
img = torch.cat((txt, img), 1)
|
456 |
+
for block in self.single_blocks:
|
457 |
+
img = block(img, vec=vec, pe=pe)
|
458 |
+
img = img[:, txt.shape[1] :, ...]
|
459 |
+
|
460 |
+
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
|
461 |
+
return img
|
462 |
+
|
463 |
+
|
464 |
+
def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
|
465 |
+
bs, c, h, w = img.shape
|
466 |
+
if bs == 1 and not isinstance(prompt, str):
|
467 |
+
bs = len(prompt)
|
468 |
+
|
469 |
+
img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
|
470 |
+
if img.shape[0] == 1 and bs > 1:
|
471 |
+
img = repeat(img, "1 ... -> bs ...", bs=bs)
|
472 |
+
|
473 |
+
img_ids = torch.zeros(h // 2, w // 2, 3)
|
474 |
+
img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
|
475 |
+
img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
|
476 |
+
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
|
477 |
+
|
478 |
+
if isinstance(prompt, str):
|
479 |
+
prompt = [prompt]
|
480 |
+
txt = t5(prompt)
|
481 |
+
if txt.shape[0] == 1 and bs > 1:
|
482 |
+
txt = repeat(txt, "1 ... -> bs ...", bs=bs)
|
483 |
+
txt_ids = torch.zeros(bs, txt.shape[1], 3)
|
484 |
+
|
485 |
+
vec = clip(prompt)
|
486 |
+
if vec.shape[0] == 1 and bs > 1:
|
487 |
+
vec = repeat(vec, "1 ... -> bs ...", bs=bs)
|
488 |
+
|
489 |
+
return {
|
490 |
+
"img": img,
|
491 |
+
"img_ids": img_ids.to(img.device),
|
492 |
+
"txt": txt.to(img.device),
|
493 |
+
"txt_ids": txt_ids.to(img.device),
|
494 |
+
"vec": vec.to(img.device),
|
495 |
+
}
|
496 |
+
|
497 |
+
|
498 |
+
def time_shift(mu: float, sigma: float, t: Tensor):
|
499 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
500 |
+
|
501 |
+
|
502 |
+
def get_lin_function(
|
503 |
+
x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
|
504 |
+
) -> Callable[[float], float]:
|
505 |
+
m = (y2 - y1) / (x2 - x1)
|
506 |
+
b = y1 - m * x1
|
507 |
+
return lambda x: m * x + b
|
508 |
+
|
509 |
+
|
510 |
+
def get_schedule(
|
511 |
+
num_steps: int,
|
512 |
+
image_seq_len: int,
|
513 |
+
base_shift: float = 0.5,
|
514 |
+
max_shift: float = 1.15,
|
515 |
+
shift: bool = True,
|
516 |
+
) -> list[float]:
|
517 |
+
# extra step for zero
|
518 |
+
timesteps = torch.linspace(1, 0, num_steps + 1)
|
519 |
+
|
520 |
+
# shifting the schedule to favor high timesteps for higher signal images
|
521 |
+
if shift:
|
522 |
+
# eastimate mu based on linear estimation between two points
|
523 |
+
mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
|
524 |
+
timesteps = time_shift(mu, 1.0, timesteps)
|
525 |
+
|
526 |
+
return timesteps.tolist()
|
527 |
+
|
528 |
+
|
529 |
+
def denoise(
|
530 |
+
model: Flux,
|
531 |
+
# model input
|
532 |
+
img: Tensor,
|
533 |
+
img_ids: Tensor,
|
534 |
+
txt: Tensor,
|
535 |
+
txt_ids: Tensor,
|
536 |
+
vec: Tensor,
|
537 |
+
# sampling parameters
|
538 |
+
timesteps: list[float],
|
539 |
+
guidance: float = 4.0,
|
540 |
+
use_cfg_guidance = False,
|
541 |
+
):
|
542 |
+
# this is ignored for schnell
|
543 |
+
guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
|
544 |
+
for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:])):
|
545 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
546 |
+
|
547 |
+
if use_cfg_guidance:
|
548 |
+
half_x = img[:len(img)//2]
|
549 |
+
img = torch.cat([half_x, half_x], dim=0)
|
550 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
551 |
+
|
552 |
+
pred = model(
|
553 |
+
img=img,
|
554 |
+
img_ids=img_ids,
|
555 |
+
txt=txt,
|
556 |
+
txt_ids=txt_ids,
|
557 |
+
y=vec,
|
558 |
+
timesteps=t_vec,
|
559 |
+
guidance=guidance_vec,
|
560 |
+
use_guidance_vec=not use_cfg_guidance,
|
561 |
+
)
|
562 |
+
|
563 |
+
if use_cfg_guidance:
|
564 |
+
uncond, cond = pred.chunk(2, dim=0)
|
565 |
+
model_output = uncond + guidance * (cond - uncond)
|
566 |
+
pred = torch.cat([model_output, model_output], dim=0)
|
567 |
+
|
568 |
+
img = img + (t_prev - t_curr) * pred
|
569 |
+
|
570 |
+
return img
|
571 |
+
|
572 |
+
|
573 |
+
def unpack(x: Tensor, height: int, width: int) -> Tensor:
|
574 |
+
return rearrange(
|
575 |
+
x,
|
576 |
+
"b (h w) (c ph pw) -> b c (h ph) (w pw)",
|
577 |
+
h=math.ceil(height / 16),
|
578 |
+
w=math.ceil(width / 16),
|
579 |
+
ph=2,
|
580 |
+
pw=2,
|
581 |
+
)
|
582 |
+
|
583 |
+
@dataclass
|
584 |
+
class SamplingOptions:
|
585 |
+
prompt: str
|
586 |
+
width: int
|
587 |
+
height: int
|
588 |
+
guidance: float
|
589 |
+
seed: int | None
|
590 |
+
|
591 |
+
|
592 |
+
def get_image(image) -> torch.Tensor | None:
|
593 |
+
if image is None:
|
594 |
+
return None
|
595 |
+
image = Image.fromarray(image).convert("RGB")
|
596 |
+
|
597 |
+
transform = transforms.Compose([
|
598 |
+
transforms.ToTensor(),
|
599 |
+
transforms.Lambda(lambda x: 2.0 * x - 1.0),
|
600 |
+
])
|
601 |
+
img: torch.Tensor = transform(image)
|
602 |
+
return img[None, ...]
|
603 |
+
|
604 |
+
|
605 |
+
# ---------------- Demo ----------------
|
606 |
+
|
607 |
+
|
608 |
+
class EmptyInitWrapper(torch.overrides.TorchFunctionMode):
|
609 |
+
def __init__(self, device=None):
|
610 |
+
self.device = device
|
611 |
+
|
612 |
+
def __torch_function__(self, func, types, args=(), kwargs=None):
|
613 |
+
kwargs = kwargs or {}
|
614 |
+
if getattr(func, "__module__", None) == "torch.nn.init":
|
615 |
+
if "tensor" in kwargs:
|
616 |
+
return kwargs["tensor"]
|
617 |
+
else:
|
618 |
+
return args[0]
|
619 |
+
if (
|
620 |
+
self.device is not None
|
621 |
+
and func in torch.utils._device._device_constructors()
|
622 |
+
and kwargs.get("device") is None
|
623 |
+
):
|
624 |
+
kwargs["device"] = self.device
|
625 |
+
return func(*args, **kwargs)
|
626 |
+
|
627 |
+
with EmptyInitWrapper():
|
628 |
+
model = Flux().to(dtype=torch.bfloat16, device="cuda")
|
629 |
+
sd = load_file("./consolidated_s6700.safetensors")
|
630 |
+
sd = {k.replace("model.", ""): v for k, v in sd.items()}
|
631 |
+
result = model.load_state_dict(sd)
|
632 |
+
|
633 |
+
@torch.no_grad()
|
634 |
+
def generate_image(
|
635 |
+
prompt, neg_prompt, width, height, guidance, seed,
|
636 |
+
do_img2img, init_image, image2image_strength, resize_img,
|
637 |
+
progress=gr.Progress(track_tqdm=True),
|
638 |
+
):
|
639 |
+
if seed == 0:
|
640 |
+
seed = int(random.random() * 1000000)
|
641 |
+
|
642 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
643 |
+
torch_device = torch.device(device)
|
644 |
+
|
645 |
+
if do_img2img and init_image is not None:
|
646 |
+
init_image = get_image(init_image)
|
647 |
+
if resize_img:
|
648 |
+
init_image = torch.nn.functional.interpolate(init_image, (height, width))
|
649 |
+
else:
|
650 |
+
h, w = init_image.shape[-2:]
|
651 |
+
init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
|
652 |
+
height = init_image.shape[-2]
|
653 |
+
width = init_image.shape[-1]
|
654 |
+
init_image = ae.encode(init_image.to(torch_device)).latent_dist.sample()
|
655 |
+
init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
|
656 |
+
|
657 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
658 |
+
x = torch.randn(1, 16, 2 * math.ceil(height / 16), 2 * math.ceil(width / 16), device=device, dtype=torch.bfloat16, generator=generator)
|
659 |
+
|
660 |
+
num_steps = 28
|
661 |
+
timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
|
662 |
+
|
663 |
+
if do_img2img and init_image is not None:
|
664 |
+
t_idx = int((1 - image2image_strength) * num_steps)
|
665 |
+
t = timesteps[t_idx]
|
666 |
+
timesteps = timesteps[t_idx:]
|
667 |
+
x = t * x + (1.0 - t) * init_image.to(x.dtype)
|
668 |
+
|
669 |
+
inp = prepare(t5=t5, clip=clip, img=x, prompt=[neg_prompt, prompt])
|
670 |
+
x = denoise(model, **inp, timesteps=timesteps, guidance=guidance, use_cfg_guidance=True)
|
671 |
+
|
672 |
+
# with profile(activities=[ProfilerActivity.CPU],record_shapes=True,profile_memory=True) as prof:
|
673 |
+
# print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=20))
|
674 |
+
|
675 |
+
x = unpack(x.float(), height, width)
|
676 |
+
with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
|
677 |
+
x = 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 |
+
|
684 |
+
return img, seed
|
685 |
+
|
686 |
+
def create_demo():
|
687 |
+
with gr.Blocks(theme="bethecloud/storj_theme") as demo:
|
688 |
+
with gr.Row():
|
689 |
+
with gr.Column():
|
690 |
+
prompt = gr.Textbox(label="Prompt", value="a photo of a forest with mist swirling around the tree trunks. The word 'FLUX' is painted over it in big, red brush strokes with visible texture")
|
691 |
+
neg_prompt = gr.Textbox(label="Negative Prompt", value="bad photo")
|
692 |
+
width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=1360)
|
693 |
+
height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=768)
|
694 |
+
guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
|
695 |
+
seed = gr.Number(label="Seed", precision=-1)
|
696 |
+
do_img2img = gr.Checkbox(label="Image to Image", value=False)
|
697 |
+
init_image = gr.Image(label="Input Image", visible=False)
|
698 |
+
image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising strength", value=0.8, visible=False)
|
699 |
+
resize_img = gr.Checkbox(label="Resize image", value=True, visible=False)
|
700 |
+
generate_button = gr.Button("Generate")
|
701 |
+
|
702 |
+
with gr.Column():
|
703 |
+
output_image = gr.Image(label="Generated Image")
|
704 |
+
output_seed = gr.Text(label="Used Seed")
|
705 |
+
|
706 |
+
do_img2img.change(
|
707 |
+
fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
|
708 |
+
inputs=[do_img2img],
|
709 |
+
outputs=[init_image, image2image_strength, resize_img]
|
710 |
+
)
|
711 |
+
|
712 |
+
generate_button.click(
|
713 |
+
fn=generate_image,
|
714 |
+
inputs=[prompt, neg_prompt, width, height, guidance, seed, do_img2img, init_image, image2image_strength, resize_img],
|
715 |
+
outputs=[output_image, output_seed]
|
716 |
+
)
|
717 |
+
|
718 |
+
examples = [
|
719 |
+
"a tiny astronaut hatching from an egg on the moon",
|
720 |
+
"a cat holding a sign that says hello world",
|
721 |
+
"an anime illustration of a wiener schnitzel",
|
722 |
+
]
|
723 |
+
|
724 |
+
return demo
|
725 |
+
|
726 |
+
if __name__ == "__main__":
|
727 |
+
demo = create_demo()
|
728 |
+
demo.launch(share=True)
|