ginipick commited on
Commit
b679234
·
verified ·
1 Parent(s): b486d62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -766
app.py CHANGED
@@ -709,772 +709,6 @@ def create_demo():
709
  )
710
 
711
 
712
- with gr.Row():
713
- with gr.Column():
714
- prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")
715
- width = gr.Slider(minimum=128, maximum=2048, step=64, label="Width", value=640)
716
- height = gr.Slider(minimum=128, maximum=2048, step=64, label="Height", value=640)
717
- guidance = gr.Slider(minimum=1.0, maximum=5.0, step=0.1, label="Guidance", value=3.5)
718
- inference_steps = gr.Slider(
719
- label="Inference steps",
720
- minimum=1,
721
- maximum=30,
722
- step=1,
723
- value=16,
724
- )
725
- seed = gr.Number(label="Seed", precision=-1)
726
- do_img2img = gr.Checkbox(label="Image to Image", value=False)
727
- init_image = gr.Image(label="Initial Image", visible=False)
728
- image2image_strength = gr.Slider(
729
- minimum=0.0,
730
- maximum=1.0,
731
- step=0.01,
732
- label="Noising Strength",
733
- value=0.8,
734
- visible=False
735
- )
736
- resize_img = gr.Checkbox(label="Resize Initial Image", value=True, visible=False)
737
- generate_button = gr.Button("Generate", variant="primary")
738
- with gr.Column():
739
- output_image = gr.Image(label="Result")
740
- output_seed = gr.Text(label="Seed Used")
741
-
742
- do_img2img.change(
743
- fn=lambda x: [gr.update(visible=x), gr.update(visible=x), gr.update(visible=x)],
744
- inputs=[do_img2img],
745
- outputs=[init_image, image2image_strength, resize_img]
746
- )
747
-
748
- generate_button.click(
749
- fn=generate_image,
750
- inputs=[
751
- prompt, width, height, guidance,
752
- inference_steps, seed, do_img2img,
753
- init_image, image2image_strength, resize_img
754
- ],
755
- outputs=[output_image, output_seed]
756
- )
757
- return demo
758
-
759
- if __name__ == "__main__":
760
- # Create the demo
761
- demo = create_demo()
762
- # Enable the queue to handle concurrency
763
- demo.queue()
764
- # Launch with show_api=False and share=True to avoid the "bool is not iterable" error
765
- # and the "ValueError: When localhost is not accessible..." error.
766
- # Remove mcp_server=True as it's not a valid parameter
767
- demo.launch(show_api=False, share=True, server_name="0.0.0.0")import os
768
- # Comment out spaces import to avoid the error
769
- # import spaces
770
-
771
- import time
772
- import gradio as gr
773
- import torch
774
- from PIL import Image
775
- from torchvision import transforms
776
- from dataclasses import dataclass, field
777
- import math
778
- from typing import Callable
779
-
780
- from tqdm import tqdm
781
- import bitsandbytes as bnb
782
- from bitsandbytes.nn.modules import Params4bit, QuantState
783
-
784
- import torch
785
- import random
786
- from einops import rearrange, repeat
787
- from diffusers import AutoencoderKL
788
- from torch import Tensor, nn
789
- from transformers import CLIPTextModel, CLIPTokenizer
790
- from transformers import T5EncoderModel, T5Tokenizer
791
-
792
- # ---------------- Encoders ----------------
793
-
794
- class HFEmbedder(nn.Module):
795
- def __init__(self, version: str, max_length: int, **hf_kwargs):
796
- super().__init__()
797
- self.is_clip = version.startswith("openai")
798
- self.max_length = max_length
799
- self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
800
-
801
- if self.is_clip:
802
- self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(version, max_length=max_length)
803
- self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(version, **hf_kwargs)
804
- else:
805
- self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(version, max_length=max_length)
806
- self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(version, **hf_kwargs)
807
-
808
- self.hf_module = self.hf_module.eval().requires_grad_(False)
809
-
810
- def forward(self, text: list[str]) -> Tensor:
811
- batch_encoding = self.tokenizer(
812
- text,
813
- truncation=True,
814
- max_length=self.max_length,
815
- return_length=False,
816
- return_overflowing_tokens=False,
817
- padding="max_length",
818
- return_tensors="pt",
819
- )
820
-
821
- outputs = self.hf_module(
822
- input_ids=batch_encoding["input_ids"].to(self.hf_module.device),
823
- attention_mask=None,
824
- output_hidden_states=False,
825
- )
826
- return outputs[self.output_key]
827
-
828
- device = "cuda" if torch.cuda.is_available() else "cpu"
829
- t5 = HFEmbedder("DeepFloyd/t5-v1_1-xxl", max_length=512, torch_dtype=torch.bfloat16).to(device)
830
- clip = HFEmbedder("openai/clip-vit-large-patch14", max_length=77, torch_dtype=torch.bfloat16).to(device)
831
- ae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=torch.bfloat16).to(device)
832
-
833
- # ---------------- NF4 ----------------
834
-
835
- def functional_linear_4bits(x, weight, bias):
836
- import bitsandbytes as bnb
837
- out = bnb.matmul_4bit(x, weight.t(), bias=bias, quant_state=weight.quant_state)
838
- out = out.to(x)
839
- return out
840
-
841
- class ForgeParams4bit(Params4bit):
842
- """Subclass to force re-quantization to GPU if needed."""
843
- def to(self, *args, **kwargs):
844
- import torch
845
- device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
846
- if device is not None and device.type == "cuda" and not self.bnb_quantized:
847
- return self._quantize(device)
848
- else:
849
- n = ForgeParams4bit(
850
- torch.nn.Parameter.to(self, device=device, dtype=dtype, non_blocking=non_blocking),
851
- requires_grad=self.requires_grad,
852
- quant_state=self.quant_state,
853
- compress_statistics=False,
854
- blocksize=64,
855
- quant_type=self.quant_type,
856
- quant_storage=self.quant_storage,
857
- bnb_quantized=self.bnb_quantized,
858
- module=self.module
859
- )
860
- self.module.quant_state = n.quant_state
861
- self.data = n.data
862
- self.quant_state = n.quant_state
863
- return n
864
-
865
- class ForgeLoader4Bit(nn.Module):
866
- def __init__(self, *, device, dtype, quant_type, **kwargs):
867
- super().__init__()
868
- self.dummy = nn.Parameter(torch.empty(1, device=device, dtype=dtype))
869
- self.weight = None
870
- self.quant_state = None
871
- self.bias = None
872
- self.quant_type = quant_type
873
-
874
- def _save_to_state_dict(self, destination, prefix, keep_vars):
875
- super()._save_to_state_dict(destination, prefix, keep_vars)
876
- from bitsandbytes.nn.modules import QuantState
877
- quant_state = getattr(self.weight, "quant_state", None)
878
- if quant_state is not None:
879
- for k, v in quant_state.as_dict(packed=True).items():
880
- destination[prefix + "weight." + k] = v if keep_vars else v.detach()
881
- return
882
-
883
- def _load_from_state_dict(
884
- self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
885
- ):
886
- from bitsandbytes.nn.modules import Params4bit
887
- import torch
888
-
889
- quant_state_keys = {k[len(prefix + "weight."):] for k in state_dict.keys() if k.startswith(prefix + "weight.")}
890
- if any('bitsandbytes' in k for k in quant_state_keys):
891
- quant_state_dict = {k: state_dict[prefix + "weight." + k] for k in quant_state_keys}
892
- self.weight = ForgeParams4bit.from_prequantized(
893
- data=state_dict[prefix + 'weight'],
894
- quantized_stats=quant_state_dict,
895
- requires_grad=False,
896
- device=torch.device('cuda'),
897
- module=self
898
- )
899
- self.quant_state = self.weight.quant_state
900
-
901
- if prefix + 'bias' in state_dict:
902
- self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
903
- del self.dummy
904
- elif hasattr(self, 'dummy'):
905
- if prefix + 'weight' in state_dict:
906
- self.weight = ForgeParams4bit(
907
- state_dict[prefix + 'weight'].to(self.dummy),
908
- requires_grad=False,
909
- compress_statistics=True,
910
- quant_type=self.quant_type,
911
- quant_storage=torch.uint8,
912
- module=self,
913
- )
914
- self.quant_state = self.weight.quant_state
915
-
916
- if prefix + 'bias' in state_dict:
917
- self.bias = torch.nn.Parameter(state_dict[prefix + 'bias'].to(self.dummy))
918
-
919
- del self.dummy
920
- else:
921
- super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
922
-
923
- class Linear(ForgeLoader4Bit):
924
- def __init__(self, *args, device=None, dtype=None, **kwargs):
925
- super().__init__(device=device, dtype=dtype, quant_type='nf4')
926
-
927
- def forward(self, x):
928
- self.weight.quant_state = self.quant_state
929
- if self.bias is not None and self.bias.dtype != x.dtype:
930
- self.bias.data = self.bias.data.to(x.dtype)
931
- return functional_linear_4bits(x, self.weight, self.bias)
932
-
933
- import torch.nn as nn
934
- nn.Linear = Linear
935
-
936
- # ---------------- Model ----------------
937
-
938
- def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> Tensor:
939
- q, k = apply_rope(q, k, pe)
940
- x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
941
- x = x.permute(0, 2, 1, 3).reshape(x.size(0), x.size(2), -1)
942
- return x
943
-
944
- def rope(pos, dim, theta):
945
- import torch
946
- scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
947
- omega = 1.0 / (theta ** scale)
948
- out = pos.unsqueeze(-1) * omega.unsqueeze(0)
949
- cos_out = torch.cos(out)
950
- sin_out = torch.sin(out)
951
- out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
952
- b, n, d, _ = out.shape
953
- out = out.view(b, n, d, 2, 2)
954
- return out.float()
955
-
956
- def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
957
- xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
958
- xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
959
- xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
960
- xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
961
- return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
962
-
963
- class EmbedND(nn.Module):
964
- def __init__(self, dim: int, theta: int, axes_dim: list[int]):
965
- super().__init__()
966
- self.dim = dim
967
- self.theta = theta
968
- self.axes_dim = axes_dim
969
-
970
- def forward(self, ids: Tensor) -> Tensor:
971
- import torch
972
- n_axes = ids.shape[-1]
973
- emb = torch.cat(
974
- [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
975
- dim=-3,
976
- )
977
- return emb.unsqueeze(1)
978
-
979
- def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
980
- import torch, math
981
- t = time_factor * t
982
- half = dim // 2
983
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)
984
- args = t[:, None].float() * freqs[None]
985
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
986
- if dim % 2:
987
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
988
- if torch.is_floating_point(t):
989
- embedding = embedding.to(t)
990
- return embedding
991
-
992
- class MLPEmbedder(nn.Module):
993
- def __init__(self, in_dim: int, hidden_dim: int):
994
- super().__init__()
995
- self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
996
- self.silu = nn.SiLU()
997
- self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
998
-
999
- def forward(self, x: Tensor) -> Tensor:
1000
- return self.out_layer(self.silu(self.in_layer(x)))
1001
-
1002
- class RMSNorm(torch.nn.Module):
1003
- def __init__(self, dim: int):
1004
- super().__init__()
1005
- self.scale = nn.Parameter(torch.ones(dim))
1006
-
1007
- def forward(self, x: Tensor):
1008
- import torch
1009
- x_dtype = x.dtype
1010
- x = x.float()
1011
- rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
1012
- return (x * rrms).to(dtype=x_dtype) * self.scale
1013
-
1014
- class QKNorm(torch.nn.Module):
1015
- def __init__(self, dim: int):
1016
- super().__init__()
1017
- self.query_norm = RMSNorm(dim)
1018
- self.key_norm = RMSNorm(dim)
1019
-
1020
- def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
1021
- q = self.query_norm(q)
1022
- k = self.key_norm(k)
1023
- return q.to(v), k.to(v)
1024
-
1025
- class SelfAttention(nn.Module):
1026
- def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
1027
- super().__init__()
1028
- self.num_heads = num_heads
1029
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
1030
- head_dim = dim // num_heads
1031
- self.norm = QKNorm(head_dim)
1032
- self.proj = nn.Linear(dim, dim)
1033
-
1034
- def forward(self, x: Tensor, pe: Tensor) -> Tensor:
1035
- qkv = self.qkv(x)
1036
- B, L, _ = qkv.shape
1037
- qkv = qkv.view(B, L, 3, self.num_heads, -1)
1038
- q, k, v = qkv.permute(2, 0, 3, 1, 4)
1039
- q, k = self.norm(q, k, v)
1040
- x = attention(q, k, v, pe=pe)
1041
- x = self.proj(x)
1042
- return x
1043
-
1044
- from dataclasses import dataclass
1045
-
1046
- @dataclass
1047
- class ModulationOut:
1048
- shift: Tensor
1049
- scale: Tensor
1050
- gate: Tensor
1051
-
1052
- class Modulation(nn.Module):
1053
- def __init__(self, dim: int, double: bool):
1054
- super().__init__()
1055
- self.is_double = double
1056
- self.multiplier = 6 if double else 3
1057
- self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
1058
-
1059
- def forward(self, vec: Tensor):
1060
- out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
1061
- first = ModulationOut(*out[:3])
1062
- second = ModulationOut(*out[3:]) if self.is_double else None
1063
- return first, second
1064
-
1065
- class DoubleStreamBlock(nn.Module):
1066
- def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False):
1067
- super().__init__()
1068
- mlp_hidden_dim = int(hidden_size * mlp_ratio)
1069
- self.num_heads = num_heads
1070
- self.hidden_size = hidden_size
1071
- self.img_mod = Modulation(hidden_size, double=True)
1072
- self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1073
- self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
1074
- self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1075
- self.img_mlp = nn.Sequential(
1076
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
1077
- nn.GELU(approximate="tanh"),
1078
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
1079
- )
1080
- self.txt_mod = Modulation(hidden_size, double=True)
1081
- self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1082
- self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
1083
- self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1084
- self.txt_mlp = nn.Sequential(
1085
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
1086
- nn.GELU(approximate="tanh"),
1087
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
1088
- )
1089
-
1090
- def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
1091
- img_mod1, img_mod2 = self.img_mod(vec)
1092
- txt_mod1, txt_mod2 = self.txt_mod(vec)
1093
-
1094
- # Image attention
1095
- img_modulated = self.img_norm1(img)
1096
- img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift
1097
- img_qkv = self.img_attn.qkv(img_modulated)
1098
- B, L, _ = img_qkv.shape
1099
- H = self.num_heads
1100
- D = img_qkv.shape[-1] // (3 * H)
1101
- img_q, img_k, img_v = img_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
1102
- img_q, img_k = self.img_attn.norm(img_q, img_k, img_v)
1103
-
1104
- # Text attention
1105
- txt_modulated = self.txt_norm1(txt)
1106
- txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift
1107
- txt_qkv = self.txt_attn.qkv(txt_modulated)
1108
- B, L, _ = txt_qkv.shape
1109
- txt_q, txt_k, txt_v = txt_qkv.view(B, L, 3, H, D).permute(2, 0, 3, 1, 4)
1110
- txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v)
1111
-
1112
- # Combined attention
1113
- q = torch.cat((txt_q, img_q), dim=2)
1114
- k = torch.cat((txt_k, img_k), dim=2)
1115
- v = torch.cat((txt_v, img_v), dim=2)
1116
- attn = attention(q, k, v, pe=pe)
1117
- txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
1118
-
1119
- # Img final
1120
- img = img + img_mod1.gate * self.img_attn.proj(img_attn)
1121
- img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift)
1122
-
1123
- # Text final
1124
- txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn)
1125
- txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
1126
- return img, txt
1127
-
1128
- class SingleStreamBlock(nn.Module):
1129
- def __init__(
1130
- self,
1131
- hidden_size: int,
1132
- num_heads: int,
1133
- mlp_ratio: float = 4.0,
1134
- qk_scale: float | None = None,
1135
- ):
1136
- super().__init__()
1137
- self.hidden_dim = hidden_size
1138
- self.num_heads = num_heads
1139
- head_dim = hidden_size // num_heads
1140
- self.scale = qk_scale or head_dim**-0.5
1141
- self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
1142
- self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
1143
- self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
1144
- self.norm = QKNorm(head_dim)
1145
- self.hidden_size = hidden_size
1146
- self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1147
- self.mlp_act = nn.GELU(approximate="tanh")
1148
- self.modulation = Modulation(hidden_size, double=False)
1149
-
1150
- def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
1151
- mod, _ = self.modulation(vec)
1152
- x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift
1153
- qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
1154
- qkv = qkv.view(qkv.size(0), qkv.size(1), 3, self.num_heads, self.hidden_size // self.num_heads)
1155
- q, k, v = qkv.permute(2, 0, 3, 1, 4)
1156
- q, k = self.norm(q, k, v)
1157
- attn = attention(q, k, v, pe=pe)
1158
- output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
1159
- return x + mod.gate * output
1160
-
1161
- class LastLayer(nn.Module):
1162
- def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
1163
- super().__init__()
1164
- self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
1165
- self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
1166
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
1167
-
1168
- def forward(self, x: Tensor, vec: Tensor) -> Tensor:
1169
- shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
1170
- x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
1171
- x = self.linear(x)
1172
- return x
1173
-
1174
- from dataclasses import dataclass, field
1175
-
1176
- @dataclass
1177
- class FluxParams:
1178
- in_channels: int = 64
1179
- vec_in_dim: int = 768
1180
- context_in_dim: int = 4096
1181
- hidden_size: int = 3072
1182
- mlp_ratio: float = 4.0
1183
- num_heads: int = 24
1184
- depth: int = 19
1185
- depth_single_blocks: int = 38
1186
- axes_dim: list[int] = field(default_factory=lambda: [16, 56, 56])
1187
- theta: int = 10000
1188
- qkv_bias: bool = True
1189
- guidance_embed: bool = True
1190
-
1191
- class Flux(nn.Module):
1192
- def __init__(self, params = FluxParams()):
1193
- super().__init__()
1194
- self.params = params
1195
- self.in_channels = params.in_channels
1196
- self.out_channels = self.in_channels
1197
- if params.hidden_size % params.num_heads != 0:
1198
- raise ValueError(
1199
- f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
1200
- )
1201
- pe_dim = params.hidden_size // params.num_heads
1202
- if sum(params.axes_dim) != pe_dim:
1203
- raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
1204
- self.hidden_size = params.hidden_size
1205
- self.num_heads = params.num_heads
1206
- self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
1207
- self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
1208
- self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
1209
- self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
1210
- self.guidance_in = (
1211
- MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
1212
- )
1213
- self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
1214
-
1215
- self.double_blocks = nn.ModuleList(
1216
- [
1217
- DoubleStreamBlock(
1218
- self.hidden_size,
1219
- self.num_heads,
1220
- mlp_ratio=params.mlp_ratio,
1221
- qkv_bias=params.qkv_bias,
1222
- )
1223
- for _ in range(params.depth)
1224
- ]
1225
- )
1226
-
1227
- self.single_blocks = nn.ModuleList(
1228
- [
1229
- SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio)
1230
- for _ in range(params.depth_single_blocks)
1231
- ]
1232
- )
1233
-
1234
- self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)
1235
-
1236
- def forward(
1237
- self,
1238
- img: Tensor,
1239
- img_ids: Tensor,
1240
- txt: Tensor,
1241
- txt_ids: Tensor,
1242
- timesteps: Tensor,
1243
- y: Tensor,
1244
- guidance: Tensor | None = None,
1245
- ) -> Tensor:
1246
- if img.ndim != 3 or txt.ndim != 3:
1247
- raise ValueError("Input img and txt tensors must have 3 dimensions.")
1248
- img = self.img_in(img)
1249
- vec = self.time_in(timestep_embedding(timesteps, 256))
1250
- if self.params.guidance_embed:
1251
- if guidance is None:
1252
- raise ValueError("No guidance strength provided for guidance-distilled model.")
1253
- vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
1254
- vec = vec + self.vector_in(y)
1255
- txt = self.txt_in(txt)
1256
- ids = torch.cat((txt_ids, img_ids), dim=1)
1257
- pe = self.pe_embedder(ids)
1258
- for block in self.double_blocks:
1259
- img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
1260
- img = torch.cat((txt, img), 1)
1261
- for block in self.single_blocks:
1262
- img = block(img, vec=vec, pe=pe)
1263
- img = img[:, txt.shape[1] :, ...]
1264
- img = self.final_layer(img, vec)
1265
- return img
1266
-
1267
- def prepare(t5: HFEmbedder, clip: HFEmbedder, img: Tensor, prompt: str | list[str]) -> dict[str, Tensor]:
1268
- import torch
1269
- bs, c, h, w = img.shape
1270
- if bs == 1 and not isinstance(prompt, str):
1271
- bs = len(prompt)
1272
- img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
1273
- if img.shape[0] == 1 and bs > 1:
1274
- img = repeat(img, "1 ... -> bs ...", bs=bs)
1275
- img_ids = torch.zeros(h // 2, w // 2, 3)
1276
- img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]
1277
- img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]
1278
- img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
1279
- if isinstance(prompt, str):
1280
- prompt = [prompt]
1281
- txt = t5(prompt)
1282
- if txt.shape[0] == 1 and bs > 1:
1283
- txt = repeat(txt, "1 ... -> bs ...", bs=bs)
1284
- txt_ids = torch.zeros(bs, txt.shape[1], 3)
1285
- vec = clip(prompt)
1286
- if vec.shape[0] == 1 and bs > 1:
1287
- vec = repeat(vec, "1 ... -> bs ...", bs=bs)
1288
- return {
1289
- "img": img,
1290
- "img_ids": img_ids.to(img.device),
1291
- "txt": txt.to(img.device),
1292
- "txt_ids": txt_ids.to(img.device),
1293
- "vec": vec.to(img.device),
1294
- }
1295
-
1296
- def time_shift(mu: float, sigma: float, t: Tensor):
1297
- import math
1298
- return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
1299
-
1300
- def get_lin_function(
1301
- x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15
1302
- ) -> Callable[[float], float]:
1303
- import math
1304
- m = (y2 - y1) / (x2 - x1)
1305
- b = y1 - m * x1
1306
- return lambda x: m * x + b
1307
-
1308
- def get_schedule(
1309
- num_steps: int,
1310
- image_seq_len: int,
1311
- base_shift: float = 0.5,
1312
- max_shift: float = 1.15,
1313
- shift: bool = True,
1314
- ) -> list[float]:
1315
- import torch
1316
- import math
1317
- timesteps = torch.linspace(1, 0, num_steps + 1)
1318
- if shift:
1319
- mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
1320
- timesteps = time_shift(mu, 1.0, timesteps)
1321
- return timesteps.tolist()
1322
-
1323
- def denoise(
1324
- model: Flux,
1325
- img: Tensor,
1326
- img_ids: Tensor,
1327
- txt: Tensor,
1328
- txt_ids: Tensor,
1329
- vec: Tensor,
1330
- timesteps: list[float],
1331
- guidance: float = 4.0,
1332
- ):
1333
- import torch
1334
- guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
1335
- for t_curr, t_prev in tqdm(zip(timesteps[:-1], timesteps[1:]), total=len(timesteps) - 1):
1336
- t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
1337
- pred = model(
1338
- img=img,
1339
- img_ids=img_ids,
1340
- txt=txt,
1341
- txt_ids=txt_ids,
1342
- y=vec,
1343
- timesteps=t_vec,
1344
- guidance=guidance_vec,
1345
- )
1346
- img = img + (t_prev - t_curr) * pred
1347
- return img
1348
-
1349
- def unpack(x: Tensor, height: int, width: int) -> Tensor:
1350
- return rearrange(
1351
- x,
1352
- "b (h w) (c ph pw) -> b c (h ph) (w pw)",
1353
- h=math.ceil(height / 16),
1354
- w=math.ceil(width / 16),
1355
- ph=2,
1356
- pw=2,
1357
- )
1358
-
1359
- @dataclass
1360
- class SamplingOptions:
1361
- prompt: str
1362
- width: int
1363
- height: int
1364
- guidance: float
1365
- seed: int | None
1366
-
1367
- def get_image(image) -> torch.Tensor | None:
1368
- if image is None:
1369
- return None
1370
- image = Image.fromarray(image).convert("RGB")
1371
- transform = transforms.Compose([
1372
- transforms.ToTensor(),
1373
- transforms.Lambda(lambda x: 2.0 * x - 1.0),
1374
- ])
1375
- img: torch.Tensor = transform(image)
1376
- return img[None, ...]
1377
-
1378
- # Load the NF4 quantized checkpoint
1379
- from huggingface_hub import hf_hub_download
1380
- from safetensors.torch import load_file
1381
-
1382
- sd = load_file(hf_hub_download(repo_id="lllyasviel/flux1-dev-bnb-nf4", filename="flux1-dev-bnb-nf4-v2.safetensors"))
1383
- sd = {k.replace("model.diffusion_model.", ""): v for k, v in sd.items() if "model.diffusion_model" in k}
1384
- model = Flux().to(dtype=torch.bfloat16, device=device)
1385
- result = model.load_state_dict(sd)
1386
- model_zero_init = False
1387
-
1388
- # Remove @spaces.GPU decorator - we'll handle GPU allocation manually
1389
- # @spaces.GPU
1390
- @torch.no_grad()
1391
- def generate_image(
1392
- prompt, width, height, guidance, inference_steps, seed,
1393
- do_img2img, init_image, image2image_strength, resize_img,
1394
- progress=gr.Progress(track_tqdm=True),
1395
- ):
1396
- if seed == 0:
1397
- seed = int(random.random() * 1_000_000)
1398
-
1399
- device = "cuda" if torch.cuda.is_available() else "cpu"
1400
- torch_device = torch.device(device)
1401
-
1402
- global model, model_zero_init
1403
- if not model_zero_init:
1404
- model = model.to(torch_device)
1405
- model_zero_init = True
1406
-
1407
- if do_img2img and init_image is not None:
1408
- init_image = get_image(init_image)
1409
- if resize_img:
1410
- init_image = torch.nn.functional.interpolate(init_image, (height, width))
1411
- else:
1412
- h, w = init_image.shape[-2:]
1413
- init_image = init_image[..., : 16 * (h // 16), : 16 * (w // 16)]
1414
- height = init_image.shape[-2]
1415
- width = init_image.shape[-1]
1416
- init_image = ae.encode(init_image.to(torch_device).to(torch.bfloat16)).latent_dist.sample()
1417
- init_image = (init_image - ae.config.shift_factor) * ae.config.scaling_factor
1418
-
1419
- generator = torch.Generator(device=device).manual_seed(seed)
1420
- x = torch.randn(
1421
- 1,
1422
- 16,
1423
- 2 * math.ceil(height / 16),
1424
- 2 * math.ceil(width / 16),
1425
- device=device,
1426
- dtype=torch.bfloat16,
1427
- generator=generator
1428
- )
1429
-
1430
- timesteps = get_schedule(inference_steps, (x.shape[-1] * x.shape[-2]) // 4, shift=True)
1431
-
1432
- if do_img2img and init_image is not None:
1433
- t_idx = int((1 - image2image_strength) * inference_steps)
1434
- t = timesteps[t_idx]
1435
- timesteps = timesteps[t_idx:]
1436
- x = t * x + (1.0 - t) * init_image.to(x.dtype)
1437
-
1438
- inp = prepare(t5=t5, clip=clip, img=x, prompt=prompt)
1439
- x = denoise(model, **inp, timesteps=timesteps, guidance=guidance)
1440
- x = unpack(x.float(), height, width)
1441
-
1442
- with torch.autocast(device_type=torch_device.type, dtype=torch.bfloat16):
1443
- x = (x / ae.config.scaling_factor) + ae.config.shift_factor
1444
- x = ae.decode(x).sample
1445
-
1446
- x = x.clamp(-1, 1)
1447
- x = rearrange(x[0], "c h w -> h w c")
1448
- img = Image.fromarray((127.5 * (x + 1.0)).cpu().byte().numpy())
1449
- return img, seed
1450
-
1451
- def create_demo():
1452
- with gr.Blocks(css=".gradio-container {background-color: #282828 !important;}") as demo:
1453
- gr.HTML(
1454
- """
1455
- <div style="text-align: center; margin: 0 auto;">
1456
- <h1 style="color: #ffffff; font-weight: 900;">
1457
- FluxLLama
1458
- </h1>
1459
- </div>
1460
- """
1461
- )
1462
-
1463
- gr.HTML(
1464
- """
1465
- <div class='container' style='display:flex; justify-content:center; gap:12px;'>
1466
- <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank">
1467
- <img src="https://img.shields.io/static/v1?label=OpenFree&message=BEST%20AI%20Services&color=%230000ff&labelColor=%23000080&logo=huggingface&logoColor=%23ffa500&style=for-the-badge" alt="OpenFree badge">
1468
- </a>
1469
-
1470
- <a href="https://discord.gg/openfreeai" target="_blank">
1471
- <img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="Discord badge">
1472
- </a>
1473
- </div>
1474
- """
1475
- )
1476
-
1477
-
1478
  with gr.Row():
1479
  with gr.Column():
1480
  prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")
 
709
  )
710
 
711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712
  with gr.Row():
713
  with gr.Column():
714
  prompt = gr.Textbox(label="Prompt", value="A majestic castle on top of a floating island")