Team Ai
Apppublic

hugging-apps/echo-memory

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
sd_ipadapter.py58 linesDownload Raw Back to models
1from .svd_image_encoder import SVDImageEncoder2from .sdxl_ipadapter import IpAdapterImageProjModel, IpAdapterModule, SDXLIpAdapterStateDictConverter3from transformers import CLIPImageProcessor4import torch5 6 7class IpAdapterCLIPImageEmbedder(SVDImageEncoder):8    def __init__(self):9        super().__init__()10        self.image_processor = CLIPImageProcessor()11 12    def forward(self, image):13        pixel_values = self.image_processor(images=image, return_tensors="pt").pixel_values14        pixel_values = pixel_values.to(device=self.embeddings.class_embedding.device, dtype=self.embeddings.class_embedding.dtype)15        return super().forward(pixel_values)16 17 18class SDIpAdapter(torch.nn.Module):19    def __init__(self):20        super().__init__()21        shape_list = [(768, 320)] * 2 + [(768, 640)] * 2 + [(768, 1280)] * 5 + [(768, 640)] * 3  + [(768, 320)] * 3 + [(768, 1280)] * 122        self.ipadapter_modules = torch.nn.ModuleList([IpAdapterModule(*shape) for shape in shape_list])23        self.image_proj = IpAdapterImageProjModel(cross_attention_dim=768, clip_embeddings_dim=1024, clip_extra_context_tokens=4)24        self.set_full_adapter()25 26    def set_full_adapter(self):27        block_ids = [1, 4, 9, 12, 17, 20, 40, 43, 46, 50, 53, 56, 60, 63, 66, 29]28        self.call_block_id = {(i, 0): j for j, i in enumerate(block_ids)}29 30    def set_less_adapter(self):31        # IP-Adapter for SD v1.5 doesn't support this feature.32        self.set_full_adapter()33 34    def forward(self, hidden_states, scale=1.0):35        hidden_states = self.image_proj(hidden_states)36        hidden_states = hidden_states.view(1, -1, hidden_states.shape[-1])37        ip_kv_dict = {}38        for (block_id, transformer_id) in self.call_block_id:39            ipadapter_id = self.call_block_id[(block_id, transformer_id)]40            ip_k, ip_v = self.ipadapter_modules[ipadapter_id](hidden_states)41            if block_id not in ip_kv_dict:42                ip_kv_dict[block_id] = {}43            ip_kv_dict[block_id][transformer_id] = {44                "ip_k": ip_k,45                "ip_v": ip_v,46                "scale": scale47            }48        return ip_kv_dict49 50    @staticmethod51    def state_dict_converter():52        return SDIpAdapterStateDictConverter()53 54 55class SDIpAdapterStateDictConverter(SDXLIpAdapterStateDictConverter):56    def __init__(self):57        pass58