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
+
from torchvision import transforms
|
8 |
+
from dataclasses import dataclass
|
9 |
+
import math
|
10 |
+
from typing import Callable
|
11 |
+
from tqdm import tqdm
|
12 |
+
import bitsandbytes as bnb
|
13 |
+
from bitsandbytes.nn.modules import Params4bit, QuantState
|
14 |
+
import torch
|
15 |
+
import random
|
16 |
+
from einops import rearrange, repeat
|
17 |
+
from diffusers import AutoencoderKL
|
18 |
+
from torch import Tensor, nn
|
19 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
20 |
+
from transformers import T5EncoderModel, T5Tokenizer
|
21 |
+
from transformers import pipeline, AutoTokenizer, MarianMTModel
|
22 |
+
|
23 |
+
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
|
24 |
+
# ---------------- Encoders ----------------
|
25 |
+
|
26 |
+
|
27 |
+
class HFEmbedder(nn.Module):
|
28 |
+
def __init__(self, version: str, max_length: int, **hf_kwargs):
|
29 |
+
super().__init__()
|
30 |
+
self.is_clip = version.startswith("openai")
|
31 |
+
self.max_length = max_length
|
32 |
+
self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
|
33 |
+
|
34 |
+
if self.is_clip:
|
35 |
+
self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
|
36 |
+
self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
|
37 |
+
else:
|
38 |
+
self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
|
39 |
+
self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
|
40 |
+
|
41 |
+
self.hf_module = self.hf_module.eval().requires_grad_(False)
|
42 |
+
|
43 |
+
def forward(self, text: list[str]) -> Tensor:
|
44 |
+
batch_encoding = self.tokenizer(
|
45 |
+
text,
|
46 |
+
truncation=True,
|
47 |
+
max_length=self.max_length,
|
48 |
+
return_length=False,
|
49 |
+
return_overflowing_tokens=False,
|
50 |
+
padding="max_length",
|
51 |
+
return_tensors="pt",
|
52 |
+
)
|
53 |
+
|
54 |
+
outputs = self.hf_module(
|
55 |
+
input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
|
56 |
+
attention_mask=None,
|
57 |
+
output_hidden_states=False,
|
58 |
+
)
|
59 |
+
return outputs[self.output_key]
|
60 |
+
|
61 |
+
|
62 |
+
device = "cuda"
|
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 |
+
# quantize(t5, weights=qfloat8)
|
67 |
+
# freeze(t5)
|
68 |
+
|
69 |
+
|
70 |
+
# ---------------- NF4 ----------------
|
71 |
+
|
72 |
+
|
73 |
+
def functional_linear_4bits(x, weight, bias):
|
74 |
+
out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
|
75 |
+
out = out.to(x)
|
76 |
+
return out
|
77 |
+
|
78 |
+
|
79 |
+
def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantState:
|
80 |
+
if state is None:
|
81 |
+
return None
|
82 |
+
|
83 |
+
device = device or state.absmax.device
|
84 |
+
|
85 |
+
state2 = (
|
86 |
+
QuantState(
|
87 |
+
absmax=state.state2.absmax.to(device),
|
88 |
+
shape=state.state2.shape,
|
89 |
+
code=state.state2.code.to(device),
|
90 |
+
blocksize=state.state2.blocksize,
|
91 |
+
quant_type=state.state2.quant_type,
|
92 |
+
dtype=state.state2.dtype,
|
93 |
+
)
|
94 |
+
if state.nested
|
95 |
+
else None
|
96 |
+
)
|
97 |
+
|
98 |
+
return QuantState(
|
99 |
+
absmax=state.absmax.to(device),
|
100 |
+
shape=state.shape,
|
101 |
+
code=state.code.to(device),
|
102 |
+
blocksize=state.blocksize,
|
103 |
+
quant_type=state.quant_type,
|
104 |
+
dtype=state.dtype,
|
105 |
+
offset=state.offset.to(device) if state.nested else None,
|
106 |
+
state2=state2,
|
107 |
+
)
|
108 |
+
|
109 |
+
|
110 |
+
class ForgeParams4bit(Params4bit):
|
111 |
+
def to(self, *args, **kwargs):
|
112 |
+
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
|
113 |
+
if device is not None and device.type == "cuda" and not self.bnb_quantized:
|
114 |
+
return self._quantize(device)
|
115 |
+
else:
|
116 |
+
n = ForgeParams4bit(
|
117 |
+
torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
|
118 |
+
requires_grad=self.requires_grad,
|
119 |
+
quant_state=copy_quant_state(self.quant_state, device),
|
120 |
+
# blocksize=self.blocksize,
|
121 |
+
# compress_statistics=self.compress_statistics,
|
122 |
+
compress_statistics=False,
|
123 |
+
blocksize=64,
|
124 |
+
quant_type=self.quant_type,
|
125 |
+
quant_storage=self.quant_storage,
|
126 |
+
bnb_quantized=self.bnb_quantized,
|
127 |
+
module=self.module
|
128 |
+
)
|
129 |
+
self.module.quant_state = n.quant_state
|
130 |
+
self.data = n.data
|
131 |
+
self.quant_state = n.quant_state
|
132 |
+
return n
|
133 |
+
|
134 |
+
|
135 |
+
class ForgeLoader4Bit(torch.nn.Module):
|
136 |
+
def __init__(self, *, device, dtype, quant_type, **kwargs):
|
137 |
+
super().__init__()
|
138 |
+
self.dummy = torch.nn.Parameter(torch.empty(1, device=device, dtype=dtype))
|
139 |
+
self.weight = None
|
140 |
+
self.quant_state = None
|
141 |
+
self.bias = None
|
142 |
+
self.quant_type = quant_type
|
143 |
+
|
144 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
145 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
146 |
+
quant_state = getattr(self.weight, "quant_state", None)
|
147 |
+
if quant_state is not None:
|
148 |
+
for k, v in quant_state.as_dict(packed=True).items():
|
149 |
+
destination[prefix + "weight." + k] = v if keep_vars else v.detach()
|
150 |
+
return
|
151 |
+
|
152 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
|
153 |
+
quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
|
154 |
+
|
155 |
+
if any('bitsandbytes' in k for k in quant_state_keys):
|
156 |
+
quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
|
157 |
+
|
158 |
+
self.weight = ForgeParams4bit.from_prequantized(
|
159 |
+
data=state_dict[prefix + 'weight'],
|
160 |
+
quantized_stats=quant_state_dict,
|
161 |
+
requires_grad=False,
|
162 |
+
# device=self.dummy.device,
|
163 |
+
device=torch.device('cuda'),
|
164 |
+
module=self
|
165 |
+
)
|
166 |
+
self.quant_state = self.weight.quant_state
|
167 |
+
|
168 |
+
if prefix + 'bias' in state_dict:
|
169 |
+
self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
|
170 |
+
|
171 |
+
del self.dummy
|
172 |
+
elif hasattr(self, 'dummy'):
|
173 |
+
if prefix + 'weight' in state_dict:
|
174 |
+
self.weight = ForgeParams4bit(
|
175 |
+
state_dict[prefix + 'weight'].to(self.dummy),
|
176 |
+
requires_grad=False,
|
177 |
+
compress_statistics=True,
|
178 |
+
quant_type=self.quant_type,
|
179 |
+
quant_storage=torch.uint8,
|
180 |
+
module=self,
|
181 |
+
)
|
182 |
+
self.quant_state = self.weight.quant_state
|
183 |
+
|
184 |
+
if prefix + 'bias' in state_dict:
|
185 |
+
self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
|
186 |
+
|
187 |
+
del self.dummy
|
188 |
+
else:
|
189 |
+
super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
|
190 |
+
|
191 |
+
|
192 |
+
class Linear(ForgeLoader4Bit):
|
193 |
+
def __init__(self, *args, device=None, dtype=None, **kwargs):
|
194 |
+
super().__init__(device=device, dtype=dtype, quant_type='nf4')
|
195 |
+
|
196 |
+
def forward(self, x):
|
197 |
+
self.weight.quant_state = self.quant_state
|
198 |
+
|
199 |
+
if self.bias is not None and self.bias.dtype != x.dtype:
|
200 |
+
# Maybe this can also be set to all non-bnb ops since the cost is very low.
|
201 |
+
# And it only invokes one time, and most linear does not have bias
|
202 |
+
self.bias.data = self.bias.data.to(x.dtype)
|
203 |
+
|
204 |
+
return functional_linear_4bits(x, self.weight, self.bias)
|
205 |
+
|
206 |
+
|
207 |
+
nn.Linear = Linear
|
208 |
+
|
209 |
+
|
210 |
+
# ---------------- Model ----------------
|
211 |
+
|
212 |
+
|
213 |
+
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
|
214 |
+
q, k = apply_rope(q, k, pe)
|
215 |
+
|
216 |
+
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
217 |
+
# x = rearrange(x, "B H L D -> B L (H D)")
|
218 |
+
x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
|
219 |
+
|
220 |
+
return x
|
221 |
+
|
222 |
+
|
223 |
+
def rope(pos, dim, theta):
|
224 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
225 |
+
omega = 1.0 / (theta ** scale)
|
226 |
+
|
227 |
+
# out = torch.einsum("...n,d->...nd", pos, omega)
|
228 |
+
out = pos.unsqueeze(-1) * omega.unsqueeze(0)
|
229 |
+
|
230 |
+
cos_out = torch.cos(out)
|
231 |
+
sin_out = torch.sin(out)
|
232 |
+
out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
|
233 |
+
|
234 |
+
# out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
|
235 |
+
b, n, d, _ = out.shape
|
236 |
+
out = out.view(b, n, d, 2, 2)
|
237 |
+
|
238 |
+
return out.float()
|
239 |
+
|
240 |
+
|
241 |
+
def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
242 |
+
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
|
243 |
+
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
|
244 |
+
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
|
245 |
+
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
|
246 |
+
return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
|
247 |
+
|
248 |
+
|
249 |
+
class EmbedND(nn.Module):
|
250 |
+
def __init__(self, dim: int, theta: int, axes_dim: list[int]):
|
251 |
+
super().__init__()
|
252 |
+
self.dim = dim
|
253 |
+
self.theta = theta
|
254 |
+
self.axes_dim = axes_dim
|
255 |
+
|
256 |
+
def forward(self, ids: Tensor) -> Tensor:
|
257 |
+
n_axes = ids.shape[-1]
|
258 |
+
emb = torch.cat(
|
259 |
+
[rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
|
260 |
+
dim=-3,
|
261 |
+
)
|
262 |
+
|
263 |
+
return emb.unsqueeze(1)
|
264 |
+
|
265 |
+
|
266 |
+
def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
|
267 |
+
"""
|
268 |
+
Create sinusoidal timestep embeddings.
|
269 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
270 |
+
These may be fractional.
|
271 |
+
:param dim: the dimension of the output.
|
272 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
273 |
+
:return: an (N, D) Tensor of positional embeddings.
|
274 |
+
"""
|
275 |
+
t = time_factor * t
|
276 |
+
half = dim // 2
|
277 |
+
|
278 |
+
# Do not block CUDA steam, but having about 1e-4 differences with Flux official codes:
|
279 |
+
# freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half)
|
280 |
+
|
281 |
+
# Block CUDA steam, but consistent with official codes:
|
282 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
|
283 |
+
|
284 |
+
args = t[:, None].float() * freqs[None]
|
285 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
286 |
+
if dim % 2:
|
287 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
288 |
+
if torch.is_floating_point(t):
|
289 |
+
embedding = embedding.to(t)
|
290 |
+
return embedding
|
291 |
+
|
292 |
+
|
293 |
+
class MLPEmbedder(nn.Module):
|
294 |
+
def __init__(self, in_dim: int, hidden_dim: int):
|
295 |
+
super().__init__()
|
296 |
+
self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
|
297 |
+
self.silu = nn.SiLU()
|
298 |
+
self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
299 |
+
|
300 |
+
def forward(self, x: Tensor) -> Tensor:
|
301 |
+
return self.out_layer(self.silu(self.in_layer(x)))
|
302 |
+
|
303 |
+
|
304 |
+
class RMSNorm(torch.nn.Module):
|
305 |
+
def __init__(self, dim: int):
|
306 |
+
super().__init__()
|
307 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
308 |
+
|
309 |
+
def forward(self, x: Tensor):
|
310 |
+
x_dtype = x.dtype
|
311 |
+
x = x.float()
|
312 |
+
rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
|
313 |
+
return (x * rrms).to(dtype=x_dtype) * self.scale
|
314 |
+
|
315 |
+
|
316 |
+
class QKNorm(torch.nn.Module):
|
317 |
+
def __init__(self, dim: int):
|
318 |
+
super().__init__()
|
319 |
+
self.query_norm = RMSNorm(dim)
|
320 |
+
self.key_norm = RMSNorm(dim)
|
321 |
+
|
322 |
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
|
323 |
+
q = self.query_norm(q)
|
324 |
+
k = self.key_norm(k)
|
325 |
+
return q.to(v), k.to(v)
|
326 |
+
|
327 |
+
|
328 |
+
class SelfAttention(nn.Module):
|
329 |
+
def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
|
330 |
+
super().__init__()
|
331 |
+
self.num_heads = num_heads
|
332 |
+
head_dim = dim // num_heads
|
333 |
+
|
334 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
335 |
+
self.norm = QKNorm(head_dim)
|
336 |
+
self.proj = nn.Linear(dim, dim)
|
337 |
+
|
338 |
+
def forward(self, x: Tensor, pe: Tensor) -> Tensor:
|
339 |
+
qkv = self.qkv(x)
|
340 |
+
# q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
341 |
+
B, L, _ = qkv.shape
|
342 |
+
qkv = qkv.view(B, L, 3, self.num_heads, -1)
|
343 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
344 |
+
q, k = self.norm(q, k, v)
|
345 |
+
x = attention(q, k, v, pe=pe)
|
346 |
+
x = self.proj(x)
|
347 |
+
return x
|
348 |
+
|
349 |
+
|
350 |
+
@dataclass
|
351 |
+
class ModulationOut:
|
352 |
+
shift: Tensor
|
353 |
+
scale: Tensor
|
354 |
+
gate: Tensor
|
355 |
+
|
356 |
+
|
357 |
+
class Modulation(nn.Module):
|
358 |
+
def __init__(self, dim: int, double: bool):
|
359 |
+
super().__init__()
|
360 |
+
self.is_double = double
|
361 |
+
self.multiplier = 6 if double else 3
|
362 |
+
self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
|
363 |
+
|
364 |
+
def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
|
365 |
+
out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
|
366 |
+
|
367 |
+
return (
|
368 |
+
ModulationOut(*out[:3]),
|
369 |
+
ModulationOut(*out[3:]) if self.is_double else None,
|
370 |
+
)
|
371 |
+
|
372 |
+
|
373 |
+
class DoubleStreamBlock(nn.Module):
|
374 |
+
def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
|
375 |
+
super().__init__()
|
376 |
+
|
377 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
378 |
+
self.num_heads = num_heads
|
379 |
+
self.hidden_size = hidden_size
|
380 |
+
self.img_mod = Modulation(hidden_size, double=True)
|
381 |
+
self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
382 |
+
self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
383 |
+
|
384 |
+
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
385 |
+
self.img_mlp = nn.Sequential(
|
386 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
387 |
+
nn.GELU(approximate="tanh"),
|
388 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
389 |
+
)
|
390 |
+
|
391 |
+
self.txt_mod = Modulation(hidden_size, double=True)
|
392 |
+
self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
393 |
+
self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
394 |
+
|
395 |
+
self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
396 |
+
self.txt_mlp = nn.Sequential(
|
397 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
398 |
+
nn.GELU(approximate="tanh"),
|
399 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
400 |
+
)
|
401 |
+
|
402 |
+
def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
|
403 |
+
img_mod1, img_mod2 = self.img_mod(vec)
|
404 |
+
txt_mod1, txt_mod2 = self.txt_mod(vec)
|
405 |
+
|
406 |
+
# prepare image for attention
|
407 |
+
img_modulated = self.img_norm1(img)
|
408 |
+
img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
|
409 |
+
img_qkv = self.img_attn.qkv(img_modulated)
|
410 |
+
# 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)
|
411 |
+
B, L, _ = img_qkv.shape
|
412 |
+
H = self.num_heads
|
413 |
+
D = img_qkv.shape[-1] // (3 * H)
|
414 |
+
img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
415 |
+
img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
|
416 |
+
|
417 |
+
# prepare txt for attention
|
418 |
+
txt_modulated = self.txt_norm1(txt)
|
419 |
+
txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
|
420 |
+
txt_qkv = self.txt_attn.qkv(txt_modulated)
|
421 |
+
# 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)
|
422 |
+
B, L, _ = txt_qkv.shape
|
423 |
+
txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
|
424 |
+
txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
|
425 |
+
|
426 |
+
# run actual attention
|
427 |
+
q = torch.cat((txt_q, img_q), dim=2)
|
428 |
+
k = torch.cat((txt_k, img_k), dim=2)
|
429 |
+
v = torch.cat((txt_v, img_v), dim=2)
|
430 |
+
|
431 |
+
attn = attention(q, k, v, pe=pe)
|
432 |
+
txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
|
433 |
+
|
434 |
+
# calculate the img bloks
|
435 |
+
img = img + img_mod1.gate * self.img_attn.proj(img_attn)
|
436 |
+
img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
|
437 |
+
|
438 |
+
# calculate the txt bloks
|
439 |
+
txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
|
440 |
+
txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
|
441 |
+
return img, txt
|
442 |
+
|
443 |
+
|
444 |
+
class SingleStreamBlock(nn.Module):
|
445 |
+
"""
|
446 |
+
A DiT block with parallel linear layers as described in
|
447 |
+
https://arxiv.org/abs/2302.05442 and adapted modulation interface.
|
448 |
+
"""
|
449 |
+
|
450 |
+
def __init__(
|
451 |
+
self,
|
452 |
+
hidden_size: int,
|
453 |
+
num_heads: int,
|
454 |
+
mlp_ratio: float = 4.0,
|
455 |
+
qk_scale: float | None = None,
|
456 |
+
):
|
457 |
+
super().__init__()
|
458 |
+
self.hidden_dim = hidden_size
|
459 |
+
self.num_heads = num_heads
|
460 |
+
head_dim = hidden_size // num_heads
|
461 |
+
self.scale = qk_scale or head_dim**-0.5
|
462 |
+
|
463 |
+
self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
464 |
+
# qkv and mlp_in
|
465 |
+
self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
|
466 |
+
# proj and mlp_out
|
467 |
+
self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
|
468 |
+
|
469 |
+
self.norm = QKNorm(head_dim)
|
470 |
+
|
471 |
+
self.hidden_size = hidden_size
|
472 |
+
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
473 |
+
|
474 |
+
self.mlp_act = nn.GELU(approximate="tanh")
|
475 |
+
self.modulation = Modulation(hidden_size, double=False)
|
476 |
+
|
477 |
+
def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
|
478 |
+
mod, _ = self.modulation(vec)
|
479 |
+
x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
|
480 |
+
qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
|
481 |
+
|
482 |
+
# q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
483 |
+
qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
|
484 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4)
|
485 |
+
q, k = self.norm(q, k, v)
|
486 |
+
|
487 |
+
# compute attention
|
488 |
+
attn = attention(q, k, v, pe=pe)
|
489 |
+
# compute activation in mlp stream, cat again and run second linear layer
|
490 |
+
output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
|
491 |
+
return x + mod.gate * output
|
492 |
+
|
493 |
+
|
494 |
+
class LastLayer(nn.Module):
|
495 |
+
def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
|
496 |
+
super().__init__()
|
497 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
498 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
499 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
|
500 |
+
|
501 |
+
def forward(self, x: Tensor, vec: Tensor) -> Tensor:
|
502 |
+
shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
|
503 |
+
x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
|
504 |
+
x = self.linear(x)
|
505 |
+
return x
|
506 |
+
|
507 |
+
|
508 |
+
class FluxParams:
|
509 |
+
in_channels: int = 64
|
510 |
+
vec_in_dim: int = 768
|
511 |
+
context_in_dim: int = 4096
|
512 |
+
hidden_size: int = 3072
|
513 |
+
mlp_ratio: float = 4.0
|
514 |
+
num_heads: int = 24
|
515 |
+
depth: int = 19
|
516 |
+
depth_single_blocks: int = 38
|
517 |
+
axes_dim: list = [16, 56, 56]
|
518 |
+
theta: int = 10_000
|
519 |
+
qkv_bias: bool = True
|
520 |
+
guidance_embed: bool = True
|
521 |
+
|
522 |
+
|
523 |
+
class Flux(nn.Module):
|
524 |
+
"""
|
525 |
+
Transformer model for flow matching on sequences.
|
526 |
+
"""
|
527 |
+
|
528 |
+
def __init__(self, params = FluxParams()):
|
529 |
+
super().__init__()
|
530 |
+
|
531 |
+
self.params = params
|
532 |
+
self.in_channels = params.in_channels
|
533 |
+
self.out_channels = self.in_channels
|
534 |
+
if params.hidden_size % params.num_heads != 0:
|
535 |
+
raise ValueError(
|
536 |
+
f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
|
537 |
+
)
|
538 |
+
pe_dim = params.hidden_size // params.num_heads
|
539 |
+
if sum(params.axes_dim) != pe_dim:
|
540 |
+
raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
|
541 |
+
self.hidden_size = params.hidden_size
|
542 |
+
self.num_heads = params.num_heads
|
543 |
+
self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
|
544 |
+
self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
|
545 |
+
self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
|
546 |
+
self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
|
547 |
+
self.guidance_in = (
|
548 |
+
MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
|
549 |
+
)
|
550 |
+
self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
|
551 |
+
|
552 |
+
self.double_blocks = nn.ModuleList(
|
553 |
+
[
|
554 |
+
DoubleStreamBlock(
|
555 |
+
self.hidden_size,
|
556 |
+
self.num_heads,
|
557 |
+
mlp_ratio=params.mlp_ratio,
|
558 |
+
qkv_bias=params.qkv_bias,
|
559 |
+
)
|
560 |
+
for _ in range(params.depth)
|
561 |
+
]
|
562 |
+
)
|
563 |
+
|
564 |
+
self.single_blocks = nn.ModuleList(
|
565 |
+
[
|
566 |
+
SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
|
567 |
+
for _ in range(params.depth_single_blocks)
|
568 |
+
]
|
569 |
+
)
|
570 |
+
|
571 |
+
self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
|
572 |
+
|
573 |
+
def forward(
|
574 |
+
self,
|
575 |
+
img: Tensor,
|
576 |
+
img_ids: Tensor,
|
577 |
+
txt: Tensor,
|
578 |
+
txt_ids: Tensor,
|
579 |
+
timesteps: Tensor,
|
580 |
+
y: Tensor,
|
581 |
+
guidance: Tensor | None = None,
|
582 |
+
) -> Tensor:
|
583 |
+
if img.ndim != 3 or txt.ndim != 3:
|
584 |
+
raise ValueError("Input img and txt tensors must have 3 dimensions.")
|
585 |
+
|
586 |
+
# running on sequences img
|
587 |
+
img = self.img_in(img)
|
588 |
+
vec = self.time_in(timestep_embedding(timesteps, 256))
|
589 |
+
if self.params.guidance_embed:
|
590 |
+
if guidance is None:
|
591 |
+
raise ValueError("Didn't get guidance strength for guidance distilled model.")
|
592 |
+
vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
|
593 |
+
vec = vec + self.vector_in(y)
|
594 |
+
txt = self.txt_in(txt)
|
595 |
+
|
596 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
597 |
+
pe = self.pe_embedder(ids)
|
598 |
+
|
599 |
+
for block in self.double_blocks:
|
600 |
+
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
|
601 |
+
|
602 |
+
img = torch.cat((txt, img), 1)
|
603 |
+
for block in self.single_blocks:
|
604 |
+
img = block(img, vec=vec, pe=pe)
|
605 |
+
img = img[:, txt.shape[1] :, ...]
|
606 |
+
|
607 |
+
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
|
608 |
+
return img
|
609 |
+
|
610 |
+
|
611 |
+
def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
|
612 |
+
bs, c, h, w = img.shape
|
613 |
+
if bs == 1 and not isinstance(prompt, str):
|
614 |
+
bs = len(prompt)
|
615 |
+
|
616 |
+
img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
|
617 |
+
if img.shape[0] == 1 and bs > 1:
|
618 |
+
img = repeat(img, "1 ... -> bs ...", bs=bs)
|
619 |
+
|
620 |
+
img_ids = torch.zeros(h // 2, w // 2, 3)
|
621 |
+
img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
|
622 |
+
img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
|
623 |
+
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
|
624 |
+
|
625 |
+
if isinstance(prompt, str):
|
626 |
+
prompt = [prompt]
|
627 |
+
txt = t5(prompt)
|
628 |
+
if txt.shape[0] == 1 and bs > 1:
|
629 |
+
txt = repeat(txt, "1 ... -> bs ...", bs=bs)
|
630 |
+
txt_ids = torch.zeros(bs, txt.shape[1], 3)
|
631 |
+
|
632 |
+
vec = clip(prompt)
|
633 |
+
if vec.shape[0] == 1 and bs > 1:
|
634 |
+
vec = repeat(vec, "1 ... -> bs ...", bs=bs)
|
635 |
+
|
636 |
+
return {
|
637 |
+
"img": img,
|
638 |
+
"img_ids": img_ids.to(img.device),
|
639 |
+
"txt": txt.to(img.device),
|
640 |
+
"txt_ids": txt_ids.to(img.device),
|
641 |
+
"vec": vec.to(img.device),
|
642 |
+
}
|
643 |
+
|
644 |
+
|
645 |
+
def time_shift(mu: float, sigma: float, t: Tensor):
|
646 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
647 |
+
|
648 |
+
|
649 |
+
def get_lin_function(
|
650 |
+
x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
|
651 |
+
) -> Callable[[float], float]:
|
652 |
+
m = (y2 - y1) / (x2 - x1)
|
653 |
+
b = y1 - m * x1
|
654 |
+
return lambda x: m * x + b
|
655 |
+
|
656 |
+
|
657 |
+
def get_schedule(
|
658 |
+
num_steps: int,
|
659 |
+
image_seq_len: int,
|
660 |
+
base_shift: float = 0.5,
|
661 |
+
max_shift: float = 1.15,
|
662 |
+
shift: bool = True,
|
663 |
+
) -> list[float]:
|
664 |
+
# extra step for zero
|
665 |
+
timesteps = torch.linspace(1, 0, num_steps + 1)
|
666 |
+
|
667 |
+
# shifting the schedule to favor high timesteps for higher signal images
|
668 |
+
if shift:
|
669 |
+
# eastimate mu based on linear estimation between two points
|
670 |
+
mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
|
671 |
+
timesteps = time_shift(mu, 1.0, timesteps)
|
672 |
+
|
673 |
+
return timesteps.tolist()
|
674 |
+
|
675 |
+
|
676 |
+
def denoise(
|
677 |
+
model: Flux,
|
678 |
+
# model input
|
679 |
+
img: Tensor,
|
680 |
+
img_ids: Tensor,
|
681 |
+
txt: Tensor,
|
682 |
+
txt_ids: Tensor,
|
683 |
+
vec: Tensor,
|
684 |
+
# sampling parameters
|
685 |
+
timesteps: list[float],
|
686 |
+
guidance: float = 4.0,
|
687 |
+
):
|
688 |
+
# this is ignored for schnell
|
689 |
+
guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
|
690 |
+
for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
|
691 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
692 |
+
pred = model(
|
693 |
+
img=img,
|
694 |
+
img_ids=img_ids,
|
695 |
+
txt=txt,
|
696 |
+
txt_ids=txt_ids,
|
697 |
+
y=vec,
|
698 |
+
timesteps=t_vec,
|
699 |
+
guidance=guidance_vec,
|
700 |
+
)
|
701 |
+
img = img + (t_prev - t_curr) * pred
|
702 |
+
return img
|
703 |
+
|
704 |
+
|
705 |
+
def unpack(x: Tensor, height: int, width: int) -> Tensor:
|
706 |
+
return rearrange(
|
707 |
+
x,
|
708 |
+
"b (h w) (c ph pw) -> b c (h ph) (w pw)",
|
709 |
+
h=math.ceil(height / 16),
|
710 |
+
w=math.ceil(width / 16),
|
711 |
+
ph=2,
|
712 |
+
pw=2,
|
713 |
+
)
|
714 |
+
|
715 |
+
@dataclass
|
716 |
+
class SamplingOptions:
|
717 |
+
prompt: str
|
718 |
+
width: int
|
719 |
+
height: int
|
720 |
+
guidance: float
|
721 |
+
seed: int | None
|
722 |
+
|
723 |
+
|
724 |
+
def get_image(image) -> torch.Tensor | None:
|
725 |
+
if image is None:
|
726 |
+
return None
|
727 |
+
image = Image.fromarray(image).convert("RGB")
|
728 |
+
|
729 |
+
transform = transforms.Compose([
|
730 |
+
transforms.ToTensor(),
|
731 |
+
transforms.Lambda(lambda x: 2.0 * x - 1.0),
|
732 |
+
])
|
733 |
+
img: torch.Tensor = transform(image)
|
734 |
+
return img[None, ...]
|
735 |
+
|
736 |
+
|
737 |
+
# ---------------- Demo ----------------
|
738 |
+
|
739 |
+
|
740 |
+
from huggingface_hub import hf_hub_download
|
741 |
+
from safetensors.torch import load_file
|
742 |
+
|
743 |
+
sd = load_file(hf_hub_download(repo_id="lllyasviel/flux1-dev-bnb-nf4", filename="flux1-dev-bnb-nf4-v2.safetensors"))
|
744 |
+
sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
|
745 |
+
model = Flux().to(dtype=torch.bfloat16, device="cuda")
|
746 |
+
result = model.load_state_dict(sd)
|
747 |
+
model_zero_init = False
|
748 |
+
|
749 |
+
# model = Flux().to(dtype=torch.bfloat16, device="cuda")
|
750 |
+
# result = model.load_state_dict(load_file("/storage/dev/nyanko/flux-dev/flux1-dev.sft"))
|
751 |
+
|
752 |
+
|
753 |
+
# 언어-모델 매핑 딕셔너리 추가
|
754 |
+
TRANSLATORS = {
|
755 |
+
"Korean": "Helsinki-NLP/opus-mt-ko-en",
|
756 |
+
"Japanese": "Helsinki-NLP/opus-mt-ja-en",
|
757 |
+
"Chinese": "Helsinki-NLP/opus-mt-zh-en",
|
758 |
+
"Russian": "Helsinki-NLP/opus-mt-ru-en",
|
759 |
+
"Spanish": "Helsinki-NLP/opus-mt-es-en",
|
760 |
+
"French": "Helsinki-NLP/opus-mt-fr-en",
|
761 |
+
"Arabic": "Helsinki-NLP/opus-mt-ar-en",
|
762 |
+
"Bengali": "Helsinki-NLP/opus-mt-bn-en",
|
763 |
+
"Estonian": "Helsinki-NLP/opus-mt-et-en",
|
764 |
+
"Polish": "Helsinki-NLP/opus-mt-pl-en",
|
765 |
+
"Swedish": "Helsinki-NLP/opus-mt-sv-en",
|
766 |
+
"Thai": "Helsinki-NLP/opus-mt-th-en",
|
767 |
+
"Urdu": "Helsinki-NLP/opus-mt-ur-en",
|
768 |
+
"Bulgarian": "Helsinki-NLP/opus-mt-bg-en",
|
769 |
+
"Catalan": "Helsinki-NLP/opus-mt-ca-en",
|
770 |
+
"Czech": "Helsinki-NLP/opus-mt-cs-en",
|
771 |
+
"Azerbaijani": "Helsinki-NLP/opus-mt-az-en",
|
772 |
+
"Basque": "Helsinki-NLP/opus-mt-bat-en",
|
773 |
+
"Bicolano": "Helsinki-NLP/opus-mt-bcl-en",
|
774 |
+
"Bemba": "Helsinki-NLP/opus-mt-bem-en",
|
775 |
+
"Berber": "Helsinki-NLP/opus-mt-ber-en",
|
776 |
+
"Bislama": "Helsinki-NLP/opus-mt-bi-en",
|
777 |
+
"Bantu": "Helsinki-NLP/opus-mt-bnt-en",
|
778 |
+
"Brazilian Sign Language": "Helsinki-NLP/opus-mt-bzs-en",
|
779 |
+
"Caucasian": "Helsinki-NLP/opus-mt-cau-en",
|
780 |
+
"Cebuano": "Helsinki-NLP/opus-mt-ceb-en",
|
781 |
+
"Celtic": "Helsinki-NLP/opus-mt-cel-en",
|
782 |
+
"Chuukese": "Helsinki-NLP/opus-mt-chk-en",
|
783 |
+
"Creoles and pidgins (French)": "Helsinki-NLP/opus-mt-cpf-en",
|
784 |
+
"Seychelles Creole": "Helsinki-NLP/opus-mt-crs-en",
|
785 |
+
"American Sign Language": "Helsinki-NLP/opus-mt-ase-en",
|
786 |
+
"Artificial Language": "Helsinki-NLP/opus-mt-art-en",
|
787 |
+
"Atlantic-Congo": "Helsinki-NLP/opus-mt-alv-en",
|
788 |
+
"Afroasiatic": "Helsinki-NLP/opus-mt-afa-en",
|
789 |
+
"Afrikaans": "Helsinki-NLP/opus-mt-af-en",
|
790 |
+
"Austroasiatic": "Helsinki-NLP/opus-mt-aav-en"
|
791 |
+
}
|
792 |
+
|
793 |
+
# 번역기 캐시 딕셔너리
|
794 |
+
translators_cache = {}
|
795 |
+
|
796 |
+
def get_translator(lang):
|
797 |
+
if lang not in translators_cache:
|
798 |
+
model_name = TRANSLATORS[lang]
|
799 |
+
try:
|
800 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
801 |
+
model = MarianMTModel.from_pretrained(
|
802 |
+
model_name,
|
803 |
+
torch_dtype=torch.float16,
|
804 |
+
low_cpu_mem_usage=True
|
805 |
+
)
|
806 |
+
translators_cache[lang] = pipeline(
|
807 |
+
"translation",
|
808 |
+
model=model,
|
809 |
+
tokenizer=tokenizer,
|
810 |
+
device=-1 # CPU 사용
|
811 |
+
)
|
812 |
+
except Exception as e:
|
813 |
+
print(f"Error loading translator for {lang}: {e}")
|
814 |
+
return None
|
815 |
+
return translators_cache[lang]
|
816 |
+
|
817 |
+
def translate_prompt(prompt, source_lang):
|
818 |
+
if source_lang == "English":
|
819 |
+
return prompt
|
820 |
+
|
821 |
+
translator = get_translator(source_lang)
|
822 |
+
if translator is None:
|
823 |
+
print(f"Translation failed for {source_lang}, using original prompt")
|
824 |
+
return prompt
|
825 |
+
|
826 |
+
try:
|
827 |
+
translated = translator(prompt, max_length=512)[0]['translation_text']
|
828 |
+
print(f"Translated from {source_lang}: {translated}")
|
829 |
+
return translated
|
830 |
+
except Exception as e:
|
831 |
+
print(f"Translation error: {e}")
|
832 |
+
return prompt
|
833 |
+
|
834 |
+
@spaces.GPU
|
835 |
+
@torch.no_grad()
|
836 |
+
def generate_image(
|
837 |
+
prompt, source_lang, width, height, guidance, inference_steps, seed,
|
838 |
+
do_img2img, init_image, image2image_strength, resize_img,
|
839 |
+
progress=gr.Progress(track_tqdm=True),
|
840 |
+
):
|
841 |
+
try:
|
842 |
+
translated_prompt = translate_prompt(prompt, source_lang)
|
843 |
+
except Exception as e:
|
844 |
+
print(f"Translation failed: {e}")
|
845 |
+
translated_prompt = prompt
|
846 |
+
|
847 |
+
|
848 |
+
if seed == 0:
|
849 |
+
seed = int(random.random() * 1000000)
|
850 |
+
|
851 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
852 |
+
torch_device = torch.device(device)
|
853 |
+
|
854 |
+
global model, model_zero_init
|
855 |
+
if not model_zero_init:
|
856 |
+
model = model.to(torch_device)
|
857 |
+
model_zero_init = True
|
858 |
+
|
859 |
+
if do_img2img and init_image is not None:
|
860 |
+
init_image = get_image(init_image)
|
861 |
+
if resize_img:
|
862 |
+
init_image = torch.nn.functional.interpolate(init_image, (height, width))
|
863 |
+
else:
|
864 |
+
h, w = init_image.shape[-2:]
|
865 |
+
init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
|
866 |
+
height = init_image.shape[-2]
|
867 |
+
width = init_image.shape[-1]
|
868 |
+
init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
|
869 |
+
init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
|
870 |
+
|
871 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
872 |
+
x = torch.randn(1, 16, 2 * math.ceil(height / 16), 2 * math.ceil(width / 16),
|
873 |
+
device=device, dtype=torch.bfloat16, generator=generator)
|
874 |
+
|
875 |
+
num_steps = inference_steps
|
876 |
+
timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
|
877 |
+
|
878 |
+
if do_img2img and init_image is not None:
|
879 |
+
t_idx = int((1 - image2image_strength) * num_steps)
|
880 |
+
t = timesteps[t_idx]
|
881 |
+
timesteps = timesteps[t_idx:]
|
882 |
+
x = t * x + (1.0 - t) * init_image.to(x.dtype)
|
883 |
+
|
884 |
+
inp = prepare(t5=t5, clip=clip, img=x, prompt=translated_prompt)
|
885 |
+
x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
|
886 |
+
|
887 |
+
x = unpack(x.float(), height, width)
|
888 |
+
with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
|
889 |
+
x = (x / ae.config.scaling_factor) + ae.config.shift_factor
|
890 |
+
x = ae.decode(x).sample
|
891 |
+
|
892 |
+
x = x.clamp(-1, 1)
|
893 |
+
x = rearrange(x[0], "c h w -> h w c")
|
894 |
+
img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
|
895 |
+
|
896 |
+
return img, seed, translated_prompt
|
897 |
+
|
898 |
+
css = """
|
899 |
+
footer {
|
900 |
+
visibility: hidden;
|
901 |
+
}
|
902 |
+
"""
|
903 |
+
|
904 |
+
def create_demo():
|
905 |
+
with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css) as demo:
|
906 |
+
with gr.Row():
|
907 |
+
with gr.Column():
|
908 |
+
source_lang = gr.Dropdown(
|
909 |
+
choices=["English"] + sorted(list(TRANSLATORS.keys())),
|
910 |
+
value="English",
|
911 |
+
label="Source Language"
|
912 |
+
)
|
913 |
+
|
914 |
+
prompt = gr.Textbox(
|
915 |
+
label="Prompt",
|
916 |
+
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."
|
917 |
+
)
|
918 |
+
|
919 |
+
width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=768)
|
920 |
+
height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=768)
|
921 |
+
guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
|
922 |
+
inference_steps = gr.Slider(
|
923 |
+
label="Inference steps",
|
924 |
+
minimum=1,
|
925 |
+
maximum=30,
|
926 |
+
step=1,
|
927 |
+
value=30,
|
928 |
+
)
|
929 |
+
seed = gr.Number(label="Seed", precision=-1)
|
930 |
+
do_img2img = gr.Checkbox(label="Image to Image", value=False)
|
931 |
+
init_image = gr.Image(label="Input Image", visible=False)
|
932 |
+
image2image_strength = gr.Slider(
|
933 |
+
minimum=0.0, maximum=1.0, step=0.01,
|
934 |
+
label="Noising strength", value=0.8, visible=False
|
935 |
+
)
|
936 |
+
resize_img = gr.Checkbox(label="Resize image", value=True, visible=False)
|
937 |
+
generate_button = gr.Button("Generate")
|
938 |
+
|
939 |
+
with gr.Column():
|
940 |
+
output_image = gr.Image(label="Generated Image")
|
941 |
+
output_seed = gr.Text(label="Used Seed")
|
942 |
+
translated_prompt = gr.Text(label="Translated Prompt")
|
943 |
+
|
944 |
+
# Examples 섹션 수정
|
945 |
+
examples = [
|
946 |
+
# English examples
|
947 |
+
["A majestic dragon soaring through clouds at sunset", "English", 768, 768, 3.5, 30],
|
948 |
+
["A cyberpunk city street at night with neon signs", "English", 768, 768, 3.5, 30],
|
949 |
+
# Korean examples
|
950 |
+
["달빛이 비치는 ���요한 한옥 정원", "Korean", 768, 768, 3.5, 30],
|
951 |
+
["벚꽃이 흩날리는 서울의 봄 풍경", "Korean", 768, 768, 3.5, 30],
|
952 |
+
# Spanish examples
|
953 |
+
["Un bailarín de flamenco en las calles de Sevilla", "Spanish", 768, 768, 3.5, 30],
|
954 |
+
["Una colorida fiesta mexicana con piñatas", "Spanish", 768, 768, 3.5, 30],
|
955 |
+
# Chinese examples
|
956 |
+
["中国长城在晨雾中若隐若现", "Chinese", 768, 768, 3.5, 30],
|
957 |
+
["古老的江南水乡,小桥流水人家", "Chinese", 768, 768, 3.5, 30]
|
958 |
+
]
|
959 |
+
|
960 |
+
gr.Examples(
|
961 |
+
examples=examples,
|
962 |
+
inputs=[prompt, source_lang, width, height, guidance, inference_steps],
|
963 |
+
outputs=[output_image, output_seed, translated_prompt],
|
964 |
+
fn=generate_image,
|
965 |
+
cache_examples=True
|
966 |
+
)
|
967 |
+
|
968 |
+
do_img2img.change(
|
969 |
+
fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
|
970 |
+
inputs=[do_img2img],
|
971 |
+
outputs=[init_image, image2image_strength, resize_img]
|
972 |
+
)
|
973 |
+
|
974 |
+
generate_button.click(
|
975 |
+
fn=generate_image,
|
976 |
+
inputs=[
|
977 |
+
prompt, source_lang, width, height, guidance, inference_steps,
|
978 |
+
seed, do_img2img, init_image, image2image_strength, resize_img
|
979 |
+
],
|
980 |
+
outputs=[output_image, output_seed, translated_prompt]
|
981 |
+
)
|
982 |
+
|
983 |
+
return demo
|
984 |
+
|
985 |
+
if __name__ == "__main__":
|
986 |
+
demo = create_demo()
|
987 |
+
demo.launch(share=True) # share=True 추가
|