2024-01-22 02:51:22 +00:00
|
|
|
from .utils import load_torch_file, transformers_convert, state_dict_prefix_replace
|
2023-04-02 03:19:15 +00:00
|
|
|
import os
|
2023-04-09 19:47:35 +00:00
|
|
|
import torch
|
2023-12-09 16:56:31 +00:00
|
|
|
import json
|
2024-03-10 15:37:08 +00:00
|
|
|
import logging
|
2023-08-28 19:26:29 +00:00
|
|
|
|
2023-06-15 00:13:08 +00:00
|
|
|
import comfy.ops
|
2023-08-28 19:26:29 +00:00
|
|
|
import comfy.model_patcher
|
|
|
|
import comfy.model_management
|
2023-10-26 05:53:01 +00:00
|
|
|
import comfy.utils
|
2023-12-09 16:56:31 +00:00
|
|
|
import comfy.clip_model
|
|
|
|
|
|
|
|
class Output:
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return getattr(self, key)
|
|
|
|
def __setitem__(self, key, item):
|
|
|
|
setattr(self, key, item)
|
2023-10-26 05:53:01 +00:00
|
|
|
|
2024-11-21 13:38:23 +00:00
|
|
|
def clip_preprocess(image, size=224, mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]):
|
|
|
|
mean = torch.tensor(mean, device=image.device, dtype=image.dtype)
|
|
|
|
std = torch.tensor(std, device=image.device, dtype=image.dtype)
|
2023-12-16 08:06:10 +00:00
|
|
|
image = image.movedim(-1, 1)
|
|
|
|
if not (image.shape[2] == size and image.shape[3] == size):
|
|
|
|
scale = (size / min(image.shape[2], image.shape[3]))
|
|
|
|
image = torch.nn.functional.interpolate(image, size=(round(scale * image.shape[2]), round(scale * image.shape[3])), mode="bicubic", antialias=True)
|
|
|
|
h = (image.shape[2] - size)//2
|
|
|
|
w = (image.shape[3] - size)//2
|
|
|
|
image = image[:,:,h:h+size,w:w+size]
|
2023-10-26 05:53:01 +00:00
|
|
|
image = torch.clip((255. * image), 0, 255).round() / 255.0
|
|
|
|
return (image - mean.view([3,1,1])) / std.view([3,1,1])
|
2023-04-02 03:19:15 +00:00
|
|
|
|
|
|
|
class ClipVisionModel():
|
|
|
|
def __init__(self, json_config):
|
2023-12-09 16:56:31 +00:00
|
|
|
with open(json_config) as f:
|
|
|
|
config = json.load(f)
|
|
|
|
|
2024-07-17 17:05:38 +00:00
|
|
|
self.image_size = config.get("image_size", 224)
|
2024-11-21 13:38:23 +00:00
|
|
|
self.image_mean = config.get("image_mean", [0.48145466, 0.4578275, 0.40821073])
|
|
|
|
self.image_std = config.get("image_std", [0.26862954, 0.26130258, 0.27577711])
|
2023-08-28 19:26:29 +00:00
|
|
|
self.load_device = comfy.model_management.text_encoder_device()
|
|
|
|
offload_device = comfy.model_management.text_encoder_offload_device()
|
2023-12-16 07:47:26 +00:00
|
|
|
self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
|
|
|
|
self.model = comfy.clip_model.CLIPVisionModelProjection(config, self.dtype, offload_device, comfy.ops.manual_cast)
|
2023-12-15 23:53:08 +00:00
|
|
|
self.model.eval()
|
2023-08-28 19:26:29 +00:00
|
|
|
|
|
|
|
self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
|
2024-01-18 00:37:19 +00:00
|
|
|
|
2023-04-02 03:19:15 +00:00
|
|
|
def load_sd(self, sd):
|
2023-06-19 01:21:17 +00:00
|
|
|
return self.model.load_state_dict(sd, strict=False)
|
2023-04-02 03:19:15 +00:00
|
|
|
|
2024-01-18 00:37:19 +00:00
|
|
|
def get_sd(self):
|
|
|
|
return self.model.state_dict()
|
|
|
|
|
2023-04-02 03:19:15 +00:00
|
|
|
def encode_image(self, image):
|
2023-08-28 19:26:29 +00:00
|
|
|
comfy.model_management.load_model_gpu(self.patcher)
|
2024-11-21 13:38:23 +00:00
|
|
|
pixel_values = clip_preprocess(image.to(self.load_device), size=self.image_size, mean=self.image_mean, std=self.image_std).float()
|
2023-12-16 07:47:26 +00:00
|
|
|
out = self.model(pixel_values=pixel_values, intermediate_output=-2)
|
2023-09-08 18:06:58 +00:00
|
|
|
|
2023-12-09 16:56:31 +00:00
|
|
|
outputs = Output()
|
|
|
|
outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
|
|
|
|
outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
|
|
|
|
outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
|
2023-04-02 03:19:15 +00:00
|
|
|
return outputs
|
|
|
|
|
2023-06-22 17:03:50 +00:00
|
|
|
def convert_to_transformers(sd, prefix):
|
2023-04-02 03:19:15 +00:00
|
|
|
sd_k = sd.keys()
|
2023-06-22 17:03:50 +00:00
|
|
|
if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
|
2023-04-02 03:19:15 +00:00
|
|
|
keys_to_replace = {
|
2023-06-22 17:03:50 +00:00
|
|
|
"{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
|
|
|
|
"{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
|
|
|
|
"{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
|
|
|
|
"{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
|
|
|
|
"{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
|
|
|
|
"{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
|
|
|
|
"{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
|
2023-04-02 03:19:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for x in keys_to_replace:
|
|
|
|
if x in sd_k:
|
|
|
|
sd[keys_to_replace[x]] = sd.pop(x)
|
|
|
|
|
2023-06-22 17:03:50 +00:00
|
|
|
if "{}proj".format(prefix) in sd_k:
|
|
|
|
sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
|
2023-04-02 03:19:15 +00:00
|
|
|
|
2023-08-18 15:13:29 +00:00
|
|
|
sd = transformers_convert(sd, prefix, "vision_model.", 48)
|
2024-01-18 00:37:19 +00:00
|
|
|
else:
|
|
|
|
replace_prefix = {prefix: ""}
|
|
|
|
sd = state_dict_prefix_replace(sd, replace_prefix)
|
2023-04-02 03:19:15 +00:00
|
|
|
return sd
|
|
|
|
|
2023-06-23 05:08:05 +00:00
|
|
|
def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
|
|
|
if convert_keys:
|
|
|
|
sd = convert_to_transformers(sd, prefix)
|
2023-08-18 15:13:29 +00:00
|
|
|
if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
|
|
|
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
|
|
|
|
elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
|
2023-04-02 03:19:15 +00:00
|
|
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
|
2023-10-18 23:48:36 +00:00
|
|
|
elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
|
2024-11-21 13:38:23 +00:00
|
|
|
if sd["vision_model.encoder.layers.0.layer_norm1.weight"].shape[0] == 1152:
|
|
|
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_384.json")
|
|
|
|
elif sd["vision_model.embeddings.position_embedding.weight"].shape[0] == 577:
|
2024-07-17 17:12:50 +00:00
|
|
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336.json")
|
|
|
|
else:
|
|
|
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
|
2023-10-18 23:48:36 +00:00
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2023-04-02 03:19:15 +00:00
|
|
|
clip = ClipVisionModel(json_config)
|
2023-06-19 01:21:17 +00:00
|
|
|
m, u = clip.load_sd(sd)
|
2023-08-18 15:13:29 +00:00
|
|
|
if len(m) > 0:
|
2024-03-10 15:37:08 +00:00
|
|
|
logging.warning("missing clip vision: {}".format(m))
|
2023-06-19 01:21:17 +00:00
|
|
|
u = set(u)
|
|
|
|
keys = list(sd.keys())
|
|
|
|
for k in keys:
|
|
|
|
if k not in u:
|
2024-10-05 17:22:39 +00:00
|
|
|
sd.pop(k)
|
2023-04-02 03:19:15 +00:00
|
|
|
return clip
|
|
|
|
|
|
|
|
def load(ckpt_path):
|
|
|
|
sd = load_torch_file(ckpt_path)
|
2023-08-18 15:13:29 +00:00
|
|
|
if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
|
|
|
|
return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
|
|
|
|
else:
|
|
|
|
return load_clipvision_from_sd(sd)
|