
    ^j׆                     D   d dl Z d dlZd dl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 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mZ dd
lmZ  e       rd dlZ e       rd dlm Z  d dl!m"Z"m#Z# dZ$ ejJ                  e&      Z'erddl(m)Z)m*Z*  G d d      Z+defdZ,y)    N)replace)TYPE_CHECKINGAnyLiteralOptional)	safe_open   )PeftConfigLike)get_model_conversion_mapping)	CONFIG_NAMEcached_filecheck_peft_versionextract_commit_hashfind_adapter_config_fileis_accelerate_availableis_peft_availableis_torch_availablelogging)DownloadKwargs)log_state_dict_report)dispatch_model)get_balanced_memoryinfer_auto_device_mapz0.19.1)LoadStateDictConfigLoadStateDictInfoc                      e Zd ZU dZdZdZedz  ed<   eee	f   ed<   	 	 	 	 	 	 	 	 	 	 d'dedz  dedz  deee
f   dz  d	eed
f   dz  dededeed   z  dedeee
f   dz  ded   ddfdZ	 d(deded   ddfdZd)dedz  ddfdZdee   ez  ddfdZd*dZd*dZdee   fdZd+dedz  dedz  defdZ	 	 	 d,d ed!edz  d"edz  d#edz  ddf
d$Zd%ee   ez  ddfd&Zy)-PeftAdapterMixinu'  
    A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
    more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT
    library: https://huggingface.co/docs/peft/index

    Currently supported PEFT methods are all non-prompt learning methods (LoRA, IA³, etc.). Other PEFT models such as
    prompt tuning, prompt learning are out of scope as these adapters are not "injectable" into a torch module. For
    using these methods, please refer to the usage guide of PEFT library.

    With this mixin, if the correct PEFT version is installed (>= 0.19.1), it is possible to:

    - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
    - Attach new adapters in the model and train them with Trainer or by your own.
    - Attach multiple adapters and iteratively activate / deactivate them
    - Activate / deactivate all adapters from the model.
    - Get the `state_dict` of the active adapter.
    FN_prepare_peft_hotswap_kwargspeft_configautopeft_model_idadapter_nameadapter_state_dictztorch.Tensorlow_cpu_mem_usageis_trainablehotswaplocal_files_onlyadapter_kwargsload_configr   returnr   c                 
  ./ ddl m. ddlm} ddlm}m}m} |rd|d<   |
|
j                  ni }|j                  |       |j                  d	d        |d0i |}
|xs |
j                  }|d
k(  r8t        | dd      }t        | j                  xr || j                  v       }|xr |}|r\| j                  r|| j                  vrt!        d      t#        .fd| j                  j%                         D              rt!        d      ||nd}|	xs i }	ddl m}m} | j                  r|s|| j                  v rt!        d| d      |r%| j                  r|| j                  vrt!        d      |||t!        d      |` |
j*                  j                  d0i |	 t-        |fi |
j*                  }|t!        d| d       |j.                  |fi |
j*                  }ddlm} t5        |       }t7        |d      r| |_         ||||      }|s
 ||| |       |h/|@t        |dd      3/j;                  |j<                  j>                  jA                                dtB        dt        f/fd}| j                  sd| _        ||ddg}|
jD                  du r|jG                          dx}}d}|D ]>  }	  ||dd|jI                  d       r|
jD                  nddd||
j*                  !      \  }} n ||xs tK        d"      g i }}t        | d#d$| jL                  i      } d}!| jO                         D ]  }"t        |"d%d      }#|#d}! n |!rtQ               }$||}%n|h|d   jI                  d       rT|Ri }%|D ]J  }&tS        |&d&d'(      }'|$j;                  |'       |'jU                         D ]  }(|'jW                  |(      |%|(<    L n.|!i }%|D ]  })|%j                   ||)              nt!        d)      |%}t#        d* |j%                         D              rt!        d+       || ||       tY        |
|||| ,      }
| j[                  | |||
| j]                         D *+cg c]  \  }*}+ ||*      s|* c}+}*-      \  },}+|j8                  rIdd.l/m0}- | jc                          | jO                         D ]   }"te        |"|-      s|"jg                  d       " |,jh                  D (ch c]  }( ||(      s|( c}(|,_4        tk        | |
j                  |
jl                  |,tn        /       |,S # tJ        $ r}|}Y d}~d}~ww xY wc c}+}*w c c}(w )1u  
        Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
        invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft

        Requires PEFT to be installed as a backend to load the adapter weights.

        Args:
            peft_model_id (`str`, *optional*):
                The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
                and adapter weights.
            adapter_name (`str`, *optional*):
                The adapter name to use. If not set, will use the name "default".
            load_config (`LoadStateDictConfig`, *optional*):
                A load configuration to reuse when pulling adapter weights, typically from `from_pretrained`.
            kwargs (`dict[str, Any]`, *optional*):
                Additional `LoadStateDictConfig` fields passed as keyword arguments.
            peft_config (`dict[str, Any]`, *optional*):
                The configuration of the adapter to add, supported adapters are all non-prompt learning configs (LoRA,
                IA³, etc). This argument is used in case users directly pass PEFT state dicts.
            adapter_state_dict (`dict[str, torch.Tensor]`, *optional*):
                The state dict of the adapter to load. This argument is used in case users directly pass PEFT state
                dicts.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `False`):
                Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process.
            is_trainable (`bool`, *optional*, defaults to `False`):
                Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
                used for inference.
            hotswap : (`"auto"` or `bool`, *optional*, defaults to `"auto"`)
                Whether to substitute an existing (LoRA) adapter with the newly loaded adapter in-place. This means
                that, instead of loading an additional adapter, this will take the existing adapter weights and replace
                them with the weights of the new adapter. This can be faster and more memory efficient. However, the
                main advantage of hotswapping is that when the model is compiled with torch.compile, loading the new
                adapter does not require recompilation of the model. When using hotswapping, the passed `adapter_name`
                should be the name of an already loaded adapter.

                If the new adapter and the old adapter have different ranks and/or LoRA alphas (i.e. scaling), you need
                to call an additional method before loading the adapter:

                ```py
                model = AutoModel.from_pretrained(...)
                max_rank = ...  # the highest rank among all LoRAs that you want to load
                # call *before* compiling and loading the LoRA adapter
                model.enable_peft_hotswap(target_rank=max_rank)
                model.load_adapter(file_name_1, adapter_name="default")
                # optionally compile the model now
                model = torch.compile(model, ...)
                output_1 = model(...)
                # now you can hotswap the 2nd adapter, use the same name as for the 1st
                # hotswap is activated by default since enable_peft_hotswap was called
                model.load_adapter(file_name_2, adapter_name="default")
                output_2 = model(...)
                ```

                By default, hotswap is disabled and requires passing `hotswap=True`. If you called
                `enable_peft_hotswap` first, it is enabled. You can still manually disable it in that case by passing
                `hotswap=False`.

                Note that hotswapping comes with a couple of limitations documented here:
                https://huggingface.co/docs/peft/main/en/package_reference/hotswap
            adapter_kwargs (`dict[str, Any]`, *optional*):
                Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and
                `find_adapter_config_file` method.
        r   )PeftType)_maybe_shard_state_dict_for_tpr	   )r   _get_resolved_checkpoint_filesload_state_dictTr'   Npretrained_model_name_or_pathr    _hotswap_enabledFz\To hotswap an adapter, there must already be an existing adapter with the same adapter name.c              3   P   K   | ]  }|j                   j                  k7    y wN)	peft_typeLORA).0confr,   s     i/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/integrations/peft.py	<genexpr>z0PeftAdapterMixin.load_adapter.<locals>.<genexpr>   s     Yt4>>X]]2Ys   #&zMHotswapping is currently only supported for LoRA, please set `hotswap=False`.default
PeftConfiginject_adapter_in_modelAdapter with name - already exists. Please use a different name.zhYou should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter.z adapter model file not found in zB. Make sure you are passing the correct path to the adapter model.)build_peft_weight_mappinginference_mode)r   r4   keyr*   c                 .     t         fdD              S )Nc              3   &   K   | ]  }|v  
 y wr3    )r6   markerrB   s     r8   r9   zHPeftAdapterMixin.load_adapter.<locals>.is_adapter_key.<locals>.<genexpr>   s     Gv}Gs   )any)rB   adapter_key_markerss   `r8   is_adapter_keyz5PeftAdapterMixin.load_adapter.<locals>.is_adapter_key   s    G3FGGG    zadapter_model.safetensorszadapter_model.binz.safetensors)r0   variant	gguf_fileuse_safetensors
user_agentis_remote_codetransformers_explicit_filenamedownload_kwargsz@Could not download either a .bin or a .safetensors adapter file.hf_device_map _tp_infoptcpu)	frameworkdevicez5Neither a state dict nor checkpoint files were found.c              3   R   K   | ]  }t        |t        j                          ! y wr3   )
isinstancetorchTensor)r6   vs     r8   r9   z0PeftAdapterMixin.load_adapter.<locals>.<genexpr>6  s     Xqz!U\\22Xs   %'z<Expected all values in the adapter state dict to be tensors.)r0   sharded_metadataweight_mapping
device_map)model
state_dictcheckpoint_filesr)   expected_keysBaseTunerLayer)ra   r0   ignore_mismatched_sizesloading_infologgerrE   )8peftr,   peft.utils.save_and_loadr-   modeling_utilsr   r.   r/   __dict__update
setdefaultr0   getattrbool_hf_peft_config_loadedr   
ValueErrorrG   valuesr<   r=   rQ   r   from_pretrained)peft.utils.transformers_weight_conversionr@   r   hasattrrA   addr4   valuelowerstrrM   reverseendswithOSErrorrX   modulessetr   keys
get_tensorr   _load_pretrained_modelnamed_parameterspeft.tuners.tuners_utilsrf   evalrZ   requires_grad_missing_keysr   rg   ri   )0selfr!   r"   r   r#   r$   r%   r&   r'   r(   r)   kwargsr-   r   r.   r/   base_load_confighotswap_enablednot_first_adapterr<   r=   adapter_config_filer@   weight_conversionspeft_weight_conversionsrI   adapter_filenamesrc   r^   
last_erroradapter_filenameerrorr`   has_tp_adaptersmoduletp_infoall_pointermerged_state_dictfilefile_pointerk	ckpt_filen_rh   rf   r,   rH   s0                                                 @@r8   load_adapterzPeftAdapterMixin.load_adapterP   s   Z 	"Kii)-F%&3>3J;//PR'##$CTJ)=,<=%R)R)Rf%d,>FO $T%@%@%glVZVfVfFf h%;*;G//\IYIY5Y r  Yt?O?O?V?V?XYY !pqq'3'?|Y'-2<&&ldN^N^>^1,?lmnnt::TXTdTd@dn   &8&@[EXz  .K''..@@":#--#
 #* 6}o F% % 
 5*44--K
 	X9$?; 01-9)9K& #<<NP\ju"v#K|D+n"w{K'N'Z##K$9$9$?$?$E$E$GH	H 	H 	H ***.D'%!<>Q R**e3!))+266/J$5 ' '9W6C $"&;K;T;TUc;dK77jo#'',7G(3(C(C:6$&6 '$  ' oG,n$oo13R.T?R4EF
  lln 	Ffj$7G""&		 %K!-$6! ,$Q'00@&.$&!, JD#,TT%#PLOOL1)..0 J/;/F/Fq/I)!,JJ "-$&!!1 II%,,_Y-GHI !!XYY!2X<N<U<U<WXX !_``*41C\R*7-2!
 55)-# *.)>)>)@VANSTDU1V 6 
a %%?IIK,,. 1fn5))%01 1=0I0I$_1^\]M^Q$_!*5*S*S$/$G$G%	
 i  '!&J'@ W %`s0   5:T$T=-T= U.U$	T:-T55T:target_rankcheck_compiled)r   warnignorec                     t        | di       r?|dk(  rt        d      |dk(  rt        j                  d       n|dk7  rt	        d| d      d	| _        ||d
| _        y)a  Enables the possibility to hotswap PEFT adapters with different ranks, or, if the model is compiled, without
        triggering recompilation.

        Right now, hotswapping is only supported for LoRA.

        Calling this method is only required when hotswapping adapters and if the model is compiled or if the ranks of
        the loaded adapters differ. If the ranks are all identical and the model is not compiled, hotswapping works
        without calling this method first.

        Args:
            target_rank (`int`, *optional*, defaults to `128`):
                The highest rank among all the adapters that will be loaded.
            check_compiled (`str`, *optional*, defaults to `"error"`):
                How to handle the case when the model is already compiled, which should generally be avoided. The
                options are:
                  - "error" (default): raise an error
                  - "warn": issue a warning
                  - "ignore": do nothing
        r   r   z<Call `enable_peft_hotswap` before loading the first adapter.r   zhIt is recommended to call `enable_peft_hotswap` before loading the first adapter to avoid recompilation.r   zCcheck_compiles should be one of 'error', 'warn', or 'ignore', got 'z
' instead.T)r   r   N)rp   RuntimeErrorri   warningrs   r1   r   )r   r   r   s      r8   enable_peft_hotswapz$PeftAdapterMixin.enable_peft_hotswap`  sy    , 4+("#abb6)~  8+ YZhYiist  !%<G[i,j)rJ   c                 b   t        t               ddlm}m} |xs d}| j
                  sd| _        n|| j                  v rt        d| d      t        ||      st        dt        |       d	      | j                  j                  d
d      |_         ||| |       | j                  |       y)u  
        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        official documentation: https://huggingface.co/docs/peft

        Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
        name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
        default adapter name).

        Note that the newly added adapter is not automatically activated. To activate it, use `model.set_adapter`.

        Args:
            adapter_config (`~peft.PeftConfig`):
                The configuration of the adapter to add, supported adapters are non-prompt learning methods (LoRA,
                IA³, etc.).
            adapter_name (`str`, *optional*, defaults to `"default"`):
                The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
        min_versionr   r;   r:   Tr>   r?   z8adapter_config should be an instance of PeftConfig. Got z	 instead.name_or_pathN)r   MIN_PEFT_VERSIONrj   r<   r=   rr   r   rs   rZ   	TypeErrortyperm   getbase_model_name_or_pathset_adapter)r   adapter_configr"   r<   r=   s        r8   add_adapterzPeftAdapterMixin.add_adapter  s    $ 	'78<#0y***.D'T---1,?lmnn.*5VW[\jWkVlluvww 261B1B>SW1X.lC&rJ   c           	      |   t        t               | j                  st        d      t	        |t
              rpt        |      t        | j                        z
  }t        |      dkD  rt        ddj                  |       dt        | j                  j                                      || j                  vr2t        d| dt        | j                  j                                      dd	lm} dd
lm} d}| j                         D ]'  \  }}t	        |||f      s|j!                  |       d}) |st        d      y)a  
        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        official documentation: https://huggingface.co/docs/peft

        Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.

        Args:
            adapter_name (`Union[list[str], str]`):
                The name of the adapter to set. Can be also a list of strings to set multiple adapters.
        r   0No adapter loaded. Please load an adapter first.r   z)Following adapter(s) could not be found: , zV. Make sure you are passing the correct adapter name(s). current loaded adapters are: r>   z7 not found. Please pass the correct adapter name among re   ModulesToSaveWrapperFTzhDid not succeeded in setting the adapter. Please make sure you are using a model that supports adapters.N)r   r   rr   rs   rZ   listr   r   lenjoinr   r   rf   
peft.utilsr   named_modulesr   )r   r"   missingrf   r   _adapters_has_been_setr   r   s           r8   r   zPeftAdapterMixin.set_adapter  sZ    	'78**OPPd+,'#d.>.>*??G7|a ?		'@R?S T559$:J:J:O:O:Q5R4SU  !1!11$\N2ijnosoo  pE  pE  pG  kH  jI  J  	<3!&++- 	.IAv&>3G"HI""<0)-&	.
 &z  &rJ   c                     t        t               | j                  st        d      ddlm} ddlm} | j                         D ]&  \  }}t        |||f      s|j                  d       ( y)	a,  
        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        official documentation: https://huggingface.co/docs/peft

        Disable all adapters that are attached to the model. This leads to inferring with the base model only.
        r   r   r   re   r   FenabledN)r   r   rr   rs   r   rf   r   r   r   rZ   enable_adapters)r   rf   r   r   r   s        r8   disable_adaptersz!PeftAdapterMixin.disable_adapters  se     	'78**OPP;3++- 	6IAv&>3G"HI&&u&5	6rJ   c                     t        t               | j                  st        d      ddlm} | j                         D ]$  \  }}t        ||      s|j                  d       & y)z
        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        official documentation: https://huggingface.co/docs/peft

        Enable adapters that are attached to the model.
        r   r   r   re   Tr   N)	r   r   rr   rs   r   rf   r   rZ   r   )r   rf   r   r   s       r8   r   z PeftAdapterMixin.enable_adapters  s\     	'78**OPP;++- 	5IAv&.1&&t&4	5rJ   c                     t        t               | j                  st        d      ddlm} | j                         D ]  \  }}t        ||      s|j                  } n t        t              r|g}|S )a3  
        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        official documentation: https://huggingface.co/docs/peft

        Gets the current active adapters of the model. In case of multi-adapter inference (combining multiple adapters
        for inference) returns the list of all active adapters so that users can deal with them accordingly.

        For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return
        a single string.
        r   r   r   re   )
r   r   rr   rs   r   rf   r   rZ   active_adapterr{   )r   rf   r   r   active_adapterss        r8   r   z PeftAdapterMixin.active_adapters  ss     	'78**OPP;++- 	IAv&.1"("7"7	 os+./OrJ   rb   c                     t        t               | j                  st        d      ddlm} || j                         d   } || ||      }|S )ax  
        If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
        official documentation: https://huggingface.co/docs/peft

        Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
        If no adapter_name is passed, the active adapter is used.

        Args:
            adapter_name (`str`, *optional*):
                The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
            state_dict (nested dictionary of `torch.Tensor`, *optional*)
                The state dictionary of the model. Will default to `self.state_dict()`, but can be used if special
                precautions need to be taken when recovering the state dictionary of a model (like when using model
                parallelism).
        r   r   r   )get_peft_model_state_dict)rb   r"   )r   r   rr   rs   rj   r   r   )r   r"   rb   r   r#   s        r8   get_adapter_state_dictz'PeftAdapterMixin.get_adapter_state_dict  sT      	'78**OPP2//1!4L6t
amn!!rJ   r`   
max_memoryoffload_folderoffload_indexc                     i }dt        j                  t              j                  v r||d<   | j                  }|dk7  rt        | |||dk(        }t        |t              rt        | ||      }t        | f||d| y)a  
        Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
        accelerate (i.e. with `device_map=xxx`)

        Args:
            device_map (`str` or `dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
                A map that specifies where each submodule should go. It doesn't need to be refined to each
                parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
                same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
                like `1`) on which the model will be allocated, the device map will map the entire model to this
                device. Passing `device_map = 0` means put the whole model on GPU 0.

                To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
                more information about each option see [designing a device
                map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
            max_memory (`Dict`, *optional*):
                A dictionary device identifier to 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*):
                If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
            offload_index (`int`, *optional*):
                The offload_index argument to be passed to `accelerate.dispatch_model` method.
        r   
sequentialbalanced_low_0)r   no_split_module_classeslow_zero)r   r   )r`   offload_dirN)	inspect	signaturer   
parameters_no_split_modulesr   rZ   r{   r   )r   r`   r   r   r   dispatch_model_kwargsr   s          r8   _dispatch_accelerate_modelz+PeftAdapterMixin._dispatch_accelerate_model5  s    < !# g//?JJJ5B!/2"&"8"8%,%(?$(88	J j#&.E\J 		
!&	
 $		
rJ   adapter_namesc                    t        t               | j                  st        d      ddlm} t        |t              r|g}|D cg c]  }|| j                  vs| }}|rt        ddj                  |             |D cg c]6  }| j                  |   j                  j                  j                          d8 }}t        ||      D ]G  \  }} || ||       t        | d	d
      st        | d      s,| j                  j!                  |d       I t#        | j                        dk(  r
| `d
| _        yyc c}w c c}w )z
        Delete a PEFT adapter from the underlying model.

        Args:
            adapter_names (`Union[list[str], str]`):
                The name(s) of the adapter(s) to delete.
        r   r   r   )delete_adapterz@The following adapter(s) are not present and cannot be deleted: r   r   )r"   prefixrr   Fr   N)r   r   rr   rs   peft.functionalr   rZ   r{   r   r   r4   ry   rz   ziprp   rw   popr   )r   r   r   namemissing_adaptersr"   prefixesr   s           r8   r   zPeftAdapterMixin.delete_adapterm  sI    	'78**OPP2mS)*OM .;[Td$JZJZ>ZD[[RSWS\S\]mSnRop  fssUat''5??EEKKMNaPss$'x$@ 	9 L&4l6Jt5u='$P]B^  $$\48		9 t A% */D' & \ ts   D8D8;D=)
NNNNFFr    FNN)   r   r3   )r*   N)NN)NNN)__name__
__module____qualname____doc__rr   r   dict__annotations__r{   r
   r   rq   r   r   r   intr   r   r   r   r   r   r   r   r   r   rE   rJ   r8   r   r   9   s   $ #04 $+4c>)** %)#'-1?C"'"*0!&047;NTzN DjN #s(^d*	N
 !n!45<N  N N 'N N S#X-N 34N 
Nb \c#k#k6=>W6X#k	#kJ&'d
 &'d &'P'S	C 'D 'R6&5$c :"3: "RVY]R] "im "@ "&%)$(6
6
 $J6
 d
	6

 Tz6
 
6
p%0DIO %0 %0rJ   r   rQ   c                 v   | 
t               sd | |fS |j                  d      }|j                  d      t        | t        |j                  d      t	        |j                  dd            |j                  d      t	        |j                  dd            ||j                  d      |j                  d	      ddd
      }t        |d       |d<   |j                  dd       }|j                  dd       }||j                         }dD ]  }||vs||v s||   ||<    d|v r|d   |d<   t	        |j                  dd            |d<   t	        |j                  dd            |d<   |xs ||d<   t        | fi |}|t        j                  j                  |      rt        |dd      5 }	| }t        j                  j                  |       rAt        j                  j                  t        j                  j                  | t                    st        j                   |	      d   } d d d        || |fS # 1 sw Y   xY w)Ntokencommit_hash	cache_dirforce_downloadFproxiesr'   revision	subfolder)
r   r   r   r'   r   r   r    _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errors_adapter_model_path)r   r   r   _commit_hashrzutf-8)encodingr   )r   r   r   r   rq   r   r   copyr   ospathisfileopenexistsr   jsonload)
r0   rQ   r(   r   resolved_config_filer   token_from_adapter_kwargspeft_kwargsarg_namefs
             r8   maybe_load_adaptersr
    s^   
 %,4E4G2NBB(E=)1*)%))+6 3 34De LM#''	2!/"5"56H%"PQ$((4%))+6-22749 
 *==QSW)X&(,,-BDI . 2 27D A"$))+= 	BH+(o2M(7(AH%	B O+*9-*HK'(,_-@-@AQSX-Y(Z$%*./B/BCUW\/]*^&'$A(AG6)


 &277>>:M+N%sW= 		X"?
 77>>"?@:KHI 15		!=V0W-		X  =~MM		X 		Xs   'A;H//H8)-r   r  r   dataclassesr   typingr   r   r   r   safetensorsr   _typingr
   conversion_mappingr   utilsr   r   r   r   r   r   r   r   r   	utils.hubr   utils.loading_reportr   r[   
accelerater   accelerate.utilsr   r   r   
get_loggerr   ri   rl   r   r   r   r
  rE   rJ   r8   <module>r     s      	  8 8 ! $ =
 
 
 ' 8 )K   
		H	% GY	0 Y	0x:N#:NrJ   