CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
data_collator.cpython-310.pyc610 linesDownload Raw Back to __pycache__
1o

2.�Yi���@sNddlZddlZddlZddlmZddlmZddlmZddl	m3Z4mZmZm
Z
ddlZddlmZddlmZe5Z	eeegeee6ffZGd	d7�d8�Zdd�Zd7deedeee9ffdd�ZeGdd�de��Zdeedeee10ffdd�Zdeedeee11ffdd�Zdeedeee12ffdd�ZeGdd�d��Z eGdd�de��Z!d8dee"fdd �Z#d8dee"fd!d"�Z$d8dee"fd#d$�Z%eGd%d&�d&e��Z&eGd'd(�d(��Z'eGd)d*�d*e��Z(eGd+d,�d,e(��Z)dee13fd-d.�Z*dej+e14fd/d0�Z,eGd1d2�d2e(��Z-eGd3d4�d4e��Z.eGd5d6�d6e��Z/dS)9�N)�Mapping)�	dataclass)�randint)�Any�Callable�Optional�Union�)�PreTrainedTokenizerBase)�PaddingStrategyc@s eZdZddeefdd�ZdS)�DataCollatorMixinN�return_tensorscCsT|dur|j}|dkr|�|�S|dkr|�|�S|dkr"|�|�Std|�d���)N�tf�pt�npzFramework 'z' not recognized!)r
�tf_call�15torch_call�16numpy_call�17ValueError��self�featuresr
�r��E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\transformers/data/data_collator.py�__call__'s181920zDataCollatorMixin.__call__�N)�__name__�21__module__�__qualname__r�strrrrrrr&src	Os`t|d�s
|j|i|��S|j�dd�}d|jd<z|j|i|��}W||jd<|S||jd<w)zz22    Pads without triggering the warning about how using the pad function is sub-optimal when using a fast tokenizer.23    �deprecation_warningszAsking-to-pad-a-fast-tokenizerFT)�hasattr�padr �get)�	tokenizerZpad_argsZ24pad_kwargsZ
warning_state�paddedrrr�"pad_without_fast_tokenizer_warning4s252627�r&rr�returncCs4|dkrt|�S|dkrt|�S|dkrt|�SdS)a�28    Very simple data collator that simply collates batches of dict-like objects and performs special handling for29    potential keys named:30 31        - `label`: handles a single value (int or float) per object32        - `label_ids`: handles a list of values per object33 34    Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs35    to the model. See glue and ner for example of how it's useful.36    rrrN)�torch_default_data_collator�tf_default_data_collator�numpy_default_data_collator)rr
rrr�default_data_collatorJs�r+c@sFeZdZUdZdZeed<d	deeee	fdeee	ffdd�Z37dS)38�DefaultDataCollatora*39    Very simple data collator that simply collates batches of dict-like objects and performs special handling for40    potential keys named:41 42        - `label`: handles a single value (int or float) per object43        - `label_ids`: handles a list of values per object44 45    Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs46    to the model. See glue and ner for example of how it's useful.47 48    This is an object (like other data collators) rather than a pure function like default_data_collator. This can be49    helpful if you need to set a return_tensors value at initialization.50 51    Args:52        return_tensors (`str`, *optional*, defaults to `"pt"`):53            The type of Tensor to return. Allowable values are "np", "pt" and "tf".54    rr
Nrr'cCs|dur|j}t||�Sr)r
r+rrrrrys55zDefaultDataCollator.__call__r)rrr�__doc__r
r�__annotations__�list�dictrrrrrrr,cs56,r,cs�ddl}t|dt�sdd�|D�}|d}i}d|vrN|ddurNt|d|j�r0|d��n|d}t|t�r<|jn|j}|jdd�|D�|d�|d<n<d|vr�|ddur�t|d|j�rm|�	d	d�|D��|d<nt|ddt�ry|jn|j}|jd57d�|D�|d�|d<|�58�D]L\�}�dvr�|dur�t|t�s�t||j�r�|�	�fdd�|D��|�<q�t|tj
�r�|�t�	�fd
d�|D���|�<q�|��fdd�|D��|�<q�|S)NrcS�g|]}t|��qSr��vars��.0�frrr�59<listcomp>��z/torch_default_data_collator.<locals>.<listcomp>�labelcS�g|]}|d�qS�r9rr4rrrr7�r8��dtype�labels�	label_idscSr:�r?rr4rrrr7�r8cSr:r@rr4rrrr7�r8�r9r?c�g|]}|��qSrrr4��krrr7�r8crBrrr4rCrrr7�r8crBrrr4rCrrr7�r8)�torch�60isinstancer�Tensor�item�int�long�float�tensor�stack�itemsrr�ndarrayZ61from_numpy)rrE�first�batchr9r=�vrrCrr(s.$$�r(cs�ddl}t|dt�sdd�|D�}|d}i}d|vr%|ddur%d�nd|vr2|ddur2d�nd|vr?|ddur?d�nd��dur�t|�|j�rZ|�jjrV|jn|j}nBt|�tj	tj62f�rvt�|�jtj�rr|jn|j}n&t|�t
tf�r�t|�dt�r�|jn|j}n
t|�t�r�|jn|j}|j�fdd�|D�|d�|d<|��D]7\�}�d	vr�|dur�t|t�s�t||jtj	f�r�|��fd63d�|D��|�<q�|��fdd�|D��|�<q�|S)NrcSr1rr2r4rrrr7�r8z,tf_default_data_collator.<locals>.<listcomp>r9r?r>crBrrr4)�label_col_namerrr7�r8r<)r9r?r>crBrrr4rCrrr7�r8crBrrr4rCrrr7�r8)�64tensorflowrFrrGr=�65is_integer�int64�float32rrOZgenericZ66issubdtype�integer�tupler/rI�convert_to_tensorrNrrM)rrrPrQr=rRr)rDrSrr)�s8"  �r)cs�t|dt�sdd�|D�}|d}i}d|vrJ|ddurJt|dtj�r,|d��n|d}t|t�r8tjntj}tjdd�|D�|d�|d<n<d|vr�|ddur�t|dtj�rit�	d	d�|D��|d<nt|ddt�rutjntj}tjd67d�|D�|d�|d<|�68�D]4\�}�dvr�|dur�t|t�s�t|tj�r�t�	�fdd�|D��|�<q�t��fd
d�|D��|�<q�|S)NrcSr1rr2r4rrrr7�r8z/numpy_default_data_collator.<locals>.<listcomp>r9cSr:r;rr4rrrr7�r8r<r>r?cSr:r@rr4rrrr7�r8cSr:r@rr4rrrr7�r8rAcrBrrr4rCrrr7�r8crBrrr4rCrrr7�r8)rFrrrOrHrIrVrW�arrayrMrNr)rrPrQr9r=rRrrCrr*�s($�r*c@s�eZdZUdZeed<dZeee	e69fed<dZee
ed<dZee
ed<dZe	ed	<d70eee	efdee	effdd
�ZdS)�DataCollatorWithPaddinga�71    Data collator that will dynamically pad the inputs received.72 73    Args:74        tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):75            The tokenizer used for encoding the data.76        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):77            Select a strategy to pad the returned sequences (according to the model's padding side and padding index)78            among:79 80            - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single81              sequence is provided).82            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum83              acceptable input length for the model if that argument is not provided.84            - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).85        max_length (`int`, *optional*):86            Maximum length of the returned list and optionally padding length (see above).87        pad_to_multiple_of (`int`, *optional*):88            If set will pad the sequence to a multiple of the provided value.89 90            This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=91            7.0 (Volta).92        return_tensors (`str`, *optional*, defaults to `"pt"`):93            The type of Tensor to return. Allowable values are "np", "pt" and "tf".94    r$T�paddingN�95max_length�pad_to_multiple_ofrr
rr'cCsVt|j||j|j|j|jd�}d|vr|d|d<|d=d|vr)|d|d<|d=|S)N�r]r^r_r
r9r>r?)r&r$r]r^r_r
)rrrQrrrrs�z DataCollatorWithPadding.__call__)rrrr-r96r.r]r�boolrrr^rrIr_r
r/r0rrrrrrr\�s97*r\c@s�eZdZUdZeed<dZeee	e98fed<dZee
ed<dZee
ed<dZe
ed	<d99Ze	ed<dd
�Zdd�Zdd�ZdS)�"DataCollatorForTokenClassificationa�100    Data collator that will dynamically pad the inputs received, as well as the labels.101 102    Args:103        tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):104            The tokenizer used for encoding the data.105        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):106            Select a strategy to pad the returned sequences (according to the model's padding side and padding index)107            among:108 109            - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single110              sequence is provided).111            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum112              acceptable input length for the model if that argument is not provided.113            - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).114        max_length (`int`, *optional*):115            Maximum length of the returned list and optionally padding length (see above).116        pad_to_multiple_of (`int`, *optional*):117            If set will pad the sequence to a multiple of the provided value.118 119            This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=120            7.0 (Volta).121        label_pad_token_id (`int`, *optional*, defaults to -100):122            The id to use when padding the labels (-100 will be automatically ignore by PyTorch loss functions).123        return_tensors (`str`, *optional*, defaults to `"pt"`):124            The type of Tensor to return. Allowable values are "np", "pt" and "tf".125    r$Tr]Nr^r_�����label_pad_token_idrr
cs�ddl�d|dvrdnd��|dvr�fdd�|D�nd}�fdd�|D�}t�j|�j�j�jdd�}|dur<|S|d	jd126��jj}�fdd��|d
kr_���fdd�|D�|�<n
���fdd�|D�|�<�j|��j	d�|�<|S)Nrr9r>crBrr�r5�feature��127label_namerrr7Ir8zADataCollatorForTokenClassification.torch_call.<locals>.<listcomp>c�"g|]
}�fdd�|��D��qS)c�i|]\}}|�kr||�qSrr�r5rDrRrgrr�128<dictcomp>K�zLDataCollatorForTokenClassification.torch_call.<locals>.<listcomp>.<dictcomp>�rNrergrrr7K�"rr`�	input_ids�cst|�j�r129|��St|�Sr)rFrG�tolistr/)Ztensor_or_iterable�rErr�to_list\sz>DataCollatorForTokenClassification.torch_call.<locals>.to_list�rightcs(g|]}�|��jg�t|��qSr�rd�len�r5r9�r�sequence_lengthrtrrr7b��cs(g|]}�jg�t|��|��qSrrvrxryrrr7fr{r<)130rEr&r$r]r^r_�shape�padding_siderLrV)rrr>Zno_labels_featuresrQr}r)rhrrzrtrErrEs4"�	�131�z-DataCollatorForTokenClassification.torch_callcs�ddl�d|dvrdnd��|dvr�fdd�|D�nd}t�j|�j�j�j|dur/dndd�}|dur9|S��|d�jd	��jj}|d132krX��fdd�|D�|d<n��fdd�|D�|d<�fd
d�|�	�D�}|S)Nrr9r>crBrrrergrrr7qr8z>DataCollatorForTokenClassification.tf_call.<locals>.<listcomp>rr`rprqruc�(g|]}t|��jg�t|��qSr�r/rdrwrx�rrzrrr7�r{c�(g|]}�jg�t|�t|��qSr�rdrwr/rxr�rrr7�r{cs"i|]
\}}|�j|�jd��qS�r<�rZrVrk�rrrrl�roz>DataCollatorForTokenClassification.tf_call.<locals>.<dictcomp>)133rTr&r$r]r^r_rZr|r}rN�rrr>rQr}r)rhrrzrrrms0"�134�135�z*DataCollatorForTokenClassification.tf_callcs�d|dvrdnd��|dvr�fdd�|D�nd}t�j|�j�j�j|dur+dndd�}|dur5|St�|d�jd	��jj}|d136krT��fdd�|D�|d<n��fdd�|D�|d<d
d�|�	�D�}|S)Nr9rr>crBrrrergrrr7�r8zADataCollatorForTokenClassification.numpy_call.<locals>.<listcomp>rr`rprqrucr~rrrxr�rrr7�r{cr�rr�rxr�rrr7�r{cSs"i|]
\}}|tj|tjd��qSr��rr[rVrkrrrrl�rozADataCollatorForTokenClassification.numpy_call.<locals>.<dictcomp>)137r&r$r]r^r_rr[r|r}rNr�r)rhrrzrr�s."�138�139�z-DataCollatorForTokenClassification.numpy_call)rrrr-r140r.r]rrarrr^rrIr_rdr
rrrrrrrrb s141( rbr_csDddl�t|dtttjf�r�fdd�|D�}|d�d��t�fdd�|D��}|rC|dus6�|dkrCt|�j�sC�j	|dd�S|j142durRtd|jj
�d	���td143d�|D��}|durm||dkrm||d|}|d�t|�|g|j�}t|�D]!\}}|jdkr�|||d|jd�f<q~||||jdd�f<q~|S)
�_Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.rNc�g|]144}�j|�jd��qSr�)rLrJ�r5�ersrrr7��z(_torch_collate_batch.<locals>.<listcomp>c3s�|]145}|�d��kVqdS�rN��size�r5�x��length_of_firstrr�	<genexpr>�s�z'_torch_collate_batch.<locals>.<genexpr>)�dim�CYou are attempting to pad samples but the tokenizer you are using (�) does not have a pad token.css�|]}|�d�VqdSr�r�r�rrrr��s�rqru)rErFr/rYrrOr��allrGrM�	pad_tokenr�	__class__r�maxZnew_fullrw�pad_token_id�	enumerater}r|��examplesr$r_�are_tensors_same_lengthr^�result�i�exampler)r�rEr�_torch_collate_batch�s.146��147r�c	sLddl�	t|dttf�r�fdd�|D�}t|d��t�fdd�|D��}|r;|dus4�|dkr;�j|dd�S|jdurJtd|j	j148�d���td	d�|D��}|dure||dkre||d149|}g}��|d�}t
j|dft
jd�}|D]$}|jd
kr�|t|�|d<n|t|�|d<|��j|||jd��qz�j|dd�S)Nrcr�r�r�r�r�rrr7�r�z%_tf_collate_batch.<locals>.<listcomp>c3��|]	}t|��kVqdSr�rwr�r�rrr����z$_tf_collate_batch.<locals>.<genexpr>�Zaxisr�r�cs��|]}t|�VqdSrr�r�rrrr����rqr	r<ru)rrq)rr)Zconstant_values)rTrFr/rYrwr�rMr�rr�rr��rankr�zeros�int32r}�appendr"r�)	r�r$r_r�r^r�r�Zpaddingsr�r)r�rr�_tf_collate_batch�s4150��151r�cs,t|dttf�rdd�|D�}t|d��t�fdd�|D��}|r4|dus-�|dkr4tj|dd�S|jdurCtd|j	j152�d	���td153d�|D��}|dur^||dkr^||d|}tjt|�|f|j
|djd�}t|�D]!\}}|jd
kr�|||d|jd�f<qr||||jdd�f<qr|S)r�rcSsg|]154}tj|tjd��qSr�r�r�rrrr7�r�z(_numpy_collate_batch.<locals>.<listcomp>c3r�rr�r�r�rrr��r�z'_numpy_collate_batch.<locals>.<genexpr>Nr�r�r�csr�rr�r�rrrr�r�rq)r|Z155fill_valuer=ru)rFr/rYrwr�rrMr�rr�rr��fullr�r=r�r}r|r�rr�r�_numpy_collate_batch�s*156�� 157r�c@s~eZdZUdZeed<dZeee	e158fed<dZee
ed<dZee
ed<dZe	ed	<d159eee	effdd�Zd
d�ZdS)�DataCollatorForMultipleChoicea160    Data collator that dynamically pads a batch of nested examples for multiple choice, so that all choices161    of all examples have the same length.162 163    Args:164        tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):165            The tokenizer used for encoding the data.166        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):167            Select a strategy to pad the returned sequences according to the model's padding side and padding index168            among:169 170            - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence171              is provided).172            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum173              acceptable input length for the model if that argument is not provided.174            - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different175              lengths).176        max_length (`int`, *optional*):177            Maximum length of the returned list and optionally padding length (see above).178        pad_to_multiple_of (`int`, *optional*):179            Pad the sequence to a multiple of the provided value.180 181            This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=182            7.5 (Volta).183        return_tensors (`str`, *optional*, defaults to `"pt"`):184            The type of Tensor to return. Allowable values are "np", "pt" and "tf".185    r$Tr]Nr^r_rr
r�cs�ddl}d|dvrdnd��fdd�|D�}t|��t|dd��t�fdd�|D�gd	�}|jj||j|j|jd186d�}��fdd
�|��D�}|j	||j187d�|d<|S)Nrr9r>c�g|]}|����qSr��pop�r5r�rgrrr7@�z<DataCollatorForMultipleChoice.torch_call.<locals>.<listcomp>rpc3s&�|]��fdd�t��D�VqdS)c�"g|]
��fdd����D��qS)c�i|]	\}}||��qSrrrk�r�rrrlH�zQDataCollatorForMultipleChoice.torch_call.<locals>.<genexpr>.<listcomp>.<dictcomp>rn�r5�r�r�rr7HrozFDataCollatorForMultipleChoice.torch_call.<locals>.<genexpr>.<listcomp>N��ranger���num_choicesr�rr�Hs�$z;DataCollatorForMultipleChoice.torch_call.<locals>.<genexpr>)�startrr`cs i|]\}}||���d��qS������)�viewrk)�188batch_sizer�rrrlUs z<DataCollatorForMultipleChoice.torch_call.<locals>.<dictcomp>r<)rErw�sumr$r"r]r^r_rNrLrV)rr�rEr>Z
flat_examplesrQr)r�rhr�rr;s$��	z(DataCollatorForMultipleChoice.torch_callcs�ddl�d|dvrdnd��fdd�|D�}t|��t|dd���fdd�|D�}t|g�}|jj||j|j|jdd	�}���fd189d�|��D�}�j	|�j190d�|d<|S)
Nrr9r>cr�rr�rergrrr7]r�z9DataCollatorForMultipleChoice.tf_call.<locals>.<listcomp>rpcs"g|]
��fdd�t��D��qS)cr�)cr�rrrkr�rrrlar�zODataCollatorForMultipleChoice.tf_call.<locals>.<listcomp>.<listcomp>.<dictcomp>rnr��rfr�rr7arozDDataCollatorForMultipleChoice.tf_call.<locals>.<listcomp>.<listcomp>r�r�r�r�rr7`s�rr`c	s$i|]\}}|��|��df��qSr�)�reshaperk)r�r�rrrrlms$z9DataCollatorForMultipleChoice.tf_call.<locals>.<dictcomp>r<)rTrwr�r$r"r]r^r_rNrZrV)rrr>Zflattened_featuresrQr)r�rhr�rrrYs&191�192�z%DataCollatorForMultipleChoice.tf_call)rrrr-r193r.r]rrarrr^rrIr_r
r/r0rrrrrrrr�s194r�c@s�eZdZUdZeed<dZeeed<dZ	e195eee
fed<dZeeed<dZeeed<d	Zeed196<dZeed<dd
d�ZdS)�DataCollatorForSeq2Seqa�197    Data collator that will dynamically pad the inputs received, as well as the labels.198 199    Args:200        tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):201            The tokenizer used for encoding the data.202        model ([`PreTrainedModel`], *optional*):203            The model that is being trained. If set and has the *prepare_decoder_input_ids_from_labels*, use it to204            prepare the *decoder_input_ids*205 206            This is useful when using *label_smoothing* to avoid calculating loss twice.207        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):208            Select a strategy to pad the returned sequences (according to the model's padding side and padding index)209            among:210 211            - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single212              sequence is provided).213            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum214              acceptable input length for the model if that argument is not provided.215            - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).216        max_length (`int`, *optional*):217            Maximum length of the returned list and optionally padding length (see above).218        pad_to_multiple_of (`int`, *optional*):219            If set will pad the sequence to a multiple of the provided value.220 221            This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=222            7.0 (Volta).223        label_pad_token_id (`int`, *optional*, defaults to -100):224            The id to use when padding the labels (-100 will be automatically ignored by PyTorch loss functions).225        return_tensors (`str`, *optional*, defaults to `"pt"`):226            The type of Tensor to return. Allowable values are "np", "pt" and "tf".227    r$N�modelTr]r^r_rcrdrr
csV|dur�j}d|dvrdnd��|dvr �fdd�|D�nd}|dur1tdd�|D��r1d}�fdd�|D�}t�j|�j�j�j|d	�}�jd228upR�jtjk}|dur�|rst	|d�t229�rit230|�|d<n]dd�|D�|d<nS�jtjko}�jdu}|s�tdd�|D��n�j��jdur���jd
�j�j��jj
�t	|d�t231�r����fdd�|D�|d<n
���fdd�|D�|d<|�dd�du�r|dkr�ddl}|j|d|jd�|d<n&|dkr�ddl}	|	j|d|	jd�|d<ntj|dtjd�|d<nd|d<|du�r)�jdu�r)t�jd��r)�jj|dd�}232|233|d<|S)Nr9rr>crBrrrergrrr7�r8z3DataCollatorForSeq2Seq.__call__.<locals>.<listcomp>css�|]}|duVqdSrrrxrrrr��r�z2DataCollatorForSeq2Seq.__call__.<locals>.<genexpr>cri)crjrrrkrgrrrl�rmz>DataCollatorForSeq2Seq.__call__.<locals>.<listcomp>.<dictcomp>rnrergrrr7�ror`FcSsg|]	}t�|gg��qSr)r�concatenaterxrrrr7�r�csr�rr�)r5�lrrrr��r�rqcsDg|]}�dkr|�jg�t|�n�jg�t|�|�qS)rurvrx��max_label_lengthr}rrrr7�s���c234shg|]0}�dkrt�|tj�jg�t|�tjd�g�nt�tj�jg�t|�tjd�|g��qS)rur<)rr�r[rdrwrVrxr�rrr7�s�������rr<r�%prepare_decoder_input_ids_from_labels)r>�decoder_input_ids)r
r�r&r$r]r^r_rZ235DO_NOT_PADrFr/Z236MAX_LENGTHr�r}r#rErLrVrTZconstantrr[r�r!r�)rrr
r>Znon_labels_featuresrQZ237no_paddingZmax_paddingrErr�r)rhr�r}rrr�sl"�238239����240�241242�zDataCollatorForSeq2Seq.__call__r)rrrr-r243r.r�rrr]rrarrr^rIr_rdr
rrrrrr�rs244!r�c@sXeZdZUdZeed<dZeed<dZeed<dZ	e245eed<d	Zeed246<dZ
eed<d
Ze247eed<dZeed<dZeed<d
Ze248eed<dd�Zdd�Zdd�Zed3dd��Z	
d3dede249edeeeffdd�Zd eeeeeeeeffdeeeffd!d"�Zd eeeeeeeeffdeeeffd#d$�Z 	
d4dede250ed%e251edeeeffd&d'�Z!d eeeeeeeeffdeeeffd(d)�Z"	
	
d4dede252ed%e253edeeeffd*d+�Z#ed,e$j%e$j%eeefde$j%e$j%edee$j%e$j%ee$j%e$j%effd-d.��Z&ed/e$j%e$j%ed0edefd1d2��Z'd
S)5�DataCollatorForLanguageModelinga254    Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they255    are not all of the same length.256 257    Args:258        tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):259            The tokenizer used for encoding the data.260        mlm (`bool`, *optional*, defaults to `True`):261            Whether or not to use masked language modeling. If set to `False`, the labels are the same as the inputs262            with the padding tokens ignored (by setting them to -100). Otherwise, the labels are -100 for non-masked263            tokens and the value to predict for the masked token.264        whole_word_mask (`bool`, *optional*, defaults to `False`):265            Whether or not to mask whole words instead of individual tokens.266        mlm_probability (`float`, *optional*, defaults to 0.15):267            The probability with which to (randomly) mask tokens in the input, when `mlm` is set to `True`.268        mask_replace_prob (`float`, *optional*, defaults to 0.8):269            The probability with which masked tokens are replaced by the tokenizer's mask token (e.g., `[MASK]`).270            Defaults to 0.8, meaning 80% of the masked tokens will be replaced with `[MASK]`.271            Only works when `mlm` is set to `True`.272        random_replace_prob (`float`, *optional*, defaults to 0.1):273            The probability with which masked tokens are replaced by random tokens from the tokenizer's vocabulary.274            Defaults to 0.1, meaning 10% of the masked tokens will be replaced with random tokens. The remaining275            masked tokens (1 - mask_replace_prob - random_replace_prob) are left unchanged.276            Only works when `mlm` is set to `True`.277        pad_to_multiple_of (`int`, *optional*):278            If set, will pad the sequence to a multiple of the provided value.279        return_tensors (`str`):280            The type of Tensor to return. Allowable values are "np", "pt" and "tf".281        seed (`int`, *optional*):282            The seed to use for the random number generator for masking. If not provided, the global RNG will be used.283 284    <Tip>285 286    For best performance, this data collator should be used with a dataset having items that are dictionaries or287    BatchEncoding, with the `"special_tokens_mask"` key, as returned by a [`PreTrainedTokenizer`] or a288    [`PreTrainedTokenizerFast`] with the argument `return_special_tokens_mask=True`.289 290    <Example Options and Expectations>291 292    1. Default Behavior:293        - `mask_replace_prob=0.8`, `random_replace_prob=0.1`.294        - Expect 80% of masked tokens replaced with `[MASK]`, 10% replaced with random tokens, and 10% left unchanged.295 296    2. All masked tokens replaced by `[MASK]`:297        - `mask_replace_prob=1.0`, `random_replace_prob=0.0`.298        - Expect all masked tokens to be replaced with `[MASK]`. No tokens are left unchanged or replaced with random tokens.299 300    3. No `[MASK]` replacement, only random tokens:301        - `mask_replace_prob=0.0`, `random_replace_prob=1.0`.302        - Expect all masked tokens to be replaced with random tokens. No `[MASK]` replacements or unchanged tokens.303 304    4. Balanced replacement:305        - `mask_replace_prob=0.5`, `random_replace_prob=0.4`.306        - Expect 50% of masked tokens replaced with `[MASK]`, 40% replaced with random tokens, and 10% left unchanged.307 308    Note:309        The sum of `mask_replace_prob` and `random_replace_prob` must not exceed 1. If their sum is less than 1, the310        remaining proportion will consist of masked tokens left unchanged.311 312    </Tip>313    r$T�mlmF�whole_word_maskg333333�?�mlm_probability皙�����?�mask_replace_probg�������?�random_replace_probNr_�tf_experimental_compilerr
�seedcCs*|jr'|jjdur
td��|jdus|jdks|jdkr td��t|j�|_n|jr.td��|j|jdkr:td��|jdksD|jdkrHtd��|jdksR|jdkrVtd��t|j�|_t|j�|_|j	rrddl314}|j|jd	d315�|_|jr�|jj
st�dt�|jdkr�t�dd
�d|_d|_d|_dS)Nz�This tokenizer does not have a mask token which is necessary for masked language modeling. You should pass `mlm=False` to train on causal language modeling instead.rrqz*mlm_probability should be between 0 and 1.zmWhole word masking can only be used with mlm=True.If you want to use whole word masking, please set mlm=True.zHThe sum of mask_replace_prob and random_replace_prob should not exceed 1z,mask_replace_prob should be between 0 and 1.z.random_replace_prob should be between 0 and 1.T)Zjit_compilezcWhole word masking depends on offset mapping which is only natively available with fast tokenizers.zBRandom token replacement is not supported with whole word masking.zSetting mask_replace_prob to 1.)r�r$�316mask_tokenrr�rKr�r�r�r�rT�function�tf_mask_tokensZis_fast�warnings�warn�UserWarning�	generator)rrrrr�
__post_init__EsJ���317�318z-DataCollatorForLanguageModeling.__post_init__cCsL|jdkrddl}|���|�S|jdkr ddl}|jj�|�Stj�|�S)Nrrr)	r
rE�	GeneratorZmanual_seedrT�randomZ	from_seedrZdefault_rng)rr�rErrrr�
get_generatorss319320z-DataCollatorForLanguageModeling.get_generatorcCs`t��jdkr|�|j�|_dSddl}|jj�	�}|dur$d}t321|��|�|j|j�|_dS)N�MainProcessr)zZWorker process information is not available for seeding the generator. This may be becausezZyou are using multiprocessing without using a PyTorch DataLoader. The `seed` parameter canzVonly be used when using multiprocessing with a PyTorch DataLoader. Please either use azAsingle process or use a PyTorch DataLoader with multiple workers.)�mp�current_process�namer�r�r�rE�utils�dataZget_worker_infor�id)rrEZworker_infoZerror_stringrrr�322create_rngsz*DataCollatorForLanguageModeling.create_rngcCsZddl}|�||�}|r|�||�|dd�dk|j�S|�||j�|dd�dk|j�S)Nrrq)rT�fill�cast�uniformrar�)r|Zprobabilityr�rZprob_matrixrrr�tf_bernoulli�s323 "z,DataCollatorForLanguageModeling.tf_bernoulli�inputs�special_tokens_maskr'cCs�ddl}|�||j�}|�|�}|�||j|j�|@}|�||d�}|�||j|j�|@}	|�|	||�}|jdks?|j	dkrC||fSd|j}324|j	|325}|�|||j�|@|	@}|jrh|jj326|||jd�}
n327|jj328|||jd�}
|�||
|�}||fS)zw329        Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.330        rNrcrq��maxvalr=)rTr�r=r|r�r�r��wherer�r�r�r�)rr��331vocab_size�
mask_token_idr�r�input_shape�masked_indicesr>�indices_replaced�remaining_prob�random_replace_prob_scaled�indices_random�random_wordsrrrr��s,332333334���z.DataCollatorForLanguageModeling.tf_mask_tokensr�cs8ddl}�jr�jdur���t|dt�r"t�j|d�jd�}ndt	|�j�jd�i}|�335dd�}�jr{|durW�fdd�|d���
�D�}|�|j||jd	�|j�}n|�||j�}�j|�|d|j�|�jjt�j�d336�\|d<|d<|S|d}�jjdur�|�|�jjkd|�}n|�|�}||d<|S)
Nrr�r
r_rp�r_r�c�g|]337}�jj|dd��qS�T)Zalready_has_special_tokens�r$Zget_special_tokens_mask�r5�val�rrrr7����z;DataCollatorForLanguageModeling.tf_call.<locals>.<listcomp>r<)r�r�r�r>rc)rTr�r�r�rFrr&r$r_r�r�r��numpyrrr�rZrVrar�r�rwr�r��identity)rr�rrQr�r>rrrr�s<��338���339z'DataCollatorForLanguageModeling.tf_callcCs�|jr|jdur|��t|dt�rt|j|d|jd�}ndt||j|jd�i}|�	dd�}|�	dd�}|j340rJ|j|d||d�\|d<|d	<|S|d��}|jj
dur^d341|||jj
k<||d	<|S)Nrrrrprr��offset_mapping�r�rr>rc)r�r�r�rFrr&r$r_r�r�r��torch_mask_tokens�cloner��rr�rQr�rr>rrrrs(��342��z*DataCollatorForLanguageModeling.torch_callrcs�ddl}|��}|�|j�j�}|dur�fdd�|��D�}�jr7��t|�t|��\}}|j	||j343d�}nt||j�rA|�344�n|j	||j345d�}|j
|dd�|j|�jd��346�}	�jrf|���||	��}	d	||	<|j|�|j�j��jd��347�|	@}348�j��jj�||349<�jd350ks��jdkr�||fSd351�j}�j|}|j|�|j|��jd��352�|	@|353@}
|jt�j�|j|j�jd�}||
||
<||fS)�S354        Prepare masked tokens inputs/labels for masked language modeling.355        rNcrrrrrrrr7+��zEDataCollatorForLanguageModeling.torch_mask_tokens.<locals>.<listcomp>r<���value�r�rcrq�r=r�)rErr�r|r�rrr��_calc_word_ids_and_prob_mask�to_numpyrLrarFrG�masked_fill_�	bernoullir�Z356BoolTensor�_whole_word_maskr�r$�convert_tokens_to_idsr�r�rrwrJ)rr�r�rrEr>�probability_matrix�word_ids�no_mask_maskr�r�r�r�r�r�rrrr
sN357��358359��360��361362���z1DataCollatorForLanguageModeling.torch_mask_tokenscCs�|jr|jdur|��t|dt�rt|j|d|jd�}ndt||j|jd�i}|�	dd�}|�	dd�}|j363rJ|j|d||d�\|d<|d	<|St�
|d�}|jjdur_d364|||jjk<||d	<|S)Nrrrrprr�rrr>rc)r�r�r�rFrr&r$r_r�r�r��numpy_mask_tokensr�copyr�rrrrr^s(��365��z*DataCollatorForLanguageModeling.numpy_callcst�|�}t�|j�j�}|dur�fdd�|��D�}�jr,��t|�t|��\}}nt	|tj366�r7|�t�ntj
|td�}d||<�jrS�jjd||jd��t�}n
tjjd||jd��t�}�jri��||�}d||<�jr��jjd�j|jd��t�|@}	ntjjd�j|jd��t�|@}	�jj||	<�jdks��jdkr�||fSd�j}367�j|368}�jr׈jjd||jd��t�|@|	@}�jjdt�j�t�|�tjd	�}
n#tjjd||jd��t�|@|	@}tjjdt�j�t�|�tjd	�}
|
||<||fS)369rNcrrrrrrrr7�rzEDataCollatorForLanguageModeling.numpy_mask_tokens.<locals>.<listcomp>r<rrqr�rc��low�highr�r=)rr!r�r|r�rrr�rrrFrO�astyperar[r��binomialr�rr�r$r�r��integersrwZ
count_nonzerorVr)rr�r�rr>rrrr�r�r�r�r�r�rrrr }sh370	371�372373��374��375376��������z1DataCollatorForLanguageModeling.numpy_mask_tokens�offsetsc	Cs�|dd�dd�df}|dd�dd�df}tj|ddd�}d|dd�df<tj|ddd�}d|dd�df<|�t�}|||k|dkB@}tj|dd�}d||<|}||fS)z�377        Map tokens to word ids and create mask of tokens to not mask.378        Tokens that are part of the same word will have the same word id and we will only379        set a mask probability for the first token of each word.380        Nrrqr�r�)rZrollr%raZcumsum)	r(r�Ztoken_startsZ381token_endsZprev_token_endsZprev_token_specialZis_new_wordrZ	prob_maskrrrr�s382383z<DataCollatorForLanguageModeling._calc_word_ids_and_prob_maskr�maskcCs�t|�}|dk}|dd�dd�df|dd�ddd�fk|dd�dd�df@|dd�ddd�f@}tj||dd�ddd�f@dd�S)z>384        Mask whole words based on word ids and mask.385        r�Nr	r�)rr�any)rr)Z	valid_idsZ	same_wordrrrr�sX$z0DataCollatorForLanguageModeling._whole_word_maskr�NN)(rrrr-r386r.r�rar�r�rrKr�r�r_rIr�r
rr�r�r�r��staticmethodr�rrYr�r/rr0rrr
rr rrOrrrrrrr��sv387>.���388389�4/4. ����390391�4?"����392393�R��"�(r�cs2eZdZdZdeeeeeee	effdee	effdd�Z394deeeeeee	effdee	effdd�Zdeeeeeee	effdee	effdd	�Zd395d�Z
dd
ee	fdd�Zdededeeeffdd�Zdededeeeffdd�Zdededeeeffdd�Z�fdd�Z�ZS)�DataCollatorForWholeWordMaska#396    Data collator used for language modeling that masks entire words.397 398    - collates batches of tensors, honoring their tokenizer's pad_token399    - preprocesses batches for masked language modeling400 401    <Tip>402 403    This collator relies on details of the implementation of subword tokenization by [`BertTokenizer`], specifically404    that subword tokens are prefixed with *##*. For tokenizers that do not adhere to this scheme, this collator will405    produce an output that is roughly equivalent to [`.DataCollatorForLanguageModeling`].406 407    </Tip>r�r'cC�|jr|jdur|��t|dt�rdd�|D�}n	|}dd�|D�}t||j|jd�}g}|D]C}g}t|d�D]
}|j�	|�}|�408|�q;d|vrlt|d�}	t|d�}409t|410�D]}||	vrkd||||<q]|�411|�
|��q1t||j|jd�}|�||�\}
}|
|d	�S)412NrcSr:�rprr�rrrr7r8z;DataCollatorForWholeWordMask.torch_call.<locals>.<listcomp>cS�g|]}d|i�qSr/rr�rrrr7r8rrp�chinese_ref�##�rpr>)r�r�r�rFrr�r$r_rr�_convert_id_to_tokenr�rwr�rr
�rr�rp�batch_input�mask_labelsr��413ref_tokensr��token�ref_pos�len_seqr��414batch_maskr�r>rrrr
�0�415z'DataCollatorForWholeWordMask.torch_callcCs(ddl}|jr|jdur|��t|dt�rdd�|D�}n	|}dd�|D�}t||j|jd�}g}|D]C}g}t	|d�D]
}|j�416|�}	|�|	�q?d|vrpt	|d�}417t|d�}t
|�D]}||418vrod||||<qa|�|�|��q5t||j|jd�}
|�|�||j�|
�\}}||d	�S)419NrcSr:r/rr�rrrr77r8z8DataCollatorForWholeWordMask.tf_call.<locals>.<listcomp>cSr0r/rr�rrrr7:r8rrpr1r2r3)rTr�r�r�rFrr�r$r_rrr4r�rwr�rr�r�rV)rr�rrpr6r7r�r8r�r9r:r;r�r<r�r>rrrr.s2�420z$DataCollatorForWholeWordMask.tf_callcCr.)421NrcSr:r/rr�rrrr7Xr8z;DataCollatorForWholeWordMask.numpy_call.<locals>.<listcomp>cSr0r/rr�rrrr7[r8rrpr1r2r3)r�r�r�rFrr�r$r_rrr4r�rwr�rr r5rrrrQr=z'DataCollatorForWholeWordMask.numpy_callcs�|jdurt����S|jdkr(ddl}|jt��|jd�}�fdd�|D�S|jdkrTddl}|j�	d�d}|jj422j|�t���|d��
���}�fd	d�|D�S|jd423kra|j����SdS)Nrrrc�g|]}�|�qSrr�r5r���cand_indexesrrr7}r8z9DataCollatorForWholeWordMask._shuffle.<locals>.<listcomp>rr	)r�cr>rrr?r@rrr7�r8r)r�r��shuffler
rE�randpermrwr�rTZ424make_seedsZexperimentalZstateless_shuffler�r	rr)rrArE�indicesrr�rr@r�_shufflers 425426427428$429�z%DataCollatorForWholeWordMask._shuffle��input_tokensc
s>ddlm}m}t|j||f�st�d�g}t|�D]&\}}|dks'|dkr(qt|�dkr;|�	d�r;|d�430|�q|�431|g�q|�|�}t|t
dttt|�|j����}g}	t��|D]$}432t|	�|krint|	�t|433�|krtq_|434D]}��|�|	�435|�qvq_t��t|	�kr�td	���fd436d�tt|��D�}|S)zM437        Get 0/1 labels for masked tokens with whole word mask proxy438        r)�
BertTokenizer�BertTokenizerFastz�DataCollatorForWholeWordMask is only suitable for BertTokenizer-like tokenizers. Please refer to the documentation for more information.z[CLS]z[SEP]rqr2r�z?Length of covered_indexes is not equal to length of masked_lms.csg|]439}|�vr440dnd�qS)rqrrr?�Zcovered_indexesrrr7�r�zADataCollatorForWholeWordMask._whole_word_mask.<locals>.<listcomp>)ZtransformersrHrIrFr$r�r�r�rw�441startswithr�rE�minr�rI�roundr��set�addrr�)
rrGZmax_predictionsrHrIrAr�r9Znum_to_predictZ442masked_lmsZ	index_set�indexr7rrJrr�s:�443"444�z-DataCollatorForWholeWordMask._whole_word_maskr�r7csTddl}�jjdurtd��|��}|}�fdd�|��D�}|j|j||jd�dd��jj	dur@|�445�jj�}|j|dd�|��}d	||<|j|�
|j�j��jd446���|@}	�j��jj�||	<�jdkso�jdkrs||fSd�j}447�j|448}|j|�
|j|��jd449���|@|	@}|jt�j�|j|j�jd�}
|
|||<||fS)
��450        Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set451        'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.452        rN��This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the --mlm flag if you want to use this tokenizer.crrrrrrrr7�rzBDataCollatorForWholeWordMask.torch_mask_tokens.<locals>.<listcomp>r<rrrcrrqr)rEr$r�rrrrrrLrar��eqr�rr�r|r�r�rr�rrwrJ)rr�r7rEr>rr��padding_maskr�r�r�r�r�r�rrrr
�sD�453�454��455456���z.DataCollatorForWholeWordMask.torch_mask_tokenscsZddl}|�|�}�jjdurtd��|�|�}|�||j�}�fdd�|D�}||j||jd�@}�jjdurD|�jj	k}||@}|�457||d�}��|�j�j
�|@}	|�458|	�jj|�}�jdksi�jdkrm||fSd�j}459�j|460}��||�j
�|@|	@}�j
r��j
j|t�j�|jd	�}
n
|jj|t�j�|jd	�}
|�461||
|�}||fS)462rQrNrRcrrrrrrrr7�rz?DataCollatorForWholeWordMask.tf_mask_tokens.<locals>.<listcomp>r<rcrqr�)rTr|r$r�rr463r�rar�r�r�r�r�r�r�r�r�rwrVr�)rr�r7rr�r>r�r�rTr�r�r�r�r�rrrr��sB464�465466�467468469���z+DataCollatorForWholeWordMask.tf_mask_tokenscs��jjdur470td��t�|�}|�t�}�fdd�|��D�}d|tj|td�<�jj	dur8|�jj471k}d||<d||<�jrQ�jjd�j
|jd	��t�|@}ntjjd�j
|jd	��t�|@}�j��jj�||<�j
dksu�jdkry||fSd�j
}�j|}	�jr��jjd|	|jd	��t�|@|@}472�jjdt�j�|jtjd473�}n!tjjd|	|jd	��t�|@|@}474tjjdt�j�|jtjd475�}||476||477<||fS)rQNrRcrrrrrrrr77rzBDataCollatorForWholeWordMask.numpy_mask_tokens.<locals>.<listcomp>rr<rcrqr�r")r$r�rrr!r%rarrr[r�r�r�r&r�r|r�rr�r'rwrVr)rr�r7r>r�r�rTr�r�r�r�r�rrrr (sR�478479480�481��482483��� ���z.DataCollatorForWholeWordMask.numpy_mask_tokenscs.t�dt�t�j|i|��d|_d|_dS)Nz�DataCollatorForWholeWordMask is deprecated and will be removed in a future version, you can now use DataCollatorForLanguageModeling with whole_word_mask=True instead.T)r�r��
FutureWarning�super�__init__r�r��r�args�kwargs�r�rrrWis�484z%DataCollatorForWholeWordMask.__init__)rF)rrrr-r/rrIrr0rrrrrErrYr
r�r rW�
__classcell__rrr[rr-�s44!4#!*8<Ar-cCs(t|t�r|St|d�r|��}|��S)Nr	)rFr/r!r	rr�r�rrrrrts485486487rrcCs4t|tj�r|St|d�r|������St�|�S)N�detach)rFrrOr!r^�cpur	r[r]rrrr|s488489490rc@sZeZdZdZdd�Zdeeeefdeeeffdd�Z	dede491eeeffd	d492�ZdS)�DataCollatorForSOPz�493    Data collator used for sentence order prediction task.494 495    - collates batches of tensors, honoring their tokenizer's pad_token496    - preprocesses batches for both masked language modeling and sentence order prediction497    cOst�dt�dS)Nz�DataCollatorForSOP is deprecated and will be removed in a future version, you can now use DataCollatorForLanguageModeling instead.)r�r�rUrXrrrrW�s�zDataCollatorForSOP.__init__r�r'c498Cs�ddl}ddlm}dd�|D�}t||j�}|�|�\}}}dd�|D�}||d|jjd�}dd�|D�}|�|�}	|||||	d	�S)499Nr)�pad_sequencecSr:r/rr�rrrr7�r8z/DataCollatorForSOP.__call__.<locals>.<listcomp>cSr:)�token_type_idsrr�rrrr7�r8T)Zbatch_firstZ
padding_valuecSr:)�sentence_order_labelrr�rrrr7�r8)rpr>�attention_maskrbrc)rEZtorch.nn.utils.rnnrar�r$�mask_tokensr�rM)500rr�rErarpr>rdrbZsop_label_listrcrrrr�s501�zDataCollatorForSOP.__call__r�c
sXddl}�jjdurtd��|��}|�|j�j�}�fdd�|��D�}|j	|j502||jd�dd��jjdurF|�
�jj�}|j	|dd�|�|���}|��}�jjdurf|�
�jj�}	|j	|	d	d�d503||<|�|�|jd����|@}504�j��jj�||505<|�|�|jd����|@|506@}|jt�j�|j|jd�}||||<|||fS)
z�507        Prepare masked tokens inputs/labels/attention_mask for masked language modeling: 80% MASK, 10% random, 10%508        original. N-gram not applied yet.509        rNrRcrrrrrrrr7�rz2DataCollatorForSOP.mask_tokens.<locals>.<listcomp>r<rrg�?rcr�g�?)rEr$r�rrr�r|r�rrrrLrar�rSr�rrKrrrwrJ)
rr�rEr>rr�rTr�rdZattention_padding_maskr�r�r�rrrre�s4�510�511512"513zDataCollatorForSOP.mask_tokensN)rrrr-rWr/r0rrrrYrerrrrr`�s514& r`c@s4eZdZUdZeed<dZeed<dZe	ed<dZ515eed<d	ee
ee	eeeeffd516eeeffdd�Zd	ee
ee	eeeeffd517eeeffd
d�Zd	ee
ee	eeeeffd518eeeffdd�Zded519eeeeeffdd�Zded520eeeeeffdd�Zded521eeeeeffdd�ZdS)�*DataCollatorForPermutationLanguageModelingz�522    Data collator used for permutation language modeling.523 524    - collates batches of tensors, honoring their tokenizer's pad_token525    - preprocesses batches for permutation language modeling with procedures specific to XLNet526    r$gUUUUUU�?�plm_probability��max_span_lengthrr
r�r'cC�Ht|dt�rdd�|D�}t||j�}|�|�\}}}}||||d�S)NrcSr:r/rr�rrrr7�r8zIDataCollatorForPermutationLanguageModeling.torch_call.<locals>.<listcomp>�rp�	perm_mask�target_mappingr>)rFrr�r$r
�rr�rQr�rlrmr>rrrr��527z5DataCollatorForPermutationLanguageModeling.torch_callcCrj)NrcSr:r/rr�rrrr7�r8zFDataCollatorForPermutationLanguageModeling.tf_call.<locals>.<listcomp>rk)rFrr�r$r�rnrrrr�roz2DataCollatorForPermutationLanguageModeling.tf_callcCrj)NrcSr:r/rr�rrrr7�r8zIDataCollatorForPermutationLanguageModeling.numpy_call.<locals>.<listcomp>rk)rFrr�r$r rnrrrr�roz5DataCollatorForPermutationLanguageModeling.numpy_callr�cs�ddl}�jjdurtd��|�d�ddkrtd��|��}|j|jd|jd�}|j	|�d�|�d�|�d�f|j528d�}t|�d��D]J}d}|�d�}||kr�|�d�j
dd���}	t|	�j�}529||�|530|	dd���}d|||||	�f<||5317}||ksQ|�|�d��||<qD|j�fd	d532�|��D�|jd�}|j|dd��jjdur�|��jj�}
|j|
dd�|
|B}�jj||<d
||<|j	|�d�|�d�|�d�f|j533d�}t|�d��D]V}|�|�d��}|�d|�d�df��dd�}||�|�d�d�}|�|�dd��}|�||||@d�|�|�d�df�|�d|�d�f�k||@||<q�|��|||��fS)�g534        The masked tokens to be predicted for a particular sequence are determined by the following algorithm:535 536            0. Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).537            1. Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)538            2. Reserve a context of length `context_length = span_length / plm_probability` to surround span to be539               masked540            3. Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length -541               span_length]` and mask tokens `start_index:start_index + span_length`542            4. Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the543               sequence to be processed), repeat from Step 1.544        rN��This tokenizer does not have a mask token which is necessary for permutation language modeling. Please add a mask token if you want to use this tokenizer.rqr	��This collator requires that sequence lengths be even to create a leakage-free perm_mask. Please see relevant comments in source code for details.r<)rqcrrrrrrrr70r�zPDataCollatorForPermutationLanguageModeling.torch_mask_tokens.<locals>.<listcomp>rrrcr�)rEr$r�rr�rr�r|rar�rWr�rrirHrIrg�eyerLrrrr�rSr�r��aranger��	transposerC�flattenrJ)rr�rEr>r�rmr��cur_len�max_len�span_length�context_length�start_indexr�rT�
non_func_maskrl�545perm_indexrrrr
�sZ
��(546�
�547548(	 &549�z<DataCollatorForPermutationLanguageModeling.torch_mask_tokensc550s�ddl}�jjdurtd��|�|�dddkrtd��|�|�}tj|j��dt	d�}|�|�}tj551|d|d|dftjd�}tt
|��D]D}d}|�|�d}	||	kr�td�jd�}552t|553�j�}|td||554d�}d|||||555�f<||7}||	ksXt�|d�||<qI|j|�|�|j	d�}|�|�}|��fdd	�|����D��}
|j|
|j	d�}
||
@}�jjdur�|�jjk}||@}||
B}|�|�jj|�}|�||d556�}g}tt
|��D]P}|�|d�}|�|�|d|ddf��}|j�|�}|�|�|�d�}|�||||@d|�}|�|�||ddf�|�|d|df�k||@�q�|j |dd
�}|�||j!�|�||j�||�||j!�fS)rprNrqrqr	rrr<crrrrrrrr7�rzMDataCollatorForPermutationLanguageModeling.tf_mask_tokens.<locals>.<listcomp>rcr�r�r�)"rTr$r�rr|r557rr�Zas_listrar�rWr�rwrrirIrgrsr�rZr	rrr�r�r�r�rur�r�rBr�rMrV)rr�rr>r�Zlabels_shapermr�rwrxryrzr{r�rTr|rlr}rrrr�^sj
��558559"�
560561562��563564565566&��*z9DataCollatorForPermutationLanguageModeling.tf_mask_tokenscsR�jjdur567td��|jdddkrtd��t�|�}tj|jdtd�}tj|jd|jd|jdftj	d�}t568|jd�D]C}d}|jd}||krytd�jd�}t
|�j�}	|td|	|d�}569d|||570|571|�f<||	7}||ksMt�|jd�||<q@tj�fdd	�|��D�td�}d||<�jjdur�|�jjk}d572||<||B}
�jj||<d||<tj|jd|jd|jdftj	d�}t573|jd�D]G}t�|jd�}|�d|jddf�j}tj�|�|j��}d||||
|@<|�|jddf�|�d|jdf�k||@||<q�|�tj�|||�tj�fS)
rpNrqrqr	rrrr<crrrrrrrr7�r�zPDataCollatorForPermutationLanguageModeling.numpy_mask_tokens.<locals>.<listcomp>rrcr�)r$r�rr|rr!r�rar�rWr�rrirIrgrsr[rrr�r�r�rtr��Tr�rBrvr%rV)rr�r>r�rmr�rwrxryrzr{r�rTr|rlr}rrrr �sX
��574(575�
�576577(	578&579�z<DataCollatorForPermutationLanguageModeling.numpy_mask_tokensN)rrrr-r580r.rgrKrirIr
rr/rrr0rrrrYr
r�r rrrrrf�s581444c"krfcs6eZdZdZddddd��fdd�582Zdd	d583�Z�ZS)�DataCollatorWithFlatteninga�584    Data collator used for padding free approach. Does the following:585 586    - concatenates the entire mini batch into single long sequence of shape [1, total_tokens]587    - uses `separator_id` to separate sequences within the concatenated `labels`, default value is -100588    - no padding will be added, returns `input_ids`, `labels` and `position_ids` by default589    - optionally returns the kwargs contained in FlashAttentionKwargs590    - optionally returns seq_idx indicating which sequence each token belongs to591 592    <Tip warning={true}>593 594    Using `DataCollatorWithFlattening` will flatten the entire mini batch into single long sequence.595    Make sure your attention computation is able to handle it!596 597    </Tip>598    TrcF)�return_position_ids�separator_id�return_flash_attn_kwargs�return_seq_idxcsLt�j|i|��||_||_||_||_hd�|_hd�|_ddh|_dS)N>r>�position_idsrp>r>�seq_idxr�rp�max_length_q�max_length_k)	rVrWr�r�r�r��_int_64_keys�_batch_dim_keys�_py_int_keys)rr�r�r�r�rYrZr[rrrW>s	599600z#DataCollatorWithFlattening.__init__Ncs|dur|j}|dur|j}d|dv}ggd�}|jr#|�dgi�|jr-|�dgi�|jr5dg}d}t|�D]o\�}|d}	|d|	7<|r]|d|g|ddd�7<n|d|g|	dd�7<|jr}|dttt	|	���7<|jr�|d�fdd	�tt	|	��D�7<|jr�|�601|d602t	|	��t|t	|	��}q9|jr�||d<|d<||d
<|d<|dkr�ddl}603|604j
}|605j}|606j}
n|dkr�tj}tj}tj}
ntd|�d���|��D]"\}}||jvr�|g}||jv�r607||||jv�r|n|
d�||<q�|S)Nr>rr3r�r�rprqcsg|]}��qSrr)r5�_�r�rrr7hsz7DataCollatorWithFlattening.__call__.<locals>.<listcomp>r�Z
cu_seq_lens_qZ
cu_seq_lens_kr�r�rrz;return_tensors must be one of ("pt", "np"), return_tensors=z not supportedr<)r
r�r��updater�r�r�r/r�rwr�r�rErLrVr�rr[rrNr�r�r�)rrr
r�Zis_labels_providedrQZcu_seq_lensr^�samplerprEZdata_clsZdtype_64Zdtype_32rDrRrr�rrPs^608$&�609 �z#DataCollatorWithFlattening.__call__r+)rrrr-rWrr\rrr[rr+s�r)rr)0�multiprocessingr�r�r��collections.abcr�dataclassesrr�typingrrrrr	rZtokenization_utils_baser610r�rZInputDataClassr/r0rZDataCollatorrr&r+r,r(r)r*r\rbrIr�r�r�r�r�r�r-rrrOrr`rfrrrrr�<module>sl $) 3%& Zx	RT
Aluode/PerceptionLabPortable · CoolFace