o
    hHX                     @   s  d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	m
Z
 ddlmZmZ ddlmZ ddlmZmZmZmZmZ ddlZd	d
lmZmZmZmZ e rUddlmZ G dd deZ dd Z!dd Z"dd Z#dd Z$dd Z%dd Z&dd Z'dd Z(dd Z)dd  Z*d!d" Z+d#d$ Z,d%d& Z-d'd( Z.d)d* Z/d+d, Z0d-d. Z1d/d0 Z2d1d2 Z3d3d4 Z4G d5d6 d6eZ5e rddl6m7  m8Z9 d7e5d8eee d9f fd:d;Z:d<ee d=d9d8e5fd>d?Z;e9<e5e:e; G d@dA dAe=eZ>G dBdC dCe>Z?G dDdE dEe>Z@G dFdG dGZAdHdI ZBdJdK ZCdedNedOe=dPe=fdQdRZDe
dfdTeEfdUdVZFdgdWdXZGdYdZ ZHdgd[d\ZId]d^ ZJd_d` ZKdadb ZLdcdd ZMdS )hz
Generic utilities
    N)OrderedDictUserDict)MutableMapping)	ExitStackcontextmanager)fieldsis_dataclass)Enum)AnyContextManagerIterableListTuple   )is_flax_availableis_tf_availableis_torch_availableis_torch_fx_proxyc                   @   s   e Zd ZdZdddZdS )cached_propertyz
    Descriptor that mimics @property but caches output in member variable.

    From tensorflow_datasets

    Built-in in functools from Python 3.8.
    Nc                 C   sX   |d u r| S | j d u rtdd| j j }t||d }|d u r*|  |}t||| |S )Nzunreadable attribute	__cached_)fgetAttributeError__name__getattrsetattr)selfobjobjtypeattrcached r    P/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/utils/generic.py__get__-   s   

zcached_property.__get__N)r   
__module____qualname____doc__r"   r    r    r    r!   r   $   s    r   c                 C   s.   |   } | dv r
dS | dv rdS td| )zConvert a string representation of truth to true (1) or false (0).

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'.
    Raises ValueError if 'val' is anything else.
    >   1tyonyestruer   >   0fnnoofffalser   zinvalid truth value )lower
ValueError)valr    r    r!   	strtobool<   s   r6   c                 C   sH   t t| }|drdS |drdS |drdS |dr"dS d	S )
z
    Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the
    frameworks in a smart order, without the need to import the frameworks).
    z<class 'torch.ptz<class 'tensorflow.tfz<class 'jaxjaxz<class 'numpy.npN)strtype
startswith)xrepresentationr    r    r!   infer_framework_from_reprJ   s   



r@   c                    sd   t tttd t| du rg ng}dkr|d |fdd D   fdd|D S )z
    Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework
    we can guess from the repr first, then Numpy, then the others.
    r7   r8   r9   r:   Nr:   c                    s   g | ]
}| d fvr|qS )r:   r    .0r.   )preferred_frameworkr    r!   
<listcomp>j   s    z1_get_frameworks_and_test_func.<locals>.<listcomp>c                    s   i | ]}| | qS r    r    rB   )framework_to_testr    r!   
<dictcomp>k   s    z1_get_frameworks_and_test_func.<locals>.<dictcomp>)is_torch_tensoris_tf_tensoris_jax_tensoris_numpy_arrayr@   appendextend)r>   
frameworksr    )rF   rD   r!   _get_frameworks_and_test_funcZ   s   
rO   c                 C   sT   t | }| D ]	}|| r dS qt| rdS t r(ddlm} t| |r(dS dS )z
    Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray` or `np.ndarray` in the order
    defined by `infer_framework_from_repr`
    Tr   )TracerF)rO   valuesr   r   jax.corerP   
isinstance)r>   framework_to_test_func	test_funcrP   r    r    r!   	is_tensorn   s   
rV   c                 C   s   t | tjS r#   )rS   r:   ndarrayr>   r    r    r!   	_is_numpy   s   rY   c                 C   s   t | S )z/
    Tests if `x` is a numpy array or not.
    )rY   rX   r    r    r!   rK      s   rK   c                 C      dd l }t| |jS Nr   )torchrS   Tensorr>   r\   r    r    r!   	_is_torch      r_   c                 C      t  sdS t| S )z]
    Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed.
    F)r   r_   rX   r    r    r!   rH         rH   c                 C   rZ   r[   )r\   rS   devicer^   r    r    r!   _is_torch_device   r`   rd   c                 C   ra   )z]
    Tests if `x` is a torch device or not. Safe to call even if torch is not installed.
    F)r   rd   rX   r    r    r!   is_torch_device   rb   re   c                 C   s8   dd l }t| trt|| rt|| } ndS t| |jS )Nr   F)r\   rS   r;   hasattrr   dtyper^   r    r    r!   _is_torch_dtype   s   

rh   c                 C   ra   )z\
    Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed.
    F)r   rh   rX   r    r    r!   is_torch_dtype   rb   ri   c                 C   rZ   r[   )
tensorflowrS   r]   r>   r8   r    r    r!   _is_tensorflow   r`   rl   c                 C   ra   )zg
    Tests if `x` is a tensorflow tensor or not. Safe to call even if tensorflow is not installed.
    F)r   rl   rX   r    r    r!   rI      rb   rI   c                 C   s*   dd l }t|dr|| S t| |jkS )Nr   is_symbolic_tensor)rj   rf   rm   r<   r]   rk   r    r    r!   _is_tf_symbolic_tensor   s   

rn   c                 C   ra   )z
    Tests if `x` is a tensorflow symbolic tensor or not (ie. not eager). Safe to call even if tensorflow is not
    installed.
    F)r   rn   rX   r    r    r!   is_tf_symbolic_tensor   s   ro   c                 C   s   dd l m} t| |jS r[   )	jax.numpynumpyrS   rW   )r>   jnpr    r    r!   _is_jax   s   rs   c                 C   ra   )zY
    Tests if `x` is a Jax tensor or not. Safe to call even if jax is not installed.
    F)r   rs   rX   r    r    r!   rJ      rb   rJ   c                 C   s   dd dd dd dd d}t | ttfrdd |  D S t | ttfr-d	d
 | D S t| }| D ]\}}|| rE|| |   S q5t | tjrP| 	 S | S )zc
    Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
    c                 S      |     S r#   )detachcputolistr   r    r    r!   <lambda>       zto_py_obj.<locals>.<lambda>c                 S   s   |    S r#   )rq   rw   rx   r    r    r!   ry      s    c                 S   s   t |  S r#   )r:   asarrayrw   rx   r    r    r!   ry      s    c                 S      |   S r#   )rw   rx   r    r    r!   ry          rA   c                 S      i | ]	\}}|t |qS r    	to_py_objrC   kvr    r    r!   rG          zto_py_obj.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r    r   )rC   or    r    r!   rE      s    zto_py_obj.<locals>.<listcomp>)
rS   dictr   itemslisttuplerO   r:   numberrw   )r   framework_to_py_objrT   	frameworkrU   r    r    r!   r      s"   r   c                 C   s   dd dd dd dd d}t | ttfrdd |  D S t | ttfr+t| S t| }| D ]\}}|| rC|| |   S q3| S )	zc
    Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array.
    c                 S   rt   r#   )ru   rv   rq   rx   r    r    r!   ry     rz   zto_numpy.<locals>.<lambda>c                 S   r|   r#   )rq   rx   r    r    r!   ry     r}   c                 S   s
   t | S r#   )r:   r{   rx   r    r    r!   ry     s   
 c                 S   s   | S r#   r    rx   r    r    r!   ry     s    rA   c                 S   r~   r    )to_numpyr   r    r    r!   rG     r   zto_numpy.<locals>.<dictcomp>)	rS   r   r   r   r   r   r:   arrayrO   )r   framework_to_numpyrT   r   rU   r    r    r!   r     s   
r   c                       s   e Zd ZdZdddZ fddZdd	 Zd
d Zdd Zdd Z	dd Z
dd Z fddZ fddZ fddZdee fddZ  ZS )ModelOutputa  
    Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a
    tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular
    python dictionary.

    <Tip warning={true}>

    You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple
    before.

    </Tip>
    returnNc                 C   s   t  rt| tt dS dS )zRegister subclasses as pytree nodes.

        This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with
        `static_graph=True` with modules that output `ModelOutput` subclasses.
        N)r   _torch_pytree_register_pytree_node_model_output_flatten_model_output_unflatten)clsr    r    r!   __init_subclass__.  s   zModelOutput.__init_subclass__c                    sJ   t  j|i | | jtk}|r!t| s#t| j d| jj dd S d S )N.za is not a dataclasss. This is a subclass of ModelOutput and so must use the @dataclass decorator.)super__init__	__class__r   r   	TypeErrorr$   r   )r   argskwargsis_modeloutput_subclassr   r    r!   r   ;  s   
zModelOutput.__init__c           
         s  t  }t|st jj dtdd |dd D s't jj dt |d j}t fdd|dd D }|rt|st	|t
rP| }d	}nzt|}d	}W n tyc   d
}Y nw |rt|D ]F\}}t	|ttfrt|dkrt	|d ts|dkr| |d j< ntd| d nt |d |d  |d dur|d  |d < qjdS dS |dur| |d j< dS dS |D ]}t |j}	|	dur|	 |j< qdS )zeCheck the ModelOutput dataclass.

        Only occurs if @dataclass decorator has been used.
        z has no fields.c                 s   s    | ]}|j d u V  qd S r#   )defaultrC   fieldr    r    r!   	<genexpr>T  s    z,ModelOutput.__post_init__.<locals>.<genexpr>r   Nz. should not have more than one required field.r   c                 3   s     | ]}t  |jd u V  qd S r#   r   namer   r   r    r!   r   X  s    TF   zCannot set key/value for z&. It needs to be a tuple (key, value).)r   lenr4   r   r   allr   r   rV   rS   r   r   iterr   	enumerater   r   r;   r   )
r   class_fieldsfirst_fieldother_fields_are_noneiteratorfirst_field_iteratoridxelementr   r   r    r   r!   __post_init__J  sZ   


zModelOutput.__post_init__c                 O      t d| jj d)Nz$You cannot use ``__delitem__`` on a 
 instance.	Exceptionr   r   r   r   r   r    r    r!   __delitem__     zModelOutput.__delitem__c                 O   r   )Nz#You cannot use ``setdefault`` on a r   r   r   r    r    r!   
setdefault  r   zModelOutput.setdefaultc                 O   r   )NzYou cannot use ``pop`` on a r   r   r   r    r    r!   pop  r   zModelOutput.popc                 O   r   )NzYou cannot use ``update`` on a r   r   r   r    r    r!   update  r   zModelOutput.updatec                 C   s*   t |trt|  }|| S |  | S r#   )rS   r;   r   r   to_tuple)r   r   
inner_dictr    r    r!   __getitem__  s   
zModelOutput.__getitem__c                    s4   ||   v r|d urt || t || d S r#   )keysr   __setitem____setattr__)r   r   valuer   r    r!   r     s   zModelOutput.__setattr__c                    s    t  || t  || d S r#   )r   r   r   )r   keyr   r   r    r!   r     s   zModelOutput.__setitem__c                    sJ   t  s	t  S t  ^}}}t fddt D }||g|R S )Nc                 3   s    | ]	}t  |jV  qd S r#   r   r   r   r    r!   r     s    z)ModelOutput.__reduce__.<locals>.<genexpr>)r   r   
__reduce__r   r   )r   callable_args	remainingr   r   r   r!   r     s
   
zModelOutput.__reduce__c                    s   t  fdd  D S )za
        Convert self to a tuple containing all the attributes/keys that are not `None`.
        c                 3   s    | ]} | V  qd S r#   r    )rC   r   r   r    r!   r     s    z'ModelOutput.to_tuple.<locals>.<genexpr>)r   r   r   r    r   r!   r     s   zModelOutput.to_tuple)r   N)r   r$   r%   r&   r   r   r   r   r   r   r   r   r   r   r   r   r
   r   __classcell__r    r    r   r!   r      s    
8r   outputr   z_torch_pytree.Contextc                 C   s    t |  t| t |  ffS r#   )r   rQ   r<   r   )r   r    r    r!   r     s    r   rQ   contextc                 C   s    |\}}|di t t|| S )Nr    )r   zip)rQ   r   output_typer   r    r    r!   r     s   r   c                   @   s   e Zd ZdZedd ZdS )ExplicitEnumzC
    Enum with more explicit error message for missing values.
    c                 C   s$   t | d| j dt| j  )Nz is not a valid z, please select one of )r4   r   r   _value2member_map_r   )r   r   r    r    r!   	_missing_  s   zExplicitEnum._missing_N)r   r$   r%   r&   classmethodr   r    r    r    r!   r     s    r   c                   @   s   e Zd ZdZdZdZdZdS )PaddingStrategyz
    Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an
    IDE.
    longest
max_length
do_not_padN)r   r$   r%   r&   LONGEST
MAX_LENGTH
DO_NOT_PADr    r    r    r!   r     s
    r   c                   @   s    e Zd ZdZdZdZdZdZdS )
TensorTypez
    Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for
    tab-completion in an IDE.
    r7   r8   r:   r9   N)r   r$   r%   r&   PYTORCH
TENSORFLOWNUMPYJAXr    r    r    r!   r     s    r   c                   @   s2   e Zd ZdZdee fddZdd Zdd Zd	S )
ContextManagersz
    Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers`
    in the `fastcore` library.
    context_managersc                 C   s   || _ t | _d S r#   )r   r   stack)r   r   r    r    r!   r     s   zContextManagers.__init__c                 C   s   | j D ]}| j| qd S r#   )r   r   enter_context)r   context_managerr    r    r!   	__enter__  s   
zContextManagers.__enter__c                 O   s   | j j|i | d S r#   )r   __exit__r   r    r    r!   r     s   zContextManagers.__exit__N)	r   r$   r%   r&   r   r   r   r   r   r    r    r    r!   r     s
    r   c                 C   sn   t | }|dkrt| j}n|dkrt| j}nt| j}|jD ]}|dkr4|j| jdu r4 dS q#dS )zr
    Check if a given model can return loss.

    Args:
        model_class (`type`): The class of the model.
    r8   r7   return_lossTF)infer_frameworkinspect	signaturecallforward__call__
parametersr   )model_classr   r   pr    r    r!   can_return_loss  s   
r   c                 C   sn   | j }t| }|dkrt| j}n|dkrt| j}nt| j}d|v r/dd |jD S dd |jD S )zq
    Find the labels used by a given model.

    Args:
        model_class (`type`): The class of the model.
    r8   r7   QuestionAnsweringc                 S   s    g | ]}d |v s|dv r|qS )label)start_positionsend_positionsr    rC   r   r    r    r!   rE     s     zfind_labels.<locals>.<listcomp>c                 S   s   g | ]}d |v r|qS )r   r    r   r    r    r!   rE     s    )r   r   r   r   r   r   r   r   )r   
model_namer   r   r    r    r!   find_labels  s   r    r   d
parent_key	delimiterc                 C   s   ddd}t || ||S )z/Flatten a nested dict into a single level dict.r   r   c                 s   sf    |   D ]+\}}|rt|| t| n|}|r+t|tr+t|||d  E d H  q||fV  qd S )N)r   )r   r;   rS   r   flatten_dict)r   r   r   r   r   r   r    r    r!   _flatten_dict$  s   z#flatten_dict.<locals>._flatten_dictNr   r   )r   )r   r   r   r   r    r    r!   r   !  s   
r   Fuse_temp_dirc                 c   sD    |rt  }|V  W d    d S 1 sw   Y  d S | V  d S r#   )tempfileTemporaryDirectory)working_dirr   tmp_dirr    r    r!   working_or_temp_dir/  s   
"
r  c                 C   s~   t | rtj| |dS t| r|du r| jS | j| S t| r*ddl}|j| |dS t| r5t	j| |dS t
dt|  d)z
    Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy
    arrays.
    )axesNr   )permz"Type not supported for transpose: r   )rK   r:   	transposerH   TpermuterI   rj   rJ   rr   r4   r<   )r   r  r8   r    r    r!   r  8  s   r  c                 C   sj   t | r
t| |S t| r| j| S t| r!ddl}|| |S t| r+t| |S tdt	|  d)z
    Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy
    arrays.
    r   Nz Type not supported for reshape: r   )
rK   r:   reshaperH   rI   rj   rJ   rr   r4   r<   )r   newshaper8   r    r    r!   r  K  s   
r  c                 C   s   t | rtj| |dS t| r|du r|  S | j|dS t| r,ddl}|j| |dS t| r7tj| |dS tdt	|  d)z
    Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy
    arrays.
    axisNdimr   z Type not supported for squeeze: r   )
rK   r:   squeezerH   rI   rj   rJ   rr   r4   r<   r   r  r8   r    r    r!   r  ^  s   r  c                 C   sp   t | r
t| |S t| r| j|dS t| r#ddl}|j| |dS t| r.tj| |dS t	dt
|  d)z
    Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy
    arrays.
    r  r   Nr  $Type not supported for expand_dims: r   )rK   r:   expand_dimsrH   	unsqueezerI   rj   rJ   rr   r4   r<   r  r    r    r!   r  q  s   r  c                 C   s^   t | r	t| S t| r|  S t| rddl}|| S t| r%| jS tdt	|  d)z|
    Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays.
    r   Nr  r   )
rK   r:   sizerH   numelrI   rj   rJ   r4   r<   )r   r8   r    r    r!   tensor_size  s   

r  c                    s^   |   D ](\}}t|ttfr fdd|D | |< q|dur,d|vr,  d| | |< q| S )zB
    Adds the information of the repo_id to a given auto map.
    c                    s.   g | ]}|d urd|vr  d| n|qS )N--r    )rC   r   repo_idr    r!   rE     s   . z.add_model_info_to_auto_map.<locals>.<listcomp>Nr  )r   rS   r   r   )auto_mapr  r   r   r    r  r!   add_model_info_to_auto_map  s   r  c                 C   s   t | D ]6}|j}|j}|ds|ds|dkr dS |ds'|dkr* dS |ds8|d	s8|d
kr; dS qtd|  d)z
    Infers the framework of a given model without using isinstance(), because we cannot guarantee that the relevant
    classes are imported or available.
    rj   kerasTFPreTrainedModelr8   r\   PreTrainedModelr7   flaxr9   FlaxPreTrainedModelz%Could not infer framework from class r   )r   getmror$   r   r=   r   )r   
base_classmoduler   r    r    r!   r     s   r   r   )Fr#   )Nr&   r   r  collectionsr   r   collections.abcr   
contextlibr   r   dataclassesr   r   enumr	   typingr
   r   r   r   r   rq   r:   import_utilsr   r   r   r   rp   rr   propertyr   r6   r@   rO   rV   rY   rK   r_   rH   rd   re   rh   ri   rl   rI   rn   ro   rs   rJ   r   r   r   torch.utils._pytreeutils_pytreer   r   r   r   r;   r   r   r   r   r   r   r   boolr  r  r  r  r  r  r  r   r    r    r    r!   <module>   sz   	 

