
    bi8U              	          d dl Z d dlZd dlZd dlmZ d dlmZ d dlZd dlm	Z	 d dl
mZ ddlmZ ddlmZ dd	lmZmZmZ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 m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2  ejf                  e4      Z5 e       rd dl6m7Z7m8Z8 ddl9m:Z:  edd      r
 e       rdZ;ndZ;i dde*ide"e.dddidde#e/dddee-dde)d d!d"deid#deid$ed d!d%ed d!d&e$d d!d'e%dd!d(deid)e'd d!d*e!d d!d+ed d!d,e&d d!d-e(d d!e+d d!e+d d!e,dd!e d d!ed d!d. d d!d/Z<d0 Z=d1 Z>d2 Z? G d3 d4      Z@y)5    N)nullcontext)Optional)validate_hf_hub_args)Self   )__version__)DiffusersAutoQuantizer)	deprecateis_accelerate_availableis_torch_versionlogging)empty_device_cache   )SingleFileComponentError+convert_animatediff_checkpoint_to_diffusers4convert_auraflow_transformer_checkpoint_to_diffusers.convert_autoencoder_dc_checkpoint_to_diffusers2convert_chroma_transformer_checkpoint_to_diffusersconvert_controlnet_checkpoint2convert_cosmos_transformer_checkpoint_to_diffusers0convert_flux_transformer_checkpoint_to_diffusers(convert_hidream_transformer_to_diffusers.convert_hunyuan_video_transformer_to_diffusersconvert_ldm_unet_checkpointconvert_ldm_vae_checkpoint/convert_ltx_transformer_checkpoint_to_diffusers'convert_ltx_vae_checkpoint_to_diffusersconvert_lumina2_to_diffusers1convert_mochi_transformer_checkpoint_to_diffusers%convert_sana_transformer_to_diffusers/convert_sd3_transformer_checkpoint_to_diffusers4convert_stable_cascade_unet_single_file_to_diffusers$convert_wan_transformer_to_diffusersconvert_wan_vae_to_diffusers+create_controlnet_diffusers_config_from_ldm%create_unet_diffusers_config_from_ldm$create_vae_diffusers_config_from_ldmfetch_diffusers_configfetch_original_configload_single_file_checkpoint)dispatch_modelinit_empty_weights)load_model_dict_into_metaz>=z1.9.0TFStableCascadeUNetcheckpoint_mapping_fnUNet2DConditionModelunetnum_in_channelsin_channels)r/   config_mapping_fndefault_subfolderlegacy_kwargsAutoencoderKLvae)r/   r4   r5   ControlNetModel)r/   r4   SD3Transformer2DModeltransformer)r/   r5   MotionAdapterSparseControlNetModelFluxTransformer2DModelChromaTransformer2DModelLTXVideoTransformer3DModelAutoencoderKLLTXVideoAutoencoderDCMochiTransformer3DModelHunyuanVideoTransformer3DModelAuraFlowTransformer2DModelLumina2Transformer2DModelSanaTransformer2DModelc                     | S N )xs    ^/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/loaders/single_file_model.py<lambda>rM      s    1     )WanTransformer3DModelWanVACETransformer3DModelAutoencoderKLWanHiDreamImageTransformer2DModelCosmosTransformer3DModelQwenImageTransformer2DModelc                     t        | j                               j                  t        |j                                      S rI   )setkeysissubset)model_state_dictcheckpoint_state_dicts     rL   '_should_convert_state_dict_to_diffusersr[      s4    #((*+44S9N9S9S9U5VWWWrN   c                     t        j                  t        j                  d      d         }t        D ]  }t        ||      }t        | |      s|c S  y )N.r   )	importlibimport_module__name__splitSINGLE_FILE_LOADABLE_CLASSESgetattr
issubclass)clsdiffusers_moduleloadable_class_strloadable_classs       rL   '_get_single_file_loadable_mapping_classri      sT     ..x~~c/B1/EF: & !13EFc>*%%	& rN   c                 p    t        j                  |       j                  }i }|D ]  }||v s||   ||<    |S rI   )inspect	signature
parameters)
mapping_fnkwargsrm   mapping_kwargs	parameters        rL   _get_mapping_function_kwargsrr      sK    "":.99JN :	(.y(9N9%: rN   c                   <    e Zd ZdZeeddee   defd              Z	y)FromOriginalModelMixinz]
    Load pretrained weights saved in the `.ckpt` or `.safetensors` format into a model.
    N%pretrained_model_link_or_path_or_dictreturnc                    t        |       }|/t        ddj                  t        j	                                      |j                  dd      }|d}t        dd|       |}|j                  dd      }|j                  dd      }||t        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      }t        ddd}||j                  j                  |d<   |Ct        |t        j                        s)t        j                  }t         j#                  d| d       t        |t$              r|}nt'        |||	|
|||||	      }|7t)        j*                  |      }|j-                          |j/                  |      }nd}t        |   }|d   }|Rd |v r|d    }nd}|t        d!| d"      t        |t0              rt3        ||#      }t5        |fi |} |d7||d$|}n|t        |t0              r|}n:t        d%      t7        |      }|d&   }d'|v r|d'   }|xs |j                  dd      }| j9                  ||||
|(      }| j;                  |       \  }}d)|v r6|d)   } | j=                         D ]  \  }!}"|!|v s|j                  |!      ||"<     |D #ci c]  }#|#|v s|#|v s|#|j                  |#       }$}#|j?                  |$       |rt@        ntB        }% |%       5  | j+                  |      }&ddd       t5        |fi |}'tE        &jG                         |      r |d7||d*|'}(n|}(|(stI        d+| d,      | jJ                  duxr! |t        jL                  k(  xs tO        |d-      })|)r | jJ                  }*t        |*tP              s|*g}*ng }*||jS                  |&d|(|*.       d}+|rq|rt        jT                  |      nt        jT                  d/      },|&jG                         }-|(D .cg c]	  }.|.|-vs|. }/}.d0|,i}+tW        |&|(||+||*|/1       tY                n|&j[                  |(d2      \  }0}/|&j\                  7|&j\                  D ](  }1|/D #cg c]  }#t_        j`                  |1|#      |# }/}#* tc        |/      d3kD  r5t         j#                  d4| jd                   d5dj                  |/      g        ||jg                  |&       ||&_4        |||&jk                  |       |&jm                          |+d6|+i}2to        |&fi |2 |&S c c}#w # 1 sw Y   $xY wc c}.w c c}#w )8au  
        Instantiate a model from pretrained weights saved in the original `.ckpt` or `.safetensors` format. The model
        is set in evaluation mode (`model.eval()`) by default.

        Parameters:
            pretrained_model_link_or_path_or_dict (`str`, *optional*):
                Can be either:
                    - A link to the `.safetensors` or `.ckpt` file (for example
                      `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.safetensors"`) on the Hub.
                    - A path to a local *file* containing the weights of the component model.
                    - A state dict containing the component model weights.
            config (`str`, *optional*):
                - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline hosted
                  on the Hub.
                - A path to a *directory* (for example `./my_pipeline_directory/`) containing the pipeline component
                  configs in Diffusers format.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            original_config (`str`, *optional*):
                Dict or path to a yaml file containing the configuration for the model in its original format.
                    If a dict is provided, it will be used to initialize the model configuration.
            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.
            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.

            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.
            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.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 and
                is_accelerate_available() 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.
            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.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (for example the pipeline components of the
                specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
                method. See example below for more information.

        ```py
        >>> from diffusers import StableCascadeUNet

        >>> ckpt_path = "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_lite.safetensors"
        >>> model = StableCascadeUNet.from_single_file(ckpt_path)
        ```
        Nz9FromOriginalModelMixin is currently only compatible with z, pretrained_model_link_or_pathzUPlease use `pretrained_model_link_or_path_or_dict` argument instead for model classesz1.0.0configoriginal_configzz`from_single_file` cannot accept both `config` and `original_config` arguments. Please provide only one of these argumentsforce_downloadFproxiestoken	cache_dirlocal_files_only	subfolderrevisionconfig_revisiontorch_dtypequantization_configlow_cpu_mem_usagedevicedisable_mmapsingle_filepytorch)	diffusers	file_type	frameworkquantzPassed `torch_dtype` z7 is not a `torch.dtype`. Defaulting to `torch.float32`.)r{   r|   r}   r~   r   r   r   
user_agentr/   r4   z(`original_config` has been provided for z~ but no mapping functionwas found to convert the original config to a Diffusers config in`diffusers.loaders.single_file_utils`)r   )rz   
checkpointzqInvalid `config` argument. Please provide a string representing a repo idor path to a local Diffusers model repo.pretrained_model_name_or_pathr5   )r   r   r   r}   r   r6   )ry   r   zFailed to load zD. Weights for this component appear to be missing in the checkpoint.use_keep_in_fp32_modules)model
device_map
state_dictkeep_in_fp32_modulescpu )dtyper   hf_quantizerr   unexpected_keys)strictr   zESome weights of the model checkpoint were not used when initializing z: 
 r   rJ   )8ri   
ValueErrorjoinrb   rW   getr
   pop_LOW_CPU_MEM_USAGE_DEFAULTr   quant_methodvalue
isinstancetorchr   float32loggerwarningdictr*   r	   from_configvalidate_environmentupdate_torch_dtypestrr)   rr   r(   load_config_get_signature_keysitemsupdater,   r   r[   r   r   _keep_in_fp32_modulesfloat16hasattrlistpreprocess_modelr   r-   r   load_state_dict"_keys_to_ignore_on_load_unexpectedresearchlenr`   postprocess_modelr   toevalr+   )3re   ru   ro   mapping_class_namerx   deprecation_messagery   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   r   mapping_functionsr/   r4   config_mapping_kwargsdiffusers_model_config$default_pretrained_model_config_nameexpected_kwargsoptional_kwargsr6   
legacy_keynew_keykmodel_kwargsctxr   checkpoint_mapping_kwargsdiffusers_format_checkpointr   r   r   param_deviceempty_state_dict
param_namer   _patdevice_map_kwargss3                                                      rL   from_single_filez'FromOriginalModelMixin.from_single_file   s%   D ESI%KDIIVrVwVwVyLzK{|  )/

3RTX(Y%(4g   5w@ST4Q1Hd+ **%6=/"= M   $4e<**Y-

7D)JJ{D1	!::&8$?JJ{D1	::j$/ **%6=jj5$jj)>E"JJ':<VWHd+zz.%8#.]Ybc
*"5"B"B"H"HJw":k5;;+O--KNN'}4kl ;TB>J45-#!1!)%
J *1==>QRL--/&99+FK  L89KL 12I J&"&77$56I$J!$(! ( BCUBV W@ @  /3/"7Zj"k$@AR$]V\$]!%6 & /J&J_&" !fc*;A8$G  0
;7=>]7^4&*;; 12E FI% *	 &)__.R#!1( &5 &" 03/F/Fs/K,O_ "33 1/ B+8+>+>+@ A'J!V+*0**Z*@wA 7=m_@TXY]lXlAvzz!},mLm")),7$5 ;U 	<OO$:;E	< %AAV$aZ`$a!253C3C3EzR*? +-*+Ha+' +5'**!"4!55yz  %($=$=T$I $
EMM)_glD^._ 	! $#&#<#< 2D9(<'=$ $& #))6%9	 *  
395<</u||E?RL$//1-H)J^nLn
O  l+J%+!%)%9 /  !&!6!67R[`!6!aA33??? \.="[3PQARAZ1"["[\ !#NNWX[XdXdWeejlplulu  wF  mG  lH  kI  J #**51!-E"|';HH[!

!!-z :56$56g n	< 	<P& #\s0   (W!6W!2W&	W3W3'W8W8&W0rI   )
r`   
__module____qualname____doc__classmethodr   r   r   r   r   rJ   rN   rL   rt   rt      s:     ZXc] Zhl Z  ZrN   rt   )Ar^   rk   r   
contextlibr   typingr   r   huggingface_hub.utilsr   typing_extensionsr   r   r   
quantizersr	   utilsr
   r   r   r   utils.torch_utilsr   single_file_utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   
get_loggerr`   r   
accelerater+   r,   models.model_loading_utilsr-   r   rb   r[   ri   rr   rt   rJ   rN   rL   <module>r      s     	 "   6 "  / Q Q 2       > 
		H	% =FD'"'>'@!%!&\ !U\  !<B#}
		\  !;A"\ " !>H#\ * !P*+\ 2 !L3\ 8 !L9\ > !Q*?\ F !S*!G\ N !!P*#O\ V !H"W\ ^ -/]^_\ ` !R* a\ h %!O*'i\ p !!U*#q\ x  !=*"y\ @ !F*A\ J "F*
 "F*"
 ">"
 "J*'
 "T*!
 "-*$q\  ~Xa arN   