
    bi!                         d dl mZ d dlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZmZmZ dd	lmZ  ej$                  e      Z G d
 d      Zy)    )nullcontext)Dict   )!SD3IPAdapterJointAttnProcessor2_0)IPAdapterTimeImageProjection)load_model_dict_into_meta)_LOW_CPU_MEM_USAGE_DEFAULT)is_accelerate_availableis_torch_versionlogging)empty_device_cachec                   X    e Zd ZdZefdededefdZefdededefdZ	efdededdfdZ
y)	SD3Transformer2DLoadersMixinzBLoad IP-Adapters and LoRA layers into a `[SD3Transformer2DModel]`.
state_dictlow_cpu_mem_usagereturnc                    |r(t               rddlm} nd}t        j	                  d       |du rt        dd      st        d      | j                  j                  | j                  j                  z  }| j                  j                  | j                  j                  z  }|d	   j                  d
   }t        t        | j                              D ci c]  }|i  }}|j                         D ],  \  }	}
|	j                  dd
      \  }}|
|t!        |         |<   . i }|rnt"        }t%        | j                  j'                               D ]  \  }} |       5  t)        ||| j                  j                  |      ||<   d d d        |s||   j+                  ||   d       Xd| j,                  i}t/        ||   ||   || j0                          t3                |S c c}w # 1 sw Y   exY w)Nr   init_empty_weightsF,  Cannot initialize model with low cpu memory usage because `accelerate` was not found in the environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install `accelerate` for faster and less memory-intense model loading. You can do so with: 
```
pip install accelerate
```
.T>=1.9.0~Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set `low_cpu_mem_usage=False`.z0.norm_ip.linear.weight   .)maxsplit)hidden_sizeip_hidden_states_dimhead_dimtimesteps_emb_dimstrict 
device_mapdtype)r
   
accelerater   loggerwarningr   NotImplementedErrorconfigattention_head_dimnum_attention_headsshaperangelenattn_processorsitemssplitintr   	enumeratekeysr   load_state_dictdevicer   r&   r   )selfr   r   r   r   r   r    idxlayer_state_dictkeyweightsname
attn_procsinit_contextr%   s                  \/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/loaders/transformer_sd3.py%_convert_ip_adapter_attn_to_diffuserszBSD3Transformer2DLoadersMixin._convert_ip_adapter_attn_to_diffusers   s    &(9 %*!2 $-=dG-L%.  kk44t{{7V7VV#{{==@_@__&'@AGGJ 05S9M9M5N/OPCGPP&,,. 	7LC		#	2IC/6SX&t,	7
 
->)K"4#7#7#<#<#>? 	IC #D +)=![[;;&7	$
4  %4 001A#1Ft0T $++.
)t$&6s&;
Z^ZdZd	" 	7 Q s   
G'G$$G-	c           	         |r(t               rddlm} nd}t        j	                  d       |du rt        dd      st        d      |rnt        }i }|j                         D ]  \  }}|j                  d	      r|j                  d
      d   }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|j                  d	| dd	| d      }|||<    |d   j                  d   }	|d   j                  d   }
|d   j                  d   }|d    j                  d   d!z  }|d"   j                  d   }|d#   j                  d   } |       5  t        |	|
||||$      }d d d        |sj                  |d%       |S d&| j                  i}t!        ||| j"                  '       t%                |S # 1 sw Y   SxY w)(Nr   r   Fr   Tr   r   r   zlayers.r   r   z.0.norm1z.ln0z.0.norm2z.ln1z.0.to_qz
.attn.to_qz.0.to_kvz.attn.to_kvz	.0.to_outz.attn.to_out.0z.1.0z.adaln_normz.1.1z.ff.net.0.projz.1.3z	.ff.net.2z.2.1z.adaln_projzproj_in.weightzproj_out.weightzlayers.0.attn.to_q.weight@   latentsztime_embedding.linear_1.weight)	embed_dim
output_dim
hidden_dimheadsnum_queriestimestep_in_dimr!   r#   r$   )r
   r'   r   r(   r)   r   r*   r   r2   
startswithr3   replacer.   r   r7   r8   r   r&   r   )r9   r   r   r   r@   updated_state_dictr<   valuer:   rF   rG   rH   rI   rJ   rK   
image_projr%   s                    rA   +_convert_ip_adapter_image_proj_to_diffuserszHSD3Transformer2DLoadersMixin._convert_ip_adapter_image_proj_to_diffusersY   s    &(9 %*!2 $-=dG-L%. 
 .?)K  $**, 	,JC~~i(iinQ'kkGC5"9WSE;NOkkGC5"9WSE;NOkkGC5"8GC5
:STkkGC5"9WSE;UVkkGC5	":gcU.<YZkkGC5"5[7QRkkGC5"5^7TUkkGC5"5Y7OPkkGC5"5[7QR&+s#	,  ''78>>qA	'(9:@@C
'(89??B
"#>?EEaHBN(399!<,-MNTTUVW ^ 	5#%%' /J	 !&&'9$&G 	 dkk*J%j2DQ[cgcmcmn #	 	s   6II#Nc                     | j                  |d   |      }| j                  |       | j                  |d   |      | _        y)aI  Sets IP-Adapter attention processors, image projection, and loads state_dict.

        Args:
            state_dict (`Dict`):
                State dict with keys "ip_adapter", which contains parameters for attention processors, and
                "image_proj", which contains parameters for image projection net.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
                Speed up model loading only loading the pretrained weights and not initializing the weights. This also
                tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
                Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
                argument to `True` will raise an error.
        
ip_adapterrP   N)rB   set_attn_processorrQ   rP   )r9   r   r   r?   s       rA   _load_ip_adapter_weightsz5SD3Transformer2DLoadersMixin._load_ip_adapter_weights   sE     ??
<@XZkl

+JJ:VbKcevw    )__name__
__module____qualname____doc__r	   r   boolrB   r   rQ   rU    rV   rA   r   r      sw    L ;U88378	8v ;UCC37C	%CJ Tn x4 xD xrv xrV   r   N)
contextlibr   typingr   models.attention_processorr   models.embeddingsr   models.model_loading_utilsr   models.modeling_utilsr	   utilsr
   r   r   utils.torch_utilsr   
get_loggerrW   r(   r   r\   rV   rA   <module>rf      sD    #  J < B > F F 2 
		H	%Sx SxrV   