Ë
    (täiòt ã                   óÂ  — d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
 d dlmZmZ d dlmZ d dlmZ d dlmZmZmZmZ d dlZd dlZd dlZd dlmZmZmZ d dlmZ d d	lmZm Z  d d
l!m"Z" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZA ddlBmCZC ddlDmEZEmFZFmGZG ddlHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZP  G d„ d«      ZQ e;j¤                  eS«      ZT ejª                  d«      ZVe j®                  j°                  e j®                  j²                  e j®                  j´                  e j®                  j¶                  e j®                  j¸                  e j®                  jº                  e j®                  j¼                  e j®                  j¾                  e j®                  jÀ                  e j®                  jÂ                  e j®                  jÄ                  e j®                  jÆ                  e j®                  jÈ                  e j®                  jÊ                  dœZf e:dd«      rdZgndZg e6«       rd dlhZhd dlhmiZi d dljmkZkmlZl d ej@                  jÚ                  d!ejÜ                  fd"„Zod ej@                  jÚ                  d!ejà                  fd#„Zqed$„ «       Zr G d%„ d&ej@                  jÚ                  e?«      Zs G d'„ d(es«      Zty))é    N)ÚOrderedDict)Ú	ExitStackÚcontextmanager)Úwraps)ÚPath)ÚAnyÚCallableÚContextManagerÚType)Ú	DDUFEntryÚcreate_repoÚ"split_torch_state_dict_into_shards)Úvalidate_hf_hub_args)ÚTensorÚnn)ÚSelfé   )Ú__version__)ÚDiffusersAutoQuantizerÚDiffusersQuantizer)ÚQuantizationMethod)ÚCONFIG_NAMEÚFLAX_WEIGHTS_NAMEÚHF_ENABLE_PARALLEL_LOADINGÚSAFE_WEIGHTS_INDEX_NAMEÚSAFETENSORS_WEIGHTS_NAMEÚWEIGHTS_INDEX_NAMEÚWEIGHTS_NAMEÚ_add_variantÚ_get_checkpoint_shard_filesÚ_get_model_fileÚ	deprecateÚis_accelerate_availableÚis_bitsandbytes_availableÚis_bitsandbytes_versionÚis_peft_availableÚis_torch_versionÚlogging)Úis_torch_dist_rank_zero)ÚPushToHubMixinÚload_or_create_model_cardÚpopulate_model_card)Úempty_device_cacheé   )ÚContextParallelConfigÚContextParallelModelPlanÚParallelConfig)Ú_caching_allocator_warmupÚ_determine_device_mapÚ_expand_device_mapÚ_fetch_index_fileÚ_fetch_index_file_legacyÚ_load_shard_fileÚ!_load_shard_files_with_threadpoolÚload_state_dictc                   ó.   — e Zd ZdZdee   fd„Zd„ Zd„ Zy)ÚContextManagerszš
    Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers`
    in the `fastcore` library.
    Úcontext_managersc                 ó0   — || _         t        «       | _        y ©N)r<   r   Ústack)Úselfr<   s     ún/Volumes/fast/ai/experiments/MLX_z-image/.venv/lib/python3.12/site-packages/diffusers/models/modeling_utils.pyÚ__init__zContextManagers.__init__T   s   € Ø 0ˆÔÜ“[ˆ�
ó    c                 ó\   — | j                   D ]  }| j                  j                  |«       Œ y r>   )r<   r?   Úenter_context)r@   Úcontext_managers     rA   Ú	__enter__zContextManagers.__enter__X   s$   € Ø#×4Ô4ˆOØ�J‰J×$Ñ$ _Õ5ñ  5rC   c                 ó<   —  | j                   j                  |i |¤Ž y r>   )r?   Ú__exit__)r@   ÚargsÚkwargss      rA   rI   zContextManagers.__exit__\   s   € Øˆ�
‰
×Ñ˜TÐ, VÓ,rC   N)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úlistr
   rB   rG   rI   © rC   rA   r;   r;   N   s"   „ ñð
!¨¨nÑ)=ó !ò6ó-rC   r;   z(.*?)-\d{5}-of-\d{5})Úuniform_Únormal_Útrunc_normal_Ú	constant_Úxavier_uniform_Úxavier_normal_Úkaiming_uniform_Úkaiming_normal_ÚuniformÚnormalÚxavier_uniformÚxavier_normalÚkaiming_uniformÚkaiming_normalú>=ú1.9.0TF)Údispatch_model)Úload_offloaded_weightsÚsave_offload_indexÚ	parameterÚreturnc                 ó´  — ddl m} 	  || «      S # t        $ r Y nw xY w	 t        j                  | j                  «       | j                  «       «      }t        |«      j                  S # t        $ rg dt        j                  j                  dt        t        t        t         f      fd„}| j#                  |¬«      }t        |«      }|d   j                  cY S w xY w)Nr   )Ú_get_group_onload_deviceÚmodulerf   c                 óš   — | j                   j                  «       D ��cg c]  \  }}t        j                  |«      sŒ||f‘Œ! }}}|S c c}}w r>   ©Ú__dict__ÚitemsÚtorchÚ	is_tensor©ri   ÚkÚvÚtupless       rA   Úfind_tensor_attributesz4get_parameter_device.<locals>.find_tensor_attributes’   sD   € Ø)/¯©×)>Ñ)>Ô)@ÔWÑ)@¡  AÄEÇOÁOÐTUÕDV�q˜!’fÐ)@ˆFÑWØˆMùó Xó
   žA¼A©Úget_members_fnr.   )Úhooks.group_offloadingrh   Ú
ValueErrorÚ	itertoolsÚchainÚ
parametersÚbuffersÚnextÚdeviceÚStopIterationrn   r   ÚModulerP   ÚtupleÚstrr   Ú_named_members)re   rh   Úparameters_and_buffersrt   ÚgenÚfirst_tuples         rA   Úget_parameter_devicerˆ   �   sÊ   € ÝAðá'¨	Ó2Ð2øÜò Ùðúð%ô "+§¡°×1EÑ1EÓ1GÈ×IZÑIZÓI\Ó!]ÐÜÐ*Ó+×2Ñ2Ð2øÜò 	%ð	¬5¯8©8¯?©?ð 	¼tÄEÌ#ÌvÈ+ÑDVÑ?Wó 	ð ×&Ñ&Ð6LÐ&ÓMˆÜ˜3“iˆØ˜1‰~×$Ñ$Ò$ð	%ús   ˆ �	› AA' Á'A-CÃCc                 óR  ‡— t        | t        j                  «      rR| j                  «       D ]?  \  Š}t	        |d«      sŒ|j
                  }|j                  d«      }|€Œ3|j                  c S  d}| j                  «       D ]f  \  Š}|j                  }t	        | d«      r+| j                  rt        ˆfd„| j                  D «       «      rŒI|j                  «       sŒZ|j                  c S  | j                  «       D ],  }|j                  }|j                  «       sŒ |j                  c S  |�|S dt        j                  dt        t        t         f      fd„}| j#                  |¬	«      }	d}
|	D ](  }|}
|d
   j                  «       sŒ|d
   j                  c S  |
�|
d
   j                  S y)zz
    Returns the first found floating dtype in parameters if there is one, otherwise returns the last dtype it found.
    Ú_diffusers_hookÚlayerwise_castingNÚ_keep_in_fp32_modulesc              3   ó&   •K  — | ]  }|‰v –— Œ
 y ­wr>   rQ   )Ú.0ÚmÚnames     €rA   Ú	<genexpr>z&get_parameter_dtype.<locals>.<genexpr>±   s   øè ø€ ÐGÑ'F !�A˜”IÑ'Fùs   ƒri   rf   c                 óš   — | j                   j                  «       D ��cg c]  \  }}t        j                  |«      sŒ||f‘Œ! }}}|S c c}}w r>   rk   rp   s       rA   rt   z3get_parameter_dtype.<locals>.find_tensor_attributesÂ   sD   € Ø%+§_¡_×%:Ñ%:Ô%<ÔSÑ%<™T˜Q ÄÇÁÐPQÕ@R�1�a’&Ð%<ˆÑSØˆùó Tru   rv   r.   )Ú
isinstancer   r�   Únamed_modulesÚhasattrrŠ   Úget_hookÚcompute_dtypeÚnamed_parametersÚdtyperŒ   ÚanyÚis_floating_pointr}   rP   rƒ   r   r„   )re   Ú	submoduleÚregistryÚhookÚ
last_dtypeÚparamÚbufferr‚   rt   r†   Ú
last_tupler�   s              @rA   Úget_parameter_dtyper£   ›   sš  ø€ ô
 �)œRŸY™YÔ'Ø(×6Ñ6Ö8‰OˆD�)Ü˜9Ð&7Ô8ØØ ×0Ñ0ˆHØ×$Ñ$Ð%8Ó9ˆDØÑØ×)Ñ)Ò)ð  9ð €Jà ×1Ñ1Ö3‰ˆˆeØ—[‘[ˆ
ä�IÐ6Ô7Ø×/Ò/ÜÓG y×'FÒ'FÓGÔGàà×"Ñ"Õ$Ø—;‘;Òð 4ð ×#Ñ#Ö%ˆØ—\‘\ˆ
Ø×#Ñ#Õ%Ø—<‘<Òð &ð
 ÐàÐð¤r§y¡yð ´T¸%ÄÄVÀÑ:LÑ5Mó ð ×
"Ñ
"Ð2HÐ
"Ó
I€CØ€JÛˆØˆ
Ø�‰8×%Ñ%Õ'Ø˜‘8—>‘>Ò!ð ð
 Ðà˜!‰}×"Ñ"Ð"ð rC   c               #   ó¬  K  — d„ } t         j                  «       D ]*  \  }}t        t        j                  j
                  || «       Œ, 	 d–— t         j                  «       D ]*  \  }}t        t        j                  j
                  ||«       Œ, y# t         j                  «       D ]*  \  }}t        t        j                  j
                  ||«       Œ, w xY w­w)z°
    Context manager to globally disable weight initialization to speed up loading large models. To do that, all the
    torch.nn.init function are all replaced with skip.
    c                   ó   — y r>   rQ   )rJ   rK   s     rA   Ú
_skip_initz#no_init_weights.<locals>._skip_initÙ   s   € ØrC   N)ÚTORCH_INIT_FUNCTIONSrm   Úsetattrrn   r   Úinit)r¦   r�   Ú	init_funcs      rA   Úno_init_weightsr«   Ò   s™   è ø€ òô 0×5Ñ5Ö7‰ˆˆiÜ”—‘—‘˜t ZÕ0ð 8ð4Ûô  4×9Ñ9Ö;‰OˆD�)Ü”E—H‘H—M‘M 4¨Õ3ñ  <øÔ3×9Ñ9Ö;‰OˆD�)Ü”E—H‘H—M‘M 4¨Õ3ñ  <üs    ‚ACÁB ÁACÂACÃCc            "       óÞ  ‡ — e Zd ZdZeZg d¢ZdZdZdZ	dZ
dZdZg ZdZdZdZˆ fd„Zdedefˆ fd	„Zedefd
„«       Zdadedz  ddfd„Zdbd„Zdeddfd„Zdbd„Zdbd„Z	 dadededz  ddfd„Zdadedz  fd„Zd„ Z dadededz  ddfd„Z!dadedz  ddfd„Z"dbd„Z#e$jJ                  ddddfde$jL                  de$jL                  dz  de'edf   dz  de'e(e$jR                  jT                     df   dz  d eddfd!„Z+ e$jX                  d"«      d#ddddddddf
d$e$jX                  d%e$jX                  d&ed'e-dz  d ed(ed)ed*edz  d+edz  d,edz  ddfd-„Z.d.eddfd/„Z/dbd0„Z0	 	 	 	 	 	 dcd1ee1jd                  z  d2ed3edz  d4ed5edz  d6e-ez  d7efd8„Z3d9„ Z4e5e6d:ee1jd                  z  dz  de7fd;„«       «       Z8 e9e$jR                  jT                  jt                  «      ˆ fd<„«       Z: e9e$jR                  jT                  jv                  «      ˆ fd=„«       Z;ˆ fd>„Z<ˆ fd?„Z=d@„ Z>ddAœdBe?e@z  dCeAeeBf   dz  fdD„ZCe5	 	 	 	 	 	 	 	 	 	 	 	 dddEeDdFeEe   d:ee1jd                  z  dGeEe   dHedIedJeFdz  dKedLee$jL                  z  dz  dMeEe   dz  dNee-z  e$jX                  z  eAeee-z  e$jX                  z  f   z  dOedz  dPee1jd                  z  dz  dQeAeeGf   dz  dRedz  dSef dT„«       ZHe5dU„ «       ZIdNefdV„ZJe5dLe$jL                  de$jL                  fdW„«       ZKede$jX                  fdX„«       Z,ede$jL                  fdY„«       Z&dedZed[ede-fd\„ZLdfd]„ZMde$jœ                  jž                  jž                  fd^ededdfd_„ZPdEeDddfd`„ZQˆ xZRS )gÚ
ModelMixina$  
    Base class for all models.

    [`ModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
    saving models.

        - **config_name** ([`str`]) -- Filename to save a model to when calling [`~models.ModelMixin.save_pretrained`].
    )Ú_diffusers_versionÚ_class_nameÚ_name_or_pathFNTc                 ó0   •— t         ‰| �  «        d | _        y r>   )ÚsuperrB   Ú_gradient_checkpointing_func)r@   Ú	__class__s    €rA   rB   zModelMixin.__init__ý   s   ø€ Ü‰ÑÔà,0ˆÕ)rC   r�   rf   c                 óF  •— d| j                   v xr t        | j                   d   |«      }|| j                   v }|rY|sWd|› dt        | «      j                  › d|› dt        | «      j                  › d|› d�}t	        dd	|d
d¬«       | j
                  |   S t        ‰| �  |«      S )a~  The only reason we overwrite `getattr` here is to gracefully deprecate accessing
        config attributes directly. See https://github.com/huggingface/diffusers/pull/3129 We need to overwrite
        __getattr__ here in addition so that we don't trigger `torch.nn.Module`'s __getattr__':
        https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
        Ú_internal_dictzAccessing config attribute `z` directly via 'z1' object attribute is deprecated. Please access 'z' over 'z,'s config object instead, e.g. 'unet.config.z'.zdirect config name accessz1.0.0Fé   )Ústandard_warnÚ
stacklevel)rl   r•   ÚtyperL   r"   r¶   r²   Ú__getattr__)r@   r�   Úis_in_configÚis_attributeÚdeprecation_messager´   s        €rA   r»   zModelMixin.__getattr__  sû   ø€ ð (¨4¯=©=Ð8Òk¼WÀTÇ]Á]ÐScÑEdÐfjÓ=kˆØ˜tŸ}™}Ð,ˆá¡Ø$@ÀÀÐFVÔW[Ð\`ÓWa×WjÑWjÐVkð  l]ð  ^bð  ]cð  ckô  lpð  quó  lv÷  lñ  lð  k@ð  @lð  mqð  lrð  rtð  #uÐÜÐ1°7Ð<OÐ_dÐqrÕsØ×&Ñ& tÑ,Ð,ô ‰wÑ" 4Ó(Ð(rC   c                 óB   — t        d„ | j                  «       D «       «      S )zT
        Whether gradient checkpointing is activated for this model or not.
        c              3   óP   K  — | ]  }t        |d «      xr |j                  –— Œ  y­w)Úgradient_checkpointingN)r•   rÁ   )rŽ   r�   s     rA   r‘   z7ModelMixin.is_gradient_checkpointing.<locals>.<genexpr>  s*   è ø€ ÐmÑ^lÐYZ”7˜1Ð6Ó7ÒT¸A×<TÑ<TÓTÑ^lùó   ‚$&)rš   Úmodules©r@   s    rA   Úis_gradient_checkpointingz$ModelMixin.is_gradient_checkpointing  s   € ô
 ÑmÐ^b×^jÑ^jÔ^lÓmÓmÐmrC   Úgradient_checkpointing_funcc                 ó”   — | j                   s"t        | j                  j                  › d�«      ‚|€d„ }|}| j	                  d|¬«       y)aº  
        Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
        *checkpoint activations* in other frameworks).

        Args:
            gradient_checkpointing_func (`Callable`, *optional*):
                The function to use for gradient checkpointing. If `None`, the default PyTorch checkpointing function
                is used (`torch.utils.checkpoint.checkpoint`).
        z� does not support gradient checkpointing. Please make sure to set the boolean attribute `_supports_gradient_checkpointing` to `True` in the class definition.Nc                 ó”   — t        dd«      rddini }t        j                  j                  j                  | j                  g|¢­i |¤ŽS )Nr`   z1.11.0Úuse_reentrantF)r'   rn   ÚutilsÚ
checkpointÚ__call__)ri   rJ   Úckpt_kwargss      rA   r³   zNModelMixin.enable_gradient_checkpointing.<locals>._gradient_checkpointing_func-  sO   € Ü:JÈ4ÐQYÔ:Z˜°Ñ6Ð`b�Ü—{‘{×-Ñ-×8Ñ8Ø—O‘Oðàòð "ñð rC   T)ÚenablerÆ   )Ú _supports_gradient_checkpointingry   r´   rL   Ú_set_gradient_checkpointing)r@   rÆ   r³   s      rA   Úenable_gradient_checkpointingz(ModelMixin.enable_gradient_checkpointing  s`   € ð ×4Ò4ÜØ—>‘>×*Ñ*Ð+ð ,Xð Yóð ð
 'Ð.òð +GÐ'à×(Ñ(°ÐRmÐ(ÕnrC   c                 óB   — | j                   r| j                  d¬«       yy)z¶
        Deactivates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
        *checkpoint activations* in other frameworks).
        F)rÎ   N)rÏ   rÐ   rÄ   s    rA   Údisable_gradient_checkpointingz)ModelMixin.disable_gradient_checkpointing9  s#   € ð
 ×0Ò0Ø×,Ñ,°EÐ,Õ:ð 1rC   Úvalidc                 óÎ   ‡‡— dt         j                  j                  fˆˆfd„Š| j                  «       D ]/  }t	        |t         j                  j                  «      sŒ( ‰|«       Œ1 y)z=
        Set the switch for the npu flash attention.
        ri   c                 óz   •— t        | d«      r| j                  ‰«       | j                  «       D ]
  } ‰|«       Œ y )NÚset_use_npu_flash_attention)r•   r×   Úchildren)ri   ÚchildÚ$fn_recursive_set_npu_flash_attentionrÔ   s     €€rA   rÚ   zTModelMixin.set_use_npu_flash_attention.<locals>.fn_recursive_set_npu_flash_attentionF  s5   ø€ Ü�vÐ<Ô=Ø×2Ñ2°5Ô9àŸ™Ö*�Ù4°UÕ;ñ +rC   N©rn   r   r�   rØ   r“   )r@   rÔ   ri   rÚ   s    ` @rA   r×   z&ModelMixin.set_use_npu_flash_attentionA  sC   ù€ ð
	<¼¿¹¿¹ö 	<ð —m‘m–oˆFÜ˜&¤%§(¡(§/¡/Õ2Ù4°VÕ<ñ &rC   c                 ó&   — | j                  d«       y)z<
        Enable npu flash attention from torch_npu

        TN©r×   rÄ   s    rA   Úenable_npu_flash_attentionz%ModelMixin.enable_npu_flash_attentionQ  s   € ð
 	×(Ñ(¨Õ.rC   c                 ó&   — | j                  d«       y)z=
        disable npu flash attention from torch_npu

        FNrÝ   rÄ   s    rA   Údisable_npu_flash_attentionz&ModelMixin.disable_npu_flash_attentionX  s   € ð
 	×(Ñ(¨Õ/rC   Úuse_xla_flash_attentionÚpartition_specc                 óÖ   ‡‡‡‡— dt         j                  j                  fˆˆˆˆfd„Š| j                  «       D ]/  }t	        |t         j                  j                  «      sŒ( ‰|«       Œ1 y )Nri   c                 ó€   •— t        | d«      r | j                  ‰‰fi ‰¤Ž | j                  «       D ]
  } ‰|«       Œ y )NÚset_use_xla_flash_attention)r•   rå   rØ   )ri   rÙ   Ú fn_recursive_set_flash_attentionrK   râ   rá   s     €€€€rA   ræ   zPModelMixin.set_use_xla_flash_attention.<locals>.fn_recursive_set_flash_attentione  s@   ø€ Ü�vÐ<Ô=Ø2�×2Ñ2Ð3JÈNÑeÐ^dÒeàŸ™Ö*�Ù0°Õ7ñ +rC   rÛ   )r@   rá   râ   rK   ri   ræ   s    ``` @rA   rå   z&ModelMixin.set_use_xla_flash_attention_  sH   û€ ð	8´U·X±X·_±_÷ 	8ð 	8ð —m‘m–oˆFÜ˜&¤%§(¡(§/¡/Õ2Ù0°Õ8ñ &rC   c                 ó,   —  | j                   d|fi |¤Ž y)zJ
        Enable the flash attention pallals kernel for torch_xla.
        TN©rå   )r@   râ   rK   s      rA   Úenable_xla_flash_attentionz%ModelMixin.enable_xla_flash_attentionp  s   € ð 	)ˆ×(Ñ(¨¨~ÑHÀÓHrC   c                 ó&   — | j                  d«       y)zK
        Disable the flash attention pallals kernel for torch_xla.
        FNrè   rÄ   s    rA   Údisable_xla_flash_attentionz&ModelMixin.disable_xla_flash_attentionv  s   € ð 	×(Ñ(¨Õ/rC   Úattention_opc                 óÒ   ‡‡‡— dt         j                  j                  fˆˆˆfd„Š| j                  «       D ]/  }t	        |t         j                  j                  «      sŒ( ‰|«       Œ1 y )Nri   c                 ó|   •— t        | d«      r| j                  ‰‰«       | j                  «       D ]
  } ‰|«       Œ y )NÚ+set_use_memory_efficient_attention_xformers)r•   rï   rØ   )ri   rÙ   rì   Úfn_recursive_set_mem_effrÔ   s     €€€rA   rð   zXModelMixin.set_use_memory_efficient_attention_xformers.<locals>.fn_recursive_set_mem_eff€  s7   ø€ Ü�vÐLÔMØ×BÑBÀ5È,ÔWàŸ™Ö*�Ù(¨Õ/ñ +rC   rÛ   )r@   rÔ   rì   ri   rð   s    `` @rA   rï   z6ModelMixin.set_use_memory_efficient_attention_xformers|  sC   ú€ ð	0¬U¯X©X¯_©_÷ 	0ð —m‘m–oˆFÜ˜&¤%§(¡(§/¡/Õ2Ù(¨Õ0ñ &rC   c                 ó(   — | j                  d|«       y)u(  
        Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).

        When this option is enabled, you should observe lower GPU memory usage and a potential speed up during
        inference. Speed up during training is not guaranteed.

        > [!WARNING] > âš ï¸� When memory efficient attention and sliced attention are both enabled, memory efficient
        attention takes > precedent.

        Parameters:
            attention_op (`Callable`, *optional*):
                Override the default `None` operator for use as `op` argument to the
                [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
                function of xFormers.

        Examples:

        ```py
        >>> import torch
        >>> from diffusers import UNet2DConditionModel
        >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

        >>> model = UNet2DConditionModel.from_pretrained(
        ...     "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16
        ... )
        >>> model = model.to("cuda")
        >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
        ```
        TN©rï   )r@   rì   s     rA   Ú*enable_xformers_memory_efficient_attentionz5ModelMixin.enable_xformers_memory_efficient_attention‹  s   € ð< 	×8Ñ8¸¸|ÕLrC   c                 ó&   — | j                  d«       y)zs
        Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
        FNrò   rÄ   s    rA   Ú+disable_xformers_memory_efficient_attentionz6ModelMixin.disable_xformers_memory_efficient_attention«  s   € ð 	×8Ñ8¸Õ?rC   Ústorage_dtyper—   Úskip_modules_pattern.Úskip_modules_classesÚnon_blockingc                 óÄ  — ddl m} d}|€
ddlm} |}d}| j                  �|t        | j                  «      z  }| j                  �|t        | j                  «      z  }t        t        |«      «      }t        «       r6|s4ddl	m
}	 dd	lm}
 dd
lm} |	|
|fD ]  }|t        |j                  «      z  }Œ |€!t         j#                  d«       | j$                  } || |||||«       y)aÁ	  
        Activates layerwise casting for the current model.

        Layerwise casting is a technique that casts the model weights to a lower precision dtype for storage but
        upcasts them on-the-fly to a higher precision dtype for computation. This process can significantly reduce the
        memory footprint from model weights, but may lead to some quality degradation in the outputs. Most degradations
        are negligible, mostly stemming from weight casting in normalization and modulation layers.

        By default, most models in diffusers set the `_skip_layerwise_casting_patterns` attribute to ignore patch
        embedding, positional embedding and normalization layers. This is because these layers are most likely
        precision-critical for quality. If you wish to change this behavior, you can set the
        `_skip_layerwise_casting_patterns` attribute to `None`, or call
        [`~hooks.layerwise_casting.apply_layerwise_casting`] with custom arguments.

        Example:
            Using [`~models.ModelMixin.enable_layerwise_casting`]:

            ```python
            >>> from diffusers import CogVideoXTransformer3DModel

            >>> transformer = CogVideoXTransformer3DModel.from_pretrained(
            ...     "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
            ... )

            >>> # Enable layerwise casting via the model, which ignores certain modules by default
            >>> transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
            ```

        Args:
            storage_dtype (`torch.dtype`):
                The dtype to which the model should be cast for storage.
            compute_dtype (`torch.dtype`):
                The dtype to which the model weights should be cast during the forward pass.
            skip_modules_pattern (`tuple[str, ...]`, *optional*):
                A list of patterns to match the names of the modules to skip during the layerwise casting process. If
                set to `None`, default skip patterns are used to ignore certain internal layers of modules and PEFT
                layers.
            skip_modules_classes (`tuple[Type[torch.nn.Module], ...]`, *optional*):
                A list of module classes to skip during the layerwise casting process.
            non_blocking (`bool`, *optional*, defaults to `False`):
                If `True`, the weight casting operations are non-blocking.
        r   )Úapply_layerwise_castingTN)ÚDEFAULT_SKIP_MODULES_PATTERNFr   )Ú	LoHaLayer)Ú	LoKrLayer)Ú	LoraLayerzW`compute_dtype` not provided when enabling layerwise casting. Using dtype of the model.)Úhooksrû   Úhooks.layerwise_castingrü   rŒ   r‚   Ú _skip_layerwise_casting_patternsÚsetr&   Úpeft.tuners.loha.layerrý   Úpeft.tuners.lokr.layerrþ   Úpeft.tuners.lora.layerrÿ   Úadapter_layer_namesÚloggerÚinfor™   )r@   rö   r—   r÷   rø   rù   rû   Úuser_provided_patternsrü   rý   rþ   rÿ   Úlayers                rA   Úenable_layerwise_castingz#ModelMixin.enable_layerwise_casting±  sé   € õd 	4à!%ÐØÐ'ÝNà#?Ð Ø%*Ð"Ø×%Ñ%Ð1Ø ¤E¨$×*DÑ*DÓ$EÑEÐ Ø×0Ñ0Ð<Ø ¤E¨$×*OÑ*OÓ$PÑPÐ Ü$¤SÐ)=Ó%>Ó?ÐäÔÑ'=õ 9Ý8Ý8à# Y°	Ó:�Ø$¬¨e×.GÑ.GÓ(HÑHÑ$ð ;ð Ð Ü�K‰KÐqÔrØ ŸJ™JˆMáØ�- Ð0DÐFZÐ\hõ	
rC   ÚcpuÚblock_levelÚonload_deviceÚoffload_deviceÚoffload_typeÚnum_blocks_per_groupÚ
use_streamÚrecord_streamÚoffload_to_disk_pathÚblock_modulesÚexclude_kwargsc                 óú   — ddl m} t        | dd«      �&t        | dd«      r|rd}t        j	                  |«       | j
                  s"t        | j                  j                  › d�«      ‚ || |||||||||	|
|¬	«       y)
aÙ  
        Activates group offloading for the current model.

        See [`~hooks.group_offloading.apply_group_offloading`] for more information.

        Example:

            ```python
            >>> from diffusers import CogVideoXTransformer3DModel

            >>> transformer = CogVideoXTransformer3DModel.from_pretrained(
            ...     "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
            ... )

            >>> transformer.enable_group_offload(
            ...     onload_device=torch.device("cuda"),
            ...     offload_device=torch.device("cpu"),
            ...     offload_type="leaf_level",
            ...     use_stream=True,
            ... )
            ```
        r   )Úapply_group_offloadingÚenable_tilingNÚ
use_tilingFa/  Applying group offloading on autoencoders, with CUDA streams, may not work as expected if the first forward pass is executed with tiling enabled. Please make sure to either:
1. Run a forward pass with small input shapes.
2. Or, run a forward pass with tiling disabled (can still use small dummy inputs).zü does not support group offloading. Please make sure to set the boolean attribute `_supports_group_offloading` to `True` in the class definition. If you believe this is a mistake, please open an issue at https://github.com/huggingface/diffusers/issues.)ri   r  r  r  r  rù   r  r  Úlow_cpu_mem_usager  r  r  )	r   r  Úgetattrr  ÚwarningÚ_supports_group_offloadingry   r´   rL   )r@   r  r  r  r  rù   r  r  r  r  r  r  r  Úmsgs                 rA   Úenable_group_offloadzModelMixin.enable_group_offload  sŸ   € õH 	3ä�4˜¨$Ó/Ð;ÄÈÈlÐ\aÔ@bÑgqðeð ô �N‰N˜3ÔØ×.Ò.ÜØ—>‘>×*Ñ*Ð+ð ,Tð Uóð ñ 	ØØ'Ø)Ø%Ø!5Ø%Ø!Ø'Ø/Ø!5Ø'Ø)ö	
rC   Úbackendc                 ó&  — ddl m} ddlm}m}m}m} ddlm}m	} t        j                  d«       |||f}	d}
| j                  «       D ],  }t        ||	«      sŒ|j                  }t        |dd«      €Œ*d	}
 n |j!                  «       }|j"                  j%                  «       D �ch c]  }|j&                  ’Œ }}||vr!t)        d
|›d�dj+                  |«      z   «      ‚ ||«      }|
rB|j-                  |«      s1t/        |j0                  «      }t)        d|j&                  › d|› d�«      ‚ ||«        ||«       | j                  «       D ]1  }t        ||	«      sŒ|j                  }|�t3        |d«      sŒ+||_        Œ3 |j7                  |«       yc c}w )a©  
        Set the attention backend for the model.

        Args:
            backend (`str`):
                The name of the backend to set. Must be one of the available backends defined in
                `AttentionBackendName`. Available backends can be found in
                `diffusers.attention_dispatch.AttentionBackendName`. Defaults to torch native scaled dot product
                attention as backend.
        r.   ©ÚAttentionModuleMixin)ÚAttentionBackendNameÚ_AttentionBackendRegistryÚ%_check_attention_backend_requirementsÚ"_maybe_download_kernel_for_backend©Ú	AttentionÚMochiAttentionúTAttention backends are an experimental feature and the API may be subject to change.FÚ_parallel_configNTz	`backend=z ` must be one of the following: ú, z>Context parallelism is enabled but current attention backend 'zS' does not support context parallelism. Please set a compatible attention backend: z' using `model.set_attention_backend()`.Ú_attention_backend)Ú	attentionr%  Úattention_dispatchr&  r'  r(  r)  Úattention_processorr+  r,  r  r  rÃ   r“   Ú	processorr  ÚlowerÚ__members__ÚvaluesÚvaluery   ÚjoinÚ_is_context_parallel_availableÚsortedÚ_supports_context_parallelr•   r0  Úset_active_backend)r@   r"  r%  r&  r'  r(  r)  r+  r,  Úattention_classesÚparallel_config_setri   r4  ÚxÚavailable_backendsÚcompatible_backendss                   rA   Úset_attention_backendz ModelMixin.set_attention_backendJ  s©  € õ 	4÷	
ó 	
÷ 	Cä�‰ÐmÔnØ&¨Ð8LÐMÐà#ÐØ—l‘l–nˆFÜ˜fÐ&7Ô8ØØ×(Ñ(ˆIÜ�yÐ"4°dÓ;ÑGØ&*Ð#Ùð %ð —-‘-“/ˆØ/C×/OÑ/O×/VÑ/VÔ/XÓYÑ/X¨!˜aŸg›gÐ/XÐÐYØÐ,Ñ,Ü˜z  
Ð*JÐKÈdÏiÉiÐXjÓNkÑkÓlÐlá& wÓ/ˆÙÐ'@×'_Ñ'_Ð`gÔ'hÜ"(Ð)B×)]Ñ)]Ó"^ÐÜØPÐQX×Q^ÑQ^ÐP_ð `>à>QÐ=RÐRyð{óð ñ 	.¨gÔ6Ù*¨7Ô3à—l‘l–nˆFÜ˜fÐ&7Ô8ØØ×(Ñ(ˆIØÐ ¬°	Ð;OÔ(PØØ+2ˆIÕ(ð %ð 	"×4Ñ4°WÕ=ùò3 Zs   Â"Fc                 óÜ   — ddl m} ddlm}m} t
        j                  d«       |||f}| j                  «       D ]1  }t        ||«      sŒ|j                  }|�t        |d«      sŒ+d|_        Œ3 y)z¾
        Resets the attention backend for the model. Following calls to `forward` will use the environment default, if
        set, or the torch native scaled dot product attention.
        r.   r$  r*  r-  Nr0  )r1  r%  r3  r+  r,  r  r  rÃ   r“   r4  r•   r0  )r@   r%  r+  r,  r>  ri   r4  s          rA   Úreset_attention_backendz"ModelMixin.reset_attention_backendˆ  si   € õ
 	4ßBä�‰ÐmÔnà&¨Ð8LÐMÐØ—l‘l–nˆFÜ˜fÐ&7Ô8ØØ×(Ñ(ˆIØÐ ¬°	Ð;OÔ(PØØ+/ˆIÕ(ñ %rC   Úsave_directoryÚis_main_processÚsave_functionÚsafe_serializationÚvariantÚmax_shard_sizeÚpush_to_hubc           	      ó¶	  — t         j                  j                  |«      rt        j	                  d|› d�«       yt        | dd«      }	|	�I|	duxr t        |	t        «      xr |	j                  }
|
s#t        d|	j                  j                  › d�«      ‚|rt        nt        }t        ||«      }|j                  dd«      j                  d	d
«      }t        j                   |d¬«       |r�|j#                  dd«      }|j#                  dd«      }|j#                  dd«      }|j#                  dd«      }|j#                  d|j%                  t         j                  j&                  «      d   «      }t)        |d||¬«      j*                  }| }|r|j-                  |«       |j/                  «       }t1        |||¬«      }|�r
t        j2                  |«      D ]ò  }||j4                  j7                  «       v rŒ t         j                  j9                  ||«      }t         j                  j                  |«      sŒ`|j                  dd«      j                  d	d«      }|j                  dd«      }|j                  dd«      j                  d	d«      }|j;                  |«      sŒÈt<        j?                  |«      €ŒÞt        j@                  |«       Œô |j4                  jC                  «       D ]ƒ  \  }}|D �ci c]  }|||   jE                  «       “Œ }}t         j                  j9                  ||«      }|r%tF        jH                  jK                  ||ddi¬«       ŒntI        jL                  ||«       Œ… |jN                  rÇ|jP                  |jR                  dœ}|rtT        ntV        }t         j                  j9                  |t        ||«      «      }tY        |dd¬«      5 }t[        j\                  |dd¬ «      d!z   } |j_                  | «       ddd«       t        ja                  d"|› d#tc        |j4                  «      › d$|› d%�«       n8t         j                  j9                  ||«      }!t        ja                  d&|!› �«       |rXte        ¬'«      }"tg        |"«      }"|"jM                  ti        |d(«      jk                  «       «       | jm                  |||¬)«       yyc c}w # 1 sw Y   ŒÔxY w)*aø	  
        Save a model and its configuration file to a directory so that it can be reloaded using the
        [`~models.ModelMixin.from_pretrained`] class method.

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to save a model and its configuration file to. Will be created if it doesn't exist.
            is_main_process (`bool`, *optional*, defaults to `True`):
                Whether the process calling this is the main process or not. Useful during distributed training and you
                need to call this function on all processes. In this case, set `is_main_process=True` only on the main
                process to avoid race conditions.
            save_function (`Callable`):
                The function to use to save the state dictionary. Useful during distributed training when you need to
                replace `torch.save` with another method. Can be configured with the environment variable
                `DIFFUSERS_SAVE_MODE`.
            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
            variant (`str`, *optional*):
                If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
            max_shard_size (`int` or `str`, defaults to `"10GB"`):
                The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
                lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5GB"`).
                If expressed as an integer, the unit is bytes. Note that this limit will be decreased after a certain
                period of time (starting from Oct 2024) to allow users to upgrade to the latest version of `diffusers`.
                This is to establish a common default size for this argument across different libraries in the Hugging
                Face ecosystem (`transformers`, and `accelerate`, for example).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs (`dict[str, Any]`, *optional*):
                Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        zProvided path (z#) should be a directory, not a fileNÚhf_quantizerzThe model is quantized with z˜ and is not serializable - check out the warnings from the logger on the traceback to understand the reason why the quantized model is not serializable.z.binz{suffix}.binz.safetensorsz{suffix}.safetensorsT©Úexist_okÚcommit_messageÚprivateÚ	create_prFÚtokenÚrepo_idéÿÿÿÿ)rP  rR  rT  )rK  Úfilename_patternÚ z{suffix}ÚformatÚpt)Úmetadata)r[  Ú
weight_mapÚwzutf-8)Úencodingr   )ÚindentÚ	sort_keysÚ
z:The model is bigger than the maximum size per checkpoint (z) and is going to be split in z^ checkpoint shards. You can find where each parameters has been saved in the index located at Ú.zModel weights saved in )rT  z	README.md)rT  rQ  rS  )7ÚosÚpathÚisfiler  Úerrorr  r“   r   Úis_serializablery   Úquantization_configÚquant_methodr   r   r   ÚreplaceÚmakedirsÚpopÚsplitÚsepr   rU  Úsave_configÚ
state_dictr   ÚlistdirÚfilename_to_tensorsÚkeysr9  Ú
startswithÚ_REGEX_SHARDÚ	fullmatchÚremoverm   Ú
contiguousÚsafetensorsrn   Ú	save_fileÚsaveÚ
is_shardedr[  Útensor_to_filenamer   r   ÚopenÚjsonÚdumpsÚwriter	  Úlenr+   r,   r   Úas_posixÚ_upload_folder)#r@   rF  rG  rH  rI  rJ  rK  rL  rK   rN  Úquantization_serializableÚweights_nameÚweights_name_patternrQ  rR  rS  rT  rU  Úmodel_to_saverp  Ústate_dict_splitÚfilenameÚfull_filenameÚweights_without_extÚfilename_without_extÚtensorsÚtensorÚshardÚfilepathÚindexÚsave_index_fileÚfÚcontentÚpath_to_weightsÚ
model_cards#                                      rA   Úsave_pretrainedzModelMixin.save_pretrained›  sz  € ôX �7‰7�>‰>˜.Ô)Ü�L‰L˜?¨>Ð*:Ð:]Ð^Ô_Øä˜t ^°TÓ:ˆØÐ#à DÐ(ò 1Ü˜|Ô-?Ó@ò1à ×0Ñ0ð &ñ
 -Ü Ø2°<×3SÑ3S×3`Ñ3`Ð2að byð yóð ñ
 4FÕ/Ì<ˆÜ# L°'Ó:ˆØ+×3Ñ3°F¸NÓK×SÑSØÐ2ó 
Ðô 	�‰�N¨TÕ2áØ#ŸZ™ZÐ(8¸$Ó?ˆNØ—j‘j ¨DÓ1ˆGØŸ
™
 ;°Ó6ˆIØ—J‘J˜w¨Ó-ˆEØ—j‘j ¨N×,@Ñ,@ÄÇÁÇÁÓ,MÈbÑ,QÓRˆGÜ! '°DÀ'ÐQVÔW×_Ñ_ˆGð ˆñ Ø×%Ñ% nÔ5ð #×-Ñ-Ó/ˆ
ô >Ø ~ÐH\ô
Ðò
 ÜŸJ™J ~Ö6�ØÐ/×CÑC×HÑHÓJÑJØÜ "§¡§¡¨^¸XÓ F�Ü—w‘w—~‘~ mÔ4ØØ&:×&BÑ&BÀ6È2Ó&N×&VÑ&VÐWeÐgiÓ&jÐ#Ø&9×&AÑ&AÀ*ÈbÓ&QÐ#Ø'/×'7Ñ'7¸ÀÓ'C×'KÑ'KÈNÐ\^Ó'_Ð$ð ×'Ñ'Ð(;Õ<Ü$×.Ñ.Ð/CÓDÑPä—I‘I˜mÕ,ð 7ð  "2×!EÑ!E×!KÑ!KÖ!MÑˆH�gÙKRÓSÉ7À�V˜Z¨Ñ/×:Ñ:Ó<Ñ<È7ˆEÐSÜ—w‘w—|‘| N°HÓ=ˆHÙ!ô ×!Ñ!×+Ñ+¨E°8ÀxÐQUÐFVÐ+ÕWä—
‘
˜5 (Õ+ð "Nð ×&Ò&à,×5Ñ5Ø.×AÑAñˆEñ :LÕ5ÔQcˆOÜ Ÿg™gŸl™l¨>¼<ÈÐY`Ó;aÓbˆOä�o s°WÕ=ÀÜŸ*™* U°1ÀÔEÈÑL�Ø—‘˜Ô ÷ >ô �K‰KØLÈ^ÐL\ð ]ÜÐ 0× DÑ DÓEÐFð G$Ø$3Ð#4°Að7õô !Ÿg™gŸl™l¨>¸<ÓHˆOÜ�K‰KÐ1°/Ð1BÐCÔDáä2°7À%ÔHˆJÜ,¨ZÓ8ˆJØ�O‰OœD °Ó=×FÑFÓHÔIà×ÑØØØØ-Ø#ð  õ ð ùò; T÷" >Ð=ús   Ë(S
Ï-SÓSc                 óX   — t        | dd«      }|€t        d«      ‚|j                  | «      S )zŽ
        Potentially dequantize the model in case it has been quantized by a quantization method that support
        dequantization.
        rN  Nz?You need to first quantize your model in order to dequantize it)r  ry   Ú
dequantize)r@   rN  s     rA   rš  zModelMixin.dequantize6  s5   € ô
 ˜t ^°TÓ:ˆàÐÜÐ^Ó_Ð_à×&Ñ& tÓ,Ð,rC   Úpretrained_model_name_or_pathc                 ó&  — |j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  d	d«      }	|j                  d
d«      }
|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dt        «      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }|j                  dd«      }t        }|r|st        d«      ‚|�Ct	        |t
        j                  «      s)t
        j                  }t        j                  d|› d�«       d}|€d}d}|r!t        «       sd}t        j                  d«       |�t        «       st        d«      ‚|�t        dd «      st        d!«      ‚|du rt        dd «      st        d"«      ‚|du r|�t        d#|› d$�«      ‚t	        |t
        j                  «      rd%|i}nQt	        |t        «      r|d&vr	 d%t        j                  |«      i}n$t	        |t         «      r|d)k  rt        d*«      ‚d%|i}|�|€d}n|st        d+«      ‚|r|�t        dd,«      st        d-«      ‚t"        d.d/d0œ}i }|} | j$                  |f|dd|||	|
||||d1œ|¤Ž\  }}}t'        j(                  |«      }d|v xr |d   du} | s|�?| rt+        j,                  |d   |«      |d<   n||d<   t+        j.                  |d   | ¬2«      }!nd}!|!�€|!j1                  |||¬3«       |!j3                  |«      }|!j5                  |«      }|!j6                  j8                  j:                  |d4<   |€d}t        j=                  d5«       n|st        d6«      ‚| j>                  duxr |!du xs tA        |!d7d«      }"|"rF| j>                  }#t	        |#tB        «      s|#g}#|€d}t        j=                  d8«       n|st        d9«      ‚g }#d}$d}%d}&d}'tD        jF                  jI                  |«      }(|(||xs d%||||||	|
||||d:œ})tK        dPi |)¤Ž}'|�,|'�tD        jF                  jM                  |'«      stO        dPi |)¤Ž}'|'�|s|'jQ                  «       rd}$|$r|rt        d;«      ‚|r=tS        |tT        ||||	|
||||¬<«      }% | j.                  |fi |¤Ž}*d=d>l+m,}+  |+|*|%«      }*np|$rt[        ||'|||	|
|||xs d%|¬?«
      \  }%}&n(|r&	 tS        |t]        t^        |«      ||||	|
|||||¬@«      }%|%€'|$s%tS        |t]        td        |«      ||||	|
|||||¬@«      }%t	        |%tB        «      s|%g}%d}-|�Y|tA        t
        dDd«      k(  sEt	        |t
        j                  «      st        |› dEtg        |«      › d(�«      ‚| ji                  |«      }-tk        «       g}.|r#|.jm                  to        jp                  «       «       ts        |.«      5   | j.                  |fi |¤Ž}*ddd«       |-�t        jt                  |-«       d}/|$s"tw        |%d)   ||¬F«      }/*jy                  |/«       |$r|&dG   }0ntC        |/j{                  «       «      }0|!�|!j}                  *||#¬H«       t        *||||#|!«      }|!�|!j1                  |¬I«       | j�                  |*|/|%||0|||||||!|#|||¬J«      \  }*}1}2}3}4}5|1|2|3|5dKœ}6|�|||4dLœ}7tƒ        |*fi |7¤Ž |!�|!j…                  |*«       |!|*_C        |�)|tA        t
        dDd«      k(  r|!€|"s|*j‰                  |«      }*|!�|*j‹                  ||¬M«       n|*j‹                  |¬N«       |*j�                  «        |�|*j�                  |¬O«       |r|*|6fS |*S # t        $ r t        d'|› d(�«      ‚w xY w# t`        $ r>},t        jc                  dA|› dB|,› �«       |s‚ t        j                  dC«       Y d},~,�ŒÂd},~,ww xY w# 1 sw Y   �ŒäxY w)QuH!  
        Instantiate a pretrained PyTorch model from a pretrained model configuration.

        The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To
        train the model, set it back in training mode with `model.train()`.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
                Can be either:

                    - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
                      the Hub.
                    - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
                      with [`~ModelMixin.save_pretrained`].

            cache_dir (`str | os.PathLike`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            torch_dtype (`torch.dtype`, *optional*):
                Override the default `torch.dtype` and load the model with another dtype.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info (`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only(`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            from_flax (`bool`, *optional*, defaults to `False`):
                Load the model weights from a Flax checkpoint save file.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.
            device_map (`int | str | torch.device` or `dict[str, int | str | torch.device]`, *optional*):
                A map that specifies where each submodule should go. It doesn't need to be defined for each
                parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
                same device. Defaults to `None`, meaning that the model will be loaded on CPU.

                Examples:

                ```py
                >>> from diffusers import AutoModel
                >>> import torch

                >>> # This works.
                >>> model = AutoModel.from_pretrained(
                ...     "stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", device_map="cuda"
                ... )
                >>> # This also works (integer accelerator device ID).
                >>> model = AutoModel.from_pretrained(
                ...     "stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", device_map=0
                ... )
                >>> # Specifying a supported offloading strategy like "auto" also works.
                >>> model = AutoModel.from_pretrained(
                ...     "stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", device_map="auto"
                ... )
                >>> # Specifying a dictionary as `device_map` also works.
                >>> model = AutoModel.from_pretrained(
                ...     "stabilityai/stable-diffusion-xl-base-1.0",
                ...     subfolder="unet",
                ...     device_map={"": torch.device("cuda")},
                ... )
                ```

                Set `device_map="auto"` to have ðŸ¤— Accelerate automatically compute the most optimized `device_map`. For
                more information about each option see [designing a device
                map](https://huggingface.co/docs/accelerate/en/concept_guides/big_model_inference#the-devicemap). You
                can also refer to the [Diffusers-specific
                documentation](https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#model-sharding)
                for more concrete examples.
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each GPU and the available CPU RAM if unset.
            offload_folder (`str` or `os.PathLike`, *optional*):
                The path to offload weights if `device_map` contains the value `"disk"`.
            offload_state_dict (`bool`, *optional*):
                If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
                the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
                when there is some disk offload.
            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.
            variant (`str`, *optional*):
                Load weights from a specified `variant` filename such as `"fp16"` or `"ema"`. This is ignored when
                loading `from_flax`.
            use_safetensors (`bool`, *optional*, defaults to `None`):
                If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the
                `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors`
                weights. If set to `False`, `safetensors` weights are not loaded.
            disable_mmap ('bool', *optional*, defaults to 'False'):
                Whether to disable mmap when loading a Safetensors model. This option can perform better when the model
                is on a network mount or hard drive, which may not handle the seeky-ness of mmap very well.

        > [!TIP] > To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in
        with `hf > auth login`. You can also activate the special >
        ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a >
        firewalled environment.

        Example:

        ```py
        from diffusers import UNet2DConditionModel

        unet = UNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="unet")
        ```

        If you get the error message below, you need to finetune the weights for your downstream task:

        ```bash
        Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
        - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
        You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
        ```
        Ú	cache_dirNÚignore_mismatched_sizesFÚforce_downloadÚ	from_flaxÚproxiesÚoutput_loading_infoÚlocal_files_onlyrT  ÚrevisionÚtorch_dtypeÚ	subfolderÚ
device_mapÚ
max_memoryÚoffload_folderÚoffload_state_dictr  rJ  Úuse_safetensorsrh  Údduf_entriesÚdisable_mmapÚparallel_configzEParallel loading is not supported when not using `low_cpu_mem_usage`.zPassed `torch_dtype` z7 is not a `torch.dtype`. Defaulting to `torch.float32`.Ta,  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
```
.z©Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set `device_map=None`. You can install accelerate with `pip install accelerate`.r`   ra   ztLoading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set `device_map=None`.z~Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set `low_cpu_mem_usage=False`.zEYou cannot set `low_cpu_mem_usage` to `False` while using device_map=zO for loading and dispatching. Please make sure to set `low_cpu_mem_usage=True`.rX  )ÚautoÚbalancedÚbalanced_low_0Ú
sequentialzœWhen passing device_map as a string, the value needs to be a device name (e.g. cpu, cuda:0) or 'auto', 'balanced', 'balanced_low_0', 'sequential' but found rb  r   znYou can't pass device_map as a negative int. If you want to put the model on the cpu, pass device_map = 'cpu' z>Passing along a `device_map` requires `low_cpu_mem_usage=True`z1.10z=`low_cpu_mem_usage` and `device_map` require PyTorch >= 1.10.ÚmodelÚpytorch©Ú	diffusersÚ	file_typeÚ	framework)r�  Úreturn_unused_kwargsÚreturn_commit_hashrŸ  r¡  r£  rT  r¤  r¦  Ú
user_agentr¬  )Úpre_quantized)r¥  r   r§  Úquantz>Set `low_cpu_mem_usage` to True as `hf_quantizer` is not None.zD`low_cpu_mem_usage` cannot be False or None when using quantization.Úuse_keep_in_fp32_moduleszGSet `low_cpu_mem_usage` to True as `_keep_in_fp32_modules` is not None.zH`low_cpu_mem_usage` cannot be False when `keep_in_fp32_modules` is True.)Úis_localr›  r¦  r«  r�  rJ  rŸ  r¡  r£  rT  r¤  r»  Úcommit_hashr¬  zFLoading of sharded checkpoints is not supported when `from_flax=True`.)
r†  r�  rŸ  r¡  r£  rT  r¤  r¦  r»  rÀ  r.   )Ú%load_flax_checkpoint_in_pytorch_model)r�  r¡  r£  rT  r»  r¤  r¦  r¬  )r†  r�  rŸ  r¡  r£  rT  r¤  r¦  r»  rÀ  r¬  z(An error occurred while trying to fetch z: zXDefaulting to unsafe serialization. Pass `allow_pickle=False` to raise an error instead.Úfloat8_e4m3fnzA needs to be of type `torch.dtype`, e.g. `torch.float16`, but is )r­  r¬  Úall_checkpoint_keys)r³  r§  Úkeep_in_fp32_modules)r§  )rž  r  r§  r©  rª  r™   rN  rÄ  r¬  Úis_parallel_loading_enabledr­  )Úmissing_keysÚunexpected_keysÚmismatched_keysÚ
error_msgs)r§  Úoffload_dirÚoffload_index)r°   Ú_pre_quantization_dtype)r°   )ÚconfigrQ   )Hrl  Ú_LOW_CPU_MEM_USAGE_DEFAULTr   ÚNotImplementedErrorr“   rn   r™   Úfloat32r  r  r#   r'   ry   r   rƒ   ÚRuntimeErrorÚintr   Úload_configÚcopyÚdeepcopyr   Úmerge_quantization_configsÚfrom_configÚvalidate_environmentÚupdate_torch_dtypeÚupdate_device_maprh  ri  r8  r	  rŒ   r  rP   rc  rd  Úisdirr5   Úexistsr6   Úis_filer!   r   Úmodeling_pytorch_flax_utilsrÁ  r    r   r   ÚIOErrorrf  r   rº   Ú_set_default_torch_dtyper«   ÚappendÚ
accelerateÚinit_empty_weightsr;   Úset_default_dtyper9   Ú_fix_state_dict_keys_on_loadrs  Úpreprocess_modelr3   Ú_load_pretrained_modelrb   Úpostprocess_modelrN  ÚtoÚregister_to_configÚevalÚenable_parallelism)8Úclsr›  rK   r�  rž  rŸ  r   r¡  r¢  r£  rT  r¤  r¥  r¦  r§  r¨  r©  rª  r  rJ  r«  rh  r¬  r­  r®  rÅ  Úallow_pickler»  Úunused_kwargsÚconfig_pathrÍ  rÀ  r¼  rN  r¾  rÄ  r|  Úresolved_model_fileÚsharded_metadataÚ
index_filer¿  Úindex_file_kwargsr³  rÁ  ÚeÚ
dtype_origÚinit_contextsrp  Úloaded_keysrÆ  rÇ  rÈ  rË  rÉ  Úloading_infoÚdevice_map_kwargss8                                                           rA   Úfrom_pretrainedzModelMixin.from_pretrainedB  sp
  € ðF —J‘J˜{¨DÓ1ˆ	Ø"(§*¡*Ð-FÈÓ"NÐØŸ™Ð$4°eÓ<ˆØ—J‘J˜{¨EÓ2ˆ	Ø—*‘*˜Y¨Ó-ˆØ$Ÿj™jÐ)>ÀÓFÐØ!Ÿ:™:Ð&8¸$Ó?ÐØ—
‘
˜7 DÓ)ˆØ—:‘:˜j¨$Ó/ˆØ—j‘j °Ó5ˆØ—J‘J˜{¨DÓ1ˆ	Ø—Z‘Z ¨dÓ3ˆ
Ø—Z‘Z ¨dÓ3ˆ
ØŸ™Ð$4°dÓ;ˆØ#ŸZ™ZÐ(<¸dÓCÐØ"ŸJ™JÐ':Ô<VÓWÐØ—*‘*˜Y¨Ó-ˆØ Ÿ*™*Ð%6¸Ó=ˆØ$Ÿj™jÐ)>ÀÓEÐØ4:·J±J¸~ÈtÓ4TˆØ—z‘z .°%Ó8ˆØIOÏÉÐTeÐgkÓIlˆä&@Ð#Ù&Ñ/@Ü%Ð&mÓnÐnàÐ"¬:°kÄ5Ç;Á;Ô+OÜŸ-™-ˆKÜ�N‰NØ'¨ }Ð4kÐlôð ˆØÐ"Ø"ˆOØˆLáÔ%<Ô%>Ø %ÐÜ�N‰Nð.ôð Ð!Ô*AÔ*CÜ%ð`óð ð Ð!Ô*:¸4ÀÔ*IÜ%ð&óð ð
  Ñ$Ô-=¸dÀGÔ-LÜ%ð.óð ð
  Ñ%¨*Ð*@ÜØWÐXbÐWcð dRð Róð ô �j¤%§,¡,Ô/Ø˜jÐ)‰JÜ˜
¤CÔ(¨ZÐ?sÑ-sðØ ¤%§,¡,¨zÓ":Ð;‘
ô ˜
¤CÔ(Ø˜AŠ~Ü ð Eóð ð ! *Ð-�
àÐ!Ø Ð(Ø$(Ñ!Ù&Ü Ð!aÓbÐbáØÐ%Ô.>¸tÀVÔ.Lä Ð!`ÓaÐaô %Ø Ø"ñ
ˆ
ð
 ˆð 4ˆð .=¨S¯_©_Øð.
àØ!%Ø#Ø)ØØ-ØØØØ!Ø%ñ.
ð ñ.
Ñ*ˆ�˜{ô  —‘˜vÓ&ˆð .°Ð7Òe¸FÐCXÑ<YÐaeÐ<eˆÙÐ/Ð;ÙÜ0F×0aÑ0aØÐ0Ñ1Ð3Fó1�Ð,Ò-ð 1D�Ð,Ñ-Ü1×=Ñ=ØÐ,Ñ-¸]ô‰Lð  ˆLàÐ#Ø×-Ñ-¸+ÐQZÐgqÐ-ÔrØ&×9Ñ9¸+ÓFˆKØ%×7Ñ7¸
ÓCˆJð #/×"BÑ"B×"OÑ"O×"UÑ"UˆJ�wÑð !Ð(Ø$(Ð!Ü—‘Ð\Õ]Ù&Ü Ð!gÓhÐhð $'×#<Ñ#<ÀDÐ#Hò $
Ø˜DÐ Ò\¤G¨LÐ:TÐV[Ó$\ð 	!ñ $Ø#&×#<Ñ#<Ð ÜÐ2´DÔ9Ø(<Ð'=Ð$à Ð(Ø$(Ð!Ü—‘ÐeÕfÙ&Ü Ð!kÓlÐlà#%Ð àˆ
Ø"Ðð  ÐØˆ
Ü—7‘7—=‘=Ð!>Ó?ˆà Ø-JØ"š bØ.Ø"ØØ,ØØ 0ØØ Ø$Ø&Ø(ñ
Ðô  'Ñ;Ð):Ñ;ˆ
ð Ð JÐ$6¼b¿g¹g¿n¹nÈZÔ>XÜ1ÑFÐ4EÑFˆJØÐ!¡|°z×7IÑ7IÔ7KØˆJá™)ÜÐeÓfÐfñ Ü"1Ø-Ü.Ø#Ø-ØØ!1ØØ!Ø#Ø%Ø'ô#Ðð $�C—O‘O FÑ<¨mÑ<ˆEõ [á9¸%ÐATÓU‰Eñ Ü8SØ1ØØ'Ø#Ø%5ØØ)Ø%Ø'šo¨2Ø!-ô9Ñ5Ð#Ñ%5ñ !ðÜ*9Ø5Ü%1Ô2JÈGÓ%TØ"+Ø'5Ø 'Ø)9Ø#Ø!)Ø"+Ø#-Ø$/Ø%1ô+Ð'ð. #Ð*±:Ü&5Ø1Ü!-¬l¸GÓ!DØ'Ø#1Ø#Ø%5ØØ%Ø'Ø)Ø +Ø!-ô'Ð#ô Ð-¬tÔ4Ø#6Ð"7Ðð
 ˆ
ØÐ"¨;¼'Ä%ÈÐZ^Ó:_Ò+_Ü˜k¬5¯;©;Ô7Ü Ø"�mÐ#dÔeiÐjuÓevÐdwÐwxÐyóð ð ×5Ñ5°kÓBˆJä(Ó*Ð+ˆáØ× Ñ ¤×!>Ñ!>Ó!@ÔAä˜]Õ+Ø#�C—O‘O FÑ<¨mÑ<ˆE÷ ,ð Ð!Ü×#Ñ# JÔ/àˆ
Ùä(Ð)<¸QÑ)?ÈlÐiuÔvˆJà×.Ñ.¨zÔ:áØ*Ð+@ÑA‰Kä˜zŸ™Ó0Ó1ˆKàÐ#Ø×)Ñ)Ø¨
ÐI]ð *ô ô
 +Ø�:˜z¨;Ð8LÈló
ˆ
ð Ð#Ø×-Ñ-¸Ð-ÔDð ×&Ñ&ØØØØ)ØØ$;Ø/Ø!Ø)Ø1ØØ%Ø!5Ø%Ø(CØ%ð! 'ó 
ñ	
ØØØØØØð( )Ø.Ø.Ø$ñ	
ˆð Ð!à(Ø-Ø!.ñ!Ðô
 ˜5Ñ6Ð$5Ò6àÐ#Ø×*Ñ*¨5Ô1Ø!-ˆEÔð Ð#Øœw¤u¨o¸tÓDÒDØÐ$Ù,à—H‘H˜[Ó)ˆEàÐ#ð ×$Ñ$Ð3PÐjuÐ$Õvà×$Ñ$Ð3PÐ$ÔQð 	�
‰
ŒàÐ&Ø×$Ñ$¨OÐ$Ô<áØ˜,Ð&Ð&àˆøôW
  ò Ü ðTØT^ÐS_Ð_`ðbóð ðûôz ò Ü—L‘LÐ#KÐLiÐKjÐjlÐmnÐloÐ!pÔqÙ'ØÜ—N‘NØr÷ò ûð	ú÷V ,Ñ+ús0   Ê*`  Ö%`< Úbà `9à<	bá3a>á>bâbc                 ó   •— ddl m} t        | dd «      t        j                  k(  rdt        | dd«      r%t        dd«      rt        d| j                  › d	�«      ‚t        | d
d«      r%t        dd«      rt        d| j                  › d�«      ‚ || «      r/t        j                  d| j                  j                  › d�«       | S t        ‰| �4  |i |¤ŽS )Nr   ©Ú_is_group_offload_enabledÚquantization_methodÚis_loaded_in_8bitFÚ<ú0.48.0z‚Calling `cuda()` is not supported for `8-bit` quantized models with the installed version of bitsandbytes. The current device is `úL`. If you intended to move the model, please install bitsandbytes >= 0.48.0.Úis_loaded_in_4bitú0.43.2z‚Calling `cuda()` is not supported for `4-bit` quantized models with the installed version of bitsandbytes. The current device is `úL`. If you intended to move the model, please install bitsandbytes >= 0.43.2.úThe module 'zD' is group offloaded and moving it using `.cuda()` is not supported.)rx   rþ  r  r   ÚBITS_AND_BYTESr%   ry   r   r  r  r´   rL   r²   Úcuda)r@   rJ   rK   rþ  r´   s       €rA   r	  zModelMixin.cudaa  sì   ø€ åFô �4Ð.°Ó5Ô9K×9ZÑ9ZÒZÜ�tÐ0°%Ô8Ô=TÐUXÐZbÔ=cÜ ð.Ø.2¯k©k¨]ð  ;GðHóð ô ˜Ð2°EÔ:Ô?VÐWZÐ\dÔ?eÜ ð.Ø.2¯k©k¨]ð  ;GðHóð ñ % TÔ*Ü�N‰NØ˜tŸ~™~×6Ñ6Ð7Ð7{Ð|ôð ˆKä‰w‰|˜TÐ, VÑ,Ð,rC   c                 óÞ  •— ddl m} t        d„ |D «       «      xs d|v }d|v }|D ]+  }t        |t        «      sŒ	 t        j                  |«       d}Œ- |s%|D ]   }t        |t
        j                  «      sŒd} n t        | dd«      r|rt        d	«      ‚t        | d
d «      t        j                  k(  rdt        | dd«      r%t        dd«      rt        d| j                  › d�«      ‚t        | dd«      r%t        dd«      rt        d| j                  › d�«      ‚ || «      r1|r/t        j                  d| j                   j"                  › d�«       | S t%        ‰| �L  |i |¤ŽS # t        $ r Y �ŒEw xY w)Nr   rý  c              3   óP   K  — | ]  }t        |t        j                  «      –— Œ  y ­wr>   )r“   rn   r   )rŽ   Úargs     rA   r‘   z ModelMixin.to.<locals>.<genexpr>€  s   è ø€ Ð)XÑSWÈC¬*°S¼%¿,¹,×*GÑSWùrÂ   r   r™   TÚis_quantizedFzÍCasting a quantized model to a new `dtype` is unsupported. To set the dtype of unquantized layers, please use the `torch_dtype` argument when loading the model using `from_pretrained` or `from_single_file`rÿ  r   r  r  z€Calling `to()` is not supported for `8-bit` quantized models with the installed version of bitsandbytes. The current device is `r  r  r  z€Calling `to()` is not supported for `4-bit` quantized models with the installed version of bitsandbytes. The current device is `r  r  zB' is group offloaded and moving it using `.to()` is not supported.)rx   rþ  rš   r“   rƒ   rn   r   rÑ  r™   r  ry   r   r  r%   r  r  r´   rL   r²   ré  )r@   rJ   rK   rþ  Údevice_arg_or_kwarg_presentÚdtype_present_in_argsr  r´   s          €rA   ré  zModelMixin.to|  s§  ø€ åFä&)Ñ)XÑSWÓ)XÓ&XÒ&nÐ\dÐhnÐ\nÐ#Ø '¨6Ð 1Ðó ˆCÜ˜c¤3Ô'ØðÜ—‘˜SÔ!Ø.2Ñ+ð ñ %Û�Ü˜c¤5§;¡;Õ/Ø,0Ð)Ùð ô
 �4˜¨Ô/Ù$Ü ðzóð ô
 �4Ð.°Ó5Ô9K×9ZÑ9ZÒZÜ�tÐ0°%Ô8Ô=TÐUXÐZbÔ=cÜ ð.Ø.2¯k©k¨]ð  ;GðHóð ô ˜Ð2°EÔ:Ô?VÐWZÐ\dÔ?eÜ ð.Ø.2¯k©k¨]ð  ;GðHóð ñ % TÔ*Ñ/JÜ�N‰NØ˜tŸ~™~×6Ñ6Ð7Ð7yÐzôð ˆKä‰w‰z˜4Ð* 6Ñ*Ð*øôC  ò Úðús   »EÅ	E,Å+E,c                 óL   •— t        | dd«      rt        d«      ‚t        ‰| �  |Ž S )Nr  FzŒ`.half()` is not supported for quantized model. Please use the model as it is, since the model has already been cast to the correct `dtype`.)r  ry   r²   Úhalf©r@   rJ   r´   s     €rA   r  zModelMixin.half®  s3   ø€ ä�4˜¨Ô/ÜðGóð ô
 ‘7‘< Ð&Ð&rC   c                 óL   •— t        | dd«      rt        d«      ‚t        ‰| �  |Ž S )Nr  Fz�`.float()` is not supported for quantized model. Please use the model as it is, since the model has already been cast to the correct `dtype`.)r  ry   r²   Úfloatr  s     €rA   r  zModelMixin.float¹  s3   ø€ ä�4˜¨Ô/ÜðGóð ô
 ‘7‘= $Ð'Ð'rC   c                 ó  — t        | dd«      }|s#t        d| j                  j                  › d�«      ‚d}| j	                  «       D ]/  }|j                  j                  |v sŒ |j
                  |i |¤Ž d}Œ1 |st        d|› d�«      ‚y)	uå  
        Compiles *only* the frequently repeated sub-modules of a model (e.g. the Transformer layers) instead of
        compiling the entire model. This techniqueâ€”often called **regional compilation** (see the PyTorch recipe
        https://docs.pytorch.org/tutorials/recipes/regional_compilation.html) can reduce end-to-end compile time
        substantially, while preserving the runtime speed-ups you would expect from a full `torch.compile`.

        The set of sub-modules to compile is discovered by the presence of **`_repeated_blocks`** attribute in the
        model definition. Define this attribute on your model subclass as a list/tuple of class names (strings). Every
        module whose class name matches will be compiled.

        Once discovered, each matching sub-module is compiled by calling `submodule.compile(*args, **kwargs)`. Any
        positional or keyword arguments you supply to `compile_repeated_blocks` are forwarded verbatim to
        `torch.compile`.
        Ú_repeated_blocksNzM`_repeated_blocks` attribute is empty. Set `_repeated_blocks` for the class `z&` to benefit from faster compilation. FTz$Regional compilation failed because z% classes are not found in the model. )r  ry   r´   rL   rÃ   Úcompile)r@   rJ   rK   Úrepeated_blocksÚhas_compiled_regionÚsubmods         rA   Úcompile_repeated_blocksz"ModelMixin.compile_repeated_blocksÃ  s«   € ô " $Ð(:¸DÓAˆáÜð9Ø9=¿¹×9PÑ9PÐ8QÐQwðyóð ð $ÐØ—l‘l–nˆFØ×Ñ×(Ñ(¨OÒ;Ø�—‘ Ð/¨Ò/Ø&*Ñ#ð %ñ
 #ÜØ6°Ð6GÐGlÐmóð ð #rC   )Úcp_planrÍ  r  c          
      ó  — t         j                  d«       t        j                  j	                  «       s)t        j                  j                  «       st        d«      ‚ddlm} ddl	m
} ddlm}m} ddlm}m} t#        |t$        «      rt'        |¬	«      }t        j                  j)                  «       }	t        j                  j+                  «       }
t        j,                  j/                  «       j0                  }t        j2                  |«      }t        j4                  ||	|j7                  «       z  «      }|||f}|j8                  �Á| j;                  «       D ]®  }t#        ||«      sŒ|j<                  }|�t?        |d
«      sŒ+|j@                  }|€|jC                  «       \  }}n ||«      }|jE                  |«      sHtG        |jH                  «      }tK        d|jL                  jN                  › d|jP                  › d|› d�«      ‚ n d }|j8                  �L|j8                  }t        j                  jR                  jU                  ||jV                  |jX                  ¬«      }|j[                  |	|
||¬«       || _.        | j;                  «       D ]1  }t#        ||«      sŒ|j<                  }|�t?        |d«      sŒ+||_.        Œ3 |j8                  �>|€| j^                  €tK        d«      ‚|�|n| j^                  } || |j8                  |«       y y )Nz•`enable_parallelism` is an experimental feature. The API may change in the future and breaking changes may be introduced at any time without warning.zXtorch.distributed must be available and initialized before calling `enable_parallelism`.r   )Úapply_context_parallelr.   r$  )r&  r'  r*  )Úcontext_parallel_configr0  z<Context parallelism is enabled but the attention processor 'z' is using backend 'zY' which does not support context parallelism. Please set a compatible attention backend: zS using `model.set_attention_backend()` before calling `model.enable_parallelism()`.)Údevice_typeÚ
mesh_shapeÚmesh_dim_names)Úmeshr.  z\`cp_plan` must be provided either as an argument or set in the model's `_cp_plan` attribute.)0r  r  rn   ÚdistributedÚis_availableÚis_initializedrÑ  Úhooks.context_parallelr  r1  r%  r2  r&  r'  r3  r+  r,  r“   r/   r1   Úget_rankÚget_world_sizeÚ_CÚ_get_acceleratorrº   Úget_device_moduler   Údevice_countr  rÃ   r4  r•   r0  Úget_active_backendr:  r;  r<  ry   r´   rL   r8  Údevice_meshÚinit_device_meshr!  r"  Úsetupr.  Ú_cp_plan)r@   rÍ  r  r  r%  r&  r'  r+  r,  ÚrankÚ
world_sizer   Údevice_moduler   r>  ri   r4  Úattention_backendÚ_rB  r#  Ú	cp_configs                         rA   rì  zModelMixin.enable_parallelismä  så  € ô 	�‰ð dô	
ô × Ñ ×-Ñ-Ô/¼×8IÑ8I×8XÑ8XÔ8ZÜØjóð õ 	DÝ3ßWßBä�fÔ3Ô4Ü#¸FÔCˆFä× Ñ ×)Ñ)Ó+ˆÜ×&Ñ&×5Ñ5Ó7ˆ
Ü—h‘h×/Ñ/Ó1×6Ñ6ˆÜ×/Ñ/°Ó<ˆÜ—‘˜k¨4°-×2LÑ2LÓ2NÑ+NÓOˆà&¨Ð8LÐMÐà×)Ñ)Ð5ØŸ,™,ž.�Ü! &Ð*;Ô<Øà"×,Ñ,�	ØÐ$¬G°IÐ?SÔ,TØà$-×$@Ñ$@Ð!Ø$Ð,Ø+D×+WÑ+WÓ+YÑ(Ð%¡qá(<Ð=NÓ(OÐ%à0×OÑOÐPaÔbÜ*0Ð1J×1eÑ1eÓ*fÐ'Ü$ØVÐW`×WjÑWj×WsÑWsÐVtð u-Ø->×-DÑ-DÐ,Eð FFØFYÐEZð [@ðAóð ñ ð3 )ð6 ˆØ×)Ñ)Ð5Ø×6Ñ6ˆIÜ×$Ñ$×0Ñ0×AÑAØ'Ø$×/Ñ/Ø(×7Ñ7ð Bó ˆDð 	�‰�T˜: v°DˆÔ9Ø &ˆÔà—l‘l–nˆFÜ˜fÐ&7Ô8ØØ×(Ñ(ˆIØÐ ¬°	Ð;MÔ(NØØ)/ˆIÕ&ð %ð ×)Ñ)Ð5Øˆ 4§=¡=Ð#8Ü Øróð ð ")Ð!4‘g¸$¿-¹-ˆGÙ" 4¨×)GÑ)GÈÕQð 6rC   rp  rñ  rø  rž  Úassign_to_params_buffersrN  r  r™   rÄ  r§  rª  r©  r¬  rÅ  r­  c                 óˆ  — |j                  «       }t        |j                  «       «      }t        t        |«      t        |«      z
  «      }|�|j	                  ||d¬«      }t        t        |«      t        |«      z
  «      }| j
                  �7| j
                  D ](  }|D �cg c]  }t        j                  ||«      �Œ|‘Œ }}Œ* g }g }|�:d|j                  «       v r(|€t        d«      ‚t        j                  |d¬«       |€d}|�t        ||«      }t        |||
|«       |�d|j                  «       v ri nd }d\  }}|rt        j                  «       }i }|�|g}t!        j"                  |rt$        nt&        fi d|“d	|“d
|“d|
“d|“d|“d|“d|“d|“d|“d|“d|“d|“d|“d|	“d|“Ž}|r ||«      \  }}}} || z  }||z  }nW|}!t)        |«      dkD  r)ddi}"t+        «       sd|"d<   t-        j.                  |fi |"¤Ž}!|!D ]  }# ||#«      \  }}}} || z  }||z  }Œ t1        «        |�@t)        |«      dkD  r2t3        ||«       d }|r"t5        |||«       t7        j8                  |«       t)        |«      dkD  r?dj;                  |«      }$d|$v r|$dz  }$t=        d |j>                  j@                  › d!|$› �«      ‚t)        |«      dkD  r9tB        jE                  d"|› d#| j@                  › d$d%j;                  |«      g› �«       n-tB        jG                  d&|j>                  j@                  › d'�«       t)        |«      dkD  r4tB        jE                  d(|j>                  j@                  › d)|› d*|› d+�«       nUt)        |«      dk(  rGtB        jG                  d,|j>                  j@                  › d-|› d.|j>                  j@                  › d/�«       t)        |«      dkD  rdd0j;                  |D �%�&�'cg c]  \  }%}&}'d1|%› d2|&› d3|'› d4�‘Œ c}'}&}%«      }(tB        jE                  d(|j>                  j@                  › d)|› d5|(› d+�«       ||||||fS c c}w c c}'}&}%w )6NrX  )ÚprefixÚdiskzàThe current `device_map` had weights offloaded to the disk. Please provide an `offload_folder` for them. Alternatively, make sure you have `safetensors` installed if the model you are using offers the weights in this format.TrO  )NNr³  Úmodel_state_dictr§  r™   rN  rÄ  r¬  rø  rÇ  rË  r©  Ústate_dict_indexÚstate_dict_folderrž  r  r­  r.   ÚdesczLoading checkpoint shardsÚdisabler   z
	zsize mismatchz_
	You may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method.z#Error(s) in loading state_dict for z:
	z(Some weights of the model checkpoint at z! were not used when initializing z: 
 r/  z9All model checkpoint weights were used when initializing z.
zSome weights of z3 were not initialized from the model checkpoint at z and are newly initialized: zo
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.zAll the weights of z/ were initialized from the model checkpoint at zf.
If your task is similar to the task the model of the checkpoint was trained on, you can already use z* for predictions without further training.ra  z- z: found shape z in the checkpoint and z in the model instantiatedz= and are newly initialized because the shapes did not match:
)$rp  rP   rs  r  Úupdate_missing_keysÚ"_keys_to_ignore_on_load_unexpectedÚreÚsearchr7  ry   rc  rk  r4   r2   ÚtempfileÚmkdtempÚ	functoolsÚpartialr8   r7   r‚  r)   r(   Útqdmr-   rd   rc   ÚshutilÚrmtreer9  rÑ  r´   rL   r  r  r	  ))rí  r³  rp  rñ  r›  rø  rž  r9  rN  r  r™   rÄ  r§  rª  r©  r¬  rÅ  r­  r=  Úexpected_keysrÆ  rÇ  Úpatrq   rÈ  rÉ  Úexpanded_device_maprË  r?  r>  Úload_fnÚ_mismatched_keysÚ_error_msgsÚshard_filesÚshard_tqdm_kwargsÚ
shard_fileÚ	error_msgÚkeyÚshape1Úshape2Úmismatched_warnings)                                            rA   rç  z!ModelMixin._load_pretrained_model;  s�  € ð* !×+Ñ+Ó-ÐÜÐ-×2Ñ2Ó4Ó5ˆÜœC Ó.´°[Ó1AÑAÓBˆØÐ#Ø'×;Ñ;¸EÀ<ÐXZÐ;Ó[ˆLÜœs ;Ó/´#°mÓ2DÑDÓEˆð ×1Ñ1Ð=Ø×=Ô=�Ù.=Ó"[©o¨ÄÇÁÈ3ÐPQÓARÑAZ¢1¨o�Ñ"[ð >ð ˆØˆ
ð Ð! f°
×0AÑ0AÓ0CÑ&CØÐ%Ü ð:óð ô —‘˜N°TÕ:Ø!Ð)Ø%)Ð"ð Ð!Ü"4°ZÀÓ"OÐÜ% eÐ-@À%ÈÔVà(Ð4¸À:×CTÑCTÓCVÑ9V™Ð\`ˆØ.8Ñ+ÐÐ+ÙÜ (× 0Ñ 0Ó 2ÐØ!ÐàÐ!ð $. ,Ðô ×#Ñ#Ù1LÕ-ÔRbò
áð
ñ .ð
ñ "ð	
ñ
 ð
ñ &ð
ñ "6ð
ñ &ð
ñ $ð
ñ ,ð
ñ (ð
ñ *ð
ñ .ð
ñ 0ð
ñ %<ð
ñ  0ð!
ñ" &ð#
ˆñ( 'ÙMTÐUhÓMiÑJˆMÐ+Ð-=¸{Ø˜+Ñ%ˆJØÐ/Ñ/‰Oà-ˆKÜÐ&Ó'¨!Ò+Ø%+Ð-HÐ$IÐ!Ü.Ô0Ø37Ð% iÑ0Ü%Ÿl™lÐ+>ÑTÐBSÑT�ã)�
ÙQXÐYcÓQdÑN�Ð/Ð1AÀ;Ø˜kÑ)�
ØÐ#3Ñ3‘ð *ô
 	ÔàÐ$¬¨]Ó);¸aÒ)?Ü˜}¨nÔ=Ø ˆMá!Ü& uÐ.>Ð@QÔRÜ—‘Ð/Ô0äˆz‹?˜QÒØŸ™ JÓ/ˆIØ )Ñ+ØØwñ�	ô Ð!DÀUÇ_Á_×E]ÑE]ÐD^Ð^cÐdmÐcnÐoÓpÐpäˆÓ !Ò#Ü�N‰NØ:Ð;XÐ:YÐYzÐ{~÷  |Hñ  |Hð  {Ið  INð  PT÷  PYñ  PYð  Zió  Pjð  Okð  Nlð  mõô �K‰KÐSÐTY×TcÑTc×TlÑTlÐSmÐmpÐqÔräˆ|Ó˜qÒ Ü�N‰NØ" 5§?¡?×#;Ñ#;Ð"<ð =Ø1Ð2Ð2NÈ|Ènð ]nðnõô
 �Ó! QÒ&Ü�K‰KØ% e§o¡o×&>Ñ&>Ð%?ð @Ø1Ð2ð 3CØCHÇ?Á?×C[ÑC[ÐB\ð ]-ð-ôô ˆÓ !Ò#Ø!%§¡ñ 0?õá/>Ñ+˜˜V Vð ˜˜˜^¨F¨8Ð3JÈ6È(ÐRlÒmØ/>óó"Ðô �N‰NØ" 5§?¡?×#;Ñ#;Ð"<ð =Ø1Ð2ð 3Ø.Ð/ð 0AðAôð �l O°_ÀmÐU_Ð_Ð_ùòC #\ùôjs   ÂP8Â;P8ÏP=c                 óÄ  — t        j                  |j                  «      j                  }|j	                  «       D ��ci c]&  \  }}|j
                  t         j                  k(  sŒ$||“Œ( }}}t        |j	                  «       D ��ch c]%  \  }}|j
                  t         j                  k7  sŒ$|’Œ' c}}«      }t        |j                  «       «      dhz
  }||fS c c}}w c c}}w )Nr@   )	ÚinspectÚ	signaturerB   r|   rm   ÚdefaultÚ_emptyr  rs  )rí  Úobjr|   rq   rr   Úrequired_parametersÚoptional_parametersÚexpected_moduless           rA   Ú_get_signature_keyszModelMixin._get_signature_keysÝ  sÂ   € ä×&Ñ& s§|¡|Ó4×?Ñ?ˆ
Ø0:×0@Ñ0@Ô0BÔbÑ0B©¨¨1ÀaÇiÁiÔSZ×SaÑSaÓFa˜q !™tÐ0BÐÑbÜ!°×1AÑ1AÔ1CÔ"cÑ1C©¨¨AÀqÇyÁyÔT[×TbÑTbÓGb¢1Ð1CÒ"cÓdÐÜÐ2×7Ñ7Ó9Ó:¸f¸XÑEÐàÐ!4Ð4Ð4ùó	 cùÛ"cs   ½%CÁ#CÂ%C
Â)C
c                 ó¨  — t        «       }| g}t        |«      dkD  r­|j                  d«      }|j                  j                  |vrut        |t        «      rI|j                  €%t        |j                  j                  › d|› d�«      ‚|t        |j                  «      z  }|t        |j                  «       «      z  }t        |«      dkD  rŒ­t        |«      S )aš  
        Get the modules of the model that should not be split when using device_map. We iterate through the modules to
        get the underlying `_no_split_modules`.

        Args:
            device_map (`str`):
                The device map value. Options are ["auto", "balanced", "balanced_low_0", "sequential"]

        Returns:
            `list[str]`: list of modules that should not be split
        r   rV  z does not support `device_map='z_'`. To implement support, the model class needs to implement the `_no_split_modules` attribute.)r  r‚  rl  r´   rL   r“   r­   Ú_no_split_modulesry   rP   rØ   )r@   r§  rf  Úmodules_to_checkri   s        rA   Ú_get_no_split_modulesz ModelMixin._get_no_split_modulesç  sß   € ô  ›EÐØ ˜6ÐÜÐ"Ó# aÒ'Ø%×)Ñ)¨"Ó-ˆFà×Ñ×(Ñ(Ð0AÑAÜ˜f¤jÔ1Ø×/Ñ/Ð7Ü(Ø%×/Ñ/×8Ñ8Ð9Ð9XÐYcÐXdð eZð Zóð ð
 ->ÄÀF×D\ÑD\Ó@]Ñ,]Ð)Ø ¤D¨¯©Ó):Ó$;Ñ;Ð ô Ð"Ó# aÓ'ô Ð%Ó&Ð&rC   c                 óô   — |j                   st        d| j                  › d|› d�«      ‚t        j	                  d| j                  › d|› d�«       t        j                  «       }t        j                  |«       |S )a�  
        Change the default dtype and return the previous one. This is needed when wanting to instantiate the model
        under specific dtype.

        Args:
            dtype (`torch.dtype`):
                a floating dtype to set to.

        Returns:
            `torch.dtype`: the original `dtype` that can be used to restore `torch.set_default_dtype(dtype)` if it was
            modified. If it wasn't, returns `None`.

        Note `set_default_dtype` currently only works with floating-point types and asserts if for example,
        `torch.int64` is passed. So if a non-float `dtype` is passed this functions will throw an exception.
        zCan't instantiate z model under dtype=z' since it is not a floating point dtypezInstantiating z model under default dtype rb  )r›   ry   rL   r  r	  rn   Úget_default_dtyperä  )rí  r™   rö  s      rA   rà  z#ModelMixin._set_default_torch_dtype  sw   € ð" ×&Ò&ÜØ$ S§\¡\ NÐ2EÀeÀWÐLsÐtóð ô 	�‰�n S§\¡\ NÐ2MÈeÈWÐTUÐVÔWÜ×,Ñ,Ó.ˆ
Ü×Ñ Ô&ØÐrC   c                 ó   — t        | «      S )z�
        `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
        device).
        )rˆ   rÄ   s    rA   r   zModelMixin.device  s   € ô $ DÓ)Ð)rC   c                 ó   — t        | «      S )zw
        `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
        )r£   rÄ   s    rA   r™   zModelMixin.dtype'  s   € ô
 # 4Ó(Ð(rC   Úonly_trainableÚexclude_embeddingsc                 ó
  — t        | dd«      }|rt        «       rddl}nt        d«      ‚|rh| j	                  «       D ��cg c]%  \  }}t        |t        j                  «      sŒ!|› d�‘Œ' }}}| j                  «       D ��cg c]  \  }}||vsŒ|‘Œ }	}}nt        | j                  «       «      }	g }
|	D ]º  }|j                  s|rŒ|rˆt        |j                  j                  «      rht        |d«      r|j                  «       }n%t        |d«      r|j                  j                   }nd	}|
j#                  |j%                  «       d
z  |z  «       Œœ|
j#                  |j%                  «       «       Œ¼ t'        |
«      S c c}}w c c}}w )a  
        Get number of (trainable or non-embedding) parameters in the module.

        Args:
            only_trainable (`bool`, *optional*, defaults to `False`):
                Whether or not to return only the number of trainable parameters.
            exclude_embeddings (`bool`, *optional*, defaults to `False`):
                Whether or not to return only the number of non-embedding parameters.

        Returns:
            `int`: The number of parameters.

        Example:

        ```py
        from diffusers import UNet2DConditionModel

        model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
        unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
        unet.num_parameters(only_trainable=True)
        859520964
        ```
        r  Fr   NzÊbitsandbytes is not installed but it seems that the model has been loaded in 4bit precision, something went wrong make sure to install bitsandbytes with `pip install bitsandbytes`. You also need a GPU. z.weightÚelement_sizeÚquant_storager.   r   )r  r$   Úbitsandbytesry   r”   r“   r   Ú	Embeddingr˜   rP   r|   Úrequires_gradÚ
Params4bitr•   rp  rq  Úitemsizerá  ÚnumelÚsum)r@   rm  rn  r  Úbnbr�   Úmodule_typeÚembedding_param_namesre   Útotal_parametersÚtotal_numelr    Ú	num_bytess                rA   Únum_parameterszModelMixin.num_parameters.  sw  € ô0 $ DÐ*=¸uÓEÐáÜ(Ô*Ü*ä ðpóð ñ
 à:>×:LÑ:LÔ:Nô%Ù:NÑ%6 T¨;ÔR\Ð]hÔjl×jvÑjvÕRw�4�&˜Ò Ð:Nð "ñ %ð 26×1FÑ1FÔ1Hô Ù1H™o˜d IÈDÐXmÒLm’	Ð1Hð ò  ô  $ D§O¡OÓ$5Ó6Ðàˆã%ˆEØ×"Ò"ª.ñ %¬°E¸3¿6¹6×;LÑ;LÔ)MÜ˜u nÔ5Ø$)×$6Ñ$6Ó$8™	Ü  ¨Ô8Ø$)×$7Ñ$7×$@Ñ$@™	à$%˜	Ø×&Ñ& u§{¡{£}°qÑ'8¸9Ñ'DÕEà×&Ñ& u§{¡{£}Õ5ð &ô �;ÓÐùó5%ùó s   ¿"E9Á"E9Á?E?ÂE?c                 ó@  — t        | j                  «       D �cg c]#  }|j                  «       |j                  «       z  ‘Œ% c}«      }|rKt        | j	                  «       D �cg c]#  }|j                  «       |j                  «       z  ‘Œ% c}«      }||z   }|S c c}w c c}w )a  
        Get the memory footprint of a model. This will return the memory footprint of the current model in bytes.
        Useful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the
        PyTorch discussions: https://discuss.pytorch.org/t/gpu-memory-that-model-uses/56822/2

        Arguments:
            return_buffers (`bool`, *optional*, defaults to `True`):
                Whether to return the size of the buffer tensors in the computation of the memory footprint. Buffers
                are tensors that do not require gradients and not registered as parameters. E.g. mean and std in batch
                norm layers. Please see: https://discuss.pytorch.org/t/what-pytorch-means-by-buffers/120266/2
        )rx  r|   Únelementrp  r}   )r@   Úreturn_buffersr    ÚmemÚbufÚmem_bufss         rA   Úget_memory_footprintzModelMixin.get_memory_footprintn  sˆ   € ô ÈÏÉÔHYÓZÑHY¸u�5—>‘>Ó# e×&8Ñ&8Ó&:Ó:ÐHYÑZÓ[ˆÙÜÈ4Ï<É<Ì>ÓZÉ>ÀC˜CŸL™L›N¨S×-=Ñ-=Ó-?Ó?È>ÑZÓ[ˆHØ˜‘.ˆCØˆ
ùò	 [ùâZs   ˜(BÁ (BrÎ   c                 óô   — d}| j                  «       D ]>  \  }}t        |d«      sŒt        j                  d|› d|› d�«       ||_        ||_        d}Œ@ |s#t        d| j                  j                  › d�«      ‚y )	NFrÁ   z Setting `gradient_checkpointing=z` for 'Ú'TzThe module z© does not support gradient checkpointing. Please make sure to use a module that supports gradient checkpointing by creating a boolean attribute `gradient_checkpointing`.)	r”   r•   r  Údebugr³   rÁ   ry   r´   rL   )r@   rÎ   rÆ   Úis_gradient_checkpointing_setr�   ri   s         rA   rÐ   z&ModelMixin._set_gradient_checkpointing€  s”   € ð ).Ð%à ×.Ñ.Ö0‰LˆD�&Ü�vÐ7Õ8Ü—‘Ð?À¸xÀwÈtÈfÐTUÐVÔWØ6Q�Ô3Ø06�Ô-Ø04Ñ-ð 1ñ -ÜØ˜dŸn™n×5Ñ5Ð6ð 7~ð óð ð -rC   c                 óP  ‡‡— g Šˆˆfd„Š ‰d| «       ‰D �]  }|› d�|v r|j                  |› d�«      ||› d�<   |› d�|v r|j                  |› d�«      ||› d�<   |› d�|v r|j                  |› d�«      ||› d�<   |› d	�|v r|j                  |› d	�«      ||› d
�<   |› d�|v r|j                  |› d�«      ||› d�<   |› d�|v r|j                  |› d�«      ||› d�<   |› d�|v r|j                  |› d�«      ||› d�<   |› d�|v sŒó|j                  |› d�«      ||› d�<   �Œ |S )aK  
        This function fix the state dict of the model to take into account some changes that were made in the model
        architecture:
        - deprecated attention blocks (happened before we introduced sharded checkpoint,
        so this is why we apply this method only when loading non sharded checkpoints for now)
        c                 ó¶   •— t        |d«      r|j                  r‰j                  | «       |j                  «       D ]  \  }}| dk(  r|n| › d|› �} ‰||«       Œ y )NÚ_from_deprecated_attn_blockrX  rb  )r•   r�  rá  Únamed_children)r�   ri   Úsub_nameÚ
sub_moduleÚ deprecated_attention_block_pathsÚrecursive_find_attn_blocks       €€rA   r’  zJModelMixin._fix_state_dict_keys_on_load.<locals>.recursive_find_attn_block›  s_   ø€ Ü�vÐ<Ô=À&×BdÒBdØ0×7Ñ7¸Ô=à(.×(=Ñ(=Ö(?Ñ$�˜*Ø'+¨r¢z™8¸$¸¸qÀÀ
Ð7K�Ù)¨(°JÕ?ñ )@rC   rX  z.query.weightz.to_q.weightz.query.biasz
.to_q.biasz.key.weightz.to_k.weightz	.key.biasz
.to_k.biasz.value.weightz.to_v.weightz.value.biasz
.to_v.biasz.proj_attn.weightz.to_out.0.weightz.proj_attn.biasz.to_out.0.bias)rl  )r@   rp  rd  r‘  r’  s      @@rA   rå  z'ModelMixin._fix_state_dict_keys_on_load’  s¼  ù€ ð ,.Ð(õ	@ñ 	" " dÔ+ô 5ˆDð ��}Ð%¨Ñ3Ø4>·N±NÀdÀVÈ=ÐCYÓ4Z�
˜d˜V <Ð0Ñ1Ø��{Ð# zÑ1Ø2<·.±.ÀDÀ6ÈÐAUÓ2V�
˜d˜V :Ð.Ñ/ð ��{Ð# zÑ1Ø4>·N±NÀdÀVÈ;ÐCWÓ4X�
˜d˜V <Ð0Ñ1Ø��yÐ! ZÑ/Ø2<·.±.ÀDÀ6ÈÐASÓ2T�
˜d˜V :Ð.Ñ/ð ��}Ð%¨Ñ3Ø4>·N±NÀdÀVÈ=ÐCYÓ4Z�
˜d˜V <Ð0Ñ1Ø��{Ð# zÑ1Ø2<·.±.ÀDÀ6ÈÐAUÓ2V�
˜d˜V :Ð.Ñ/ð �Ð(Ð)¨ZÑ7Ø8B¿¹È$ÈÐO`ÐGaÓ8b�
˜d˜VÐ#3Ð4Ñ5Ø��Ð'¨:Ò5Ø6@·n±nÈÀvÈ_ÐE]Ó6^�
˜d˜V >Ð2Ó3ð3 5ð4 ÐrC   r>   )rf   N)TNTNÚ10GBF)FFNTNNNNNNFF)FF)T)SrL   rM   rN   rO   r   Úconfig_nameÚ_automatically_saved_argsrÏ   rC  rf  rŒ   r  r  r  r.  r2  Ú
_skip_keysrB   rƒ   r   r»   ÚpropertyÚboolrÅ   r	   rÑ   rÓ   r×   rÞ   rà   rå   ré   rë   rï   ró   rõ   rn   rÂ  r™   r‚   r   r   r�   r  r   rÒ  r!  rC  rE  rc  ÚPathLiker˜  rš  Úclassmethodr   r   rû  r   r	  ré  r  r  r  r1   r/   Údictr0   rì  r   rP   r   r   rç  rd  rh  rà  r  r†  rÊ   rË   rÐ   rå  Ú__classcell__©r´   s   @rA   r­   r­   æ   sx  ø„ ñð €KÚ VÐØ',Ð$Ø)-Ð&ØÐØ ÐØ'+Ð$Ø!%ÐØÐØÐØ€HØ€Jô1ð
) ð )¨õ )ð$ ðn¨4ò nó ðnñoÈÐTXÉð oÐdhó oó<;ð=°ð =¸$ó =ó /ó0ð PTñ9Ø'+ð9Ø=EÈ¹_ð9à	ó9ñ"I¸ÀD¹ó Iò0ñ1Àð 1ÐU]Ð`dÑUdð 1Ðptó 1ñMÀxÐRVÁð MÐbfó Mó@@ð &+×%8Ñ%8Ø,0Ø7;ØIMØ"ñS
à—{‘{ðS
ð —{‘{ TÑ)ðS
ð $ C¨ H™o°Ñ4ð	S
ð
 $ D¨¯©¯©Ñ$9¸3Ð$>Ñ?À$ÑFðS
ð ðS
ð 
óS
ðp (4 u§|¡|°EÓ':Ø)Ø+/Ø"Ø Ø#ØØ+/Ø$(Ø%)ñB
à—|‘|ðB
ð Ÿ™ðB
ð ð	B
ð
 " D™jðB
ð ðB
ð ðB
ð ðB
ð " D™jðB
ð ˜T‘zðB
ð ˜d™
ðB
ð 
óB
ðH<>¨Sð <>°Tó <>ó|0ð, !%Ø)-Ø#'Ø"Ø$*Ø!ñYà˜bŸk™kÑ)ðYð ðYð   $‘ð	Yð
 !ðYð �t‘ðYð ˜c™	ðYð óYòv
-ð ØðZ¸CÀ"Ç+Á+Ñ<MÐPTÑ<Tð ZÐcgò Zó ó ðZñz ˆ5�8‰8�?‰?×ÑÓ ó-ó !ð-ñ4 ˆ5�8‰8�?‰?×ÑÓó.+ó ð.+ôb'ô(òðJ ?Cò	URð Ð!6Ñ6ðURð �cÐ3Ð3Ñ4°tÑ;ó	URðn ð ).Ø).Ø26Ø"&Ø*.Ø15ØUYØ*.Ø37Ø48Ø38Ø"ñ%_`ð  ð_`ð " #™Yð	_`ð
 (+¨R¯[©[Ñ'8ð_`ð ˜#‘Yð_`ð "&ð_`ð #'ð_`ð )¨4Ñ/ð_`ð  ð_`ð �U—[‘[Ñ  4Ñ'ð_`ð # 3™i¨$Ñ.ð_`ð ˜#‘I §¡Ñ,¨t°C¸¸s¹ÀUÇ\Á\Ñ9QÐ4QÑ/RÑRð_`ð ! 4™Kð_`ð ˜bŸk™kÑ)¨DÑ0ð_`ð  ˜3 	˜>Ñ*¨TÑ1ð!_`ð" &*¨D¡[ð#_`ð$ ò%_`ó ð_`ðB ñ5ó ð5ð'°ó 'ð: ð¨U¯[©[ð ¸U¿[¹[ò ó ðð4 ð*˜Ÿ™ò *ó ð*ð ð)�u—{‘{ò )ó ð)ñ> ¨Tð > Ètð > Ð`có > ó@ð& "È5Ï;É;×KaÑKa×KlÑKlñØðØ@Hðà	óð$1°{ð 1Àt÷ 1rC   r­   c                   ó\   ‡ — e Zd ZdZeedeej                  z  dz  fˆ fd„«       «       Z	ˆ xZ
S )ÚLegacyModelMixinz³
    A subclass of `ModelMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
    pipeline-specific classes (like `DiTTransformer2DModel`).
    r›  Nc                 óð  •— ddl m} |j                  «       }|j                  dd «      }|j                  dd«      }|j                  dd «      }|j                  dd «      }|j                  dd «      }	|j                  d	d «      }
|j                  d
d «      }|}t        dddœ} | j
                  |f|dd||||	|
||dœ
|¤Ž\  }}} ||| «      }|| u rt        t        |�"  |fi |¤ŽS  |j                  |fi |¤ŽS )Nr.   )Ú_fetch_remapped_cls_from_configr�  rŸ  Fr¡  r£  rT  r¤  r¦  r³  r´  rµ  T)
r�  r¹  rº  rŸ  r¡  r£  rT  r¤  r¦  r»  )	Úmodel_loading_utilsr¡  rÔ  rl  r   rÓ  r²   rŸ  rû  )rí  r›  rK   r¡  Úkwargs_copyr�  rŸ  r¡  r£  rT  r¤  r¦  rð  r»  rÍ  r7  Úremapped_classr´   s                    €rA   rû  z LegacyModelMixin.from_pretrainedÌ  s<  ø€ õ 	Ið —k‘k“mˆà—J‘J˜{¨DÓ1ˆ	ØŸ™Ð$4°eÓ<ˆØ—*‘*˜Y¨Ó-ˆØ!Ÿ:™:Ð&8¸$Ó?ÐØ—
‘
˜7 DÓ)ˆØ—:‘:˜j¨$Ó/ˆØ—J‘J˜{¨DÓ1ˆ	ð 4ˆô %Ø Ø"ñ
ˆ
ð '�s—‘Øð
àØ!%Ø#Ø)ØØ-ØØØØ!ñ
ð ñ
‰ˆ��1ñ 9¸ÀÓEˆà˜SÑ ÜÔ)¨>ÑJØ-ñØ1<ñð ð 2�>×1Ñ1Ð2OÑ_ÐS^Ñ_Ð_rC   )rL   rM   rN   rO   rš  r   rƒ   rc  r™  rû  rœ  r�  s   @rA   rŸ  rŸ  Æ  s=   ø„ ñð
 Øð/`¸CÀ"Ç+Á+Ñ<MÐPTÑ<Tô /`ó ó ô/`rC   rŸ  )urÔ  rH  r\  rz   r  rc  rD  rK  rF  Úcollectionsr   Ú
contextlibr   r   r   Úpathlibr   Útypingr   r	   r
   r   ry  rn   Útorch.utils.checkpointÚhuggingface_hubr   r   r   Úhuggingface_hub.utilsr   r   r   Útyping_extensionsr   rX  r   Ú
quantizersr   r   Úquantizers.quantization_configr   rÊ   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   Úutils.distributed_utilsr)   Úutils.hub_utilsr*   r+   r,   Úutils.torch_utilsr-   Ú_modeling_parallelr/   r0   r1   r¢  r2   r3   r4   r5   r6   r7   r8   r9   r;   Ú
get_loggerrL   r  r  ru  r©   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r§   rÎ  râ  rb   Úaccelerate.utilsrc   rd   r�   r   rˆ   r™   r£   r«   r­   rŸ  rQ   rC   rA   Ú<module>rµ     s  ðó" Û Û Û Û Û 	Û 	Û Û Ý #ß 0Ý Ý ß 6Ó 6ã Û Û ß VÑ VÝ 6ß Ý "å ß CÝ ?÷÷ ÷ ÷ õ õ& >ß \Ñ \Ý 2ß _Ñ _÷	÷ 	ó 	÷-ñ -ð$ 
ˆ×	Ñ	˜HÓ	%€àˆr�z‰zÐ1Ó2€ð —‘× Ñ Ø�w‰w�‰Ø—W‘W×*Ñ*Ø—‘×"Ñ"Ø—w‘w×.Ñ.Ø—g‘g×,Ñ,ØŸ™×0Ñ0Ø—w‘w×.Ñ.Ø�w‰w�‰Ø�g‰g�n‰nØ—g‘g×,Ñ,Ø—W‘W×*Ñ*Ø—w‘w×.Ñ.Ø—g‘g×,Ñ,ñÐ ñ" �D˜'Ô"Ø!%Ñà!&Ðñ ÔÛÝ)ßKð% E§H¡H§O¡Oð %¸¿¹ó %ð44# 5§8¡8§?¡?ð 4#°u·{±{ó 4#ðn ñ4ó ð4ô&]�—‘—‘ .ô ]ô@77`�zõ 7`rC   