
     `il                        d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZmZ dd	lmZmZmZmZmZmZmZmZmZ d
dlmZmZm Z   e            rddl!m"Z"  ej#        e$          Z% ed          Z&e'ee(e         df         ee(e         df         f         Z)dZ*dZ+dZ,dZ-dZ.d Z/ G d d          Z0 G d de0          Z1d#de2fdZ3d$de2de2fdZ4d Z5d Z6d Z7 G d  d!ee(e         e)f                   Z8d"gZ9dS )%z-Factory function to build auto-model classes.    N)OrderedDict)Iterator)AnyTypeVarUnion   )PretrainedConfig)get_class_from_dynamic_moduleresolve_trust_remote_code)	CONFIG_NAMEcached_file	copy_funcextract_commit_hashfind_adapter_config_fileis_peft_availableis_torch_availableloggingrequires_backends   )
AutoConfigmodel_type_to_module_name!replace_list_option_in_docstrings)GenerationMixin_TaJ  
    This is a generic model class that will be instantiated as one of the model classes of the library when created
    with the [`~BaseAutoModelClass.from_pretrained`] class method or the [`~BaseAutoModelClass.from_config`] class
    method.

    This class cannot be instantiated directly using `__init__()` (throws an error).
ax  
        Instantiates one of the model classes of the library from a configuration.

        Note:
            Loading a model from its configuration file does **not** load the model weights. It only affects the
            model's configuration. Use [`~BaseAutoModelClass.from_pretrained`] to load the model weights.

        Args:
            config ([`PretrainedConfig`]):
                The model class to instantiate is selected based on the configuration class:

                List options
            attn_implementation (`str`, *optional*):
                The attention implementation to use in the model (if relevant). Can be any of `"eager"` (manual implementation of the attention), `"sdpa"` (using [`F.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html)), or `"flash_attention_2"` (using [Dao-AILab/flash-attention](https://github.com/Dao-AILab/flash-attention)). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual `"eager"` implementation.

        Examples:

        ```python
        >>> from transformers import AutoConfig, BaseAutoModelClass

        >>> # Download configuration from huggingface.co and cache.
        >>> config = AutoConfig.from_pretrained("checkpoint_placeholder")
        >>> model = BaseAutoModelClass.from_config(config)
        ```
ac  
        Instantiate one of the model classes of the library from a pretrained model.

        The model class to instantiate is selected based on the `model_type` property of the config object (either
        passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
        falling back to using pattern matching on `pretrained_model_name_or_path`:

        List options

        The model is set in evaluation mode by default using `model.eval()` (so for instance, dropout modules are
        deactivated). To train the model, you should first set it back in training mode with `model.train()`

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

                    - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
                    - A path to a *directory* containing model weights saved using
                      [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
                    - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
                      this case, `from_tf` should be set to `True` and a configuration object should be provided as
                      `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
                      PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
            model_args (additional positional arguments, *optional*):
                Will be passed along to the underlying model `__init__()` method.
            config ([`PretrainedConfig`], *optional*):
                Configuration for the model to use instead of an automatically loaded configuration. Configuration can
                be automatically loaded when:

                    - The model is a model provided by the library (loaded with the *model id* string of a pretrained
                      model).
                    - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
                      save directory.
                    - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
                      configuration JSON file named *config.json* is found in the directory.
            state_dict (*dict[str, torch.Tensor]*, *optional*):
                A state dictionary to use instead of a state dictionary loaded from saved weights file.

                This option can be used if you want to create a model from a pretrained configuration but load your own
                weights. In this case though, you should check if using [`~PreTrainedModel.save_pretrained`] and
                [`~PreTrainedModel.from_pretrained`] is not a simpler option.
            cache_dir (`str` or `os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
            from_tf (`bool`, *optional*, defaults to `False`):
                Load the model weights from a TensorFlow checkpoint save file (see docstring of
                `pretrained_model_name_or_path` argument).
            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.
            resume_download:
                Deprecated and ignored. All downloads are now resumed by default when possible.
                Will be removed in v5 of Transformers.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only(`bool`, *optional*, defaults to `False`):
                Whether or not to only look at local files (e.g., not try downloading the model).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.
            trust_remote_code (`bool`, *optional*, defaults to `False`):
                Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
                should only be set to `True` for repositories you trust and in which you have read the code, as it will
                execute code present on the Hub on your local machine.
            code_revision (`str`, *optional*, defaults to `"main"`):
                The specific revision to use for the code on the Hub, if the code leaves in a different repository than
                the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
                system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
                allowed by git.
            kwargs (additional keyword arguments, *optional*):
                Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
                `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
                automatically loaded:

                    - If a configuration is provided with `config`, `**kwargs` will be 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` will be first passed to the configuration class
                      initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
                      corresponds to a configuration attribute will be used to override said attribute with the
                      supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
                      will be passed to the underlying model's `__init__` function.

        Examples:

        ```python
        >>> from transformers import AutoConfig, BaseAutoModelClass

        >>> # Download model and configuration from huggingface.co and cache.
        >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")

        >>> # Update configuration during loading
        >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
        >>> model.config.output_attentions
        True

        >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
        >>> config = AutoConfig.from_pretrained("./tf_model/shortcut_placeholder_tf_model_config.json")
        >>> model = BaseAutoModelClass.from_pretrained(
        ...     "./tf_model/shortcut_placeholder_tf_checkpoint.ckpt.index", from_tf=True, config=config
        ... )
        ```
a  
        Instantiate one of the model classes of the library from a pretrained model.

        The model class to instantiate is selected based on the `model_type` property of the config object (either
        passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
        falling back to using pattern matching on `pretrained_model_name_or_path`:

        List options

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

                    - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
                    - A path to a *directory* containing model weights saved using
                      [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
                    - A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
                      case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
                      argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
                      using the provided conversion scripts and loading the TensorFlow model afterwards.
            model_args (additional positional arguments, *optional*):
                Will be passed along to the underlying model `__init__()` method.
            config ([`PretrainedConfig`], *optional*):
                Configuration for the model to use instead of an automatically loaded configuration. Configuration can
                be automatically loaded when:

                    - The model is a model provided by the library (loaded with the *model id* string of a pretrained
                      model).
                    - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
                      save directory.
                    - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
                      configuration JSON file named *config.json* is found in the directory.
            cache_dir (`str` or `os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
            from_pt (`bool`, *optional*, defaults to `False`):
                Load the model weights from a PyTorch checkpoint save file (see docstring of
                `pretrained_model_name_or_path` argument).
            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.
            resume_download:
                Deprecated and ignored. All downloads are now resumed by default when possible.
                Will be removed in v5 of Transformers.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only(`bool`, *optional*, defaults to `False`):
                Whether or not to only look at local files (e.g., not try downloading the model).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.
            trust_remote_code (`bool`, *optional*, defaults to `False`):
                Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
                should only be set to `True` for repositories you trust and in which you have read the code, as it will
                execute code present on the Hub on your local machine.
            code_revision (`str`, *optional*, defaults to `"main"`):
                The specific revision to use for the code on the Hub, if the code leaves in a different repository than
                the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based
                system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier
                allowed by git.
            kwargs (additional keyword arguments, *optional*):
                Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
                `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
                automatically loaded:

                    - If a configuration is provided with `config`, `**kwargs` will be 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` will be first passed to the configuration class
                      initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
                      corresponds to a configuration attribute will be used to override said attribute with the
                      supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
                      will be passed to the underlying model's `__init__` function.

        Examples:

        ```python
        >>> from transformers import AutoConfig, BaseAutoModelClass

        >>> # Download model and configuration from huggingface.co and cache.
        >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")

        >>> # Update configuration during loading
        >>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
        >>> model.config.output_attentions
        True

        >>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
        >>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
        >>> model = BaseAutoModelClass.from_pretrained(
        ...     "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
        ... )
        ```
c                 (   |t          |                    }t          |t          t          f          s|S d |D             }t	          | dg           }|D ]8}||v r
||         c S d| |v r|d|          c S d| |v r|d|          c S 9|d         S )Nc                     i | ]
}|j         |S  __name__).0models     y/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/auto/auto_factory.py
<dictcomp>z$_get_model_class.<locals>.<dictcomp>  s    IIIuU^UIII    architecturesTFFlaxr   )type
isinstancelisttuplegetattr)configmodel_mappingsupported_modelsname_to_modelr%   archs         r"   _get_model_classr2     s    $T&\\2&u66  II8HIIIMFOR88M 0 0=   &&&&$[[M)) d----D]]m++ //// ,
 Ar$   c                       e Zd ZdZddZed             Zededefd            Zede	e
ej        e
         f         fd            Zeddd
            ZdS )_BaseAutoModelClassNreturnc                 n    t          | j        j         d| j        j         d| j        j         d          )Nz+ is designed to be instantiated using the `z5.from_pretrained(pretrained_model_name_or_path)` or `z.from_config(config)` methods.)OSError	__class__r   )selfargskwargss      r"   __init__z_BaseAutoModelClass.__init__  sV    ~& H H.1H H'H H H
 
 	
r$   c                 l   |                     dd           }t          |d          o| j        |j        v }t	          |          | j        v }|rM|j        | j                 }d|v r|                    d          d         }nd }t          ||j        |||          }|r|rd|v r|                    d          \  }}n|j	        }t          ||fi |}	|s3|                     |j        |	d           |	                    |            |                     d	d           }
t          |	          }	 |	j        |fi |S t	          |          | j        v r#t!          || j                  }	 |	j        |fi |S t#          d
|j         d| j         dd                    d | j        D                        d          )Ntrust_remote_codeauto_map--r   upstream_repoTexist_ok
auto_classcode_revision!Unrecognized configuration class  for this kind of AutoModel: .
Model type should be one of , c              3   $   K   | ]}|j         V  d S Nr   r    cs     r"   	<genexpr>z2_BaseAutoModelClass.from_config.<locals>.<genexpr>  $      4\4\AQZ4\4\4\4\4\4\r$   .)pophasattrr   r?   r(   _model_mappingsplitr   _name_or_pathname_or_pathr
   registerr8   register_for_auto_class$add_generation_mixin_to_remote_model_from_configr2   
ValueErrorjoin)clsr-   r;   r>   has_remote_codehas_local_code	class_refrB   repo_idmodel_class_s              r"   from_configz_BaseAutoModelClass.from_config  s$   "JJ':DAA!&*55Y#,&/:Yf);; 	5Iy   ) 5 5a 8 $ 9!6#7hu! ! !  	>0 	>y  %.__T%:%:" -7	7UUfUUK " DV-{TJJJ33s3CCC

?D11A>{KKK+;+F==f===&\\S///*633EFFK+;+F==f===`0@ ` `_b_k ` `+/994\4\I[4\4\4\+\+\` ` `
 
 	
r$   r-   c                     |S )z`Additional autoclass-specific config post-loading manipulation. May be overridden in subclasses.r   )r_   r-   s     r"   _prepare_config_for_auto_classz2_BaseAutoModelClass._prepare_config_for_auto_class  s	     r$   pretrained_model_name_or_pathc                 @	                        dd           }                    d          }dd<   g d}fd|D             }                     dd           }                     dd           }	                     d	d           }
|                     d
d           }|                     dd           }|-t          j        dt                     |t          d          |}|||d
<   |	Nt          |t                    s(t          |t          fdddd|}t          ||	          }	nt          |dd           }	t                      rg|
	i }
|||
d
<   t          |fd|	i|
}|Kt          |dd          5 }t          j        |          }||
d<   |d         }d d d            n# 1 swxY w Y   t          |t                    st#          j                  }                    d          dk    r                     d          }                    d          dk    r                     d          }                    d                               d          }t'          j        |fd||	d|\  }|                    dd           dk    rdd<   |                    dd           dk    rdd<   |                    dd           |d         d<   t+          |d          o| j        |j        v }t1          |          | j        v }d }|r1|j        | j                 }d|v r|                    d          d         }t7          |||||          }|d<   |
d	<   |r|rt9          ||fd|i|}|                     dd           }|s3|                     |j        |d           |                    |            tA          |          } |j        |g|R d|i|S t1          |          | j        v rbtC          || j                  }|j"        |j#                            d d           k    r|$                                } |j        |g|R d|i|S t          d!|j         d"| j         d#d$%                    d% | j        D                        d&          )'Nr-   r>   T
_from_auto)		cache_dirforce_downloadlocal_files_onlyproxiesresume_downloadrevision	subfolderuse_auth_tokentokenc                 D    i | ]}|v |                     |          S r   )rS   )r    namer;   s     r"   r#   z7_BaseAutoModelClass.from_pretrained.<locals>.<dictcomp>  s-    \\\TU[^^dFJJt,,^^^r$   rG   _commit_hashadapter_kwargsrt   rs   zrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.zV`token` and `use_auth_token` are both specified. Please set only the argument `token`.F) _raise_exceptions_for_gated_repo%_raise_exceptions_for_missing_entries'_raise_exceptions_for_connection_errorsrzutf-8)encoding_adapter_model_pathbase_model_name_or_pathtorch_dtypeautodtypequantization_config)return_unused_kwargsrG   rw   r?   r@   r   rA   rC   rE   text_configrH   rI   rJ   rK   c              3   $   K   | ]}|j         V  d S rM   r   rN   s     r"   rP   z6_BaseAutoModelClass.from_pretrained.<locals>.<genexpr>a  rQ   r$   rR   )&rS   getwarningswarnFutureWarningr]   r)   r	   r   r   r   r,   r   r   openjsonloadcopydeepcopyr   from_pretrainedrT   r   r?   r(   rU   rV   r   r
   rY   r8   rZ   r[   r2   config_classsub_configsget_text_configr^   )r_   ri   
model_argsr;   r-   r>   hub_kwargs_names
hub_kwargsrG   commit_hashrx   rt   rs   resolved_config_filemaybe_adapter_pathfadapter_configkwargs_origre   r`   ra   rB   rb   rd   s      `                    r"   r   z#_BaseAutoModelClass.from_pretrained  sk   Hd++"JJ':;;#|

 

 

 ]\\\9I\\\


?D99jj66$4d;;w--#(8$??%M E     l   #E"'Jwf&677 D'21( 6;:?<A( ( !( ($ 22FTT%fndCC 	^%!#$.3N7+!9-" "<G"KY" " "-,cGDDD ^%)Yq\\N<YN#894BC\4]1	^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ &"233 	S-//K zz-((F22JJ}--zz'""f,,JJw''zz/00<JJ455'7-%)+(	 
   NFF }d33v==(.}%w--77"(w4d;;G0;<Q0R,-!&*55Y#,&/:Yf);; 	95Iy   ) 5 5a 85)'
 
 
 '8"# $2  	0 	78 HUYcgm K 55A " DV-{TJJJ33s3CCC>{KKK.;.-0:  CIMW[a   &\\S///*633EFFK'6+=+A+A-QU+V+VVV//11.;.-0:  CIMW[a   `0@ ` `_b_k ` `+/994\4\I[4\4\4\+\+\` ` `
 
 	
s   4"F""F&)F&Fc                     t          |d          r0|j        j        |j        k    rt          d|j         d| d          | j                            |||           dS )a  
        Register a new model for this class.

        Args:
            config_class ([`PretrainedConfig`]):
                The configuration corresponding to the model to register.
            model_class ([`PreTrainedModel`]):
                The model to register.
        r   zThe model class you are passing has a `config_class` attribute that is not consistent with the config class you passed (model has z and you passed z!. Fix one of those so they match!rC   N)rT   r   r   r]   rU   rY   )r_   r   rd   rD   s       r"   rY   z_BaseAutoModelClass.registerd  s     ;// 	K4L4UYeYn4n4n.6A6N. .`l. . .  
 	##L+#QQQQQr$   r5   NF)r   
__module____qualname__rU   r<   classmethodrf   r	   rh   r   strosPathLiker   rY   r   r$   r"   r4   r4     s        N
 
 
 
 $
 $
 [$
L 4D IY    [ M
E#r{SVGWBW<X M
 M
 M
 [M
^ R R R R [R R Rr$   r4   c                   L     e Zd ZdZe fd            Ze fd            Z xZS )_BaseAutoBackboneClassNc                 .   t          | ddg           ddlm} |                    d |                      }|                    d          t          d          |                    dd	          rt          d
          |                    d|j                  }|                    d|j                  }|                    d|j                  }|                    d|j	                  }	 ||||||	          } t                      j        |fi |S )Nvisiontimmr   )TimmBackboneConfigr-   out_featuresz0Cannot specify `out_features` for timm backbonesoutput_loading_infoFz@Cannot specify `output_loading_info=True` when loading from timmnum_channelsfeatures_onlyuse_pretrained_backboneout_indices)backboner   r   r   r   )r   models.timm_backboner   rS   r   r]   r   r   r   r   superrf   )r_   ri   r   r;   r   r-   r   r   r   r   r8   s             r"   #_load_timm_backbone_from_pretrainedz:_BaseAutoBackboneClass._load_timm_backbone_from_pretrained|  s0   #&1222>>>>>>H&8&8&:&:;;::n%%1OPPP::+U33 	a_```zz.&2EFF

?F4HII"(**-FHf"g"gjj0BCC##2%'$;#
 
 
 #uww"644V444r$   c                     |                     dd          }|r | j        |g|R i |S  t                      j        |g|R i |S )Nuse_timm_backboneF)rS   r   r   r   )r_   ri   r   r;   r   r8   s        r"   r   z&_BaseAutoBackboneClass.from_pretrained  sp    "JJ':EBB 	q:3:;Xp[epppioppp&uww&'D\z\\\U[\\\r$   )r   r   r   rU   r   r   r   __classcell__)r8   s   @r"   r   r   x  su        N5 5 5 5 [52 ] ] ] ] [] ] ] ] ]r$   r    head_docc                     t          |          dk    r|                     dd| d          S |                     dd          S )Nr   z(one of the model classes of the library z0one of the model classes of the library (with a z head) z-one of the base model classes of the library )lenreplace)	docstringr   s     r"   insert_head_docr     s\    
8}}q  6PxPPP
 
 	
 24c  r$   google-bert/bert-base-casedcheckpoint_for_examplec                    | j         }| j        }t          t          |          }|                    d|          | _        t          t          j                  }t          t          |          }|                    d|          }|                    d|          }||_         t          |j         d          |          }t          |          | _        |                    d          rt          }n$|                    d          rt          }nt          }t          t          j                  }	t          ||          }|                    d|          }|                    d|          }|                    d          d	                             d
          d         }
|                    d|
          }||	_         t          |j                   |	          }	t          |	          | _        | S )N)r   BaseAutoModelClasscheckpoint_placeholderF)use_model_typesr&   r'   /-r   shortcut_placeholder)rU   r   r   CLASS_DOCSTRINGr   __doc__r   r4   rf   FROM_CONFIG_DOCSTRINGr   r   
startswithFROM_PRETRAINED_TF_DOCSTRINGFROM_PRETRAINED_FLAX_DOCSTRINGFROM_PRETRAINED_TORCH_DOCSTRINGr   rV   )r_   r   r   r.   rv   class_docstringrf   from_config_docstringfrom_pretrained_docstringr   shortcuts              r"   auto_class_updater     s   &M<D%oIIIO!))*>EECK /;<<K+,AHUUU199:NPTUU199:RTjkk/Kh3M4PbghhhituuK!+..COt D$@!!		 	  D$B!!$C! 3 CDDO /0IT\ ] ] ] 9 A ABVX\ ] ] 9 A ABZ\r s s%++C004::3??BH 9 A ABXZb c c7OU78TUUVeffO%o66CJr$   c                     g }|                                  D ]F}t          |t          t          f          r|t          |          z  }1|                    |           G|S rM   )valuesr)   r*   r+   append)r.   resultr!   s      r"   
get_valuesr     sd    F%%'' ! !edE]++ 	!d5kk!FFMM%    Mr$   c           
      |    |d S t          |t                    rt           fd|D                       S t           |          rt           |          S t	          j        d          } |k    r8	 t          ||          S # t          $ r t          d| d  d| d          w xY wt          d| d| d          )Nc              3   8   K   | ]}t          |          V  d S rM   )getattribute_from_module)r    amodules     r"   rP   z+getattribute_from_module.<locals>.<genexpr>  s.      GGQ-fa88GGGGGGr$   transformerszCould not find z neither in z nor in !z in )r)   r+   rT   r,   	importlibimport_moduler   r]   )r   attrtransformers_modules   `  r"   r   r     s
   |t$ HGGGG$GGGGGGvt %vt$$$ $1.AA$$$	i+,?FFF 	i 	i 	igtggggQdggghhh	i K4KK5HKKKLLLs   1B $B%c                 v   dt          | j                  vr| S dt          | j                  v r| S t          | d          odt          t	          | d                    v}t          | d          odt          t	          | d                    v}|s|r&t          | j        | t          fi | j                  }|S | S )a  
    Adds `GenerationMixin` to the inheritance of `model_class`, if `model_class` is a PyTorch model.

    This function is used for backwards compatibility purposes: in v4.45, we've started a deprecation cycle to make
    `PreTrainedModel` stop inheriting from `GenerationMixin`. Without this function, older models dynamically loaded
    from the Hub may not have the `generate` method after we remove the inheritance.
    ztorch.nn.modules.module.Moduler   generateprepare_inputs_for_generation)	r   __mro__	__bases__rT   r,   r(   r   r   __dict__)rd   has_custom_generate_in_classhas_custom_prepare_inputs!model_class_with_generation_mixins       r"   r[   r[     s     (s;3F/G/GGG C 56666 $+;
#C#C $HYadZ((b b I  !(5T U U !Zksv<==t t [ $ 1'@ 1,0 ;"@BZ[EYBZ-
 -
) 10r$   c                   J   e Zd ZdZddZdefdZdee         de	fdZ
d Zdeee                  fd	Zdee         d
edee	ef         fdZdefdZdee	         fdZdeeee         e	f                  fdZdeee                  fdZdedefdZddee         de	ddfdZdS )_LazyAutoMappinga  
    " A mapping config to object (model or tokenizer for instance) that will load keys and values when it is accessed.

    Args:
        - config_mapping: The map model type to config class
        - model_mapping: The map model type to model (or tokenizer) class
    r5   Nc                     || _         d |                                D             | _        || _        | | j        _        i | _        i | _        d S )Nc                     i | ]\  }}||	S r   r   )r    kvs      r"   r#   z-_LazyAutoMapping.__init__.<locals>.<dictcomp>  s    'P'P'PA1'P'P'Pr$   )_config_mappingitems_reverse_config_mappingrU   _extra_content_modules)r9   config_mappingr.   s      r"   r<   z_LazyAutoMapping.__init__  sR    -'P'P9M9M9O9O'P'P'P$+-1* r$   c                     t          | j                                                                      | j                                                  }t          |          t          | j                  z   S rM   )setr   keysintersectionrU   r   r   )r9   common_keyss     r"   __len__z_LazyAutoMapping.__len__  sY    $.335566CCDDWD\D\D^D^__;#d&9":":::r$   keyc                 z   | j         v r| j                  S | j        j                 }|| j        v r#| j        |         }|                     ||          S fd| j                                        D             }|D ]0}|| j        v r%| j        |         }|                     ||          c S 1t                    )Nc                 0    g | ]\  }}|j         k    |S r   r   )r    r   r   r  s      r"   
<listcomp>z0_LazyAutoMapping.__getitem__.<locals>.<listcomp>*  s)    WWWTQQ#,EVEVqEVEVEVr$   )r   r   r   rU   _load_attr_from_moduler   r   KeyError)r9   r  
model_type
model_namemodel_typesmtypes    `    r"   __getitem__z_LazyAutoMapping.__getitem__!  s    $%%%&s++1#,?
,,,,Z8J..z:FFF XWWWT%9%?%?%A%AWWW  	F 	FE+++!07
225*EEEEE , smmr$   c                     t          |          }|| j        vr t          j        d| d          | j        |<   t	          | j        |         |          S )NrR   ztransformers.models)r   r   r   r   r   )r9   r  r   module_names       r"   r  z'_LazyAutoMapping._load_attr_from_module1  sV    /
;;dm++)2)@AR[ARARTi)j)jDM+&'k(BDIIIr$   c                       fd j                                         D             }|t           j                                                  z   S )Nc                 T    g | ]$\  }}|j         v                     ||          %S r   )rU   r  r    r  rv   r9   s      r"   r  z)_LazyAutoMapping.keys.<locals>.<listcomp>8  sE     
 
 
Td))) ''T22)))r$   )r   r   r*   r   r   )r9   mapping_keyss   ` r"   r   z_LazyAutoMapping.keys7  s^    
 
 
 
!17799
 
 

 d4#6#;#;#=#=>>>>r$   defaultc                 R    	 |                      |          S # t          $ r |cY S w xY wrM   )r  r  )r9   r  r  s      r"   r   z_LazyAutoMapping.get?  s?    	##C((( 	 	 	NNN	s    &&c                 D    t          |                                           S rM   )boolr   r9   s    r"   __bool__z_LazyAutoMapping.__bool__E      DIIKK   r$   c                       fd j                                         D             }|t           j                                                  z   S )Nc                 T    g | ]$\  }}|j         v                     ||          %S r   )r   r  r  s      r"   r  z+_LazyAutoMapping.values.<locals>.<listcomp>I  sE     
 
 
Td*** ''T22***r$   )rU   r   r*   r   r   )r9   mapping_valuess   ` r"   r   z_LazyAutoMapping.valuesH  s^    
 
 
 
!06688
 
 

 T%8%?%?%A%A B BBBr$   c                 |      fd j         D             }|t           j                                                  z   S )Nc                     g | ]M}|j         v                     |j         |                                       |j        |                   fNS r   )r   r  rU   )r    r  r9   s     r"   r  z*_LazyAutoMapping.items.<locals>.<listcomp>Q  sm     
 
 

 d***	 ++C1Ec1JKK++C1DS1IJJ
 +**r$   )rU   r*   r   r   )r9   mapping_itemss   ` r"   r   z_LazyAutoMapping.itemsP  sT    
 
 
 

 *
 
 
 tD$7$=$=$?$?@@@@r$   c                 D    t          |                                           S rM   )iterr   r  s    r"   __iter__z_LazyAutoMapping.__iter__[  r  r$   itemc                     || j         v rdS t          |d          r|j        | j        vrdS | j        |j                 }|| j        v S )NTr   F)r   rT   r   r   rU   )r9   r"  r  s      r"   __contains__z_LazyAutoMapping.__contains__^  sX    4&&&4tZ(( 	DMA],],]51$-@
T000r$   Fvaluec                     t          |d          r>|j        | j        v r0| j        |j                 }|| j        v r|st	          d| d          || j        |<   dS )z7
        Register a new model in this mapping.
        r   'z*' is already used by a Transformers model.N)rT   r   r   rU   r]   r   )r9   r  r%  rD   r  s        r"   rY   z_LazyAutoMapping.registerf  su     3
## 	V8T(T(T5clCJT0000 !TS!T!T!TUUU#(C   r$   r   r   )r   r   r   r   r<   intr   r(   r	   _LazyAutoMappingValuer  r  r*   r   r   r   r   r  r  r   r+   r   r   r!  r$  rY   r   r$   r"   r   r     s           ; ; ; ; ;t$45 :O     J J J?d4 012 ? ? ? ?t,-  uEZ\^E^?_    !$ ! ! ! !C23 C C C C	AtE$'7"8:O"OPQ 	A 	A 	A 	A!(4(8#9: ! ! ! !1 1$ 1 1 1 1	) 	)D!12 	);P 	)ei 	) 	) 	) 	) 	) 	)r$   r   r   )r   )r   r   ):r   r   r   r   r   r   collectionsr   collections.abcr   typingr   r   r   configuration_utilsr	   dynamic_module_utilsr
   r   utilsr   r   r   r   r   r   r   r   r   configuration_autor   r   r   
generationr   
get_loggerr   loggerr   r+   r(   r)  r   r   r   r   r   r2   r4   r   r   r   r   r   r   r[   r   __all__r   r$   r"   <module>r5     s   4 3       				  # # # # # # $ $ $ $ $ $ & & & & & & & & & & 3 3 3 3 3 3 \ \ \ \ \ \ \ \
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 i h h h h h h h h h  .------ 
	H	%	%WT]]eDItO4eDItO6LLM  4j# Xa  Fa" H  (XR XR XR XR XR XR XR XRv$] $] $] $] $]0 $] $] $]N        3  be        F  M M M(  @c) c) c) c) c){4(8#9;P#PQ c) c) c)L .r$   