ParimalX commited on
Commit
d43de2b
·
1 Parent(s): be53429

Update space

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