
    +h+i                     "   S SK r S SKJr  S SKJrJr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  S S	K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+  \)RX                  " \-5      r. " S S\(5      r/g)    N)UnpicklingError)AnyDictUnion)
FrozenDictunfreeze)
from_bytesto_bytes)flatten_dictunflatten_dict)create_repohf_hub_download)EntryNotFoundErrorRepositoryNotFoundErrorRevisionNotFoundErrorvalidate_hf_hub_args)	HTTPError   )__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\\\4   S\R                  S	\S
\4S jjrSS\\\4   S	\4S jjrSS\\\4   S	\4S jjrSS\\\4   S	\4S jjrS\R,                  S
\4S jr\	\\R2                  4S\\\R8                  4   S\R                  4S jj5       5       r  SS\\\R8                  4   S\\\4   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/james-whalen/.local/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+Lr0   )jaxtree_mapr   tree_flattenzipkeysr   )selfr1   r'   r2   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**r0   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 (`Union[Dict, FrozenDict]`):
        A `PyTree` of model parameters.
    mask (`Union[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("runwayml/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("runwayml/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)
```)rK   r8   bfloat16rE   r1   r2   s      r-   to_bf16FlaxModelMixin.to_bf16_   s    J %%fcllDAAr0   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 (`Union[Dict, FrozenDict]`):
        A `PyTree` of model parameters.
    mask (`Union[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("runwayml/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)
```)rK   r8   float32rO   s      r-   to_fp32FlaxModelMixin.to_fp32   s    2 %%fckk4@@r0   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 (`Union[Dict, FrozenDict]`):
        A `PyTree` of model parameters.
    mask (`Union[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("runwayml/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("runwayml/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)
```)rK   r8   float16rO   s      r-   to_fp16FlaxModelMixin.to_fp16   s    J %%fckk4@@r0   rngc                     [        SU  35      e)Nz.init_weights method has to be implemented for )NotImplementedError)rE   rZ   s     r-   init_weightsFlaxModelMixin.init_weights   s    !$RSWRX"YZZr0   pretrained_model_name_or_pathc                    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[-        UU5      nO0 [/        US*5       n[1        U UR3                  5       5      nSSS5        [B        RD                  RG                  S/ W5      n[I        U5      n[B        RJ                  " URL                  [B        RN                  RQ                  S05      S19n[S        [I        [U        U5      5      RW                  5       5      n[I        [U        U5      5      nU[S        URW                  5       5      -
  n[S        URW                  5       5      U-
  nU(       a#  [X        R[                  S2U S3U S435        UU l.        URW                  5        HZ  n U U;   d  M  UU    R^                  UU    R^                  :w  d  M-  [#        S5U  S6UU    R^                   S7UU    R^                   S835      e   U H  n!UU!	 M     [a        U5      S0:  aK  [X        R[                  S9U S:URb                  Rd                   S;U S<URb                  Rd                   S=3	5        O-[X        Rg                  S>URb                  Rd                   S?35        [a        U5      S0:  a4  [X        R[                  S@URb                  Rd                   SAU SBU SC35        OG[X        Rg                  SDURb                  Rd                   SEU SFURb                  Rd                   SG3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! [4        [6        R8                  R:                  4 a  n [/        U5       nUR3                  5       R=                  S+5      (       a  [?        S,5      e["        Ue! , (       d  f        SnAGN= f! [@        ["        4 a    [        S-U S.35      ef = fSnAff = f)Ha  
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 `runwayml/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`].

        </Tip>

    model_args (sequence of positional arguments, *optional*):
        All remaining positional arguments are passed to the underlying model's `__init__` method.
    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.
    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("runwayml/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 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.
```
r+   N	cache_dirforce_downloadFfrom_ptproxieslocal_files_onlytokenrevision	subfoldermodelflax)	diffusers	file_type	frameworkT)ra   return_unused_kwargsrb   rd   re   rf   rg   rh   )r'   rn   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 .)	filenamera   rb   rd   re   rf   
user_agentrh   rg   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]bCcdeCf1gr0   r   )rZ   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popr   load_configfrom_configospathjoinisdirisfiler   EnvironmentErrorr   r   r   r   r   r   
ValueErrorr   r   modeling_utilsrs   r   openr	   readr   msgpack
exceptions	ExtraData
startswithOSErrorUnicodeDecodeErrorr@   	tree_utilrA   r   
eval_shaper]   randomPRNGKeysetr   rD   loggerwarning_missing_keysshapelen	__class____name__infor   )"r*   r_   r'   
model_argsr,   r+   ra   rb   rc   rd   re   rf   rg   rh   rr   unused_kwargsri   model_kwargspretrained_path_with_subfolder
model_fileerrrs   pytorch_model_filestatestate_fefparams_shape_treerequired_paramsshape_statemissing_keysunexpected_keysrJ   unexpected_keys"                                     r-   from_pretrainedFlaxModelMixin.from_pretrained   s   t 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   #W >Z( 
Z%Z( AZ'X88AZ
Z% Z( %Z( ($]\%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)a  
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 (`Union[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_prFrf   repo_id)r   r   rf   wbzModel weights saved in )rf   r   r   )r   r   r   r   errormakedirsr~   splitsepr   r   save_configr   r   r   r
   writer   _upload_folder)rE   r   r1   r   r   r,   r   r   r   rf   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)   r6   )TF)!r   
__module____qualname____firstlineno____doc__r   config_name_automatically_saved_args_flax_internal_argsclassmethodr.   r   r   r   r8   r'   r   rK   rP   rT   rX   r@   Arrayr]   r   rS   strr   PathLiker   boolr   __static_attributes__r)   r0   r-   r    r    2   s}    K V5% %+dJ.>(? +		 +Y\ +hk +0%BeD*$45 %BS %BNAeD*$45 AS A6%AeD*$45 %AS %AN[		 [d [  ;;a,',S"++-='>a, yya,  a,N	 !%!@c2;;./@ dJ&'@ 	@
 @ @r0   r    )0r   pickler   typingr   r   r   r@   	jax.numpynumpyr8   msgpack.exceptionsr   flax.core.frozen_dictr   r   flax.serializationr	   r
   flax.traverse_utilr   r   huggingface_hubr   r   huggingface_hub.utilsr   r   r   r   requestsr    r   r   utilsr   r   r   r   r   r   modeling_flax_pytorch_utilsr   
get_loggerr   r   r    r)   r0   r-   <module>r      sj     
 " # # 
   6 3 ; 8   .  L 
		H	%~^ ~r0   