
    
3ji                        S SK r S SKJr  S SKJr  S SKrS SKJr  S SK	r
S SKJrJr  S SKJrJr  S SKJrJr  S SKJrJr  S SKJrJrJrJrJr  S	S
KJrJr  S	SK J!r!J"r"J#r#J$r$J%r%J&r&  SSK'J(r(  \&RR                  " \*5      r+ " S S\%5      r,g)    N)UnpicklingError)Any)
FrozenDictunfreeze)
from_bytesto_bytes)flatten_dictunflatten_dict)create_repohf_hub_download)EntryNotFoundErrorHfHubHTTPErrorRepositoryNotFoundErrorRevisionNotFoundErrorvalidate_hf_hub_args   )__version__is_torch_available)CONFIG_NAMEFLAX_WEIGHTS_NAMEHUGGINGFACE_CO_RESOLVE_ENDPOINTWEIGHTS_NAMEPushToHubMixinlogging   )"convert_pytorch_state_dict_to_flaxc            	          \ rS rSrSr\r/ SQr/ SQr\	S 5       r
SS\\-  S\R                  S	\S
\4S jjrSS\\-  S	\4S jjrSS\\-  S	\4S jjrSS\\-  S	\4S jjrS\R*                  S
\4S jr\	\\R0                  4S\\R6                  -  S\R                  4S jj5       5       r  SS\\R6                  -  S\\-  S\S\4S jjrSrg)FlaxModelMixin2   a  
Base class for all Flax models.

[`FlaxModelMixin`] 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 [`~FlaxModelMixin.save_pretrained`].
)_diffusers_version_class_name_name_or_path)nameparentdtypec                     U " U40 UD6$ )zJ
All context managers that the model should be initialized under go here.
 )clsconfigkwargss      ^/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/models/modeling_flax_utils.py_from_configFlaxModelMixin._from_config@   s    
 6$V$$    Nparamsr%   maskreturnc                   ^ U4S jnUc  [         R                  " XA5      $ [        U5      n[         R                  " U5      u  pg[	        XeR                  5       5       H  u  pU(       d  M  XY   n
U" U
5      XY'   M     [        U5      $ )z[
Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
c                    > [        U [        R                  5      (       aE  [        R                  " U R                  [        R
                  5      (       a  U R                  T5      n U $ N)
isinstancejnpndarray
issubdtyper%   floatingastype)paramr%   s    r+   conditional_cast:FlaxModelMixin._cast_floating_to.<locals>.conditional_castM   s?    %--#..cll2[2[U+Lr.   )jaxtree_mapr	   tree_flattenzipkeysr
   )selfr/   r%   r0   r<   flat_params	flat_mask_maskedkeyr;   s     `        r+   _cast_floating_to FlaxModelMixin._cast_floating_toG   s|    	
 <<< 099"6*''-	y*:*:*<=KFv#(#3E#:  >
 k**r.   c                 D    U R                  U[        R                  U5      $ )a  
Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
the `params` in place.

This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full
half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.

Arguments:
    params (`dict | FrozenDict`):
        A `PyTree` of model parameters.
    mask (`dict | FrozenDict`):
        A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
        for params you want to cast, and `False` for those you want to skip.

Examples:

```python
>>> from diffusers import FlaxUNet2DConditionModel

>>> # load model
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
>>> params = model.to_bf16(params)
>>> # If you don't want to cast certain parameters (for example layer norm bias and scale)
>>> # then pass the mask as follows
>>> from flax import traverse_util

>>> model, params = FlaxUNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> flat_params = traverse_util.flatten_dict(params)
>>> mask = {
...     path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
...     for path in flat_params
... }
>>> mask = traverse_util.unflatten_dict(mask)
>>> params = model.to_bf16(params, mask)
```)rI   r6   bfloat16rC   r/   r0   s      r+   to_bf16FlaxModelMixin.to_bf16_   s    J %%fcllDAAr.   c                 D    U R                  U[        R                  U5      $ )a  
Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.

Arguments:
    params (`dict | FrozenDict`):
        A `PyTree` of model parameters.
    mask (`dict | FrozenDict`):
        A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
        for params you want to cast, and `False` for those you want to skip.

Examples:

```python
>>> from diffusers import FlaxUNet2DConditionModel

>>> # Download model and configuration from huggingface.co
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> # By default, the model params will be in fp32, to illustrate the use of this method,
>>> # we'll first cast to fp16 and back to fp32
>>> params = model.to_f16(params)
>>> # now cast back to fp32
>>> params = model.to_fp32(params)
```)rI   r6   float32rM   s      r+   to_fp32FlaxModelMixin.to_fp32   s    2 %%fckk4@@r.   c                 D    U R                  U[        R                  U5      $ )a  
Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
`params` in place.

This method can be used on a GPU to explicitly convert the model parameters to float16 precision to do full
half-precision training or to save weights in float16 for inference in order to save memory and improve speed.

Arguments:
    params (`dict | FrozenDict`):
        A `PyTree` of model parameters.
    mask (`dict | FrozenDict`):
        A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
        for params you want to cast, and `False` for those you want to skip.

Examples:

```python
>>> from diffusers import FlaxUNet2DConditionModel

>>> # load model
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> # By default, the model params will be in fp32, to cast these to float16
>>> params = model.to_fp16(params)
>>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
>>> # then pass the mask as follows
>>> from flax import traverse_util

>>> model, params = FlaxUNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> flat_params = traverse_util.flatten_dict(params)
>>> mask = {
...     path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
...     for path in flat_params
... }
>>> mask = traverse_util.unflatten_dict(mask)
>>> params = model.to_fp16(params, mask)
```)rI   r6   float16rM   s      r+   to_fp16FlaxModelMixin.to_fp16   s    J %%fckk4@@r.   rngc                     [        SU  35      e)Nz.init_weights method has to be implemented for )NotImplementedError)rC   rX   s     r+   init_weightsFlaxModelMixin.init_weights   s    !$RSWRX"YZZr.   pretrained_model_name_or_pathc                    [         R                  S5        UR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      nUR                  SS5      n	UR                  S	S5      n
UR                  S
S5      nUR                  SS5      nUR                  SS5      n[        SSS.nUc  U R                  " U4USUU	U
UUUS.UD6u  p_U R
                  " U4USS.WD6u  nnUc  UO[        R                  R                  X5      n[        R                  R                  U5      (       Gal  U(       a  [        R                  R                  [        R                  R                  U[        5      5      (       d  [        S[         SU S35      e[        R                  R                  U[        5      nGO[        R                  R                  [        R                  R                  U[        5      5      (       a%  [        R                  R                  U[        5      nO[        R                  R                  [        R                  R                  U[        5      5      (       a  [        [         SU S35      e[        S[         S[         SU S35      e [        UU(       d  [        O[        UUU	U
UUUUS9
nU(       a6  [+        5       (       a  S(S)KJn  O[        S*5      eU" U5      n[1        UU5      nO0 [3        US+5       n[5        U UR7                  5       5      nSSS5        [F        RH                  RK                  S0 W5      n[M        U5      n[F        RN                  " URP                  [F        RR                  RU                  S15      S29n[W        [M        [Y        U5      5      R[                  5       5      n[M        [Y        U5      5      nU[W        UR[                  5       5      -
  n[W        UR[                  5       5      U-
  nU(       a#  [         R                  S3U S4U S535        UU l.        UR[                  5        HZ  n U U;   d  M  UU    R^                  UU    R^                  :w  d  M-  ['        S6U  S7UU    R^                   S8UU    R^                   S935      e   U H  n!UU!	 M     [a        U5      S1:  aK  [         R                  S:U S;URb                  Rd                   S<U S=URb                  Rd                   S>3	5        O-[         Rg                  S?URb                  Rd                   S@35        [a        U5      S1:  a4  [         R                  SAURb                  Rd                   SBU SCU SD35        OG[         Rg                  SEURb                  Rd                   SFU SGURb                  Rd                   SH35        U[i        U5      4$ ! [         a    [        U S35      e[          a    [        U SU S35      e["         a    [        U S[         S35      e[$         a  n[        SU S U 35      eSnAf[&         a%    [        S![(         S"U S#[         S[         S$3	5      e[         a!    [        S%U S&U S'[         S[         S3	5      ef = f! , (       d  f       GNx= f! [8        [:        R<                  R>                  4 a  n [3        U5       nUR7                  5       RA                  S,5      (       a  [C        S-5      e[&        Ue! , (       d  f        SnAGN= f! [D        [&        4 a    [        S.U S/35      ef = fSnAff = f)Ia  
Instantiate a pretrained Flax model from a pretrained model configuration.

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

            - A string, the *model id* (for example `stable-diffusion-v1-5/stable-diffusion-v1-5`) of a
              pretrained model hosted on the Hub.
            - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
              using [`~FlaxModelMixin.save_pretrained`].
    dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
        The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
        `jax.numpy.bfloat16` (on TPUs).

        This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
        specified, all the computation will be performed with the given `dtype`.

        > [!TIP] > This only specifies the dtype of the *computation* and does not influence the dtype of model
        > parameters. > > If you wish to change the dtype of the model parameters, see
        [`~FlaxModelMixin.to_fp16`] and > [`~FlaxModelMixin.to_bf16`].

    model_args (sequence of positional arguments, *optional*):
        All remaining positional arguments are passed to the underlying model's `__init__` method.
    cache_dir (`str | os.PathLike`, *optional*):
        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
        is not used.
    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.
    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.
    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_pt (`bool`, *optional*, defaults to `False`):
        Load the model weights from a PyTorch checkpoint save file.
    kwargs (remaining dictionary of keyword arguments, *optional*):
        Can be used to update the configuration object (after it is loaded) and initiate the model (for
        example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
        automatically loaded:

            - If a configuration is provided with `config`, `kwargs` are directly passed to the underlying
              model's `__init__` method (we assume all relevant updates to the configuration have already been
              done).
            - If a configuration is not provided, `kwargs` are first passed to the configuration class
              initialization function [`~ConfigMixin.from_config`]. Each key of the `kwargs` that corresponds
              to a configuration attribute is used to override said attribute with the supplied `kwargs` value.
              Remaining keys that do not correspond to any configuration attribute are passed to the underlying
              model's `__init__` function.

Examples:

```python
>>> from diffusers import FlaxUNet2DConditionModel

>>> # Download model and configuration from huggingface.co and cache.
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("./test/saved_model/")
```

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

```bash
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
```
zFlax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.r)   N	cache_dirforce_downloadFfrom_ptproxieslocal_files_onlytokenrevision	subfoldermodelflax)	diffusers	file_type	frameworkT)r_   return_unused_kwargsr`   rb   rc   rd   re   rf   )r%   rl   zError no file named z found in directory  z file found in directory z-. Please load the model using `from_pt=True`.z or .)	filenamer_   r`   rb   rc   rd   
user_agentrf   re   z is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `token` or log in with `hf auth login`.z is not a valid git identifier (branch name, tag name or commit id) that exists for this model name. Check the model page at 'https://huggingface.co/z' for available revisions.z& does not appear to have a file named z:There was a specific connection error when trying to load z:
zWe couldn't connect to 'zM' to load this model, couldn't find it in the cached files and it looks like z8 is not the path to a directory containing a file named z.
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/transformers/installation#offline-mode'.zCan't load the model for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z=' is the correct path to a directory containing a file named r   )load_state_dictz|Can't load the model in PyTorch format because PyTorch is not installed. Please, install PyTorch or use native Flax weights.rbversionzYou seem to have cloned a repository without having git-lfs installed. Please install git-lfs and run `git lfs install` followed by `git lfs pull` in the folder you cloned.zUnable to convert z  to Flax deserializable object. c                 Z    [         R                  " U [         R                  " SS9S   5      $ )Ncpu)backendr   )r>   
device_putlocal_devices)xs    r+   <lambda>0FlaxModelMixin.from_pretrained.<locals>.<lambda>  s!    3CTCT]bCcdeCf1gr.   r   )rX   zThe checkpoint z is missing required keys: zI. Make sure to call model.init_weights to initialize the missing weights.z)Trying to load the pretrained weight for z failed: checkpoint has shape z, which is incompatible with the model shape z. z(Some weights of the model checkpoint at z! were not used when initializing z: z,
- This IS expected if you are initializing zU from the checkpoint of a model trained on another task or with another architecture.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.)5loggerwarningpopr   load_configfrom_configospathjoinisdirisfiler   EnvironmentErrorr   r   r   r   r   r   
ValueErrorr   r   modeling_utilsrq   r   openr   readr   msgpack
exceptions	ExtraData
startswithOSErrorUnicodeDecodeErrorr>   	tree_utilr?   r	   
eval_shaper[   randomPRNGKeysetr   rB   _missing_keysshapelen	__class____name__infor
   )"r(   r]   r%   
model_argsr*   r)   r_   r`   ra   rb   rc   rd   re   rf   rp   unused_kwargsrg   model_kwargspretrained_path_with_subfolder
model_fileerrrq   pytorch_model_filestatestate_fefparams_shape_treerequired_paramsshape_statemissing_keysunexpected_keysrH   unexpected_keys"                                     r+   from_pretrainedFlaxModelMixin.from_pretrained   s   h 	[	
 Hd+JJ{D1	$4e<**Y.**Y-!::&8%@

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

 >$'OO-%#%)-!1!#% %!F "oofnEX\n`mn|
   *;G 	'
 77==788ww~~bggll3QS_&`aa*.|n<PQoPppqr   WW\\*H,W
-KM^ _``WW\\*HJ[\
-K\ Z[[&#n$=>\=] ^- - 
 '*+<*=T,Oc56a9 
1,16=.<'#1#%5)'%
d !##;&J  "1!< 77I5QEn*d+w&sGLLN;E ,$ &&'gino U#NN5+=+=3::CUCUVWCXYl84E+FGLLNO"8,=#>?&UZZ\)::ejjl+o=NN!"?!@@[\h[i jZ Z !-C::<Ck!eCj&6&6+c:J:P:P&P ?uDbSz''((TU`adUeUkUkTllnp    .Nn% . !#NN:;X:Y Z!!&!9!9 :"_<M N!!&!9!9 : ;.. KKSTYTcTcTlTlSmmpqr|q NN"5??#;#;"< =122N|n ]nn KK%eoo&>&>%? @12 388=8P8P7Q R nU+++} + &45 6h h 
 ) &j !//L.MMgi 
 & &455[\m[nnop  " &PQnPoore   &./N.O P>>[=\ ]::K9LDQ]P^ _]]  $ &01N0O P--J,K L//@.Al^STV 0 ,+#W%7%7%A%AB nnj)Q668..y99")!6#  #-!3 *)) +J7 n*-?
|Kk+lmmnnst   2#W# Z= Z+:Z= #AZ(<YAZ(+
Z:5Z= :Z= =$]""\:-7\$$
\7	.\:7\:: ]]]"save_directoryis_main_processpush_to_hubc                 P   [         R                  R                  U5      (       a  [        R	                  SU S35        g[         R
                  " USS9  U(       a  UR                  SS5      nUR                  SS5      nUR                  SS	5      nUR                  S
S5      n	UR                  SUR                  [         R                  R                  5      S   5      n
[        U
SXyS9R                  n
U nU(       a  UR                  U5        [         R                  R                  U[        5      n[        US5       n[        U5      nUR!                  U5        SSS5        [        R#                  SU 35        U(       a  U R%                  UW
W	WWS9  gg! , (       d  f       NB= f)az  
Save a model and its configuration file to a directory so that it can be reloaded using the
[`~FlaxModelMixin.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.
    params (`dict | FrozenDict`):
        A `PyTree` of model parameters.
    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.
    push_to_hub (`bool`, *optional*, defaults to `False`):
        Whether or not to push your model to the Hugging Face model 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 key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
zProvided path (z#) should be a directory, not a fileNT)exist_okcommit_messageprivate	create_prFrd   repo_id)r   r   rd   wbzModel weights saved in )rd   r   r   )r   r   r   r|   errormakedirsr~   splitsepr   r   save_configr   r   r   r   writer   _upload_folder)rC   r   r/   r   r   r*   r   r   r   rd   r   model_to_saveoutput_model_filer   model_bytess                  r+   save_pretrainedFlaxModelMixin.save_pretrained  sb   8 77>>.))LL?>*::]^_
NT2#ZZ(8$?NjjD1G

;6IJJw-EjjN,@,@,Mb,QRG!'D'W__G %%n5 GGLL9JK#T*a"6*KGGK  + 	-.?-@AB-#     +*s   >F
F%r'   r4   )TF) r   
__module____qualname____firstlineno____doc__r   config_name_automatically_saved_args_flax_internal_argsclassmethodr,   dictr   r6   r%   r   rI   rN   rR   rV   r>   Arrayr[   r   rQ   strr   PathLiker   boolr   __static_attributes__r'   r.   r+   r   r   2   sZ    K V5% %+z(9 +#)) +SV +be +0%BdZ/ %Bs %BNAdZ/ As A6%AdZ/ %As %AN[		 [d [  ;;_,'*R[['8_, yy_,  _,J	 !%!@bkk)@ z!@ 	@
 @ @r.   r   )-r   pickler   typingr   r>   	jax.numpynumpyr6   msgpack.exceptionsr   flax.core.frozen_dictr   r   flax.serializationr   r   flax.traverse_utilr	   r
   huggingface_hubr   r   huggingface_hub.utilsr   r   r   r   r    r   r   utilsr   r   r   r   r   r   modeling_flax_pytorch_utilsr   
get_loggerr   r|   r   r'   r.   r+   <module>r      sd     
 "  
   6 3 ; 8  /  L 
		H	%|^ |r.   