
    bi7\                       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mZ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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZF ddlGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO  G d d      ZP e@j                  eR      ZS ej                  d      ZUe%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Ze e?dd      rdZfndZf e;       rd dlgZgd dlgmhZh d dlimjZjmkZk dejJ                  j                  dej                  fd ZndejJ                  j                  dej                  fd!Zped"        Zq G d# d$ejJ                  j                  eB      Zr G d% d&er      Zsy)'    N)OrderedDict)	ExitStackcontextmanager)wraps)Path)	AnyCallableContextManagerDictListOptionalTupleTypeUnion)	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)PushToHubMixinload_or_create_model_cardpopulate_model_card)empty_device_cache   )_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     Z/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/modeling_utils.py__init__zContextManagers.__init__V   s     0[
    c                 \    | j                   D ]  }| j                  j                  |        y r?   )r=   r@   enter_context)rA   context_managers     rB   	__enter__zContextManagers.__enter__Z   s)    #44 	6OJJ$$_5	6rD   c                 <     | j                   j                  |i | y r?   )r@   __exit__)rA   argskwargss      rB   rJ   zContextManagers.__exit__^   s    

T,V,rD   N)	__name__
__module____qualname____doc__r   r
   rC   rH   rJ    rD   rB   r<   r<   P   s"    
!n)= !6-rD   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       rB   find_tensor_attributesz4get_parameter_device.<locals>.find_tensor_attributes   sA    )/)>)>)@WAEOOTUDVq!fWFWM X
   AAget_members_fnr2   )hooks.group_offloadingrh   
ValueError	itertoolschain
parametersbuffersnextdeviceStopIterationrn   r   Moduler   r   strr   _named_members)re   rh   parameters_and_buffersrt   genfirst_tuples         rB   get_parameter_devicer      s    A'	22 % "+1E1E1GIZIZI\!]*+222 	%	588?? 	tE#v+DV?W 	 &&6L&M3i1~$$$	%s    	AA' 'A-CCc                 Z   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         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     rB   	<genexpr>z&get_parameter_dtype.<locals>.<genexpr>   s     G!AIGs   ri   rf   c                     | j                   j                         D cg c]  \  }}t        j                  |      s||f! }}}|S c c}}w r?   rk   rp   s       rB   rt   z3get_parameter_dtype.<locals>.find_tensor_attributes   sA    %+__%:%:%<STQPQ@R1a&SS Tru   rv   r2   )
isinstancer   r   named_moduleshasattrr   get_hookcompute_dtypenamed_parametersdtyper   anyis_floating_pointr}   r   r   r   r   r   )re   	submoduleregistryhook
last_dtypeparambufferrt   r   
last_tupletupler   s              @rB   get_parameter_dtyper      s   
 )RYY'(668 	*OD)9&78 00H$$%89D)))	* J 113 
e[[
I67//Gy'F'FGG""$;;
 ##%  \\
##%<< 
 ryy T%V:L5M  
"
"2H
"
ICJ "
8%%'8>>!"
 !}""" rD   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   )rK   rL   s     rB   
_skip_initz#no_init_weights.<locals>._skip_init   s    rD   N)TORCH_INIT_FUNCTIONSrm   setattrrn   r   init)r   r   	init_funcs      rB   no_init_weightsr      s      0557 1itZ014  499; 	4OD)EHHMM43	4399; 	4OD)EHHMM43	4s    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 fdZdedef fd	Zedefd
       ZdZdee   ddfdZd[dZdeddfdZd[dZd[dZ	 dZdedee   ddfdZdZdee   fdZd Z	 dZdedee   ddfdZdZdee   ddfdZ d[dZ!e"jF                  ddddfde"jH                  dee"jH                     dee%edf      dee%e&e"jN                  jP                     df      d eddfd!Z) e"jT                  d"      d#ddddddfd$e"jT                  d%e"jT                  d&ed'ee+   d ed(ed)ed*ee   ddfd+Z,d,eddfd-Z-d[d.Z.	 	 	 	 	 	 d\d/e/ee0jb                  f   d0ed1ee   d2ed3ee   d4e/e+ef   d5efd6Z2d7 Z3e4e5d8ee/ee0jb                  f      de6fd9              Z7 e8e"jN                  jP                  jr                         fd:       Z9 e8e"jN                  jP                  jt                         fd;       Z: fd<Z; fd=Z<d> Z=e4	 	 	 	 	 	 	 	 	 	 	 d]d?e>d@e?e   d8e/ee0jb                  f   dAe?e   dBedCedDee@   dEedFee/ee"jH                  f      dGee?e      dHe/ee+e"jT                  eAee/e+ee"jT                  f   f   f   dIee   dJee/ee0jb                  f      dKeeAeeBf      dLee   fdM       ZCe4dN        ZDdHefdOZEe4dFe"jH                  de"jH                  fdP       ZFede"jT                  fdQ       Z*ede"jH                  fdR       Z$d^dSedTede+fdUZGd_dVZHde"j                  j                  j                  fdWededdfdXZKd?e>ddfdYZL xZMS )`
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?   )superrC   _gradient_checkpointing_func)rA   	__class__s    rB   rC   zModelMixin.__init__   s    ,0)rD   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   typerM   r'   r   r   __getattr__)rA   r   is_in_configis_attributedeprecation_messager   s        rB   r   zModelMixin.__getattr__  s     (4==8kWT]]ScEdfj=kt}},$@FVW[\`WaWjWjVk  l]  ^b  ]c  ck  lp  qu  lv  l  l  k@  @l  mq  lr  rt  #u17<O_dqrs&&t,, w"4((rD   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     rB   r   z7ModelMixin.is_gradient_checkpointing.<locals>.<genexpr>  s'     mYZ7167TA<T<TTm   $&)r   modulesrA   s    rB   is_gradient_checkpointingz$ModelMixin.is_gradient_checkpointing  s    
 m^b^j^j^lmmmrD   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   rK   ckpt_kwargss      rB   r   zNModelMixin.enable_gradient_checkpointing.<locals>._gradient_checkpointing_func,  sO    :J4QY:Z6`b{{--88OO " rD   T)enabler   ) _supports_gradient_checkpointingry   r   rM   _set_gradient_checkpointing)rA   r   r   s      rB   enable_gradient_checkpointingz(ModelMixin.enable_gradient_checkpointing  s`     44>>**+ ,X Y 
 '. +G'((Rm(nrD   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    rB   disable_gradient_checkpointingz)ModelMixin.disable_gradient_checkpointing8  s#    
 00,,E,: 1rD   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     rB   r   zTModelMixin.set_use_npu_flash_attention.<locals>.fn_recursive_set_npu_flash_attentionE  s:    v<=2259* <4U;<rD   Nrn   r   r   r   r   )rA   r   ri   r   s    ` @rB   r   z&ModelMixin.set_use_npu_flash_attention@  sH    
	< 	< mmo 	=F&%((//24V<	=rD   c                 &    | j                  d       y)z<
        Enable npu flash attention from torch_npu

        TNr   r   s    rB   enable_npu_flash_attentionz%ModelMixin.enable_npu_flash_attentionP  s    
 	((.rD   c                 &    | j                  d       y)z=
        disable npu flash attention from torch_npu

        FNr   r   s    rB   disable_npu_flash_attentionz&ModelMixin.disable_npu_flash_attentionW  s    
 	((/rD   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_attentionrL   r   r   s     rB   r   zPModelMixin.set_use_xla_flash_attention.<locals>.fn_recursive_set_flash_attentiond  sE    v<=2223JNe^de* 8078rD   r   )rA   r   r   rL   ri   r   s    ``` @rB   r   z&ModelMixin.set_use_xla_flash_attention^  sM    	8UXX__ 	8 	8 mmo 	9F&%((//208	9rD   c                 ,     | j                   d|fi | y)zJ
        Enable the flash attention pallals kernel for torch_xla.
        TNr   )rA   r   rL   s      rB   enable_xla_flash_attentionz%ModelMixin.enable_xla_flash_attentiono  s     	)((~HHrD   c                 &    | j                  d       y)zK
        Disable the flash attention pallals kernel for torch_xla.
        FNr   r   s    rB   disable_xla_flash_attentionz&ModelMixin.disable_xla_flash_attentionu  s     	((/rD   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     rB   r   zXModelMixin.set_use_memory_efficient_attention_xformers.<locals>.fn_recursive_set_mem_eff  s<    vLMBB5,W* 0(/0rD   r   )rA   r   r   ri   r   s    `` @rB   r   z6ModelMixin.set_use_memory_efficient_attention_xformers{  sH    	0UXX__ 	0 mmo 	1F&%((//2(0	1rD   c                 (    | j                  d|       y)uE  
        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.

        <Tip warning={true}>

        ⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
        precedent.

        </Tip>

        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   )rA   r   s     rB   *enable_xformers_memory_efficient_attentionz5ModelMixin.enable_xformers_memory_efficient_attention  s    D 	88|LrD   c                 &    | j                  d       y)zs
        Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
        FNr   r   s    rB   +disable_xformers_memory_efficient_attentionz6ModelMixin.disable_xformers_memory_efficient_attention  s     	88?rD   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   )rA   r   r   r   r   r   r   user_provided_patternsr   r   r   r   layers                rB   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	: I$e.G.G(HH$I  KKqr JJM-0DFZ\h	
rD   cpublock_levelonload_deviceoffload_deviceoffload_typenum_blocks_per_group
use_streamrecord_streamoffload_to_disk_pathc
                     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  getattrr  warning_supports_group_offloadingry   r   rM   )rA   r  r  r  r  r   r  r  r  r  r  msgs               rB   enable_group_offloadzModelMixin.enable_group_offload  s    D 	34$/;l\a@bgqe  NN3..>>**+ ,T U 
 	')%!5%!'/!5	
rD   backendc                    ddl m} ddlm}m} ddlm}m} t        j                  d       |j                         }|j                  j                         D ch c]  }|j                   }}||vr!t        d|ddj                  |      z          ||      } ||       |||f}	| j!                         D ]1  }
t#        |
|	      s|
j$                  }|t'        |d
      s+||_        3 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.
        r2   AttentionModuleMixin)AttentionBackendName%_check_attention_backend_requirements	AttentionMochiAttentionTAttention backends are an experimental feature and the API may be subject to change.z	`backend=z ` must be one of the following: , N_attention_backend)	attentionr#  attention_dispatchr$  r%  attention_processorr'  r(  r  r  lower__members__valuesvaluery   joinr   r   	processorr   r+  )rA   r   r#  r$  r%  r'  r(  xavailable_backendsattention_classesri   r4  s               rB   set_attention_backendz ModelMixin.set_attention_backendJ  s     	4c 	Cmn--//C/O/O/V/V/XY!aggYY,,z
*JKdiiXjNkkll&w/-g6&8LMlln 	3Ff&78((I 	;O(P+2I(	3 Zs   C,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 or
        the torch native scaled dot product attention.
        r2   r"  r&  r)  Nr+  )r,  r#  r.  r'  r(  r  r  r   r   r4  r   r+  )rA   r#  r'  r(  r7  ri   r4  s          rB   reset_attention_backendz"ModelMixin.reset_attention_backendm  sn    
 	4Bmn&8LMlln 	0Ff&78((I 	;O(P+/I(	0rD   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)rE  rG  rI  )r@  filename_pattern z{suffix}formatpt)metadata)rP  
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 )rI  z	README.md)rI  rF  rH  )7ospathisfiler  errorr  r   r   is_serializablery   quantization_configquant_methodr!   r#   r$   replacemakedirspopsplitsepr   rJ  save_config
state_dictr   listdirfilename_to_tensorskeysr3  
startswith_REGEX_SHARD	fullmatchremoverm   
contiguoussafetensorsrn   	save_filesave
is_shardedrP  tensor_to_filenamer    r"   openjsondumpswriter	  lenr/   r0   r   as_posix_upload_folder)#rA   r;  r<  r=  r>  r?  r@  rA  rL   rC  quantization_serializableweights_nameweights_name_patternrF  rG  rH  rI  rJ  model_to_savere  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#                                      rB   save_pretrainedzModelMixin.save_pretrained  s   X 77>>.)LL?>*::]^_t^T:#D( 1|-?@1 00 &
 - 2<3S3S3`3`2a by y 
 4F/<#L':+33FNKSS2 
 	NT2#ZZ(8$?NjjD1G

;6IJJw-EjjN,@,@,Mb,QRG!'D'QVW__G  %%n5 #--/
 >~H\

 JJ~6 -/CCHHJJ "^X Fww~~m4&:&B&B62&N&V&VWegi&j#&9&A&A*b&Q#'/'7'7'C'K'KN\^'_$ ''(;<$../CDPIIm,-  "2!E!E!K!K!M 	,HgKRSVZ/::<<SESww||NH=H! !!++E8xQUFV+W

5(+	, &&,55.AAE :L5QcO ggll><Y`;abOosW= !**U1EL ! KKL^L\ ] 0 D DEF G$$3#4A7 !ggll><HOKK1/1BCD27%HJ,Z8JOOD=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.
        rC  Nz?You need to first quantize your model in order to dequantize it)r  ry   
dequantize)rA   rC  s     rB   r  zModelMixin.dequantize  s5    
 t^T:^__&&t,,rD   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      }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.d/}i }|} | j$                  |f|dd|||	|
||||d0|\  }}}t'        j(                  |      }d|v xr |d   du}|s|?|rt+        j,                  |d   |      |d<   n||d<   t+        j.                  |d   |1      } nd} | | j1                  |||2       | j3                  |      }| j5                  |      }| j6                  j8                  j:                  |d3<   |d}t        j=                  d4       n|st        d5      | j>                  duxr | du xs tA        | d6d      }!|!rF| j>                  }"t	        |"tB              s|"g}"|d}t        j=                  d7       n|st        d8      g }"d}#d}$d}%d}&tD        jF                  jI                  |      }'|'||xs d$||||||	|
||||d9}(tK        dNi |(}&|,|&tD        jF                  jM                  |&      stO        dNi |(}&|&|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
        dCd      k(  sEt	        |t
        j                        st        | dDtg        |       d'      | ji                  |      },tk               g}-|r#|-jm                  to        jp                                ts        |-      5   | j.                  |fi |})ddd       |,t        jt                  |,       d}.|#s"tw        |$d(   ||E      }.)jy                  |.       |#r|%dF   }/ntC        |.j{                               }/| | j}                  )||"G       t        )||||"|       }| | j1                  |H       | j                  |)|.|$||/||||||| |"||I      \  })}0}1}2}3}4|0|1|2|4dJ}5||||3dK}6t        |)fi |6 | | j                  |)       | |)_C        |)|tA        t
        dCd      k(  r| |!s|)j                  |      })| |)j                  ||L       n|)j                  |M       |)j                          |r|)|5fS |)S # t        $ r t        d&| d'      w xY w# t`        $ r>}+t        jc                  d@| dA|+        |s t        j                  dB       Y d}+~+d}+~+ww xY w# 1 sw Y   xY w)OuL!  
        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 (`Union[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 (`Union[int, str, torch.device]` or `Dict[str, Union[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.

        </Tip>

        Example:

        ```py
        from diffusers import UNet2DConditionModel

        unet = UNet2DConditionModel.from_pretrained("runwayml/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 runwayml/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_onlyrI  revisiontorch_dtype	subfolder
device_map
max_memoryoffload_folderoffload_state_dictr  r?  use_safetensorsr]  dduf_entriesdisable_mmapzEParallel 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
```
.zLoading 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`.rM  )autobalancedbalanced_low_0
sequentialzWhen 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 rW  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  rI  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  r?  r  r  r  rI  r  r  commit_hashr  zFLoading of sharded checkpoints is not supported when `from_flax=True`.)
r{  r  r  r  r  rI  r  r  r  r  r2   )%load_flax_checkpoint_in_pytorch_model)r  r  r  rI  r  r  r  r  )r{  r  r  r  r  rI  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   rC  r  r  is_parallel_loading_enabled)missing_keysunexpected_keysmismatched_keys
error_msgs)r  offload_diroffload_index)r   _pre_quantization_dtype)r   rQ   )Gra  _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_mapr]  r^  r2  r	  r   r  listrX  rY  isdirr6   existsr7   is_filer&   r   modeling_pytorch_flax_utilsr  r%   r$   r!   IOErrorr[  r#   r   _set_default_torch_dtyper   append
accelerateinit_empty_weightsr<   set_default_dtyper:   _fix_state_dict_keys_on_loadrh  preprocess_modelr4   _load_pretrained_modelrb   postprocess_modelrC  toregister_to_configeval)7clsr  rL   r  r  r  r  r  r  r  rI  r  r  r  r  r  r  r  r  r?  r  r]  r  r  r  allow_pickler  unused_kwargsconfig_pathconfigr  r  rC  r  r  rq  resolved_model_filesharded_metadata
index_filer  index_file_kwargsr  r  e
dtype_originit_contextsre  loaded_keysr  r  r  r  r  loading_infodevice_map_kwargss7                                                          rB   from_pretrainedzModelMixin.from_pretrained'  sL
   N JJ{D1	"(**-F"N$4e<JJ{E2	**Y-$jj)>F!::&8$?

7D)::j$/jj5JJ{D1	ZZd3
ZZd3
$4d;#ZZ(<dC"JJ':<VW**Y- **%6=$jj)>E7=zz.RV7Wzz.%8&@#&/@%&mnn":k5;;+O--KNN'}4kl ""OL%<%> %NN. !*A*C%`  !*:4*I%& 
 $-=dG-L%. 
 %**@WXbWc dR R  j%,,/j)J
C(Z?s-s %,,z":;
 
C(A~  E  !*-
! ($(!& !abb%.>tV.L !`aa % "


  4 .=S__.
!%#)-!%.
 .
*{  v& .7eFCX<Yae<e/;0F0a0a013F1,- 1D,-1==,-]L  L#--+QZgq-r&99+FK%77
CJ #/"B"B"O"O"U"UJw !($(!\]& !ghh $'#<#<D#H $
D \GL:TV[$\ 	! $#&#<#< 2D9(<'=$ ($(!ef& !kll#% 
"  
77==!>? -J"b.", 0 $&(
  ';):;
 J$6bggnnZ>X1F4EFJ!|z7I7I7KJ)eff "1-.#-!1!#%'# $COOF<m<E [9%ATUE 8S1'#%5)%'o2!-95#%5 !*95%12JG%T"+'5 ')9#!)"+#-$/%1+'. #*:&51!-lG!D'#1#%5%') +!-'# -t4#6"7
 
";'%Z^:_+_k5;;7 "m#deijuevdwwxy  55kBJ(*+  !>!>!@A]+ 	=#COOF<m<E	= !##J/
()<Q)?liuvJ..z:*+@AKz01K#))
I] * 
 +:z;8Ll

 #---D &&)$;/!)1%!5%(C ' 
	
& )..$	
 !(-!.!
 56$56#**51!-E #wuotDD$,HH[)E# $$3Pju$v$$3P$Q 	

,&&O
    TT^S__`b z  LL#KLiKjjlmnlo!pq'NNr 	V	= 	=s0   _9 %` >a9`	a3aaa)c                 R   ddl m} t        | dd       t        j                  k(  r=t        | dd      rt        d      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_8bitFzCalling `cuda()` is not supported for `8-bit` quantized models.  Please use the model as it is, since the model has already been set to the correct devices.<0.43.2zCalling `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_BYTESry   r*   r   r  r  r   rM   r   cuda)rA   rK   rL   r  r   s       rB   r  zModelMixin.cudaE  s    F 4.59K9Z9ZZt0%8 s  )h7 ..2kk]  ;GH  %T*NNt~~6677{| Kw|T,V,,rD   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(  r=t        | dd      rt        d      t        dd      rt        d| j                   d       ||       r1|r/t        j                  d| j                   j"                   d       | S t%        | L  |i |S # t        $ r Y w xY w)Nr   r  c              3   P   K   | ]  }t        |t        j                           y wr?   )r   rn   r   )r   args     rB   r   z ModelMixin.to.<locals>.<genexpr>d  s     )XC*S%,,*G)Xr   r   r   Tis_quantizedFzCasting 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  z`.to` is not supported for `8-bit` bitsandbytes models. Please use the model as it is, since the model has already been set to the correct devices and casted to the correct `dtype`.r  r  zCalling `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   rM   r   r  )rA   rK   rL   r  device_arg_or_kwarg_presentdtype_present_in_argsr  r   s          rB   r  zModelMixin.to`  s   F&))XSW)X&X&n\dhn\n# '6 1  	Cc3'S!.2+	 % c5;;/,0)
 4/$ z 
 4.59K9Z9ZZt0%8 l  )h7 ..2kk]  ;GH 
 %T*/JNNt~~6677yz Kwz4*6**E   s   D88	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rA   rK   r   s     rB   r  zModelMixin.half  s3    4/G 
 7<&&rD   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     rB   r  zModelMixin.float  s3    4/G 
 7=$''rD   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   rM   r   compile)rA   rK   rL   repeated_blockshas_compiled_regionsubmods         rB   compile_repeated_blocksz"ModelMixin.compile_repeated_blocks  s     "$(:DA99=9P9P8QQwy  $lln 	+F((O;//&*#	+
 #66GGlm  #rD   re  r  r  r  assign_to_params_buffersrC  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||||
|||||||||||	d}|r ||      \  }}}}||z  }||z  }nE|} t)        |      d	kD  rt+        j,                  |d
      } | D ]  }! ||!      \  }}}}||z  }||z  } t/                |@t)        |      dkD  r2t1        ||       d }|r"t3        |||       t5        j6                  |       t)        |      dkD  r?dj9                  |      }"d|"v r|"dz  }"t;        d|j<                  j>                   d|"       t)        |      dkD  r9t@        jC                  d| d| j>                   ddj9                  |      g        n-t@        jE                  d|j<                  j>                   d       t)        |      dkD  r4t@        jC                  d|j<                  j>                   d| d| d       nUt)        |      dk(  rGt@        jE                  d|j<                  j>                   d| d|j<                  j>                   d       t)        |      dkD  rdd j9                  |D #$%cg c]  \  }#}$}%d!|# d"|$ d#|% d$ c}%}$}#      }&t@        jC                  d|j<                  j>                   d| d%|& d       ||||||fS c c}w c c}%}$}#w )&NrM  )prefixdiskzThe 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.TrD  )NN)r  model_state_dictr  r   rC  r  r  r  r  r  r  state_dict_indexstate_dict_folderr  r  r2   zLoading checkpoint shards)descr   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.rV  z- z: found shape z in the checkpoint and z in the model instantiatedz= and are newly initialized because the shapes did not match:
)#re  r  rh  r  update_missing_keys"_keys_to_ignore_on_load_unexpectedresearchr1  ry   rX  r`  r5   r3   tempfilemkdtemp	functoolspartialr9   r8   rw  r-   tqdmr1   rd   rc   shutilrmtreer3  r  r   rM   r  r  r	  )'r  r  re  r  r  r  r  r  rC  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_file	error_msgkeyshape1shape2mismatched_warnings'                                          rB   r  z!ModelMixin._load_pretrained_model  s   ( !++--2245C.[1AAB#';;E<XZ;[Ls;/#m2DDE 11=== \.="[3PQARAZ1"["[\ 
 !f
0A0A0C&C% :  NT:!)%)" !"4Z"O%e-@%V(4:CTCTCV9V\`.8++ ( 0 0 2!! $., ##1L-Rb
-!%!5%#+')-/$;/!
& 'MTUhMiJM+-={+%J//O-K&'!+%ll+>E`a) 4
QXYcQdN/1A;k)
#334
 	$]);a)?}n= M!&u.>@QR/0z?QJ/I)+w	 !DU__E]E]D^^cdmcnopp!#NN:;X:YYz{~  |H  |H  {I  IN  PT  PY  PY  Zi  Pj  Ok  Nl  m KKSTYTcTcTlTlSmmpqr|q NN"5??#;#;"< =122N|n ]nn
 !Q&KK%eoo&>&>%? @12 3CCH??C[C[B\ ]-- !#!% 0? +VV ^F83J6(Rlm" NN"5??#;#;"< =12 3./ 0AA lO_mU___{ #\bs   P;P+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 )NrA   )	inspect	signaturerC   r|   rm   default_emptyr  rh  )r  objr|   rq   rr   required_parametersoptional_parametersexpected_moduless           rB   _get_signature_keyszModelMixin._get_signature_keysf  s    &&s||4??
0:0@0@0Bb1aiiSZSaSaFaq!tbb!1A1A1C"cAqyyT[TbTbGb1"cd2779:fX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   rK  z does not support `device_map='z_'`. To implement support, the model class needs to implement the `_no_split_modules` attribute.)r  rw  ra  r   rM   r   r   _no_split_modulesry   r  r   )rA   r  r8  modules_to_checkri   s        rB   _get_no_split_modulesz ModelMixin._get_no_split_modulesp  s      E 6"#a'%))"-F((0AAfj1//7(%//8899XYcXd eZ Z 
 ->FD\D\@],]) D):$;;  "#a' %&&rD   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 rW  )r   ry   rM   r  r	  rn   get_default_dtyper  )r  r   r  s      rB   r  z#ModelMixin._set_default_torch_dtype  sw    " &&$S\\N2EeWLst  	nS\\N2MeWTUVW,,.
&rD   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    rB   r   zModelMixin.device  s     $D))rD   c                     t        |       S )zw
        `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
        )r   r   s    rB   r   zModelMixin.dtype  s    
 #4((rD   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|rt        |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 = "runwayml/stable-diffusion-v1-5"
        unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
        unet.num_parameters(only_trainable=True)
        859520964
        ```
        is_loaded_in_4bitFr   Nzbitsandbytes 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_storager2   r   )r  r)   bitsandbytesry   r   r   r   	Embeddingr   r  r|   requires_grad
Params4bitr   rC  rD  itemsizer  numelsum)rA   r?  r@  rB  bnbr   module_typeembedding_param_namesre   total_parameterstotal_numelr   	num_bytess                rB   num_parameterszModelMixin.num_parameters  sw   0 $D*=uE(** p 
 :>:L:L:N%%6T;R\]hjljvjvRw4& %! % 261F1F1H -dIDXmLm	     $DOO$56% 	6E"". %E366;L;L)Mun5$)$6$6$8	 8$)$7$7$@$@	$%	&&u{{}q'89'DE&&u{{}5	6 ;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
        )rK  r|   nelementrC  r}   )rA   return_buffersr   membufmem_bufss         rB   get_memory_footprintzModelMixin.get_memory_footprint  s~     HYZu5>>#e&8&8&::Z[4<<>ZCCLLNS-=-=-??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   rM   )rA   r   r   is_gradient_checkpointing_setr   ri   s         rB   r   z&ModelMixin._set_gradient_checkpointing	  s     ).% ..0 	5LD&v78?xwtfTUVW6Q306-04-	5 -dnn556 7~   -rD   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_blockrM  rW  )r   r`  r  named_children)r   ri   sub_name
sub_module deprecated_attention_block_pathsrecursive_find_attn_blocks       rB   re  zJModelMixin._fix_state_dict_keys_on_load.<locals>.recursive_find_attn_block$  se    v<=&BdBd077=(.(=(=(? @$*'+rz8$q
7K)(J?@rD   rM  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)ra  )rA   re  rY  rd  re  s      @@rB   r  z'ModelMixin._fix_state_dict_keys_on_load  s    ,.(	@ 	""d+ 5 	_D }%34>NNdV=CY4Z
dV<01{#z12<..D6AU2V
dV:./ {#z14>NNdV;CW4X
dV<01y!Z/2<..D6AS2T
dV:./ }%34>NNdV=CY4Z
dV<01{#z12<..D6AU2V
dV:./ ()Z78B$O`Ga8b
dV#345':56@nnv_E]6^
dV>233	_4 rD   r?   )rf   N)TNTN10GBF)FFNTNNNNNNF)FF)T)NrM   rN   rO   rP   r   config_name_automatically_saved_argsr   r  r8  r   r  r  r  rC   r   r   r   propertyboolr   r   r	   r   r   r   r   r   r   r   r   r   r   r   rn   r  r   r   r   r   r   r  r   r  r  r8  r:  r   rX  PathLiker  r  classmethodr   r   r  r   r  r  r  r  r  r   r   r   r   r   r  r6  r:  r  rR  rY  r   r   r   r  __classcell__r   s   @rB   r   r      s    K V',$)-& '+$!%1
) ) )$ n4 n noRZI[ ogk o<;= =$ = /0 SW9'+9=Eh=O9	9"I(9K I0 ?C11)1();1	1""MxPXGY "Mei "MH@ &+%8%8/3:>LP"S
{{S
  ,S
 'uS#X7	S

 'uT%((//-BC-G'HIS
 S
 
S
p (4u||E':).2" #.2=
||=
 =
 	=

 'sm=
 =
 =
 =
 'sm=
 
=
~!3S !3T !3F0, !%,0#'!%*0!Yc2;;./Y Y  )	Y
 !Y #Y c3hY Yv
- YHU3PRP[P[K[E\<] Ylp Y  Yx 588?? - !-4 588??/+ /+d'(B  ).).59"&3748^b-1<@7;6;#Z`  Z` "#Y	Z`
 (-S"++-='>Z` #YZ` "&Z` #'Z` 12Z`  Z` c5;;./0Z` 'tCy1Z` #sELL$sE#sELLBX<Y7Y2ZZ[Z` %TNZ` !sBKK'7!89Z`  tCN34!Z`" &.d^#Z` Z`x 5 5' ': U[[ U[[  4 * * * )u{{ ) )> T > t > `c > @& "5;;KaKaKlKl@H	$1{ 1t 1rD   r   c                   `     e Zd ZdZeedeeee	j                  f      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  c                    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 )Nr2   )_fetch_remapped_cls_from_configr  r  Fr  r  rI  r  r  r  r  r  T)
r  r  r  r  r  r  rI  r  r  r  )	model_loading_utilsrr  r  ra  r   r  r   rp  r  )r  r  rL   rr  kwargs_copyr  r  r  r  rI  r  r  r  r  r  _remapped_classr   s                    rB   r  z LegacyModelMixin.from_pretrainedU  s<    	I kkmJJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{D1	 4 % "

 's
!%#)-!
 
1 9ES )>J-1<  2>112O_S^__rD   )rM   rN   rO   rP   rl  r   r   r   r   rX  rk  r  rm  rn  s   @rB   rp  rp  O  sD    
 /`HU3PRP[P[K[E\<] /`  /`rD   rp  )tr  r  r.  rz   rt  rX  r  r  r  collectionsr   
contextlibr   r   r   pathlibr   typingr   r	   r
   r   r   r   r   r   r   rn  rn   torch.utils.checkpointhuggingface_hubr   r   r   huggingface_hub.utilsr   r   r   typing_extensionsr   rM  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.hub_utilsr.   r/   r0   utils.torch_utilsr1   rs  r3   r4   r5   r6   r7   r8   r9   r:   r<   
get_loggerrM   r  r  rj  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   rp  rQ   rD   rB   <module>r     s  "      	 	   # 0   Z Z Z    V V 6  "  C ?    & 
 3	 	 	- -$ 
		H	%rzz12   wwWW**""ww..gg,,00ww..wwggnngg,,WW**ww..gg,, " D'"!%!& )K%EHHOO % %44#588?? 4#u{{ 4#n 4 4&d. dN37`z 7`rD   