Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from other_impls import SD3Tokenizer, SDClipModel, SDXLClipG, T5XXLModel
|
| 2 |
+
from safetensors import safe_open
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def load_into(ckpt, model, prefix, device, dtype=None, remap=None):
|
| 7 |
+
"""Just a debugging-friendly hack to apply the weights in a safetensors file to the pytorch module."""
|
| 8 |
+
for key in ckpt.keys():
|
| 9 |
+
model_key = key
|
| 10 |
+
if remap is not None and key in remap:
|
| 11 |
+
model_key = remap[key]
|
| 12 |
+
if model_key.startswith(prefix) and not model_key.startswith("loss."):
|
| 13 |
+
path = model_key[len(prefix) :].split(".")
|
| 14 |
+
obj = model
|
| 15 |
+
for p in path:
|
| 16 |
+
if obj is list:
|
| 17 |
+
obj = obj[int(p)]
|
| 18 |
+
else:
|
| 19 |
+
obj = getattr(obj, p, None)
|
| 20 |
+
if obj is None:
|
| 21 |
+
print(
|
| 22 |
+
f"Skipping key '{model_key}' in safetensors file as '{p}' does not exist in python model"
|
| 23 |
+
)
|
| 24 |
+
break
|
| 25 |
+
if obj is None:
|
| 26 |
+
continue
|
| 27 |
+
try:
|
| 28 |
+
tensor = ckpt.get_tensor(key).to(device=device)
|
| 29 |
+
if dtype is not None and tensor.dtype != torch.int32:
|
| 30 |
+
tensor = tensor.to(dtype=dtype)
|
| 31 |
+
obj.requires_grad_(False)
|
| 32 |
+
# print(f"K: {model_key}, O: {obj.shape} T: {tensor.shape}")
|
| 33 |
+
if obj.shape != tensor.shape:
|
| 34 |
+
print(
|
| 35 |
+
f"W: shape mismatch for key {model_key}, {obj.shape} != {tensor.shape}"
|
| 36 |
+
)
|
| 37 |
+
obj.set_(tensor)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"Failed to load key '{key}' in safetensors file: {e}")
|
| 40 |
+
raise e
|
| 41 |
+
|
| 42 |
+
CLIPG_CONFIG = {
|
| 43 |
+
"hidden_act": "gelu",
|
| 44 |
+
"hidden_size": 1280,
|
| 45 |
+
"intermediate_size": 5120,
|
| 46 |
+
"num_attention_heads": 20,
|
| 47 |
+
"num_hidden_layers": 32,
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ClipG:
|
| 52 |
+
def __init__(self, model_folder: str, device: str = "cpu"):
|
| 53 |
+
safetensors_path = hf_hub_download(
|
| 54 |
+
repo_id=model_folder,
|
| 55 |
+
filename="clip_g.safetensors",
|
| 56 |
+
cache_dir=None
|
| 57 |
+
)
|
| 58 |
+
with safe_open(
|
| 59 |
+
# f"{model_folder}/clip_g.safetensors", framework="pt", device="cpu"
|
| 60 |
+
safetensors_path, framework="pt", device="cpu"
|
| 61 |
+
) as f:
|
| 62 |
+
self.model = SDXLClipG(CLIPG_CONFIG, device=device, dtype=torch.float32)
|
| 63 |
+
load_into(f, self.model.transformer, "", device, torch.float32)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
CLIPL_CONFIG = {
|
| 67 |
+
"hidden_act": "quick_gelu",
|
| 68 |
+
"hidden_size": 768,
|
| 69 |
+
"intermediate_size": 3072,
|
| 70 |
+
"num_attention_heads": 12,
|
| 71 |
+
"num_hidden_layers": 12,
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ClipL:
|
| 76 |
+
def __init__(self, model_folder: str):
|
| 77 |
+
safetensors_path = hf_hub_download(
|
| 78 |
+
repo_id=model_folder,
|
| 79 |
+
filename="clip_l.safetensors",
|
| 80 |
+
cache_dir=None
|
| 81 |
+
)
|
| 82 |
+
with safe_open(
|
| 83 |
+
# f"{model_folder}/clip_l.safetensors", framework="pt", device="cpu"
|
| 84 |
+
safetensors_path, framework="pt", device="cpu"
|
| 85 |
+
) as f:
|
| 86 |
+
self.model = SDClipModel(
|
| 87 |
+
layer="hidden",
|
| 88 |
+
layer_idx=-2,
|
| 89 |
+
device="cpu",
|
| 90 |
+
dtype=torch.float32,
|
| 91 |
+
layer_norm_hidden_state=False,
|
| 92 |
+
return_projected_pooled=False,
|
| 93 |
+
textmodel_json_config=CLIPL_CONFIG,
|
| 94 |
+
)
|
| 95 |
+
load_into(f, self.model.transformer, "", "cpu", torch.float32)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
T5_CONFIG = {
|
| 99 |
+
"d_ff": 10240,
|
| 100 |
+
"d_model": 4096,
|
| 101 |
+
"num_heads": 64,
|
| 102 |
+
"num_layers": 24,
|
| 103 |
+
"vocab_size": 32128,
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class T5XXL:
|
| 108 |
+
def __init__(self, model_folder: str, device: str = "cpu", dtype=torch.float32):
|
| 109 |
+
safetensors_path = hf_hub_download(
|
| 110 |
+
repo_id=model_folder,
|
| 111 |
+
filename="t5xxl.safetensors",
|
| 112 |
+
cache_dir=None
|
| 113 |
+
)
|
| 114 |
+
with safe_open(
|
| 115 |
+
# f"{model_folder}/t5xxl.safetensors", framework="pt", device="cpu"
|
| 116 |
+
safetensors_path, framework="pt", device="cpu"
|
| 117 |
+
) as f:
|
| 118 |
+
self.model = T5XXLModel(T5_CONFIG, device=device, dtype=dtype)
|
| 119 |
+
load_into(f, self.model.transformer, "", device, dtype)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
tokenizer = SD3Tokenizer()
|
| 123 |
+
text_encoder_device = "cpu"
|
| 124 |
+
model_folder = "stabilityai/stable-diffusion-3.5-medium"
|
| 125 |
+
print("Loading Google T5-v1-XXL...")
|
| 126 |
+
t5xxl = T5XXL(model_folder, text_encoder_device, torch.float32)
|
| 127 |
+
print("Loading OpenAI CLIP L...")
|
| 128 |
+
clip_l = ClipL(model_folder)
|
| 129 |
+
print("Loading OpenCLIP bigG...")
|
| 130 |
+
clip_g = ClipG(model_folder, text_encoder_device)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def get_cond(self, prompt):
|
| 134 |
+
print("Encode prompt...")
|
| 135 |
+
tokens = tokenizer.tokenize_with_weights(prompt)
|
| 136 |
+
l_out, l_pooled = clip_l.model.encode_token_weights(tokens["l"])
|
| 137 |
+
g_out, g_pooled = clip_g.model.encode_token_weights(tokens["g"])
|
| 138 |
+
t5_out, t5_pooled = t5xxl.model.encode_token_weights(tokens["t5xxl"])
|
| 139 |
+
lg_out = torch.cat([l_out, g_out], dim=-1)
|
| 140 |
+
lg_out = torch.nn.functional.pad(lg_out, (0, 4096 - lg_out.shape[-1]))
|
| 141 |
+
return torch.cat([lg_out, t5_out], dim=-2), torch.cat(
|
| 142 |
+
(l_pooled, g_pooled), dim=-1
|
| 143 |
+
)
|