U
    ,-eq                     @   sl  d Z ddlZddlZddlmZmZmZ ddlZddlZddlm	Z	 ddl
mZmZmZmZ ddl
mZ ddlmZmZmZ dd	lmZmZmZmZmZ dd
lmZ ddlmZ ddlm Z  e!e"Z#dZ$dZ%dddddddgZ&ej'ej(e)ej*dddZ+ej,e)ej*dddZ-ej,e)ej.ej,dddZ/ej,ej,e0e1ej,dd d!Z2ej,ej,d"d#d$Z3ej,ej,ej,d%d&d'Z4G d(d) d)ej5j6Z7G d*d+ d+e	j8Z9G d,d- d-e	j8Z:G d.d/ d/e	j8Z;G d0d1 d1e	j8Z<G d2d3 d3eZ=d4Z>d5Z?ed6e>G d7d8 d8e=Z@ed9e>G d:d; d;e=ZAed<e>G d=d> d>e=ZBed?e>G d@dA dAe=ZCedBe>G dCdD dDe=ZDdS )EzPyTorch BLOOM model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forward))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)logging   )BloomConfigzbigscience/bloom-560mr   z#bigscience/bigscience-small-testingzbigscience/bloom-1b1zbigscience/bloom-1b7zbigscience/bloom-3bzbigscience/bloom-7b1zbigscience/bloom)input_ids_shapedevicepast_key_values_lengthreturnc                 C   s   | \}}t j||| ft j|d}t j||d}|dddf |dddf k |dd|df< |dkr|d|ddd|f< |ddddddf |d||| }|S )z3
    Make causal mask used for self-attention.
    )dtyper   r   Nr   Fr   )torchemptyboolarangeexpand)r   r   r   
batch_sizeZtarget_lengthmaskZseq_idsexpanded_mask r&   i/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/bloom/modeling_bloom.py_make_causal_mask8   s    0(r(   )r$   
tgt_lengthr   c                 C   sL   | j \}}|dk	r|n|}| ddddddf tj }||d||S )zn
    Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
    Nr   )shapetor   r    r"   )r$   r)   r#   
src_lengthr%   r&   r&   r'   _expand_maskK   s    
"r-   attention_mask	num_headsr   r   c                 C   s6  | j \}}dtt| }tjddt|d     | jtjd}tjdd| | jtj	d}t
||}||krtjddtd| d     | jtjd}	t||| }
tjddd|
  d| jtj	d}tj|t
|	|gdd}| jddd |  dddddf }|d	 | }||| d||S )
a  
    Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
    relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
    `softmax(l+a) = softmax(l)`. Based on
    https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
    TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.

    Args:
    Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
        attention_mask (`torch.Tensor`):
            Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
        num_heads (`int`, *required*):
            number of heads
        dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
            dtype of the output tensor
       r   )r   r   r   r   dimN).N)r*   mathfloorlog2r   Ztensorr   float32r!   Zint32powmincatZcumsumreshaper+   )r/   r0   r   r#   
seq_lengthZclosest_power_of_2baseZpowersZslopesZ
extra_baseZnum_remaining_headsZextra_powersZarange_tensoralibir&   r&   r'   build_alibi_tensorV   s*    
     &r@   )xresidualprobtrainingr   c                 C   s   t j| ||d}|| }|S )a:  
    Dropout add function

    Args:
        x (`torch.tensor`, *required*):
            input tensor
        residual (`torch.tensor`, *required*):
            residual tensor
        prob (`float`, *required*):
            dropout probability
        training (`bool`, *required*):
            training mode
    )prD   )Fdropout)rA   rB   rC   rD   outr&   r&   r'   dropout_add   s    rI   rA   r   c                 C   s*   | d dt d|  dd|  |      S )z
    Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
    make the model jitable.

    Args:
        x (`torch.tensor`, *required*):
            input hidden states
          ?      ? e3E?r   Hm?r   tanh)rA   r&   r&   r'   bloom_gelu_forward   s    	rQ   )grA   r   c                 C   s^   |d }t d| dd| |   }d| d||  dd| |    dd|   }||  S )a8  
    gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
    0.3989423 * x * torch.exp(-0.5 * x * x)

    Args:
        g (`torch.tensor`, *required*):
            gradient output tensor
        x (`torch.tensor`, *required*):
            input tensor
    r   rM   r   rN   rK   g6vf?rO   )rR   rA   Ztanh_outffr&   r&   r'   bloom_gelu_back   s    0rT   c                   @   s<   e Zd ZeejejdddZeejejdddZdS )GeLUFunction)inputr   c                 C   s   |  | t|S N)Zsave_for_backwardrQ   )ctxrV   r&   r&   r'   forward   s    
zGeLUFunction.forward)grad_outputr   c                 C   s   | j }t||}|S rW   )Zsaved_tensorsrT   )rX   rZ   rV   tmpr&   r&   r'   backward   s    
zGeLUFunction.backwardN)__name__
__module____qualname__staticmethodr   TensorrY   r\   r&   r&   r&   r'   rU      s   rU   c                       s4   e Zd ZdZ fddZejejdddZ  ZS )	BloomGelua  
    BloomBiasGelu wrapper function that make use of the simple function on inference mode to make the model
    torchscriptable and use the autograd function in training mode to get the accurate results of the gradients Partly
    copied from Megatron-DeepSpeed code and adapted for our needs

    See here why autograd functions are not torchscriptable: https://github.com/pytorch/pytorch/issues/22329
    c                    s   t    d S rW   super__init__self	__class__r&   r'   re      s    zBloomGelu.__init__rJ   c                 C   s   | j rt|S t|S d S rW   )rD   rU   applyrQ   )rg   rA   r&   r&   r'   rY      s    
zBloomGelu.forward)	r]   r^   r_   __doc__re   r   ra   rY   __classcell__r&   r&   rh   r'   rb      s   rb   c                
       s   e Zd Zed fddZejeejejejf dddZejejddd	Z	dejejejeje
eejejf  e
ej eedddZ  ZS )BloomAttentionconfigc                    s   t    |j| _|j| _|j| _|j| _| j| j | _| j| _|j	| _	| j| j | jkrtt
d| j d| j ddt| j | _d| _tj| jd| j dd| _t| j| j| _t|j| _d S )NzA`hidden_size` must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).rL   r   Tbias)rd   re   pretraining_tpslow_but_exacthidden_sizen_headr0   head_dimZ
split_sizehidden_dropout
ValueErrorr5   sqrtinv_norm_factorbetar   Linearquery_key_valuedenseDropoutattention_dropoutrg   ro   rh   r&   r'   re      s"    
zBloomAttention.__init__)	fused_qkvr   c                 C   sV   |j \}}}|||| jd| j}|ddddf |ddddf |ddddf fS )a  
        Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory
        storage as `fused_qkv`

        Args:
            fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]

        Returns:
            query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
            value: [batch_size, seq_length, num_heads, head_dim]
        r   .r   Nr   r1   )r*   viewr0   rv   )rg   r   r#   r=   Zthree_times_hidden_sizer&   r&   r'   _split_heads   s    zBloomAttention._split_headsrJ   c                 C   sP   |j \}}}|| j }||| j|| j}|dddd}|||| j| j S )a  
        Merge heads together over the last dimension

        Args:
            x (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]

        Returns:
            torch.tensor: [batch_size, seq_length, num_heads * head_dim]
        r   r1   r   r   )r*   r0   r   rv   permuter<   )rg   rA   Zbatch_size_and_num_headsr=   _r#   r&   r&   r'   _merge_heads   s
    
zBloomAttention._merge_headsNF)hidden_statesrB   r?   r/   
layer_past	head_mask	use_cacheoutput_attentionsc	                 C   sp  |  |}	| |	\}
}}|
j\}}}}|
dd|| j || j}
|dddd|| j | j|}|dd|| j || j}|d k	r|\}}tj	||fdd}tj	||fdd}|j\}}}|dkr||f}nd }|j
|
|| j| jd}||| j||}|j}|tjkr"|tj}t||t|jj}tj|dtjd	|}| |}|d k	rn|| }||| j ||}t||}| |}| jdkr8| jr8| j| j }t|}t| jD ]h}|t |d d d d t!|| t!|d | f | j"j#d d t!|| t!|d | f  }qn
| "|}t$||| j%| j&}||f}|rl||f7 }|S )
Nr   r1   r   r   r2   T)Zbatch1Zbatch2r{   alphar4   )r3   r   )'r}   r   r*   Z	transposer<   r0   rv   r   r   r;   Zbaddbmmr{   rz   r   r   Zfloat16r+   floatZmasked_fillZfinfor:   rF   Zsoftmaxr8   r   Zbmmr   rr   rs   rt   
zeros_likerangelinearintr~   weightrI   rw   rD   )rg   r   rB   r?   r/   r   r   r   r   r   Zquery_layerZ	key_layerZvalue_layerr#   Zq_lengthr   Zpast_keyZ
past_valueZ	kv_lengthZpresentZmatmul_resultZattention_scoresZinput_dtypeZattn_weightsZattention_probsZattention_probs_reshapedZcontext_layerslicesZoutput_tensorioutputsr&   r&   r'   rY     s\    
"




,*

zBloomAttention.forward)NNFF)r]   r^   r_   r   re   r   ra   r   r   r   r   r    rY   rl   r&   r&   rh   r'   rm      s"   "    rm   c                       s:   e Zd Zed fddZejejejdddZ  ZS )BloomMLPrn   c                    sX   t    |j}|j| _|j| _t|d| | _t | _	td| || _
|j| _d S )N   )rd   re   rt   rr   rs   r   r|   dense_h_to_4hrb   	gelu_impldense_4h_to_hrw   rg   ro   rt   rh   r&   r'   re   t  s    
zBloomMLP.__init__)r   rB   r   c                 C   s   |  | |}| jdkr| jrt|}| jjjd | j }t	| jD ]f}|t
|d d d d t|| t|d | f | jjd d t|| t|d | f  }qHn
| |}t||| j| j}|S )Nr   r4   )r   r   rr   rs   r   r   r   r   r*   r   rF   r   r   rI   rw   rD   )rg   r   rB   Zintermediate_outputr   r   outputr&   r&   r'   rY     s    
,*

zBloomMLP.forward)	r]   r^   r_   r   re   r   ra   rY   rl   r&   r&   rh   r'   r   s  s   r   c                	       sZ   e Zd Zed fddZd	ejejejeeejejf  eej e	e	dddZ
  ZS )

BloomBlockrn   c                    s`   t    |j}t||jd| _|j| _t|| _	t||jd| _
t|| _|j| _|j| _d S )NZeps)rd   re   rt   r   layer_norm_epsiloninput_layernormru   r0   rm   self_attentionpost_attention_layernormr   mlp(apply_residual_connection_post_layernormrw   r   rh   r&   r'   re     s    


zBloomBlock.__init__NF)r   r?   r/   r   r   r   r   c              
   C   s   |  |}| jr|}	n|}	| j||	||||||d}
|
d }|
dd  }| |}| jr^|}	n|}	| ||	}|r~|f| }n|f|dd   }|S )N)r   r/   r?   r   r   r   r   r   )r   r   r   r   r   )rg   r   r?   r/   r   r   r   r   Zlayernorm_outputrB   Zattn_outputsZattention_outputr   r   r&   r&   r'   rY     s2    

zBloomBlock.forward)NNFF)r]   r^   r_   r   re   r   ra   r   r   r    rY   rl   r&   r&   rh   r'   r     s       r   c                       s   e Zd ZeZdZdZdgZdZ fddZ	e
jddd	Zde
jedddZeeeejejf  eeeejejf  dddZeeeejejf  eeejejf  dddZ  ZS )BloomPreTrainedModeltransformerTr   past_key_valuesc                    s   t  j|| d S rW   rc   )rg   inputskwargsrh   r&   r'   re     s    zBloomPreTrainedModel.__init__modulec                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  ndt |tj
rz|jjjd| jjd |jdk	r|jj|j 	  n$t |tr|jj	  |jjd dS )zInitialize the weights.g        )ZmeanZstdNrL   )
isinstancer   r|   r   dataZnormal_ro   Zinitializer_rangerq   Zzero_	EmbeddingZpadding_idxr   Zfill_)rg   r   r&   r&   r'   _init_weights  s    


z"BloomPreTrainedModel._init_weightsF)r   valuec                 C   s   t |tr||_d S rW   )r   
BloomModelgradient_checkpointing)rg   r   r   r&   r&   r'   _set_gradient_checkpointing  s    
z0BloomPreTrainedModel._set_gradient_checkpointing)past_key_valuer#   r   c                    s8   | d d j \}|  t fdd| D S )z
        Standardizes the format of the cache so as to match most implementations, i.e. to tuple(tuple([batch_size,
        num_heads, ...]))
        r   c                 3   s6   | ].}|d    |d   fV  qdS r   r   Nr   .0r   r#   rv   r0   r=   r&   r'   	<genexpr>  s   zBBloomPreTrainedModel._convert_to_standard_cache.<locals>.<genexpr>r*   tuple)r   r#   batch_size_times_num_headsr&   r   r'   _convert_to_standard_cache  s
    z/BloomPreTrainedModel._convert_to_standard_cache)r   r   c                    s8   | d d j \}}||  t fdd| D S )zy
        Converts the cache to the format expected by Bloom, i.e. to tuple(tuple([batch_size * num_heads, ...]))
        r   c                 3   s2   | ]*}|d    |d   fV  qdS r   r   r   r   rv   r=   r&   r'   r     s   z?BloomPreTrainedModel._convert_to_bloom_cache.<locals>.<genexpr>r   )r   r#   r0   r&   r   r'   _convert_to_bloom_cache  s
    z,BloomPreTrainedModel._convert_to_bloom_cache)F)r]   r^   r_   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementre   r   Moduler   r    r   r`   r   r   ra   r   r   r   rl   r&   r&   rh   r'   r     s"    r   a,  

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`BloomConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[2]`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

            If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
            `input_ids`.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
            Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
            `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
            their past given to this model should not be passed as `input_ids` as they have already been computed.

            Each element of `past_key_values` is a tuple (past_key, past_value):
            - past_key: [batch_size * num_heads, head_dim, kv_length]
            - past_value: [batch_size * num_heads, kv_length, head_dim]
        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.

            If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
            `past_key_values`).
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
z_The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Zed fddZejeejejdddZ	dd Z
ejeeef eejd	d
dZejdddZeeeeeeddeej eeeejejf df  eej eej eej ee ee ee ee eeejdf ef d
ddZ  ZS )r   rn   c                    s   t     j| _ j| _t j| j| _	t
| j jd| _t fddt jD | _t
| j jd| _d| _|   d S )Nr   c                    s   g | ]}t  qS r&   )r   )r   r   rn   r&   r'   
<listcomp>u  s     z'BloomModel.__init__.<locals>.<listcomp>F)rd   re   rt   Z	embed_dimru   r0   r   r   
vocab_sizeword_embeddingsr   r   word_embeddings_layernormZ
ModuleListr   Znum_hidden_layershln_fr   	post_initr   rh   rn   r'   re   j  s     zBloomModel.__init__r.   c                 C   s   t |||S rW   )r@   )rg   r/   r0   r   r&   r&   r'   r@     s    zBloomModel.build_alibi_tensorc                 C   s   | j S rW   r   rf   r&   r&   r'   get_input_embeddings  s    zBloomModel.get_input_embeddings)r/   input_shaper   r   c           	      C   sL   d }|j }|\}}|dkr(t|||d}t||d}|d kr@|n||B }|S )Nr   )r   r   )r)   )r   r(   r-   )	rg   r/   r   r   Zcombined_attention_maskr   r   r,   Zexpanded_attn_maskr&   r&   r'   _prepare_attn_mask  s      zBloomModel._prepare_attn_masknew_embeddingsc                 C   s
   || _ d S rW   r   rg   r   r&   r&   r'   set_input_embeddings  s    zBloomModel.set_input_embeddings
checkpointoutput_typer   N.)
	input_idsr   r/   r   inputs_embedsr   r   output_hidden_statesreturn_dictr   c
              
      s   |
 dddk	rtdt t|
dkr6td|
  d k	rB n| jj |d k	rV|n| jj}d k	rjn| jj	|	d k	r~|	n| jj
}	|d k	r|d k	rtdn2|d k	r|j\}}n|d k	r|j\}}}ntd|d krtd gt| j }| || jj}|d kr| |}| |}r&dnd } r4dnd }|rBdnd }| jrj| jrjrjtd	 d|}d}|d d k	r|d d jd
 }|| }|d krtj||f|jd}n||j}| j|| j|jd}| j|||f|d}tt| j|D ]\}\}}|r||f }| jrZ| jrZ fdd}tj j!!|||||||| }n||||||  |d}|d }dkr||d f } r||rd
nd f }q| "|}|r||f }|	stdd ||||fD S t#||||dS )Nposition_idsFz`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore passing `position_ids`.r   Got unexpected arguments: zDYou cannot specify both input_ids and inputs_embeds at the same timez5You have to specify either input_ids or inputs_embedsr&   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...r1   r   )r   )r   r   c                    s    fdd}|S )Nc                     s    | dS )N)r   r   r&   )r   )r   r   r   r&   r'   custom_forward  s    zIBloomModel.forward.<locals>.create_custom_forward.<locals>.custom_forwardr&   )r   r   r   r   r   r'   create_custom_forward  s    z1BloomModel.forward.<locals>.create_custom_forward)r   r/   r   r   r   r?   Tr   c                 s   s   | ]}|d k	r|V  qd S rW   r&   )r   vr&   r&   r'   r   %  s      z%BloomModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   r   
attentions)$popwarningswarnFutureWarninglenrx   ro   r   r   r   use_return_dictr*   r   r   Zget_head_maskZn_layerr   r   r   rD   loggerZwarning_oncer   Zonesr   r+   r@   r0   r   r   	enumerateziputilsr   r   r   )rg   r   r   r/   r   r   r   r   r   r   deprecated_argumentsr#   r=   r   r   ZpresentsZall_self_attentionsZall_hidden_statesZseq_length_with_pastr   r?   Zcausal_maskr   blockr   r   r   r&   r   r'   rY     s    





	



zBloomModel.forward)	NNNNNNNNN)r]   r^   r_   r   re   r   ra   r   r   r@   r   r   
BoolTensorr   r   r   BLOOM_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   
LongTensorr    r   rY   rl   r&   r&   rh   r'   r   e  sH    
          r   z
    The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    c                       s6  e Zd ZdgZed fddZdd Zejddd	Z	dej
eej eej eej edddZeeeeeeddeej
 eeeejejf df  eej eej eej eej ee ee ee ee eeej ef dddZeeejejf df ej
eeejejf df dddZ  ZS )BloomForCausalLMzlm_head.weightrn   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFrp   )
rd   re   r   r   r   r|   rt   r   lm_headr   r   rh   r&   r'   re   9  s    
zBloomForCausalLM.__init__c                 C   s   | j S rW   r   rf   r&   r&   r'   get_output_embeddingsA  s    z&BloomForCausalLM.get_output_embeddingsr   c                 C   s
   || _ d S rW   r   r   r&   r&   r'   set_output_embeddingsD  s    z&BloomForCausalLM.set_output_embeddingsN)r   r   r/   r   r   c                 K   s~   |r@|d d df  d}|d d jd |jd kr@| |}|d k	rZ|d krZd|i}nd|i}|||d|d |S )Nr4   r   r   r   r   )r   r   r/   )Z	unsqueezer*   r   updateget)rg   r   r   r/   r   r   Zmodel_inputsr&   r&   r'   prepare_inputs_for_generationG  s    	

z.BloomForCausalLM.prepare_inputs_for_generationr   .r   r   r/   r   r   labelsr   r   r   r   r   c                 K   s8  | dddk	rtdt t|dkr6td| |
dk	rB|
n| jj}
| j||||||||	|
d	}|d }| 	|}d}|dk	r|
|j}|ddd	ddf  }|dd
df  }|j\}}}t }|||| |||| }|
s |f|d
d  }|dk	r|f| S |S t|||j|j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        r   Fr   r   r   Nr   r/   r   r   r   r   r   r   .r4   r   losslogitsr   r   r   )r   r   r   r   r   rx   ro   r   r   r   r+   r   
contiguousr*   r   r   r   r   r   r   )rg   r   r   r/   r   r   r   r   r   r   r   r   transformer_outputsr   Z	lm_logitsr   Zshift_logitsZshift_labelsr#   r=   r   loss_fctr   r&   r&   r'   rY   f  sT    
 zBloomForCausalLM.forward)pastbeam_idxr   c                    sD   | j |t d} fdd|D tfdd|D }| |S )aL  
        This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
        [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
        beam_idx at every generation step.

        Output shares the same memory storage as `past`.
        )r#   c                    s&   i | ]}|D ]}|j  |j qqS r&   )r   r+   )r   r   Z
past_state)r  r&   r'   
<dictcomp>  s
       z3BloomForCausalLM._reorder_cache.<locals>.<dictcomp>c                 3   sB   | ]:}|d   d  |d  j |d  d  |d  j fV  qdS r   )Zindex_selectr   r   )device_to_beam_idxr&   r'   r     s   z2BloomForCausalLM._reorder_cache.<locals>.<genexpr>)r   r   r   r   )rg   r  r  Zstandardized_pastZreordered_pastr&   )r  r  r'   _reorder_cache  s    

zBloomForCausalLM._reorder_cache)NNN)
NNNNNNNNNN)r]   r^   r_   Z_tied_weights_keysr   re   r   r   ra   r   r   r   dictr   r   r   r   r   r   r   r   r    r   rY   r	  rl   r&   r&   rh   r'   r   /  s^                J r   a  
    The Bloom Model transformer with a sequence classification head on top (linear layer).

    [`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-1) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                       s   e Zd Zed fddZeeeee	e
dd
eej eeeejejf df  eej eej eej eej ee ee ee ee eeej e	f ddd	Z  ZS )BloomForSequenceClassificationrn   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S r   )
rd   re   
num_labelsr   r   r   r|   rt   scorer   r   rh   r&   r'   re     s
    
z'BloomForSequenceClassification.__init__r   N.r   c                 K   sR  | dddk	rtdt t|dkr6td| |
dk	rB|
n| jj}
| j||||||||	|
d	}|d }| 	|}|dk	r|j
d }n
|j
d }| jjdkr|dkrtd	| jjdkrd
}nD|dk	rt|| jjd
d |j}nd
}t| jj d |tj||jd|f }d}|dk	r
| jjdkr| jdkrRd| j_n:| jdkr|jtjksz|jtjkrd| j_nd| j_| jjdkrt }| jdkr|| | }n
|||}n>| jjdkrt }|||}n| jjdkr
t }|||}|
s:|f|dd  }|dk	r6|f| S |S t|||j |j!|j"dS )  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        r   Fr   r   r   Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r4   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   Z
regressionZsingle_label_classificationZmulti_label_classificationr   )#r   r   r   r   r   rx   ro   r   r   r  r*   Zpad_token_idr   nesumr+   r   r   warningri   r]   r!   Zproblem_typer  r   longr   r	   squeezer   r   r   r   r   r   )rg   r   r   r/   r   r   r   r   r   r   r   r   r  r   r  r#   Zsequence_lengthsZpooled_logitsr   r  r   r&   r&   r'   rY     s    

$

(

z&BloomForSequenceClassification.forward)
NNNNNNNNNN)r]   r^   r_   r   re   r   r   r   r   r   r   r   r   r   r   ra   r    r   rY   rl   r&   r&   rh   r'   r    s<   	          r  z
    Bloom Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Zed fddZeeeee	e
dd
eej eeeejejf df  eej eej eej eej ee ee ee ee eeej e	f ddd	Z  ZS )BloomForTokenClassificationrn   c                    s   t  | |j| _t|| _t|dr:|jd k	r:|j}n t|drV|jd k	rV|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropoutrw   g?)rd   re   r  r   r   hasattrr  rw   r   r   rG   r|   rt   
classifierr   )rg   ro   r  rh   r&   r'   re   ]  s    
z$BloomForTokenClassification.__init__r   N.r   c                 K   s  | dddk	rtdt t|dkr6td| |
dk	rB|
n| jj}
| j||||||||	|
d	}|d }| 	|}| 
|}d}|dk	r||j}|j\}}t }|||| | j||| }|
s|f|dd  }|dk	r|f| S |S t|||j|jd	S )
r  r   Fr   r   r   Nr   r1   )r   r  r   r   )r   r   r   r   r   rx   ro   r   r   rG   r  r+   r   r*   r   r   r  r   r   r   )rg   r   r   r/   r   r   r   r   r   r   r   r   r  r   r  r   r#   r=   r  r   r&   r&   r'   rY   n  sP    


 z#BloomForTokenClassification.forward)
NNNNNNNNNN)r]   r^   r_   r   re   r   r   r   r   r   r   r   r   r   r   ra   r    r   rY   rl   r&   r&   rh   r'   r  U  s<             r  z
    The BLOOM Model transformer with a span classification head on top for extractive question-answering tasks like
    SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       s   e Zd Z fddZeeddeej	 eej
 eej	 eej
 eej
 eej	 eej	 ee ee ee eeef dddZ  ZS )	BloomForQuestionAnsweringc                    s2   t  | t|| _t|jd| _|   d S )Nr1   )	rd   re   r   r   r   r|   rt   
qa_outputsr   r   rh   r&   r'   re     s    
z"BloomForQuestionAnswering.__init__zbatch_size, sequence_lengthN)r   r/   r   r   r   start_positionsend_positionsr   r   r   r   c              
   C   sN  |
dk	r|
n| j j}
| j|||||||	|
d}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|
s8||f|dd  }|dk	r4|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        N)r/   r   r   r   r   r   r   r   r   r4   r2   )Zignore_indexr1   )r   start_logits
end_logitsr   r   )ro   r   r   r  splitr  r  r   sizeclampr   r   r   r   )rg   r   r/   r   r   r   r  r  r   r   r   r   Zsequence_outputr  r  r  Z
total_lossZignored_indexr  Z
start_lossZend_lossr   r&   r&   r'   rY     sN    






z!BloomForQuestionAnswering.forward)
NNNNNNNNNN)r]   r^   r_   re   r   r   formatr   r   r   ZFloatTensorr    r   r   r   rY   rl   r&   r&   rh   r'   r    s2             
r  )Erk   r5   r   typingr   r   r   r   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   r	   r
   rF   Z
file_utilsr   r   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r   r   Zconfiguration_bloomr   Z
get_loggerr]   r   r   r   Z#BLOOM_PRETRAINED_MODEL_ARCHIVE_LISTSizer   r   r   r(   ra   r-   r   r@   r   r    rI   rQ   rT   ZautogradFunctionrU   r   rb   rm   r   r   r   ZBLOOM_START_DOCSTRINGr   r   r   r  r  r  r&   r&   r&   r'   <module>   s   
  , !GF7 G w^