ginipick commited on
Commit
f113450
·
verified ·
1 Parent(s): 4f211fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -55
app.py CHANGED
@@ -66,42 +66,15 @@ ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="va
66
  # ---------------- NF4 ----------------
67
 
68
  def functional_linear_4bits(x, weight, bias):
 
69
  out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
70
  out = out.to(x)
71
  return out
72
 
73
- def copy_quant_state(state: QuantState, device: torch.device = None) -> QuantState:
74
- if state is None:
75
- return None
76
-
77
- device = device or state.absmax.device
78
-
79
- state2 = (
80
- QuantState(
81
- absmax=state.state2.absmax.to(device),
82
- shape=state.state2.shape,
83
- code=state.state2.code.to(device),
84
- blocksize=state.state2.blocksize,
85
- quant_type=state.state2.quant_type,
86
- dtype=state.state2.dtype,
87
- )
88
- if state.nested
89
- else None
90
- )
91
-
92
- return QuantState(
93
- absmax=state.absmax.to(device),
94
- shape=state.shape,
95
- code=state.code.to(device),
96
- blocksize=state.blocksize,
97
- quant_type=state.quant_type,
98
- dtype=state.dtype,
99
- offset=state.offset.to(device) if state.nested else None,
100
- state2=state2,
101
- )
102
-
103
  class ForgeParams4bit(Params4bit):
 
104
  def to(self, *args, **kwargs):
 
105
  device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
106
  if device is not None and device.type == "cuda" and not self.bnb_quantized:
107
  return self._quantize(device)
@@ -109,7 +82,7 @@ class ForgeParams4bit(Params4bit):
109
  n = ForgeParams4bit(
110
  torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
111
  requires_grad=self.requires_grad,
112
- quant_state=copy_quant_state(self.quant_state, device),
113
  compress_statistics=False,
114
  blocksize=64,
115
  quant_type=self.quant_type,
@@ -122,10 +95,10 @@ class ForgeParams4bit(Params4bit):
122
  self.quant_state = n.quant_state
123
  return n
124
 
125
- class ForgeLoader4Bit(torch.nn.Module):
126
  def __init__(self, *, device, dtype, quant_type, **kwargs):
127
  super().__init__()
128
- self.dummy = torch.nn.Parameter(torch.empty(1, device=device, dtype=dtype))
129
  self.weight = None
130
  self.quant_state = None
131
  self.bias = None
@@ -133,18 +106,22 @@ class ForgeLoader4Bit(torch.nn.Module):
133
 
134
  def _save_to_state_dict(self, destination, prefix, keep_vars):
135
  super()._save_to_state_dict(destination, prefix, keep_vars)
 
136
  quant_state = getattr(self.weight, "quant_state", None)
137
  if quant_state is not None:
138
  for k, v in quant_state.as_dict(packed=True).items():
139
  destination[prefix + "weight." + k] = v if keep_vars else v.detach()
140
  return
141
 
142
- def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
143
- quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
 
 
 
144
 
 
145
  if any('bitsandbytes' in k for k in quant_state_keys):
146
  quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
147
-
148
  self.weight = ForgeParams4bit.from_prequantized(
149
  data=state_dict[prefix + 'weight'],
150
  quantized_stats=quant_state_dict,
@@ -156,7 +133,6 @@ class ForgeLoader4Bit(torch.nn.Module):
156
 
157
  if prefix + 'bias' in state_dict:
158
  self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
159
-
160
  del self.dummy
161
  elif hasattr(self, 'dummy'):
162
  if prefix + 'weight' in state_dict:
@@ -183,12 +159,11 @@ class Linear(ForgeLoader4Bit):
183
 
184
  def forward(self, x):
185
  self.weight.quant_state = self.quant_state
186
-
187
  if self.bias is not None and self.bias.dtype != x.dtype:
188
  self.bias.data = self.bias.data.to(x.dtype)
189
-
190
  return functional_linear_4bits(x, self.weight, self.bias)
191
 
 
192
  nn.Linear = Linear
193
 
194
  # ---------------- Model ----------------
@@ -200,6 +175,7 @@ def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
200
  return x
201
 
202
  def rope(pos, dim, theta):
 
203
  scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
204
  omega = 1.0 / (theta ** scale)
205
  out = pos.unsqueeze(-1) * omega.unsqueeze(0)
@@ -225,6 +201,7 @@ class EmbedND(nn.Module):
225
  self.axes_dim = axes_dim
226
 
227
  def forward(self, ids: Tensor) -> Tensor:
 
228
  n_axes = ids.shape[-1]
229
  emb = torch.cat(
230
  [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
@@ -233,6 +210,7 @@ class EmbedND(nn.Module):
233
  return emb.unsqueeze(1)
234
 
235
  def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
 
236
  t = time_factor * t
237
  half = dim // 2
238
  freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
@@ -260,6 +238,7 @@ class RMSNorm(torch.nn.Module):
260
  self.scale = nn.Parameter(torch.ones(dim))
261
 
262
  def forward(self, x: Tensor):
 
263
  x_dtype = x.dtype
264
  x = x.float()
265
  rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
@@ -295,6 +274,8 @@ class SelfAttention(nn.Module):
295
  x = self.proj(x)
296
  return x
297
 
 
 
298
  @dataclass
299
  class ModulationOut:
300
  shift: Tensor
@@ -308,12 +289,11 @@ class Modulation(nn.Module):
308
  self.multiplier = 6 if double else 3
309
  self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
310
 
311
- def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
312
  out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
313
- return (
314
- ModulationOut(*out[:3]),
315
- ModulationOut(*out[3:]) if self.is_double else None,
316
- )
317
 
318
  class DoubleStreamBlock(nn.Module):
319
  def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
@@ -424,6 +404,8 @@ class LastLayer(nn.Module):
424
  x = self.linear(x)
425
  return x
426
 
 
 
427
  @dataclass
428
  class FluxParams:
429
  in_channels: int = 64
@@ -516,6 +498,7 @@ class Flux(nn.Module):
516
  return img
517
 
518
  def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
 
519
  bs, c, h, w = img.shape
520
  if bs == 1 and not isinstance(prompt, str):
521
  bs = len(prompt)
@@ -544,11 +527,13 @@ def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[st
544
  }
545
 
546
  def time_shift(mu: float, sigma: float, t: Tensor):
 
547
  return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
548
 
549
  def get_lin_function(
550
  x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
551
  ) -> Callable[[float], float]:
 
552
  m = (y2 - y1) / (x2 - x1)
553
  b = y1 - m * x1
554
  return lambda x: m * x + b
@@ -560,6 +545,8 @@ def get_schedule(
560
  max_shift: float = 1.15,
561
  shift: bool = True,
562
  ) -> list[float]:
 
 
563
  timesteps = torch.linspace(1, 0, num_steps + 1)
564
  if shift:
565
  mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
@@ -567,7 +554,7 @@ def get_schedule(
567
  return timesteps.tolist()
568
 
569
  def denoise(
570
- model: "Flux",
571
  img: Tensor,
572
  img_ids: Tensor,
573
  txt: Tensor,
@@ -576,6 +563,7 @@ def denoise(
576
  timesteps: list[float],
577
  guidance: float = 4.0,
578
  ):
 
579
  guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
580
  for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
581
  t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
@@ -620,6 +608,7 @@ def get_image(image) -> torch.Tensor | None:
620
  img: torch.Tensor = transform(image)
621
  return img[None, ...]
622
 
 
623
  from huggingface_hub import hf_hub_download
624
  from safetensors.torch import load_file
625
 
@@ -637,16 +626,16 @@ def generate_image(
637
  progress=gr.Progress(track_tqdm=True),
638
  ):
639
  if seed == 0:
640
- seed = int(random.random() * 1000000)
641
-
642
  device = "cuda" if torch.cuda.is_available() else "cpu"
643
  torch_device = torch.device(device)
644
-
645
  global model, model_zero_init
646
  if not model_zero_init:
647
  model = model.to(torch_device)
648
  model_zero_init = True
649
-
650
  if do_img2img and init_image is not None:
651
  init_image = get_image(init_image)
652
  if resize_img:
@@ -670,11 +659,10 @@ def generate_image(
670
  generator=generator
671
  )
672
 
673
- num_steps = inference_steps
674
- timesteps = get_schedule(num_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
675
 
676
  if do_img2img and init_image is not None:
677
- t_idx = int((1 - image2image_strength) * num_steps)
678
  t = timesteps[t_idx]
679
  timesteps = timesteps[t_idx:]
680
  x = t * x + (1.0 - t) * init_image.to(x.dtype)
@@ -682,9 +670,11 @@ def generate_image(
682
  inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
683
  x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
684
  x = unpack(x.float(), height, width)
 
685
  with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
686
  x = (x / ae.config.scaling_factor) + ae.config.shift_factor
687
  x = ae.decode(x).sample
 
688
  x = x.clamp(-1, 1)
689
  x = rearrange(x[0], "c h w -> h w c")
690
  img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
@@ -717,7 +707,14 @@ def create_demo():
717
  seed = gr.Number(label="Seed", precision=-1)
718
  do_img2img = gr.Checkbox(label="Image to Image", value=False)
719
  init_image = gr.Image(label="Initial Image", visible=False)
720
- image2image_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Noising Strength", value=0.8, visible=False)
 
 
 
 
 
 
 
721
  resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
722
  generate_button = gr.Button("Generate", variant="primary")
723
  with gr.Column():
@@ -732,11 +729,20 @@ def create_demo():
732
 
733
  generate_button.click(
734
  fn=generate_image,
735
- inputs=[prompt, width, height, guidance, inference_steps, seed, do_img2img, init_image, image2image_strength, resize_img],
 
 
 
 
736
  outputs=[output_image, output_seed]
737
  )
738
  return demo
739
 
740
  if __name__ == "__main__":
 
741
  demo = create_demo()
742
- demo.launch()
 
 
 
 
 
66
  # ---------------- NF4 ----------------
67
 
68
  def functional_linear_4bits(x, weight, bias):
69
+ import bitsandbytes as bnb
70
  out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
71
  out = out.to(x)
72
  return out
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  class ForgeParams4bit(Params4bit):
75
+ """Subclass to force re-quantization to GPU if needed."""
76
  def to(self, *args, **kwargs):
77
+ import torch
78
  device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
79
  if device is not None and device.type == "cuda" and not self.bnb_quantized:
80
  return self._quantize(device)
 
82
  n = ForgeParams4bit(
83
  torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
84
  requires_grad=self.requires_grad,
85
+ quant_state=self.quant_state,
86
  compress_statistics=False,
87
  blocksize=64,
88
  quant_type=self.quant_type,
 
95
  self.quant_state = n.quant_state
96
  return n
97
 
98
+ class ForgeLoader4Bit(nn.Module):
99
  def __init__(self, *, device, dtype, quant_type, **kwargs):
100
  super().__init__()
101
+ self.dummy = nn.Parameter(torch.empty(1, device=device, dtype=dtype))
102
  self.weight = None
103
  self.quant_state = None
104
  self.bias = None
 
106
 
107
  def _save_to_state_dict(self, destination, prefix, keep_vars):
108
  super()._save_to_state_dict(destination, prefix, keep_vars)
109
+ from bitsandbytes.nn.modules import QuantState
110
  quant_state = getattr(self.weight, "quant_state", None)
111
  if quant_state is not None:
112
  for k, v in quant_state.as_dict(packed=True).items():
113
  destination[prefix + "weight." + k] = v if keep_vars else v.detach()
114
  return
115
 
116
+ def _load_from_state_dict(
117
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
118
+ ):
119
+ from bitsandbytes.nn.modules import Params4bit
120
+ import torch
121
 
122
+ quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
123
  if any('bitsandbytes' in k for k in quant_state_keys):
124
  quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
 
125
  self.weight = ForgeParams4bit.from_prequantized(
126
  data=state_dict[prefix + 'weight'],
127
  quantized_stats=quant_state_dict,
 
133
 
134
  if prefix + 'bias' in state_dict:
135
  self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
 
136
  del self.dummy
137
  elif hasattr(self, 'dummy'):
138
  if prefix + 'weight' in state_dict:
 
159
 
160
  def forward(self, x):
161
  self.weight.quant_state = self.quant_state
 
162
  if self.bias is not None and self.bias.dtype != x.dtype:
163
  self.bias.data = self.bias.data.to(x.dtype)
 
164
  return functional_linear_4bits(x, self.weight, self.bias)
165
 
166
+ import torch.nn as nn
167
  nn.Linear = Linear
168
 
169
  # ---------------- Model ----------------
 
175
  return x
176
 
177
  def rope(pos, dim, theta):
178
+ import torch
179
  scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
180
  omega = 1.0 / (theta ** scale)
181
  out = pos.unsqueeze(-1) * omega.unsqueeze(0)
 
201
  self.axes_dim = axes_dim
202
 
203
  def forward(self, ids: Tensor) -> Tensor:
204
+ import torch
205
  n_axes = ids.shape[-1]
206
  emb = torch.cat(
207
  [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
 
210
  return emb.unsqueeze(1)
211
 
212
  def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
213
+ import torch, math
214
  t = time_factor * t
215
  half = dim // 2
216
  freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
 
238
  self.scale = nn.Parameter(torch.ones(dim))
239
 
240
  def forward(self, x: Tensor):
241
+ import torch
242
  x_dtype = x.dtype
243
  x = x.float()
244
  rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
 
274
  x = self.proj(x)
275
  return x
276
 
277
+ from dataclasses import dataclass
278
+
279
  @dataclass
280
  class ModulationOut:
281
  shift: Tensor
 
289
  self.multiplier = 6 if double else 3
290
  self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
291
 
292
+ def forward(self, vec: Tensor):
293
  out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
294
+ first = ModulationOut(*out[:3])
295
+ second = ModulationOut(*out[3:]) if self.is_double else None
296
+ return first, second
 
297
 
298
  class DoubleStreamBlock(nn.Module):
299
  def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
 
404
  x = self.linear(x)
405
  return x
406
 
407
+ from dataclasses import dataclass, field
408
+
409
  @dataclass
410
  class FluxParams:
411
  in_channels: int = 64
 
498
  return img
499
 
500
  def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
501
+ import torch
502
  bs, c, h, w = img.shape
503
  if bs == 1 and not isinstance(prompt, str):
504
  bs = len(prompt)
 
527
  }
528
 
529
  def time_shift(mu: float, sigma: float, t: Tensor):
530
+ import math
531
  return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
532
 
533
  def get_lin_function(
534
  x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
535
  ) -> Callable[[float], float]:
536
+ import math
537
  m = (y2 - y1) / (x2 - x1)
538
  b = y1 - m * x1
539
  return lambda x: m * x + b
 
545
  max_shift: float = 1.15,
546
  shift: bool = True,
547
  ) -> list[float]:
548
+ import torch
549
+ import math
550
  timesteps = torch.linspace(1, 0, num_steps + 1)
551
  if shift:
552
  mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
 
554
  return timesteps.tolist()
555
 
556
  def denoise(
557
+ model: Flux,
558
  img: Tensor,
559
  img_ids: Tensor,
560
  txt: Tensor,
 
563
  timesteps: list[float],
564
  guidance: float = 4.0,
565
  ):
566
+ import torch
567
  guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
568
  for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
569
  t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
 
608
  img: torch.Tensor = transform(image)
609
  return img[None, ...]
610
 
611
+ # Load the NF4 quantized checkpoint
612
  from huggingface_hub import hf_hub_download
613
  from safetensors.torch import load_file
614
 
 
626
  progress=gr.Progress(track_tqdm=True),
627
  ):
628
  if seed == 0:
629
+ seed = int(random.random() * 1_000_000)
630
+
631
  device = "cuda" if torch.cuda.is_available() else "cpu"
632
  torch_device = torch.device(device)
633
+
634
  global model, model_zero_init
635
  if not model_zero_init:
636
  model = model.to(torch_device)
637
  model_zero_init = True
638
+
639
  if do_img2img and init_image is not None:
640
  init_image = get_image(init_image)
641
  if resize_img:
 
659
  generator=generator
660
  )
661
 
662
+ timesteps = get_schedule(inference_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
 
663
 
664
  if do_img2img and init_image is not None:
665
+ t_idx = int((1 - image2image_strength) * inference_steps)
666
  t = timesteps[t_idx]
667
  timesteps = timesteps[t_idx:]
668
  x = t * x + (1.0 - t) * init_image.to(x.dtype)
 
670
  inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
671
  x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
672
  x = unpack(x.float(), height, width)
673
+
674
  with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
675
  x = (x / ae.config.scaling_factor) + ae.config.shift_factor
676
  x = ae.decode(x).sample
677
+
678
  x = x.clamp(-1, 1)
679
  x = rearrange(x[0], "c h w -> h w c")
680
  img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
 
707
  seed = gr.Number(label="Seed", precision=-1)
708
  do_img2img = gr.Checkbox(label="Image to Image", value=False)
709
  init_image = gr.Image(label="Initial Image", visible=False)
710
+ image2image_strength = gr.Slider(
711
+ minimum=0.0,
712
+ maximum=1.0,
713
+ step=0.01,
714
+ label="Noising Strength",
715
+ value=0.8,
716
+ visible=False
717
+ )
718
  resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
719
  generate_button = gr.Button("Generate", variant="primary")
720
  with gr.Column():
 
729
 
730
  generate_button.click(
731
  fn=generate_image,
732
+ inputs=[
733
+ prompt, width, height, guidance,
734
+ inference_steps, seed, do_img2img,
735
+ init_image, image2image_strength, resize_img
736
+ ],
737
  outputs=[output_image, output_seed]
738
  )
739
  return demo
740
 
741
  if __name__ == "__main__":
742
+ # Create the demo
743
  demo = create_demo()
744
+ # Enable the queue to handle concurrency
745
+ demo.queue()
746
+ # Launch with show_api=False and share=True to avoid the "bool is not iterable" error
747
+ # and the "ValueError: When localhost is not accessible..." error.
748
+ demo.launch(show_api=False, share=True, server_name="0.0.0.0")