ginipick commited on
Commit
712534c
·
verified ·
1 Parent(s): 021621e

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -916
app.py DELETED
@@ -1,916 +0,0 @@
1
- # import os
2
- import spaces
3
-
4
- import time
5
- import gradio as gr
6
- import torch
7
- from PIL import Image
8
- from torchvision import transforms
9
- from dataclasses import dataclass
10
- import math
11
- from typing import Callable
12
-
13
- from tqdm import tqdm
14
- import bitsandbytes as bnb
15
- from bitsandbytes.nn.modules import Params4bit, QuantState
16
-
17
- import torch
18
- import random
19
- from einops import rearrange, repeat
20
- from diffusers import AutoencoderKL
21
- from torch import Tensor, nn
22
- from transformers import CLIPTextModel, CLIPTokenizer
23
- from transformers import T5EncoderModel, T5Tokenizer
24
- # from optimum.quanto import freeze, qfloat8, quantize
25
- from transformers import pipeline
26
-
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
-
63
- device = "cuda"
64
- t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
65
- clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
66
- ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
67
- # quantize(t5, weights=qfloat8)
68
- # freeze(t5)
69
-
70
-
71
- # ---------------- NF4 ----------------
72
-
73
-
74
- def functional_linear_4bits(x, weight, bias):
75
- out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
76
- out = out.to(x)
77
- return out
78
-
79
-
80
- def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantState:
81
- if state is None:
82
- return None
83
-
84
- device = device or state.absmax.device
85
-
86
- state2 = (
87
- QuantState(
88
- absmax=state.state2.absmax.to(device),
89
- shape=state.state2.shape,
90
- code=state.state2.code.to(device),
91
- blocksize=state.state2.blocksize,
92
- quant_type=state.state2.quant_type,
93
- dtype=state.state2.dtype,
94
- )
95
- if state.nested
96
- else None
97
- )
98
-
99
- return QuantState(
100
- absmax=state.absmax.to(device),
101
- shape=state.shape,
102
- code=state.code.to(device),
103
- blocksize=state.blocksize,
104
- quant_type=state.quant_type,
105
- dtype=state.dtype,
106
- offset=state.offset.to(device) if state.nested else None,
107
- state2=state2,
108
- )
109
-
110
-
111
- class ForgeParams4bit(Params4bit):
112
- def to(self, *args, **kwargs):
113
- device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
114
- if device is not None and device.type == "cuda" and not self.bnb_quantized:
115
- return self._quantize(device)
116
- else:
117
- n = ForgeParams4bit(
118
- torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
119
- requires_grad=self.requires_grad,
120
- quant_state=copy_quant_state(self.quant_state, device),
121
- # blocksize=self.blocksize,
122
- # compress_statistics=self.compress_statistics,
123
- compress_statistics=False,
124
- blocksize=64,
125
- quant_type=self.quant_type,
126
- quant_storage=self.quant_storage,
127
- bnb_quantized=self.bnb_quantized,
128
- module=self.module
129
- )
130
- self.module.quant_state = n.quant_state
131
- self.data = n.data
132
- self.quant_state = n.quant_state
133
- return n
134
-
135
-
136
- class ForgeLoader4Bit(torch.nn.Module):
137
- def __init__(self, *, device, dtype, quant_type, **kwargs):
138
- super().__init__()
139
- self.dummy = torch.nn.Parameter(torch.empty(1, device=device, dtype=dtype))
140
- self.weight = None
141
- self.quant_state = None
142
- self.bias = None
143
- self.quant_type = quant_type
144
-
145
- def _save_to_state_dict(self, destination, prefix, keep_vars):
146
- super()._save_to_state_dict(destination, prefix, keep_vars)
147
- quant_state = getattr(self.weight, "quant_state", None)
148
- if quant_state is not None:
149
- for k, v in quant_state.as_dict(packed=True).items():
150
- destination[prefix + "weight." + k] = v if keep_vars else v.detach()
151
- return
152
-
153
- def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
154
- quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
155
-
156
- if any('bitsandbytes' in k for k in quant_state_keys):
157
- quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
158
-
159
- self.weight = ForgeParams4bit.from_prequantized(
160
- data=state_dict[prefix + 'weight'],
161
- quantized_stats=quant_state_dict,
162
- requires_grad=False,
163
- # device=self.dummy.device,
164
- device=torch.device('cuda'),
165
- module=self
166
- )
167
- self.quant_state = self.weight.quant_state
168
-
169
- if prefix + 'bias' in state_dict:
170
- self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
171
-
172
- del self.dummy
173
- elif hasattr(self, 'dummy'):
174
- if prefix + 'weight' in state_dict:
175
- self.weight = ForgeParams4bit(
176
- state_dict[prefix + 'weight'].to(self.dummy),
177
- requires_grad=False,
178
- compress_statistics=True,
179
- quant_type=self.quant_type,
180
- quant_storage=torch.uint8,
181
- module=self,
182
- )
183
- self.quant_state = self.weight.quant_state
184
-
185
- if prefix + 'bias' in state_dict:
186
- self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
187
-
188
- del self.dummy
189
- else:
190
- super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
191
-
192
-
193
- class Linear(ForgeLoader4Bit):
194
- def __init__(self, *args, device=None, dtype=None, **kwargs):
195
- super().__init__(device=device, dtype=dtype, quant_type='nf4')
196
-
197
- def forward(self, x):
198
- self.weight.quant_state = self.quant_state
199
-
200
- if self.bias is not None and self.bias.dtype != x.dtype:
201
- # Maybe this can also be set to all non-bnb ops since the cost is very low.
202
- # And it only invokes one time, and most linear does not have bias
203
- self.bias.data = self.bias.data.to(x.dtype)
204
-
205
- return functional_linear_4bits(x, self.weight, self.bias)
206
-
207
-
208
- nn.Linear = Linear
209
-
210
-
211
- # ---------------- Model ----------------
212
-
213
-
214
- def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
215
- q, k = apply_rope(q, k, pe)
216
-
217
- x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
218
- # x = rearrange(x, "B H L D -> B L (H D)")
219
- x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
220
-
221
- return x
222
-
223
-
224
- def rope(pos, dim, theta):
225
- scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
226
- omega = 1.0 / (theta ** scale)
227
-
228
- # out = torch.einsum("...n,d->...nd", pos, omega)
229
- out = pos.unsqueeze(-1) * omega.unsqueeze(0)
230
-
231
- cos_out = torch.cos(out)
232
- sin_out = torch.sin(out)
233
- out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
234
-
235
- # out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
236
- b, n, d, _ = out.shape
237
- out = out.view(b, n, d, 2, 2)
238
-
239
- return out.float()
240
-
241
-
242
- def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
243
- xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
244
- xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
245
- xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
246
- xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
247
- return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
248
-
249
-
250
- class EmbedND(nn.Module):
251
- def __init__(self, dim: int, theta: int, axes_dim: list[int]):
252
- super().__init__()
253
- self.dim = dim
254
- self.theta = theta
255
- self.axes_dim = axes_dim
256
-
257
- def forward(self, ids: Tensor) -> Tensor:
258
- n_axes = ids.shape[-1]
259
- emb = torch.cat(
260
- [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
261
- dim=-3,
262
- )
263
-
264
- return emb.unsqueeze(1)
265
-
266
-
267
- def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
268
- """
269
- Create sinusoidal timestep embeddings.
270
- :param t: a 1-D Tensor of N indices, one per batch element.
271
- These may be fractional.
272
- :param dim: the dimension of the output.
273
- :param max_period: controls the minimum frequency of the embeddings.
274
- :return: an (N, D) Tensor of positional embeddings.
275
- """
276
- t = time_factor * t
277
- half = dim // 2
278
-
279
- # Do not block CUDA steam, but having about 1e-4 differences with Flux official codes:
280
- # freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half)
281
-
282
- # Block CUDA steam, but consistent with official codes:
283
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
284
-
285
- args = t[:, None].float() * freqs[None]
286
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
287
- if dim % 2:
288
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
289
- if torch.is_floating_point(t):
290
- embedding = embedding.to(t)
291
- return embedding
292
-
293
-
294
- class MLPEmbedder(nn.Module):
295
- def __init__(self, in_dim: int, hidden_dim: int):
296
- super().__init__()
297
- self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
298
- self.silu = nn.SiLU()
299
- self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
300
-
301
- def forward(self, x: Tensor) -> Tensor:
302
- return self.out_layer(self.silu(self.in_layer(x)))
303
-
304
-
305
- class RMSNorm(torch.nn.Module):
306
- def __init__(self, dim: int):
307
- super().__init__()
308
- self.scale = nn.Parameter(torch.ones(dim))
309
-
310
- def forward(self, x: Tensor):
311
- x_dtype = x.dtype
312
- x = x.float()
313
- rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
314
- return (x * rrms).to(dtype=x_dtype) * self.scale
315
-
316
-
317
- class QKNorm(torch.nn.Module):
318
- def __init__(self, dim: int):
319
- super().__init__()
320
- self.query_norm = RMSNorm(dim)
321
- self.key_norm = RMSNorm(dim)
322
-
323
- def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
324
- q = self.query_norm(q)
325
- k = self.key_norm(k)
326
- return q.to(v), k.to(v)
327
-
328
-
329
- class SelfAttention(nn.Module):
330
- def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
331
- super().__init__()
332
- self.num_heads = num_heads
333
- head_dim = dim // num_heads
334
-
335
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
336
- self.norm = QKNorm(head_dim)
337
- self.proj = nn.Linear(dim, dim)
338
-
339
- def forward(self, x: Tensor, pe: Tensor) -> Tensor:
340
- qkv = self.qkv(x)
341
- # q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
342
- B, L, _ = qkv.shape
343
- qkv = qkv.view(B, L, 3, self.num_heads, -1)
344
- q, k, v = qkv.permute(2, 0, 3, 1, 4)
345
- q, k = self.norm(q, k, v)
346
- x = attention(q, k, v, pe=pe)
347
- x = self.proj(x)
348
- return x
349
-
350
-
351
- @dataclass
352
- class ModulationOut:
353
- shift: Tensor
354
- scale: Tensor
355
- gate: Tensor
356
-
357
-
358
- class Modulation(nn.Module):
359
- def __init__(self, dim: int, double: bool):
360
- super().__init__()
361
- self.is_double = double
362
- self.multiplier = 6 if double else 3
363
- self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
364
-
365
- def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
366
- out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
367
-
368
- return (
369
- ModulationOut(*out[:3]),
370
- ModulationOut(*out[3:]) if self.is_double else None,
371
- )
372
-
373
-
374
- class DoubleStreamBlock(nn.Module):
375
- def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
376
- super().__init__()
377
-
378
- mlp_hidden_dim = int(hidden_size * mlp_ratio)
379
- self.num_heads = num_heads
380
- self.hidden_size = hidden_size
381
- self.img_mod = Modulation(hidden_size, double=True)
382
- self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
383
- self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
384
-
385
- self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
386
- self.img_mlp = nn.Sequential(
387
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
388
- nn.GELU(approximate="tanh"),
389
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
390
- )
391
-
392
- self.txt_mod = Modulation(hidden_size, double=True)
393
- self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
394
- self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
395
-
396
- self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
397
- self.txt_mlp = nn.Sequential(
398
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
399
- nn.GELU(approximate="tanh"),
400
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
401
- )
402
-
403
- def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
404
- img_mod1, img_mod2 = self.img_mod(vec)
405
- txt_mod1, txt_mod2 = self.txt_mod(vec)
406
-
407
- # prepare image for attention
408
- img_modulated = self.img_norm1(img)
409
- img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
410
- img_qkv = self.img_attn.qkv(img_modulated)
411
- # 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)
412
- B, L, _ = img_qkv.shape
413
- H = self.num_heads
414
- D = img_qkv.shape[-1] // (3 * H)
415
- img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
416
- img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
417
-
418
- # prepare txt for attention
419
- txt_modulated = self.txt_norm1(txt)
420
- txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
421
- txt_qkv = self.txt_attn.qkv(txt_modulated)
422
- # 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)
423
- B, L, _ = txt_qkv.shape
424
- txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
425
- txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
426
-
427
- # run actual attention
428
- q = torch.cat((txt_q, img_q), dim=2)
429
- k = torch.cat((txt_k, img_k), dim=2)
430
- v = torch.cat((txt_v, img_v), dim=2)
431
-
432
- attn = attention(q, k, v, pe=pe)
433
- txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
434
-
435
- # calculate the img bloks
436
- img = img + img_mod1.gate * self.img_attn.proj(img_attn)
437
- img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
438
-
439
- # calculate the txt bloks
440
- txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
441
- txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
442
- return img, txt
443
-
444
-
445
- class SingleStreamBlock(nn.Module):
446
- """
447
- A DiT block with parallel linear layers as described in
448
- https://arxiv.org/abs/2302.05442 and adapted modulation interface.
449
- """
450
-
451
- def __init__(
452
- self,
453
- hidden_size: int,
454
- num_heads: int,
455
- mlp_ratio: float = 4.0,
456
- qk_scale: float | None = None,
457
- ):
458
- super().__init__()
459
- self.hidden_dim = hidden_size
460
- self.num_heads = num_heads
461
- head_dim = hidden_size // num_heads
462
- self.scale = qk_scale or head_dim**-0.5
463
-
464
- self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
465
- # qkv and mlp_in
466
- self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
467
- # proj and mlp_out
468
- self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
469
-
470
- self.norm = QKNorm(head_dim)
471
-
472
- self.hidden_size = hidden_size
473
- self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
474
-
475
- self.mlp_act = nn.GELU(approximate="tanh")
476
- self.modulation = Modulation(hidden_size, double=False)
477
-
478
- def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
479
- mod, _ = self.modulation(vec)
480
- x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
481
- qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
482
-
483
- # q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
484
- qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
485
- q, k, v = qkv.permute(2, 0, 3, 1, 4)
486
- q, k = self.norm(q, k, v)
487
-
488
- # compute attention
489
- attn = attention(q, k, v, pe=pe)
490
- # compute activation in mlp stream, cat again and run second linear layer
491
- output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
492
- return x + mod.gate * output
493
-
494
-
495
- class LastLayer(nn.Module):
496
- def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
497
- super().__init__()
498
- self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
499
- self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
500
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
501
-
502
- def forward(self, x: Tensor, vec: Tensor) -> Tensor:
503
- shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
504
- x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
505
- x = self.linear(x)
506
- return x
507
-
508
-
509
- class FluxParams:
510
- in_channels: int = 64
511
- vec_in_dim: int = 768
512
- context_in_dim: int = 4096
513
- hidden_size: int = 3072
514
- mlp_ratio: float = 4.0
515
- num_heads: int = 24
516
- depth: int = 19
517
- depth_single_blocks: int = 38
518
- axes_dim: list = [16, 56, 56]
519
- theta: int = 10_000
520
- qkv_bias: bool = True
521
- guidance_embed: bool = True
522
-
523
-
524
- class Flux(nn.Module):
525
- """
526
- Transformer model for flow matching on sequences.
527
- """
528
-
529
- def __init__(self, params = FluxParams()):
530
- super().__init__()
531
-
532
- self.params = params
533
- self.in_channels = params.in_channels
534
- self.out_channels = self.in_channels
535
- if params.hidden_size % params.num_heads != 0:
536
- raise ValueError(
537
- f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
538
- )
539
- pe_dim = params.hidden_size // params.num_heads
540
- if sum(params.axes_dim) != pe_dim:
541
- raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
542
- self.hidden_size = params.hidden_size
543
- self.num_heads = params.num_heads
544
- self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
545
- self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
546
- self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
547
- self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
548
- self.guidance_in = (
549
- MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
550
- )
551
- self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
552
-
553
- self.double_blocks = nn.ModuleList(
554
- [
555
- DoubleStreamBlock(
556
- self.hidden_size,
557
- self.num_heads,
558
- mlp_ratio=params.mlp_ratio,
559
- qkv_bias=params.qkv_bias,
560
- )
561
- for _ in range(params.depth)
562
- ]
563
- )
564
-
565
- self.single_blocks = nn.ModuleList(
566
- [
567
- SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
568
- for _ in range(params.depth_single_blocks)
569
- ]
570
- )
571
-
572
- self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
573
-
574
- def forward(
575
- self,
576
- img: Tensor,
577
- img_ids: Tensor,
578
- txt: Tensor,
579
- txt_ids: Tensor,
580
- timesteps: Tensor,
581
- y: Tensor,
582
- guidance: Tensor | None = None,
583
- ) -> Tensor:
584
- if img.ndim != 3 or txt.ndim != 3:
585
- raise ValueError("Input img and txt tensors must have 3 dimensions.")
586
-
587
- # running on sequences img
588
- img = self.img_in(img)
589
- vec = self.time_in(timestep_embedding(timesteps, 256))
590
- if self.params.guidance_embed:
591
- if guidance is None:
592
- raise ValueError("Didn't get guidance strength for guidance distilled model.")
593
- vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
594
- vec = vec + self.vector_in(y)
595
- txt = self.txt_in(txt)
596
-
597
- ids = torch.cat((txt_ids, img_ids), dim=1)
598
- pe = self.pe_embedder(ids)
599
-
600
- for block in self.double_blocks:
601
- img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
602
-
603
- img = torch.cat((txt, img), 1)
604
- for block in self.single_blocks:
605
- img = block(img, vec=vec, pe=pe)
606
- img = img[:, txt.shape[1] :, ...]
607
-
608
- img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
609
- return img
610
-
611
-
612
- def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
613
- bs, c, h, w = img.shape
614
- if bs == 1 and not isinstance(prompt, str):
615
- bs = len(prompt)
616
-
617
- img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
618
- if img.shape[0] == 1 and bs > 1:
619
- img = repeat(img, "1 ... -> bs ...", bs=bs)
620
-
621
- img_ids = torch.zeros(h // 2, w // 2, 3)
622
- img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
623
- img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
624
- img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
625
-
626
- if isinstance(prompt, str):
627
- prompt = [prompt]
628
- txt = t5(prompt)
629
- if txt.shape[0] == 1 and bs > 1:
630
- txt = repeat(txt, "1 ... -> bs ...", bs=bs)
631
- txt_ids = torch.zeros(bs, txt.shape[1], 3)
632
-
633
- vec = clip(prompt)
634
- if vec.shape[0] == 1 and bs > 1:
635
- vec = repeat(vec, "1 ... -> bs ...", bs=bs)
636
-
637
- return {
638
- "img": img,
639
- "img_ids": img_ids.to(img.device),
640
- "txt": txt.to(img.device),
641
- "txt_ids": txt_ids.to(img.device),
642
- "vec": vec.to(img.device),
643
- }
644
-
645
-
646
- def time_shift(mu: float, sigma: float, t: Tensor):
647
- return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
648
-
649
-
650
- def get_lin_function(
651
- x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
652
- ) -> Callable[[float], float]:
653
- m = (y2 - y1) / (x2 - x1)
654
- b = y1 - m * x1
655
- return lambda x: m * x + b
656
-
657
-
658
- def get_schedule(
659
- num_steps: int,
660
- image_seq_len: int,
661
- base_shift: float = 0.5,
662
- max_shift: float = 1.15,
663
- shift: bool = True,
664
- ) -> list[float]:
665
- # extra step for zero
666
- timesteps = torch.linspace(1, 0, num_steps + 1)
667
-
668
- # shifting the schedule to favor high timesteps for higher signal images
669
- if shift:
670
- # eastimate mu based on linear estimation between two points
671
- mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
672
- timesteps = time_shift(mu, 1.0, timesteps)
673
-
674
- return timesteps.tolist()
675
-
676
-
677
- def denoise(
678
- model: Flux,
679
- # model input
680
- img: Tensor,
681
- img_ids: Tensor,
682
- txt: Tensor,
683
- txt_ids: Tensor,
684
- vec: Tensor,
685
- # sampling parameters
686
- timesteps: list[float],
687
- guidance: float = 4.0,
688
- ):
689
- # this is ignored for schnell
690
- guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
691
- for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
692
- t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
693
- pred = model(
694
- img=img,
695
- img_ids=img_ids,
696
- txt=txt,
697
- txt_ids=txt_ids,
698
- y=vec,
699
- timesteps=t_vec,
700
- guidance=guidance_vec,
701
- )
702
- img = img + (t_prev - t_curr) * pred
703
- return img
704
-
705
-
706
- def unpack(x: Tensor, height: int, width: int) -> Tensor:
707
- return rearrange(
708
- x,
709
- "b (h w) (c ph pw) -> b c (h ph) (w pw)",
710
- h=math.ceil(height / 16),
711
- w=math.ceil(width / 16),
712
- ph=2,
713
- pw=2,
714
- )
715
-
716
- @dataclass
717
- class SamplingOptions:
718
- prompt: str
719
- width: int
720
- height: int
721
- guidance: float
722
- seed: int | None
723
-
724
-
725
- def get_image(image) -> torch.Tensor | None:
726
- if image is None:
727
- return None
728
- image = Image.fromarray(image).convert("RGB")
729
-
730
- transform = transforms.Compose([
731
- transforms.ToTensor(),
732
- transforms.Lambda(lambda x: 2.0 * x - 1.0),
733
- ])
734
- img: torch.Tensor = transform(image)
735
- return img[None, ...]
736
-
737
-
738
- # ---------------- Demo ----------------
739
-
740
-
741
- from huggingface_hub import hf_hub_download
742
- from safetensors.torch import load_file
743
-
744
- sd = load_file(hf_hub_download(repo_id="lllyasviel/flux1-dev-bnb-nf4", filename="flux1-dev-bnb-nf4-v2.safetensors"))
745
- sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
746
- model = Flux().to(dtype=torch.bfloat16, device="cuda")
747
- result = model.load_state_dict(sd)
748
- model_zero_init = False
749
-
750
-
751
- @spaces.GPU
752
- @torch.no_grad()
753
- def generate_image(
754
- prompt, width, height, guidance, inference_steps, seed,
755
- do_img2img, init_image, image2image_strength, resize_img,
756
- progress=gr.Progress(track_tqdm=True),
757
- ):
758
- translated_prompt = prompt
759
-
760
- # 한글, 일본어, 중국어, 스페인어 문자 감지
761
- def contains_korean(text):
762
- return any('\u3131' <= c <= '\u318E' or '\uAC00' <= c <= '\uD7A3' for c in text)
763
-
764
- def contains_japanese(text):
765
- return any('\u3040' <= c <= '\u309F' or '\u30A0' <= c <= '\u30FF' or '\u4E00' <= c <= '\u9FFF' for c in text)
766
-
767
- def contains_chinese(text):
768
- return any('\u4e00' <= c <= '\u9fff' for c in text)
769
-
770
- def contains_spanish(text):
771
- # 스페인어 특수 문자 포함 확인
772
- spanish_chars = set('áéíóúüñ¿¡')
773
- return any(c in spanish_chars for c in text.lower())
774
-
775
- # 번역기 추가
776
- ko_translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
777
- ja_translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ja-en")
778
- zh_translator = pipeline("translation", model="Helsinki-NLP/opus-mt-zh-en")
779
- es_translator = pipeline("translation", model="Helsinki-NLP/opus-mt-es-en")
780
-
781
- # 각 언어 감지 후 번역
782
- if contains_korean(prompt):
783
- translated_prompt = ko_translator(prompt, max_length=512)[0]['translation_text']
784
- print(f"Translated Korean prompt: {translated_prompt}")
785
- prompt = translated_prompt
786
- elif contains_japanese(prompt):
787
- translated_prompt = ja_translator(prompt, max_length=512)[0]['translation_text']
788
- print(f"Translated Japanese prompt: {translated_prompt}")
789
- prompt = translated_prompt
790
- elif contains_chinese(prompt):
791
- translated_prompt = zh_translator(prompt, max_length=512)[0]['translation_text']
792
- print(f"Translated Chinese prompt: {translated_prompt}")
793
- prompt = translated_prompt
794
- elif contains_spanish(prompt):
795
- translated_prompt = es_translator(prompt, max_length=512)[0]['translation_text']
796
- print(f"Translated Spanish prompt: {translated_prompt}")
797
- prompt = translated_prompt
798
-
799
- if seed == 0:
800
- seed = int(random.random() * 1000000)
801
-
802
- device = "cuda" if torch.cuda.is_available() else "cpu"
803
- torch_device = torch.device(device)
804
-
805
-
806
- global model, model_zero_init
807
- if not model_zero_init:
808
- model = model.to(torch_device)
809
- model_zero_init = True
810
-
811
- if do_img2img and init_image is not None:
812
- init_image = get_image(init_image)
813
- if resize_img:
814
- init_image = torch.nn.functional.interpolate(init_image, (height, width))
815
- else:
816
- h, w = init_image.shape[-2:]
817
- init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
818
- height = init_image.shape[-2]
819
- width = init_image.shape[-1]
820
- init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
821
- init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
822
-
823
- generator = torch.Generator(device=device).manual_seed(seed)
824
- x = torch.randn(1, 16, 2 * math.ceil(height / 16), 2 * math.ceil(width / 16), device=device, dtype=torch.bfloat16, generator=generator)
825
-
826
- num_steps = inference_steps
827
- timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
828
-
829
- if do_img2img and init_image is not None:
830
- t_idx = int((1 - image2image_strength) * num_steps)
831
- t = timesteps[t_idx]
832
- timesteps = timesteps[t_idx:]
833
- x = t * x + (1.0 - t) * init_image.to(x.dtype)
834
-
835
- inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
836
- x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
837
-
838
- # with profile(activities=[ProfilerActivity.CPU],record_shapes=True,profile_memory=True) as prof:
839
- # print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=20))
840
-
841
- x = unpack(x.float(), height, width)
842
- with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
843
- x = x = (x / ae.config.scaling_factor) + ae.config.shift_factor
844
- x = ae.decode(x).sample
845
-
846
- x = x.clamp(-1, 1)
847
- x = rearrange(x[0], "c h w -> h w c")
848
- img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
849
-
850
-
851
- return img, seed, translated_prompt
852
-
853
- css = """
854
- footer {
855
- visibility: hidden;
856
- }
857
- """
858
-
859
-
860
- def create_demo():
861
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css) as demo:
862
- gr.Markdown("# FLUXllama Multilingual")
863
-
864
- with gr.Row():
865
- with gr.Column():
866
- prompt = gr.Textbox(label="Prompt(Supports English, Korean, and Japanese)", value="A cute and fluffy golden retriever puppy sitting upright, holding a neatly designed white sign with bold, colorful lettering that reads 'Have a Happy Day!' in cheerful fonts. The puppy has expressive, sparkling eyes, a happy smile, and fluffy ears slightly flopped. The background is a vibrant and sunny meadow with soft-focus flowers, glowing sunlight filtering through the trees, and a warm golden glow that enhances the joyful atmosphere. The sign is framed with small decorative flowers, adding a charming and wholesome touch. Ensure the text on the sign is clear and legible.")
867
-
868
- width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=768)
869
- height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=768)
870
- guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
871
- inference_steps = gr.Slider(
872
- label="Inference steps",
873
- minimum=1,
874
- maximum=30,
875
- step=1,
876
- value=30,
877
- )
878
- seed = gr.Number(label="Seed", precision=-1)
879
- do_img2img = gr.Checkbox(label="Image to Image", value=False)
880
- init_image = gr.Image(label="Input Image", visible=False)
881
- image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising strength", value=0.8, visible=False)
882
- resize_img = gr.Checkbox(label="Resize image", value=True, visible=False)
883
- generate_button = gr.Button("Generate")
884
-
885
- with gr.Column():
886
- output_image = gr.Image(label="Generated Image")
887
- output_seed = gr.Text(label="Used Seed")
888
- output_translated = gr.Text(label="Translated Prompt")
889
-
890
- # Examples 컴포넌트 추가
891
- gr.Examples(
892
- examples=[
893
- "a tiny astronaut hatching from an egg on the moon",
894
- "썬글라스 착용한 귀여운 흰색 고양이가 'LOVE'라는 표지판을 들고있다",
895
- "桜が流れる夜の街、照明",
896
- ],
897
- inputs=prompt, # 예제가 입력될 컴포넌트 지정
898
- )
899
-
900
- do_img2img.change(
901
- fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
902
- inputs=[do_img2img],
903
- outputs=[init_image, image2image_strength, resize_img]
904
- )
905
-
906
- generate_button.click(
907
- fn=generate_image,
908
- inputs=[prompt, width, height, guidance, inference_steps, seed, do_img2img, init_image, image2image_strength, resize_img],
909
- outputs=[output_image, output_seed, output_translated]
910
- )
911
-
912
- return demo
913
-
914
- if __name__ == "__main__":
915
- demo = create_demo()
916
- demo.launch()