o
    Zh                  
   @   sh  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 dd
l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"m#Z#m$Z$ ddl%m&Z& e# r}ddl'm(Z( ddl)m*Z* e$+e,Z-dej.de/dej0dej.fddZ1dej.dej.de2de3dej.f
ddZ4dej.dej.fddZ5d ej.dej.dej.fd!d"Z6G d#d$ d$ej7j8Z9G d%d& d&e	j:Z;G d'd( d(e	j:Z<G d)d* d*e	j:Z=G d+d, d,e	j:Z>e"G d-d. d.e Z?e"G d/d0 d0e?Z@e"d1d2G d3d4 d4e?eZAe"d5d2G d6d7 d7e?ZBe"G d8d9 d9e?ZCe"G d:d; d;e?ZDg d<ZEdS )=zPyTorch BLOOM model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availablelogging   )BloomConfig)	BlockMask)make_flex_block_causal_maskattention_mask	num_headsdtypereturnc                 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rvt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`):
            number of heads
        dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
            dtype of the output tensor
       r   devicer    r   r   dimN).N)shapemathfloorlog2torchZtensorr$   float32arangeint32powmincatZcumsumreshapeto)r   r   r    
batch_size
seq_lengthZclosest_power_of_2baseZpowersZslopesZ
extra_baseZnum_remaining_headsZextra_powersZarange_tensoralibi r9   W/var/www/auris/lib/python3.10/site-packages/transformers/models/bloom/modeling_bloom.pybuild_alibi_tensor7   s"   
 $ &r;   xresidualprobtrainingc                 C   s   t j| ||d}|| }|S )a
  
    Dropout add function

    Args:
        x (`torch.tensor`):
            input tensor
        residual (`torch.tensor`):
            residual tensor
        prob (`float`):
            dropout probability
        training (`bool`):
            training mode
    )pr?   )Fdropout)r<   r=   r>   r?   outr9   r9   r:   dropout_addc   s   rD   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`):
            input hidden states
          ?      ? e3E?r   Hm?r,   tanh)r<   r9   r9   r:   bloom_gelu_forwardv   s   *	rK   gc                 C   s^   |d }t d| dd| |   }d| d||  dd| |    dd|   }||  S )a   
    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`):
            gradient output tensor
        x (`torch.tensor`):
            input tensor
    r   rG   r   rH   rE   g6vf?rI   )rL   r<   Ztanh_outffr9   r9   r:   bloom_gelu_back   s   0rN   c                   @   s@   e Zd ZedejdejfddZedejdejfddZdS )	GeLUFunctioninputr!   c                 C   s   |  | t|S N)Zsave_for_backwardrK   )ctxrP   r9   r9   r:   forward   s   
zGeLUFunction.forwardgrad_outputc                 C   s   | j }t||}|S rQ   )Zsaved_tensorsrN   )rR   rT   rP   tmpr9   r9   r:   backward   s   
zGeLUFunction.backwardN)__name__
__module____qualname__staticmethodr,   TensorrS   rV   r9   r9   r9   r:   rO      s
    rO   c                       s6   e Zd ZdZ fddZdejdejf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 rQ   super__init__self	__class__r9   r:   r_      s   zBloomGelu.__init__r<   r!   c                 C   s   | j rt|S t|S rQ   )r?   rO   applyrK   )ra   r<   r9   r9   r:   rS      s   
zBloomGelu.forward)	rW   rX   rY   __doc__r_   r,   r[   rS   __classcell__r9   r9   rb   r:   r\      s    r\   c                       s   e Zd Zddedee f fddZdejde	ejejejf fdd	Z
d
ejdejfddZ					ddejdejdejdejdee deej dededeej fddZ  ZS )BloomAttentionNconfig	layer_idxc                    s   t    |j| _|j| _|j| _|j| _| j| j | _| j| _|j	| _	| j| j | jkr:t
d| j d| j ddt| j | _d| _|| _|d u rXtd| j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).rF   zInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.r   Tbias)r^   r_   pretraining_tpslow_but_exacthidden_sizen_headr   head_dimZ
split_sizehidden_dropout
ValueErrorr)   sqrtinv_norm_factorbetari   loggerwarning_oncerc   rW   r   Linearquery_key_valuedenseDropoutattention_dropout)ra   rh   ri   rb   r9   r:   r_      s0   

zBloomAttention.__init__	fused_qkvr!   c                 C   sz   |j \}}}|||| jd| j}|ddddf dd}|ddddf dd}|ddddf dd}|||fS )a  
        Split the last dimension into (num_heads, head_dim) and reshapes to (bs, heads, len, dim) shape
        without making any copies, results share same memory storage as `fused_qkv`

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

        Returns:
            query: [batch_size, num_heads, seq_length, head_dim]
            key: [batch_size, num_heads, seq_length, head_dim]
            value: [batch_size, num_heads, seq_length, head_dim]
        r   .r   Nr   r"   )r(   viewr   rp   	transpose)ra   r}   r5   r6   Zthree_times_hidden_sizequery_layer	key_layervalue_layerr9   r9   r:   _reshape   s   
zBloomAttention._reshaper<   c                 C   sP   |j \}}}|| j }||| j|| j}|dddd}|||| j| j S )z
        Merge heads together over the last dimension

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

        Returns:
            torch.tensor: [batch_size, seq_length, num_heads * head_dim]
        r   r"   r   r   )r(   r   r~   rp   Zpermuter3   )ra   r<   Zbatch_size_and_num_headsr6   _r5   r9   r9   r:   _merge_heads   s
   
zBloomAttention._merge_headsFhidden_statesr=   r8   r   
layer_past	head_mask	use_cacheoutput_attentionscache_positionc
                 C   s$  |j \}
}}| |}| |\}}}|d ur&d|	i}|||| j|\}}||
| j d| j}||
| j d| jdd}||
| j d| j}|j	||| j
| jd}||
| j|d}|d urz|d d d d d d d |j d f }|| }tj|dtjd|j}| |}|d ur|| }||
| j |d}t||}| |}| jdkr| jr| j| j }t|}t| jD ]3}|t|d d d d t|| t|d | f | jjd d t|| t|d | f  }qn| |}t||| j | j!}||f}|r||f7 }|S )Nr   r'   )Zbatch1Zbatch2ru   alpha)r&   r    r   )"r(   ry   r   updateri   r3   r   rp   r   Zbaddbmmru   rt   r~   rA   Zsoftmaxr,   r-   r4   r    r|   Zbmmr   rl   rm   rn   
zeros_likerangelinearintrz   weightrD   rq   r?   )ra   r   r=   r8   r   r   r   r   r   r   r5   Zq_lengthr   r}   r   r   r   Zcache_kwargsZattention_scoresZattn_weightscausal_maskZattention_probsZattention_probs_reshapedZcontext_layerslicesZoutput_tensorioutputsr9   r9   r:   rS     sR   
&


,*

zBloomAttention.forwardrQ   NNFFN)rW   rX   rY   r   r   r   r_   r,   r[   r   r   r   r   bool
LongTensorrS   rf   r9   r9   rb   r:   rg      s8    $!	
rg   c                       s>   e Zd Zdef fddZdejdejdejfddZ  ZS )	BloomMLPrh   c                    sX   t    |j}|j| _|j| _t|d| | _t | _	td| || _
|j| _d S )N   )r^   r_   rn   rl   rm   r   rx   dense_h_to_4hr\   	gelu_impldense_4h_to_hrq   )ra   rh   rn   rb   r9   r:   r_   S  s   
zBloomMLP.__init__r   r=   r!   c                 C   s   |  | |}| jdkrY| jrYt|}| jjjd | j }t	| jD ]3}|t
|d d d d t|| t|d | f | jjd d t|| t|d | f  }q$n| |}t||| j| j}|S )Nr   r'   )r   r   rl   rm   r,   r   r   r   r(   r   rA   r   r   rD   rq   r?   )ra   r   r=   Zintermediate_outputr   r   outputr9   r9   r:   rS   ^  s   
,*
zBloomMLP.forward)	rW   rX   rY   r   r_   r,   r[   rS   rf   r9   r9   rb   r:   r   R  s    $r   c                       sx   e Zd Zddedee f fddZ					ddejdejd	ejd
ee	 deej de
de
deej fddZ  ZS )
BloomBlockNrh   ri   c                    sb   t    |j}t||jd| _|j| _t||| _	t||jd| _
t|| _|j| _|j| _d S )NZeps)r^   r_   rn   r   layer_norm_epsiloninput_layernormro   r   rg   self_attentionpost_attention_layernormr   mlp(apply_residual_connection_post_layernormrq   )ra   rh   ri   rn   rb   r9   r:   r_   r  s   

zBloomBlock.__init__Fr   r8   r   r   r   r   r   r   c	                 C   s   |  |}	| jr|	}
n|}
| j|	|
|||||||d	}|d }|dd  }| |}	| jr0|	}
n|}
| |	|
}|rA|f| }|S |f|dd   }|S )N)r   r   r8   r   r   r   r   r   r   )r   r   r   r   r   )ra   r   r8   r   r   r   r   r   r   Zlayernorm_outputr=   Zattn_outputsZattention_outputr   r   r9   r9   r:   rS     s6   


zBloomBlock.forwardrQ   r   )rW   rX   rY   r   r   r   r_   r,   r[   r   r   r   rS   rf   r9   r9   rb   r:   r   q  s0    	r   c                       sN   e Zd ZeZdZdZdgZdZdZ	dZ
dZ fddZdejfdd	Z  ZS )
BloomPreTrainedModeltransformerTr   past_key_valuesc                    s   t  j|i | d S rQ   r]   )ra   Zinputskwargsrb   r9   r:   r_     s   zBloomPreTrainedModel.__init__modulec                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |trW|jj	  |jjd dS dS )zInitialize the weights.        )meanZstdNrF   )
isinstancer   rx   r   dataZnormal_rh   Zinitializer_rangerk   Zzero_	EmbeddingZpadding_idxr   Zfill_)ra   r   r9   r9   r:   _init_weights  s   


z"BloomPreTrainedModel._init_weights)rW   rX   rY   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_cache_classZ_supports_static_cacheZ_supports_quantized_cacher_   r   Moduler   rf   r9   r9   rb   r:   r     s    r   c                       sf  e Zd Zdef fddZdejdedejdejfdd	Z	d
d Z
dejfddZe										d&deej deeeeeejejf df f  deej deej deej dee dee dee dee deej deeejdf ef fddZ	d'deejdf dejdejdedef
dd Zedejd!ed"edejdejd#efd$d%Z  ZS )(
BloomModelrh   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  |d qS ))ri   )r   ).0r   rh   r9   r:   
<listcomp>  s    z'BloomModel.__init__.<locals>.<listcomp>F)r^   r_   rn   Z	embed_dimro   r   r   r   
vocab_sizeword_embeddingsr   r   word_embeddings_layernormZ
ModuleListr   Znum_hidden_layershln_fgradient_checkpointing	post_initra   rh   rb   r   r:   r_     s    zBloomModel.__init__r   r   r    r!   c                 C   s   t |||S rQ   )r;   )ra   r   r   r    r9   r9   r:   r;     s   zBloomModel.build_alibi_tensorc                 C      | j S rQ   r   r`   r9   r9   r:   get_input_embeddings     zBloomModel.get_input_embeddingsnew_embeddingsc                 C   
   || _ d S rQ   r   ra   r   r9   r9   r:   set_input_embeddings     
zBloomModel.set_input_embeddingsN	input_idsr   .r   inputs_embedsr   r   output_hidden_statesreturn_dictr   c                 K   s  | dddurtdt t|dkrtd| |dur!|n| jj}|dur+|n| jj}|dur5|n| jj	}|	dur?|	n| jj
}	|du |duA rOtd| jr^| jr^|r^td d}|du rg| |}d}|rt|tsd	}|du rzt }n
t|}td
 |j\}}}|dur| nd}|| }|
du rtj||| |jd}
| || jj}| |}d}|rdnd}|rdnd}|du rtj||f|jd}n||j}| j|| j|j d}| !|||
||}t"| j#D ]L\}}|r||f }| jr| jr| $|j%|||||| |||
	}n|||||| ||||
d}|d }|r,|d }|r;|||r6dnd f }q| &|}|rI||f }|rN|nd}|rW|' }|	sgt(dd ||||fD S t)||||dS )  
        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)
        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: Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...TzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r$   r9   )r    )r   r   r   r   r   r8   r   r   r"   c                 s   s    | ]	}|d ur|V  qd S rQ   r9   )r   vr9   r9   r:   	<genexpr>  s    z%BloomModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   r   
attentions)*popwarningswarnFutureWarninglenrr   rh   r   r   r   use_return_dictr   r?   rv   rw   r   r   r   r   Zfrom_legacy_cacher(   get_seq_lengthr,   r.   r$   Zget_head_maskZn_layerr   Zonesr4   r;   r   r    _update_causal_mask	enumerater   Z_gradient_checkpointing_func__call__r   Zto_legacy_cachetupler   )ra   r   r   r   r   r   r   r   r   r   r   deprecated_argumentsZreturn_legacy_cacher5   r6   r   Zpast_lengthZseq_length_with_pastr   Znext_decoder_cacheZall_self_attentionsZall_hidden_statesr8   r   r   blockr   Z
next_cacher9   r9   r:   rS     s   







zBloomModel.forwardFr   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )NZflash_attention_2r   Zflex_attentionr   FZsdpa)r   Zpast_key_values_lengthZis_trainingr   r'   )sequence_lengthtarget_lengthr    r   r5   )cudaZxpuZnpu)rh   Z_attn_implementationanyr   r,   r[   r   r   Zis_compileabler   Z_ignore_causal_mask_sdpar?   r    r(   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr$   typefinfor1   Z_unmask_unattended)ra   r   r   r   r   r   Zpast_seen_tokensZusing_compilable_cacher    r   r   r   	min_dtyper9   r9   r:   r     sT   




zBloomModel._update_causal_maskr   r   r5   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )Z
fill_valuer    r$   r   )Zdiagonalr   r'   r   )r&   r,   r   r1   fullr$   Ztriur.   r3   expandcloner(   r4   Zmasked_fill)r   r   r   r    r   r5   r   r   r   Zmask_lengthZpadding_maskr9   r9   r:   r     s,    $
6  z@BloomModel._prepare_4d_causal_attention_mask_with_cache_position
NNNNNNNNNN)F)rW   rX   rY   r   r_   r,   r[   r   r    r;   r   r   r   r   r   r   r   r   r   r   rS   r   rZ   r   rf   r9   r9   rb   r:   r     s     "	
 #
Dr   z
    The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    )Zcustom_introc                       sL  e Zd ZdgZdef fddZdd Zdejfdd	Z		
	
	
	
	d!ddZ
e	
	
	
	
	
	
	
	
	
	
	
d"deej deeeeeejejf df f  deej deej deej deej dee dee dee dee deej deeej ef fddZdeeejejf df dejdeeejejf df fdd Z  ZS )#BloomForCausalLMzlm_head.weightrh   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFrj   )
r^   r_   r   r   r   rx   rn   r   lm_headr   r   rb   r9   r:   r_     s   
zBloomForCausalLM.__init__c                 C   r   rQ   r   r`   r9   r9   r:   get_output_embeddings$  r   z&BloomForCausalLM.get_output_embeddingsr   c                 C   r   rQ   r   r   r9   r9   r:   set_output_embeddings'  r   z&BloomForCausalLM.set_output_embeddingsNTc                 K   s>  |d urL|d ur|j d dkr|d d |j d  d f }n.|d us+|d |j d kr:|d d |j d  d f }n|j d |j d krL|d d |f }|d ur_t||j d kr_|d d}n
|jtjdd d}t|tr|d ur| }	|j \}
}|	| }tj|
||j	|j
d}tj||gdd}|||||d	 |S )
Nr   r   r'   )r   r   )Zmemory_format)r   r   r#   r%   )r   r   r   r   )r(   r   r   r,   Zcontiguous_formatr   r   r   Zzerosr$   r    r2   r   )ra   r   r   r   r   r   r   r   Zmodel_inputsr   r5   r6   diffZnew_attn_maskr9   r9   r:   prepare_inputs_for_generation*  s8   
z.BloomForCausalLM.prepare_inputs_for_generationr   r   .r   r   r   labelsr   r   r   r   r   r!   c                 K   s   | dd}| dddurtdt t|dkr!td| |
dur'|
n| jj}
| j||||||||	|
|d
}|d }| 	|}d}|durZ|
|j}| j||| jj|d	}|
sp|f|d
d  }|durn|f| S |S t|||j|j|jdS )aZ  
        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)
        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]`
        num_items_in_batchNr   Fr   r   r   )	r   r   r   r   r   r   r   r   r   )r   r   r   losslogitsr   r   r   )r   r   r   r   r   rr   rh   r   r   r   r4   r$   Zloss_functionr   r   r   r   r   )ra   r   r   r   r   r   r   r   r   r   r   r   r   r   transformer_outputsr   Z	lm_logitsr   r   r9   r9   r:   rS   h  sT   "
zBloomForCausalLM.forwardpastbeam_idxc                    s,    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`.
        c                    s&   i | ]}|D ]
}|j  |j qqS r9   )r$   r4   )r   r   Z
past_state)r   r9   r:   
<dictcomp>  s
    z3BloomForCausalLM._reorder_cache.<locals>.<dictcomp>c                 3   sD    | ]}|d   d  |d  j |d  d  |d  j fV  qdS )r   r   N)Zindex_selectr$   )r   r   )device_to_beam_idxr9   r:   r     s    
z2BloomForCausalLM._reorder_cache.<locals>.<genexpr>)r   )ra   r   r   Zreordered_pastr9   )r   r  r:   _reorder_cache  s   
zBloomForCausalLM._reorder_cache)NNNNT)NNNNNNNNNNN)rW   rX   rY   Z_tied_weights_keysr   r_   r   r,   r[   r   r   r   r   r   r   r   r   r   r   rS   r  rf   r9   r9   rb   r:   r     sn    
>"	
V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                          e Zd Zdef fddZe										ddeej dee	e
eeejejf df f  deej d	eej d
eej deej dee dee dee dee de	eej ef fddZ  ZS )BloomForSequenceClassificationrh   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S r   )
r^   r_   
num_labelsr   r   r   rx   rn   scorer   r   rb   r9   r:   r_     s
   
z'BloomForSequenceClassification.__init__Nr   r   .r   r   r   r   r   r   r   r   r!   c                 K   s`  | dddurtdt t|dkrtd| |
dur!|
n| jj}
| j||||||||	|
d	}|d }| 	|}|durF|j
d }n|j
d }| jjdu rY|dkrYtd	| jjdu rbd
}n1|dur|| jjk|jtj}tj|j
d
 |jtjd}|| d
}nd
}t| jj d |tj||jd|f }d}|dur| jjdu r| jdkrd| j_n| jdkr|jtjks|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ur"|f| S |S t|||j |j!|j"dS )4  
        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)
        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   Nr   r   r   r   r   r   r   r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r'   r#   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   rr   rh   r   r   r  r(   Zpad_token_idr4   r$   r,   r/   r.   Zargmaxrv   rw   rc   rW   Zproblem_typer  r    longr   r	   squeezer   r   r   r   r   r   )ra   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r5   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesZpooled_logitsr   loss_fctr   r9   r9   r:   rS     s    




"


z&BloomForSequenceClassification.forwardr   )rW   rX   rY   r   r_   r   r   r,   r   r   r   r   r[   r   r   rS   rf   r9   r9   rb   r:   r    sH    	"	
r  c                       r  )BloomForTokenClassificationrh   c                    s   t  | |j| _t|| _t|dr|jd ur|j}nt|dr+|jd ur+|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropoutrq   g?)r^   r_   r  r   r   hasattrr  rq   r   r{   rB   rx   rn   
classifierr   )ra   rh   r  rb   r9   r:   r_   f  s   
z$BloomForTokenClassification.__init__Nr   r   .r   r   r   r   r   r   r   r   r!   c                 K   s  | dddurtdt t|dkrtd| |
dur!|
n| jj}
| j||||||||	|
d	}|d }| 	|}| 
|}d}|durf||j}|j\}}t }|||| | j||| }|
s||f|dd  }|durz|f| S |S t|||j|jd	S )
r  r   Fr   r   r   Nr	  r"   )r   r   r   r   )r   r   r   r   r   rr   rh   r   r   rB   r  r4   r$   r(   r   r~   r  r   r   r   )ra   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r5   r6   r  r   r9   r9   r:   rS   w  sN    


z#BloomForTokenClassification.forwardr   )rW   rX   rY   r   r_   r   r   r,   r   r   r   r   r[   r   r   rS   rf   r9   r9   rb   r:   r  d  sH    "	
r  c                       s   e Zd Z fddZe										ddeej deej deej deej deej d	eej d
eej dee	 dee	 dee	 de
eef fddZ  ZS )BloomForQuestionAnsweringc                    s2   t  | t|| _t|jd| _|   d S )Nr"   )	r^   r_   r   r   r   rx   rn   
qa_outputsr   r   rb   r9   r:   r_     s   
z"BloomForQuestionAnswering.__init__Nr   r   r   r   r   start_positionsend_positionsr   r   r   r!   c              
   C   sF  |
dur|
n| j j}
| j|||||||	|
d}|d }| |}|jddd\}}|d }|d }d}|dur|durt| dkrN|d}t| dkr[|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|
s||f|dd  }|dur|f| S |S t||||j|jd	S )
r   N)r   r   r   r   r   r   r   r   r   r'   r%   )Zignore_indexr"   )r   start_logits
end_logitsr   r   )rh   r   r   r  splitr  
contiguousr   sizeclampr   r   r   r   )ra   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   r9   r9   r:   rS     sN   






z!BloomForQuestionAnswering.forwardr   )rW   rX   rY   r_   r   r   r,   r   ZFloatTensorr   r   r   r   rS   rf   r9   r9   rb   r:   r    sH    	

r  )r   r   r   r  r  r  )Fre   r)   r   typingr   r   r   r,   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   r	   r
   rA   Zcache_utilsr   r   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   Zconfiguration_bloomr   Z!torch.nn.attention.flex_attentionr   Zintegrations.flex_attentionr   Z
get_loggerrW   rv   r[   r   r    r;   floatr   rD   rK   rN   ZautogradFunctionrO   r   r\   rg   r   r   r   r   r   r  r  r  __all__r9   r9   r9   r:   <module>   sd   
 $, I  ; ?dV