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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from dataclasses import dataclass
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import torch
|
6 |
+
from PIL import Image
|
7 |
+
from torchvision import transforms
|
8 |
+
from dataclasses import dataclass
|
9 |
+
import math
|
10 |
+
from typing import Callable
|
11 |
+
|
12 |
+
from tqdm import tqdm
|
13 |
+
import bitsandbytes as bnb
|
14 |
+
from bitsandbytes.nn.modules import Params4bit, QuantState
|
15 |
+
|
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 safetensors.torch import load_file
|
25 |
+
from optimum.quanto import freeze, qfloat8, quantize
|
26 |
+
|
27 |
+
|
28 |
+
# ---------------- Encoders ----------------
|
29 |
+
|
30 |
+
|
31 |
+
class HFEmbedder(nn.Module):
|
32 |
+
def __init__(self, version: str, max_length: int, **hf_kwargs):
|
33 |
+
super().__init__()
|
34 |
+
self.is_clip = version.startswith("openai")
|
35 |
+
self.max_length = max_length
|
36 |
+
self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
|
37 |
+
|
38 |
+
if self.is_clip:
|
39 |
+
self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
|
40 |
+
self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
|
41 |
+
else:
|
42 |
+
self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
|
43 |
+
self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
|
44 |
+
|
45 |
+
self.hf_module = self.hf_module.eval().requires_grad_(False)
|
46 |
+
|
47 |
+
def forward(self, text: list[str]) -> Tensor:
|
48 |
+
batch_encoding = self.tokenizer(
|
49 |
+
text,
|
50 |
+
truncation=True,
|
51 |
+
max_length=self.max_length,
|
52 |
+
return_length=False,
|
53 |
+
return_overflowing_tokens=False,
|
54 |
+
padding="max_length",
|
55 |
+
return_tensors="pt",
|
56 |
+
)
|
57 |
+
|
58 |
+
outputs = self.hf_module(
|
59 |
+
input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
|
60 |
+
attention_mask=None,
|
61 |
+
output_hidden_states=False,
|
62 |
+
)
|
63 |
+
return outputs[self.output_key]
|
64 |
+
|
65 |
+
|
66 |
+
device = "cuda"
|
67 |
+
t5 = HFEmbedder("google/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
|
68 |
+
clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
|
69 |
+
ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
|
70 |
+
quantize(t5, weights=qfloat8)
|
71 |
+
freeze(t5)
|
72 |
+
|
73 |
+
|
74 |
+
# ---------------- NF4 ----------------
|
75 |
+
|
76 |
+
|
77 |
+
def functional_linear_4bits(x, weight, bias):
|
78 |
+
out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
|
79 |
+
out = out.to(x)
|
80 |
+
return out
|
81 |
+
|
82 |
+
|
83 |
+
def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantState:
|
84 |
+
if state is None:
|
85 |
+
return None
|
86 |
+
|
87 |
+
device = device or state.absmax.device
|
88 |
+
|
89 |
+
state2 = (
|
90 |
+
QuantState(
|
91 |
+
absmax=state.state2.absmax.to(device),
|
92 |
+
shape=state.state2.shape,
|
93 |
+
code=state.state2.code.to(device),
|
94 |
+
blocksize=state.state2.blocksize,
|
95 |
+
quant_type=state.state2.quant_type,
|
96 |
+
dtype=state.state2.dtype,
|
97 |
+
)
|
98 |
+
if state.nested
|
99 |
+
else None
|
100 |
+
)
|
101 |
+
|
102 |
+
return QuantState(
|
103 |
+
absmax=state.absmax.to(device),
|
104 |
+
shape=state.shape,
|
105 |
+
code=state.code.to(device),
|
106 |
+
blocksize=state.blocksize,
|
107 |
+
quant_type=state.quant_type,
|
108 |
+
dtype=state.dtype,
|
109 |
+
offset=state.offset.to(device) if state.nested else None,
|
110 |
+
state2=state2,
|
111 |
+
)
|
112 |
+
|
113 |
+
|
114 |
+
class ForgeParams4bit(Params4bit):
|
115 |
+
def to(self, *args, **kwargs):
|
116 |
+
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
|
117 |
+
if device is not None and device.type == "cuda" and not self.bnb_quantized:
|
118 |
+
return self._quantize(device)
|
119 |
+
else:
|
120 |
+
n = ForgeParams4bit(
|
121 |
+
torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
|
122 |
+
requires_grad=self.requires_grad,
|
123 |
+
quant_state=copy_quant_state(self.quant_state, device),
|
124 |
+
blocksize=self.blocksize,
|
125 |
+
compress_statistics=self.compress_statistics,
|
126 |
+
quant_type=self.quant_type,
|
127 |
+
quant_storage=self.quant_storage,
|
128 |
+
bnb_quantized=self.bnb_quantized,
|
129 |
+
module=self.module
|
130 |
+
)
|
131 |
+
self.module.quant_state = n.quant_state
|
132 |
+
self.data = n.data
|
133 |
+
self.quant_state = n.quant_state
|
134 |
+
return n
|
135 |
+
|
136 |
+
|
137 |
+
class ForgeLoader4Bit(torch.nn.Module):
|
138 |
+
def __init__(self, *, device, dtype, quant_type, **kwargs):
|
139 |
+
super().__init__()
|
140 |
+
self.dummy = torch.nn.Parameter(torch.empty(1, device=device, dtype=dtype))
|
141 |
+
self.weight = None
|
142 |
+
self.quant_state = None
|
143 |
+
self.bias = None
|
144 |
+
self.quant_type = quant_type
|
145 |
+
|
146 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
147 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
148 |
+
quant_state = getattr(self.weight, "quant_state", None)
|
149 |
+
if quant_state is not None:
|
150 |
+
for k, v in quant_state.as_dict(packed=True).items():
|
151 |
+
destination[prefix + "weight." + k] = v if keep_vars else v.detach()
|
152 |
+
return
|
153 |
+
|
154 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
|
155 |
+
quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
|
156 |
+
|
157 |
+
if any('bitsandbytes' in k for k in quant_state_keys):
|
158 |
+
quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
|
159 |
+
|
160 |
+
self.weight = ForgeParams4bit.from_prequantized(
|
161 |
+
data=state_dict[prefix + 'weight'],
|
162 |
+
quantized_stats=quant_state_dict,
|
163 |
+
requires_grad=False,
|
164 |
+
device=self.dummy.device,
|
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 |
+
|
220 |
+
return x
|
221 |
+
|
222 |
+
|
223 |
+
def rope(pos: Tensor, dim: int, theta: int) -> Tensor:
|
224 |
+
assert dim % 2 == 0
|
225 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
226 |
+
omega = 1.0 / (theta**scale)
|
227 |
+
out = torch.einsum("...n,d->...nd", pos, omega)
|
228 |
+
out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1)
|
229 |
+
out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
|
230 |
+
return out.float()
|
231 |
+
|
232 |
+
|
233 |
+
def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
234 |
+
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
|
235 |
+
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
|
236 |
+
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
|
237 |
+
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
|
238 |
+
return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
|
239 |
+
|
240 |
+
|
241 |
+
class EmbedND(nn.Module):
|
242 |
+
def __init__(self, dim: int, theta: int, axes_dim: list[int]):
|
243 |
+
super().__init__()
|
244 |
+
self.dim = dim
|
245 |
+
self.theta = theta
|
246 |
+
self.axes_dim = axes_dim
|
247 |
+
|
248 |
+
def forward(self, ids: Tensor) -> Tensor:
|
249 |
+
n_axes = ids.shape[-1]
|
250 |
+
emb = torch.cat(
|
251 |
+
[rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
|
252 |
+
dim=-3,
|
253 |
+
)
|
254 |
+
|
255 |
+
return emb.unsqueeze(1)
|
256 |
+
|
257 |
+
|
258 |
+
def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
|
259 |
+
"""
|
260 |
+
Create sinusoidal timestep embeddings.
|
261 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
262 |
+
These may be fractional.
|
263 |
+
:param dim: the dimension of the output.
|
264 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
265 |
+
:return: an (N, D) Tensor of positional embeddings.
|
266 |
+
"""
|
267 |
+
t = time_factor * t
|
268 |
+
half = dim // 2
|
269 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
|
270 |
+
t.device
|
271 |
+
)
|
272 |
+
|
273 |
+
args = t[:, None].float() * freqs[None]
|
274 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
275 |
+
if dim % 2:
|
276 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
277 |
+
if torch.is_floating_point(t):
|
278 |
+
embedding = embedding.to(t)
|
279 |
+
return embedding
|
280 |
+
|
281 |
+
|
282 |
+
class MLPEmbedder(nn.Module):
|
283 |
+
def __init__(self, in_dim: int, hidden_dim: int):
|
284 |
+
super().__init__()
|
285 |
+
self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
|
286 |
+
self.silu = nn.SiLU()
|
287 |
+
self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
288 |
+
|
289 |
+
def forward(self, x: Tensor) -> Tensor:
|
290 |
+
return self.out_layer(self.silu(self.in_layer(x)))
|
291 |
+
|
292 |
+
|
293 |
+
class RMSNorm(torch.nn.Module):
|
294 |
+
def __init__(self, dim: int):
|
295 |
+
super().__init__()
|
296 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
297 |
+
|
298 |
+
def forward(self, x: Tensor):
|
299 |
+
x_dtype = x.dtype
|
300 |
+
x = x.float()
|
301 |
+
rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
|
302 |
+
return (x * rrms).to(dtype=x_dtype) * self.scale
|
303 |
+
|
304 |
+
|
305 |
+
class QKNorm(torch.nn.Module):
|
306 |
+
def __init__(self, dim: int):
|
307 |
+
super().__init__()
|
308 |
+
self.query_norm = RMSNorm(dim)
|
309 |
+
self.key_norm = RMSNorm(dim)
|
310 |
+
|
311 |
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
|
312 |
+
q = self.query_norm(q)
|
313 |
+
k = self.key_norm(k)
|
314 |
+
return q.to(v), k.to(v)
|
315 |
+
|
316 |
+
|
317 |
+
class SelfAttention(nn.Module):
|
318 |
+
def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
|
319 |
+
super().__init__()
|
320 |
+
self.num_heads = num_heads
|
321 |
+
head_dim = dim // num_heads
|
322 |
+
|
323 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
324 |
+
self.norm = QKNorm(head_dim)
|
325 |
+
self.proj = nn.Linear(dim, dim)
|
326 |
+
|
327 |
+
def forward(self, x: Tensor, pe: Tensor) -> Tensor:
|
328 |
+
qkv = self.qkv(x)
|
329 |
+
q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
330 |
+
q, k = self.norm(q, k, v)
|
331 |
+
x = attention(q, k, v, pe=pe)
|
332 |
+
x = self.proj(x)
|
333 |
+
return x
|
334 |
+
|
335 |
+
|
336 |
+
@dataclass
|
337 |
+
class ModulationOut:
|
338 |
+
shift: Tensor
|
339 |
+
scale: Tensor
|
340 |
+
gate: Tensor
|
341 |
+
|
342 |
+
|
343 |
+
class Modulation(nn.Module):
|
344 |
+
def __init__(self, dim: int, double: bool):
|
345 |
+
super().__init__()
|
346 |
+
self.is_double = double
|
347 |
+
self.multiplier = 6 if double else 3
|
348 |
+
self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
|
349 |
+
|
350 |
+
def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
|
351 |
+
out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
|
352 |
+
|
353 |
+
return (
|
354 |
+
ModulationOut(*out[:3]),
|
355 |
+
ModulationOut(*out[3:]) if self.is_double else None,
|
356 |
+
)
|
357 |
+
|
358 |
+
|
359 |
+
class DoubleStreamBlock(nn.Module):
|
360 |
+
def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
|
361 |
+
super().__init__()
|
362 |
+
|
363 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
364 |
+
self.num_heads = num_heads
|
365 |
+
self.hidden_size = hidden_size
|
366 |
+
self.img_mod = Modulation(hidden_size, double=True)
|
367 |
+
self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
368 |
+
self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
369 |
+
|
370 |
+
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
371 |
+
self.img_mlp = nn.Sequential(
|
372 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
373 |
+
nn.GELU(approximate="tanh"),
|
374 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
375 |
+
)
|
376 |
+
|
377 |
+
self.txt_mod = Modulation(hidden_size, double=True)
|
378 |
+
self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
379 |
+
self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
|
380 |
+
|
381 |
+
self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
382 |
+
self.txt_mlp = nn.Sequential(
|
383 |
+
nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
|
384 |
+
nn.GELU(approximate="tanh"),
|
385 |
+
nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
|
386 |
+
)
|
387 |
+
|
388 |
+
def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
|
389 |
+
img_mod1, img_mod2 = self.img_mod(vec)
|
390 |
+
txt_mod1, txt_mod2 = self.txt_mod(vec)
|
391 |
+
|
392 |
+
# prepare image for attention
|
393 |
+
img_modulated = self.img_norm1(img)
|
394 |
+
img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
|
395 |
+
img_qkv = self.img_attn.qkv(img_modulated)
|
396 |
+
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)
|
397 |
+
img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
|
398 |
+
|
399 |
+
# prepare txt for attention
|
400 |
+
txt_modulated = self.txt_norm1(txt)
|
401 |
+
txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
|
402 |
+
txt_qkv = self.txt_attn.qkv(txt_modulated)
|
403 |
+
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)
|
404 |
+
txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
|
405 |
+
|
406 |
+
# run actual attention
|
407 |
+
q = torch.cat((txt_q, img_q), dim=2)
|
408 |
+
k = torch.cat((txt_k, img_k), dim=2)
|
409 |
+
v = torch.cat((txt_v, img_v), dim=2)
|
410 |
+
|
411 |
+
attn = attention(q, k, v, pe=pe)
|
412 |
+
txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
|
413 |
+
|
414 |
+
# calculate the img bloks
|
415 |
+
img = img + img_mod1.gate * self.img_attn.proj(img_attn)
|
416 |
+
img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
|
417 |
+
|
418 |
+
# calculate the txt bloks
|
419 |
+
txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
|
420 |
+
txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
|
421 |
+
return img, txt
|
422 |
+
|
423 |
+
|
424 |
+
class SingleStreamBlock(nn.Module):
|
425 |
+
"""
|
426 |
+
A DiT block with parallel linear layers as described in
|
427 |
+
https://arxiv.org/abs/2302.05442 and adapted modulation interface.
|
428 |
+
"""
|
429 |
+
|
430 |
+
def __init__(
|
431 |
+
self,
|
432 |
+
hidden_size: int,
|
433 |
+
num_heads: int,
|
434 |
+
mlp_ratio: float = 4.0,
|
435 |
+
qk_scale: float | None = None,
|
436 |
+
):
|
437 |
+
super().__init__()
|
438 |
+
self.hidden_dim = hidden_size
|
439 |
+
self.num_heads = num_heads
|
440 |
+
head_dim = hidden_size // num_heads
|
441 |
+
self.scale = qk_scale or head_dim**-0.5
|
442 |
+
|
443 |
+
self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
444 |
+
# qkv and mlp_in
|
445 |
+
self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
|
446 |
+
# proj and mlp_out
|
447 |
+
self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
|
448 |
+
|
449 |
+
self.norm = QKNorm(head_dim)
|
450 |
+
|
451 |
+
self.hidden_size = hidden_size
|
452 |
+
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
453 |
+
|
454 |
+
self.mlp_act = nn.GELU(approximate="tanh")
|
455 |
+
self.modulation = Modulation(hidden_size, double=False)
|
456 |
+
|
457 |
+
def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
|
458 |
+
mod, _ = self.modulation(vec)
|
459 |
+
x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
|
460 |
+
qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
|
461 |
+
|
462 |
+
q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
463 |
+
q, k = self.norm(q, k, v)
|
464 |
+
|
465 |
+
# compute attention
|
466 |
+
attn = attention(q, k, v, pe=pe)
|
467 |
+
# compute activation in mlp stream, cat again and run second linear layer
|
468 |
+
output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
|
469 |
+
return x + mod.gate * output
|
470 |
+
|
471 |
+
|
472 |
+
class LastLayer(nn.Module):
|
473 |
+
def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
|
474 |
+
super().__init__()
|
475 |
+
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
476 |
+
self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
|
477 |
+
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
|
478 |
+
|
479 |
+
def forward(self, x: Tensor, vec: Tensor) -> Tensor:
|
480 |
+
shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
|
481 |
+
x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
|
482 |
+
x = self.linear(x)
|
483 |
+
return x
|
484 |
+
|
485 |
+
|
486 |
+
class FluxParams:
|
487 |
+
in_channels: int = 64
|
488 |
+
vec_in_dim: int = 768
|
489 |
+
context_in_dim: int = 4096
|
490 |
+
hidden_size: int = 3072
|
491 |
+
mlp_ratio: float = 4.0
|
492 |
+
num_heads: int = 24
|
493 |
+
depth: int = 19
|
494 |
+
depth_single_blocks: int = 38
|
495 |
+
axes_dim: list = [16, 56, 56]
|
496 |
+
theta: int = 10_000
|
497 |
+
qkv_bias: bool = True
|
498 |
+
guidance_embed: bool = True
|
499 |
+
|
500 |
+
|
501 |
+
class Flux(nn.Module):
|
502 |
+
"""
|
503 |
+
Transformer model for flow matching on sequences.
|
504 |
+
"""
|
505 |
+
|
506 |
+
def __init__(self, params = FluxParams()):
|
507 |
+
super().__init__()
|
508 |
+
|
509 |
+
self.params = params
|
510 |
+
self.in_channels = params.in_channels
|
511 |
+
self.out_channels = self.in_channels
|
512 |
+
if params.hidden_size % params.num_heads != 0:
|
513 |
+
raise ValueError(
|
514 |
+
f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
|
515 |
+
)
|
516 |
+
pe_dim = params.hidden_size // params.num_heads
|
517 |
+
if sum(params.axes_dim) != pe_dim:
|
518 |
+
raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
|
519 |
+
self.hidden_size = params.hidden_size
|
520 |
+
self.num_heads = params.num_heads
|
521 |
+
self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
|
522 |
+
self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
|
523 |
+
self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
|
524 |
+
self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
|
525 |
+
self.guidance_in = (
|
526 |
+
MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
|
527 |
+
)
|
528 |
+
self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
|
529 |
+
|
530 |
+
self.double_blocks = nn.ModuleList(
|
531 |
+
[
|
532 |
+
DoubleStreamBlock(
|
533 |
+
self.hidden_size,
|
534 |
+
self.num_heads,
|
535 |
+
mlp_ratio=params.mlp_ratio,
|
536 |
+
qkv_bias=params.qkv_bias,
|
537 |
+
)
|
538 |
+
for _ in range(params.depth)
|
539 |
+
]
|
540 |
+
)
|
541 |
+
|
542 |
+
self.single_blocks = nn.ModuleList(
|
543 |
+
[
|
544 |
+
SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
|
545 |
+
for _ in range(params.depth_single_blocks)
|
546 |
+
]
|
547 |
+
)
|
548 |
+
|
549 |
+
self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
|
550 |
+
|
551 |
+
def forward(
|
552 |
+
self,
|
553 |
+
img: Tensor,
|
554 |
+
img_ids: Tensor,
|
555 |
+
txt: Tensor,
|
556 |
+
txt_ids: Tensor,
|
557 |
+
timesteps: Tensor,
|
558 |
+
y: Tensor,
|
559 |
+
guidance: Tensor | None = None,
|
560 |
+
) -> Tensor:
|
561 |
+
if img.ndim != 3 or txt.ndim != 3:
|
562 |
+
raise ValueError("Input img and txt tensors must have 3 dimensions.")
|
563 |
+
|
564 |
+
# running on sequences img
|
565 |
+
img = self.img_in(img)
|
566 |
+
vec = self.time_in(timestep_embedding(timesteps, 256))
|
567 |
+
if self.params.guidance_embed:
|
568 |
+
if guidance is None:
|
569 |
+
raise ValueError("Didn't get guidance strength for guidance distilled model.")
|
570 |
+
vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
|
571 |
+
vec = vec + self.vector_in(y)
|
572 |
+
txt = self.txt_in(txt)
|
573 |
+
|
574 |
+
ids = torch.cat((txt_ids, img_ids), dim=1)
|
575 |
+
pe = self.pe_embedder(ids)
|
576 |
+
|
577 |
+
for block in self.double_blocks:
|
578 |
+
img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
|
579 |
+
|
580 |
+
img = torch.cat((txt, img), 1)
|
581 |
+
for block in self.single_blocks:
|
582 |
+
img = block(img, vec=vec, pe=pe)
|
583 |
+
img = img[:, txt.shape[1] :, ...]
|
584 |
+
|
585 |
+
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
|
586 |
+
return img
|
587 |
+
|
588 |
+
|
589 |
+
def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
|
590 |
+
bs, c, h, w = img.shape
|
591 |
+
if bs == 1 and not isinstance(prompt, str):
|
592 |
+
bs = len(prompt)
|
593 |
+
|
594 |
+
img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
|
595 |
+
if img.shape[0] == 1 and bs > 1:
|
596 |
+
img = repeat(img, "1 ... -> bs ...", bs=bs)
|
597 |
+
|
598 |
+
img_ids = torch.zeros(h // 2, w // 2, 3)
|
599 |
+
img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
|
600 |
+
img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
|
601 |
+
img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
|
602 |
+
|
603 |
+
if isinstance(prompt, str):
|
604 |
+
prompt = [prompt]
|
605 |
+
txt = t5(prompt)
|
606 |
+
if txt.shape[0] == 1 and bs > 1:
|
607 |
+
txt = repeat(txt, "1 ... -> bs ...", bs=bs)
|
608 |
+
txt_ids = torch.zeros(bs, txt.shape[1], 3)
|
609 |
+
|
610 |
+
vec = clip(prompt)
|
611 |
+
if vec.shape[0] == 1 and bs > 1:
|
612 |
+
vec = repeat(vec, "1 ... -> bs ...", bs=bs)
|
613 |
+
|
614 |
+
return {
|
615 |
+
"img": img,
|
616 |
+
"img_ids": img_ids.to(img.device),
|
617 |
+
"txt": txt.to(img.device),
|
618 |
+
"txt_ids": txt_ids.to(img.device),
|
619 |
+
"vec": vec.to(img.device),
|
620 |
+
}
|
621 |
+
|
622 |
+
|
623 |
+
def time_shift(mu: float, sigma: float, t: Tensor):
|
624 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
625 |
+
|
626 |
+
|
627 |
+
def get_lin_function(
|
628 |
+
x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
|
629 |
+
) -> Callable[[float], float]:
|
630 |
+
m = (y2 - y1) / (x2 - x1)
|
631 |
+
b = y1 - m * x1
|
632 |
+
return lambda x: m * x + b
|
633 |
+
|
634 |
+
|
635 |
+
def get_schedule(
|
636 |
+
num_steps: int,
|
637 |
+
image_seq_len: int,
|
638 |
+
base_shift: float = 0.5,
|
639 |
+
max_shift: float = 1.15,
|
640 |
+
shift: bool = True,
|
641 |
+
) -> list[float]:
|
642 |
+
# extra step for zero
|
643 |
+
timesteps = torch.linspace(1, 0, num_steps + 1)
|
644 |
+
|
645 |
+
# shifting the schedule to favor high timesteps for higher signal images
|
646 |
+
if shift:
|
647 |
+
# eastimate mu based on linear estimation between two points
|
648 |
+
mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
|
649 |
+
timesteps = time_shift(mu, 1.0, timesteps)
|
650 |
+
|
651 |
+
return timesteps.tolist()
|
652 |
+
|
653 |
+
|
654 |
+
def denoise(
|
655 |
+
model: Flux,
|
656 |
+
# model input
|
657 |
+
img: Tensor,
|
658 |
+
img_ids: Tensor,
|
659 |
+
txt: Tensor,
|
660 |
+
txt_ids: Tensor,
|
661 |
+
vec: Tensor,
|
662 |
+
# sampling parameters
|
663 |
+
timesteps: list[float],
|
664 |
+
guidance: float = 4.0,
|
665 |
+
):
|
666 |
+
# this is ignored for schnell
|
667 |
+
guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
|
668 |
+
for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
|
669 |
+
t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
|
670 |
+
pred = model(
|
671 |
+
img=img,
|
672 |
+
img_ids=img_ids,
|
673 |
+
txt=txt,
|
674 |
+
txt_ids=txt_ids,
|
675 |
+
y=vec,
|
676 |
+
timesteps=t_vec,
|
677 |
+
guidance=guidance_vec,
|
678 |
+
)
|
679 |
+
|
680 |
+
img = img + (t_prev - t_curr) * pred
|
681 |
+
|
682 |
+
return img
|
683 |
+
|
684 |
+
|
685 |
+
def unpack(x: Tensor, height: int, width: int) -> Tensor:
|
686 |
+
return rearrange(
|
687 |
+
x,
|
688 |
+
"b (h w) (c ph pw) -> b c (h ph) (w pw)",
|
689 |
+
h=math.ceil(height / 16),
|
690 |
+
w=math.ceil(width / 16),
|
691 |
+
ph=2,
|
692 |
+
pw=2,
|
693 |
+
)
|
694 |
+
|
695 |
+
@dataclass
|
696 |
+
class SamplingOptions:
|
697 |
+
prompt: str
|
698 |
+
width: int
|
699 |
+
height: int
|
700 |
+
guidance: float
|
701 |
+
seed: int | None
|
702 |
+
|
703 |
+
|
704 |
+
def get_image(image) -> torch.Tensor | None:
|
705 |
+
if image is None:
|
706 |
+
return None
|
707 |
+
image = Image.fromarray(image).convert("RGB")
|
708 |
+
|
709 |
+
transform = transforms.Compose([
|
710 |
+
transforms.ToTensor(),
|
711 |
+
transforms.Lambda(lambda x: 2.0 * x - 1.0),
|
712 |
+
])
|
713 |
+
img: torch.Tensor = transform(image)
|
714 |
+
return img[None, ...]
|
715 |
+
|
716 |
+
|
717 |
+
# ---------------- Demo ----------------
|
718 |
+
|
719 |
+
|
720 |
+
from pathlib import Path
|
721 |
+
|
722 |
+
if not Path("flux1-dev-bnb-nf4.safetensors").exists():
|
723 |
+
torch.hub.download_url_to_file("https://huggingface.co/lllyasviel/flux1-dev-bnb-nf4/resolve/main/flux1-dev-bnb-nf4.safetensors", "flux1-dev-bnb-nf4.safetensors")
|
724 |
+
|
725 |
+
sd = load_file("flux1-dev-bnb-nf4.safetensors")
|
726 |
+
sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
|
727 |
+
model = Flux().to(dtype=torch.float16, device="cuda")
|
728 |
+
result = model.load_state_dict(sd)
|
729 |
+
print(result)
|
730 |
+
|
731 |
+
# model = Flux().to(dtype=torch.bfloat16, device="cuda")
|
732 |
+
# result = model.load_state_dict(load_file("/storage/dev/nyanko/flux-dev/flux1-dev.sft"))
|
733 |
+
|
734 |
+
@torch.inference_mode()
|
735 |
+
def generate_image(
|
736 |
+
prompt, width, height, guidance, seed,
|
737 |
+
do_img2img, init_image, image2image_strength, resize_img,
|
738 |
+
progress=gr.Progress(track_tqdm=True),
|
739 |
+
):
|
740 |
+
if seed == 0:
|
741 |
+
seed = int(random.random() * 1000000)
|
742 |
+
|
743 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
744 |
+
torch_device = torch.device(device)
|
745 |
+
|
746 |
+
if do_img2img and init_image is not None:
|
747 |
+
init_image = get_image(init_image)
|
748 |
+
if resize_img:
|
749 |
+
init_image = torch.nn.functional.interpolate(init_image, (height, width))
|
750 |
+
else:
|
751 |
+
h, w = init_image.shape[-2:]
|
752 |
+
init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
|
753 |
+
height = init_image.shape[-2]
|
754 |
+
width = init_image.shape[-1]
|
755 |
+
init_image = ae.encode(init_image.to(torch_device))
|
756 |
+
|
757 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
758 |
+
x = torch.randn(1, 16, 2 * math.ceil(height / 16), 2 * math.ceil(width / 16), device=device, dtype=torch.bfloat16, generator=generator)
|
759 |
+
|
760 |
+
num_steps = 25
|
761 |
+
timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
|
762 |
+
|
763 |
+
if do_img2img and init_image is not None:
|
764 |
+
t_idx = int((1 - image2image_strength) * num_steps)
|
765 |
+
t = timesteps[t_idx]
|
766 |
+
timesteps = timesteps[t_idx:]
|
767 |
+
x = t * x + (1.0 - t) * init_image.to(x.dtype)
|
768 |
+
|
769 |
+
inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
|
770 |
+
x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
|
771 |
+
x = unpack(x.float(), height, width)
|
772 |
+
with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
|
773 |
+
x = x = (x / ae.config.scaling_factor) + ae.config.shift_factor
|
774 |
+
x = ae.decode(x).sample
|
775 |
+
|
776 |
+
x = x.clamp(-1, 1)
|
777 |
+
x = rearrange(x[0], "c h w -> h w c")
|
778 |
+
img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
|
779 |
+
|
780 |
+
return img, seed
|
781 |
+
|
782 |
+
def create_demo():
|
783 |
+
with gr.Blocks(theme="bethecloud/storj_theme") as demo:
|
784 |
+
gr.HTML(
|
785 |
+
"""
|
786 |
+
<div style="text-align: center; margin: 0 auto;">
|
787 |
+
<div
|
788 |
+
style="
|
789 |
+
display: inline-flex;
|
790 |
+
align-items: center;
|
791 |
+
gap: 0.8rem;
|
792 |
+
font-size: 1.75rem;
|
793 |
+
"
|
794 |
+
>
|
795 |
+
<svg
|
796 |
+
width="0.65em"
|
797 |
+
height="0.65em"
|
798 |
+
viewBox="0 0 115 115"
|
799 |
+
fill="none"
|
800 |
+
xmlns="http://www.w3.org/2000/svg"
|
801 |
+
>
|
802 |
+
<rect width="23" height="23" fill="white"></rect>
|
803 |
+
<rect y="69" width="23" height="23" fill="white"></rect>
|
804 |
+
<rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
|
805 |
+
<rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
|
806 |
+
<rect x="46" width="23" height="23" fill="white"></rect>
|
807 |
+
<rect x="46" y="69" width="23" height="23" fill="white"></rect>
|
808 |
+
<rect x="69" width="23" height="23" fill="black"></rect>
|
809 |
+
<rect x="69" y="69" width="23" height="23" fill="black"></rect>
|
810 |
+
<rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
|
811 |
+
<rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
|
812 |
+
<rect x="115" y="46" width="23" height="23" fill="white"></rect>
|
813 |
+
<rect x="115" y="115" width="23" height="23" fill="white"></rect>
|
814 |
+
<rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
|
815 |
+
<rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
|
816 |
+
<rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
|
817 |
+
<rect x="92" y="69" width="23" height="23" fill="white"></rect>
|
818 |
+
<rect x="69" y="46" width="23" height="23" fill="white"></rect>
|
819 |
+
<rect x="69" y="115" width="23" height="23" fill="white"></rect>
|
820 |
+
<rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
|
821 |
+
<rect x="46" y="46" width="23" height="23" fill="black"></rect>
|
822 |
+
<rect x="46" y="115" width="23" height="23" fill="black"></rect>
|
823 |
+
<rect x="46" y="69" width="23" height="23" fill="black"></rect>
|
824 |
+
<rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
|
825 |
+
<rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
|
826 |
+
<rect x="23" y="69" width="23" height="23" fill="black"></rect>
|
827 |
+
</svg>
|
828 |
+
<h1 style="font-weight: 900; margin-bottom: 7px;margin-top:5px">
|
829 |
+
FLUX.1 dev NF4 Quantized Demo
|
830 |
+
</h1>
|
831 |
+
</div>
|
832 |
+
<p style="margin-bottom: 20px; font-size: 94%; line-height: 23px;">
|
833 |
+
12B param rectified flow transformer guidance-distilled from <a href="https://blackforestlabs.ai/">FLUX.1 [pro]</a>
|
834 |
+
<a href="https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md">[non-commercial license]</a> <a href="https://blackforestlabs.ai/announcing-black-forest-labs/">[blog]</a> <a href="https://huggingface.co/black-forest-labs/FLUX.1-dev">[model]</a>
|
835 |
+
</p>
|
836 |
+
</div>
|
837 |
+
"""
|
838 |
+
)
|
839 |
+
with gr.Row():
|
840 |
+
with gr.Column():
|
841 |
+
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")
|
842 |
+
|
843 |
+
width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=1360)
|
844 |
+
height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=768)
|
845 |
+
guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
|
846 |
+
seed = gr.Number(label="Seed", precision=-1)
|
847 |
+
do_img2img = gr.Checkbox(label="Image to Image", value=False)
|
848 |
+
init_image = gr.Image(label="Input Image", visible=False)
|
849 |
+
image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising strength", value=0.8, visible=False)
|
850 |
+
resize_img = gr.Checkbox(label="Resize image", value=True, visible=False)
|
851 |
+
generate_button = gr.Button("Generate")
|
852 |
+
|
853 |
+
with gr.Column():
|
854 |
+
output_image = gr.Image(label="Generated Image")
|
855 |
+
output_seed = gr.Number(label="Used Seed", precision=0)
|
856 |
+
|
857 |
+
do_img2img.change(
|
858 |
+
fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
|
859 |
+
inputs=[do_img2img],
|
860 |
+
outputs=[init_image, image2image_strength, resize_img]
|
861 |
+
)
|
862 |
+
|
863 |
+
generate_button.click(
|
864 |
+
fn=generate_image,
|
865 |
+
inputs=[prompt, width, height, guidance, seed, do_img2img, init_image, image2image_strength, resize_img],
|
866 |
+
outputs=[output_image, output_seed]
|
867 |
+
)
|
868 |
+
|
869 |
+
examples = [
|
870 |
+
"a tiny astronaut hatching from an egg on the moon",
|
871 |
+
"a cat holding a sign that says hello world",
|
872 |
+
"an anime illustration of a wiener schnitzel",
|
873 |
+
]
|
874 |
+
|
875 |
+
return demo
|
876 |
+
|
877 |
+
if __name__ == "__main__":
|
878 |
+
demo = create_demo()
|
879 |
+
demo.launch()
|