U
    5Af                  	   @   sJ  d Z ddlZddlmZmZmZmZ ddlZddlm	  m
Z ddlZddlm	Z	 ddlmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& e! rddl'm(Z( e#)e*Z+dZ,ej-e.e.ej/ej0e1ej-e.dddZ2G dd de	j3Z4e5e4 G dd de	j3Z6G dd de6Z7G dd de6Z8dd Z9d8dd Z:G d!d" d"e	j3Z;ej-e.ej-d#d$d%Z<G d&d' d'e	j3Z=G d(d) d)e=Z>G d*d+ d+e=Z?e=e>e?d,Z@G d-d. d.e	j3ZAd/ZBed0eBG d1d2 d2eZCd3ZDed0eBG d4d5 d5eCZEG d6d7 d7eCZFdS )9zPyTorch OLMo model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss   )ACT2FN)CacheDynamicCacheStaticCache)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast)PreTrainedModel)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )
OlmoConfig)_flash_attention_forwardr   )attention_masksequence_lengthtarget_lengthdtypedevice	min_dtypecache_position
batch_sizec                 C   s.  | dk	r|   dkr| }ntj||f|||d}|dkrHtj|dd}|tj||d|ddk9 }|ddddddf |ddd}| dk	r*| }| jd }	|ddddddd|	f | ddddddf  }
|
dk}
|ddddddd|	f 	|
||ddddddd|	f< |S )	a  
    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.
        device (`torch.device`):
            The device to plcae the 4D attention mask on.
        min_dtype (`float`):
            The minimum value representable with the dtype `dtype`.
        cache_position (`torch.Tensor`):
            Indices depicting the position of the input sequence tokens in the sequence.
        batch_size (`torch.Tensor`):
            Batch size.
    N   )Z
fill_valuer   r   r   )Zdiagonalr   r   )
dimtorchfullZtriuarangereshapeexpandcloneshapeZmasked_fill)r   r   r   r   r   r    r!   r"   causal_maskZmask_lengthZpadding_mask r/   J/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/olmo/modeling_olmo.py5_prepare_4d_causal_attention_mask_with_cache_position=   s"     $

8   r1   c                       s<   e Zd ZdZedd fddZejejdddZ  Z	S )	OlmoLayerNormz/LayerNorm but with no learnable weight or bias.N)hidden_sizereturnc                    s   t    |f| _d S N)super__init__normalized_shape)selfr3   	__class__r/   r0   r7   u   s    
zOlmoLayerNorm.__init__)hidden_statesr4   c                 C   s,   |j }tj|jtjd| jd d dd|S )Nr   gh㈵>)Zeps)r   FZ
layer_normtor'   float32r8   )r9   r<   Z
orig_dtyper/   r/   r0   forwardy   s     zOlmoLayerNorm.forward)
__name__
__module____qualname____doc__intr7   r'   TensorrA   __classcell__r/   r/   r:   r0   r2   r   s   r2   c                       s.   e Zd Zd	 fdd	Ze dd Z  ZS )
OlmoRotaryEmbedding   '  N      ?c                    sl   t    || _|| _|| _|| _d| jtjd| jdtjd	 
|| j   }| jd|dd || _d S )NrL   r      r=   inv_freqF
persistent)r6   r7   scaling_factorr&   max_position_embeddingsbaser'   r)   int64floatr?   register_bufferZmax_seq_len_cached)r9   r&   rR   rS   r   rQ   rN   r:   r/   r0   r7      s    
0zOlmoRotaryEmbedding.__init__c           
   	   C   s   | j d d d d f  |jd dd}|d d d d d f  }|jj}t|tr`|dkr`|nd}tj	|dd@ | |  
dd}tj||fdd	}| }| }	W 5 Q R X |j|jd
|	j|jd
fS )Nr   r%   r   ZmpscpuF)device_typeZenabledrM   r&   r=   )rN   rU   r+   r-   r   type
isinstancestrr'   Zautocast	transposecatcossinr?   r   )
r9   xposition_idsZinv_freq_expandedZposition_ids_expandedrX   ZfreqsZembr_   r`   r/   r/   r0   rA      s    (zOlmoRotaryEmbedding.forward)rJ   rK   NrL   )rB   rC   rD   r7   r'   Zno_gradrA   rH   r/   r/   r:   r0   rI      s   rI   c                       s    e Zd ZdZ fddZ  ZS ) OlmoLinearScalingRotaryEmbeddingzZOlmoRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                    s(   |  | j }t ||\}}||fS r5   )rU   rQ   r6   rA   )r9   ra   rb   r_   r`   r:   r/   r0   rA      s    z(OlmoLinearScalingRotaryEmbedding.forwardrB   rC   rD   rE   rA   rH   r/   r/   r:   r0   rc      s   rc   c                       s    e Zd ZdZ fddZ  ZS )$OlmoDynamicNTKScalingRotaryEmbeddingzlOlmoRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillac                    s   t |d }|| jkr| j| j| | j | jd  | j| jd    }d|t jd| jdt jd 	|j
| j   }| jd|dd t ||\}}||fS )	Nr   rM   rL   r   r=   rN   FrO   )r'   maxrR   rS   rQ   r&   r)   rT   rU   r?   r   rV   r6   rA   )r9   ra   rb   Zseq_lenrS   rN   r_   r`   r:   r/   r0   rA      s    
*z,OlmoDynamicNTKScalingRotaryEmbedding.forwardrd   r/   r/   r:   r0   re      s   re   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr%   rM   rY   )r-   r'   r^   )ra   x1Zx2r/   r/   r0   rotate_half   s    rh   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezerh   )qkr_   r`   rb   Zunsqueeze_dimZq_embedZk_embedr/   r/   r0   apply_rotary_pos_emb   s
    

rl   c                       s$   e Zd Z fddZdd Z  ZS )OlmoMLPc                    sr   t    || _|j| _|j| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _	t
|j | _d S NFbias)r6   r7   configr3   Zintermediate_sizer   Linear	gate_projup_proj	down_projr	   Z
hidden_actact_fnr9   rq   r:   r/   r0   r7      s    
zOlmoMLP.__init__c                 C   s    |  | | || | S r5   )ru   rv   rs   rt   )r9   ra   r/   r/   r0   rA      s    zOlmoMLP.forward)rB   rC   rD   r7   rA   rH   r/   r/   r:   r0   rm      s   
rm   )r<   n_repr4   c                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r-   r+   r*   )r<   rx   batchnum_key_value_headsslenhead_dimr/   r/   r0   	repeat_kv   s
    0r}   c                       s   e Zd ZdZdeee d fddZdd Zde	j
ee	j
 ee	j ee eeee	j ee	j
ee	j
 eee	j
  f d	d
dZ  ZS )OlmoAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrq   	layer_idxc                    s0  t    || _|| _|d kr4td| jj d |j| _|j	| _	|j
| _| j	| j | _|j| _| j| j | _|j| _|j| _d| _| j| j | j	krtd| j	 d| j dtj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j	|jd| _|   d S )Nz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.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).ro   )r6   r7   rq   r   loggerwarning_oncer;   rB   attention_dropoutr3   Znum_attention_heads	num_headsr|   rz   num_key_value_groupsrR   
rope_theta	is_causal
ValueErrorr   rr   Zattention_biasq_projk_projv_projo_proj
_init_roper9   rq   r   r:   r/   r0   r7     s2    
zOlmoAttention.__init__c                 C   s   | j jd kr$t| j| j| jd| _nj| j jd }| j jd }|dkr^t| j| j|| jd| _n0|dkrt| j| j|| jd| _nt	d| d S )N)rR   rS   rZ   ZfactorZlinear)rR   rQ   rS   ZdynamiczUnknown RoPE scaling type )
rq   Zrope_scalingrI   r|   rR   r   
rotary_embrc   re   r   )r9   Zscaling_typerQ   r/   r/   r0   r   )  s.    


zOlmoAttention._init_ropeFr<   r   rb   past_key_valueoutput_attentions	use_cacher!   r4   c                 K   sL  |  \}	}
}| |}| |}| |}| jjd k	r|j| jj | jjd |j| jj | jjd |j| jj | jjd ||	|
| j| j	
dd}||	|
| j| j	
dd}||	|
| j| j	
dd}| ||\}}t||||\}}|d k	r"|||d}|||| j|\}}t|| j}t|| j}t||
ddt| j	 }|d k	r|d d d d d d d |jd f }|| }tjj|dtjd|j}tjj|| j| jd	}t||}|  |	| j|
| j	fkrt d
|	| j|
| j	f d|   |
dd! }|"|	|
| j#}| $|}|sBd }|||fS )Nminrf   r   rM   r`   r_   r!   r   r%   )r&   r   )ptrainingz `attn_output` should be of size z	, but is )%sizer   r   r   rq   clip_qkvclamp_viewr   r|   r]   rz   r   rl   updater   r}   r   r'   matmulmathsqrtr-   r   
functionalZsoftmaxr@   r?   r   dropoutr   r   r   
contiguousr*   r3   r   )r9   r<   r   rb   r   r   r   r!   kwargsbszq_len_query_states
key_statesvalue_statesr_   r`   cache_kwargsattn_weightsr.   attn_outputr/   r/   r0   rA   D  sF    



 
&
zOlmoAttention.forward)N)NNNFFN)rB   rC   rD   rE   r   r   rF   r7   r   r'   rG   
LongTensorr
   boolr   rA   rH   r/   r/   r:   r0   r~     s&   !      r~   c                       sr   e Zd ZdZ fddZd	ejeej eej ee	 e
e
eej eejeej eeej  f dddZ  ZS )
OlmoFlashAttention2aD  
    OLMo flash attention module. This module inherits from `OlmoAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|| t  | _d S r5   )r6   r7   r   _flash_attn_uses_top_left_mask)r9   argsr   r:   r/   r0   r7     s    zOlmoFlashAttention2.__init__NFr   c                 K   s$  d}|  \}	}
}| |}| |}| |}| jjd k	r|j| jj | jjd |j| jj | jjd |j| jj | jjd ||	|
| j| j	
dd}||	|
| j| j	
dd}||	|
| j| j	
dd}| ||\}}t||||\}}|d k	r&|||d}|||| j|\}}|
dd}|
dd}|
dd}| jrX| jnd}|j}|tjkrt rt }n"t| jdr| jj}n
| jjj}td| d	 ||}||}||}t|||||
||| j| jd
	}| |	|
| j!" }| #|}|sd }|||fS )NFr   r   rM   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)rb   r   Zuse_top_left_maskr   )$r   r   r   r   rq   r   r   r   r   r|   r]   rz   r   rl   r   r   r   r   r   r'   r@   Zis_autocast_enabledZget_autocast_gpu_dtypehasattrr   weightr   r   r?   r   r   r   r*   r3   r   r   )r9   r<   r   rb   r   r   r   r!   r   r   r   r   r   r   r   r_   r`   r   Zdropout_rateZinput_dtypeZtarget_dtyper   r   r/   r/   r0   rA     sd    












zOlmoFlashAttention2.forward)NNNFFN)rB   rC   rD   rE   r7   r'   rG   r   r   r
   r   r   rA   rH   r/   r/   r:   r0   r     s$         r   c                       sj   e Zd ZdZdejeej eej ee e	e	eej e
ejeej ee
ej  f d fddZ  ZS )OlmoSdpaAttentionz
    OLMo attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `OlmoAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr   c              	      s>  |r(t d t j|||||||dS | \}}	}
| |}| |}| |}| jj	d k	r|j
| jj	 | jj	d |j
| jj	 | jj	d |j
| jj	 | jj	d |||	| j| jdd}|||	| j| jdd}|||	| j| jdd}| ||\}}t||||\}}|d k	rJ|||d}|||| j|\}}t|| j}t|| j}|}|d k	r|d d d d d d d |jd f }|jjdkr|d k	r| }| }| }|d kr|	dkrd	nd
}tjjj||||| jr | jnd|d}|dd }|||	| j }| !|}|d |fS )Na  OlmoModel is using OlmoSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r<   r   rb   r   r   r   r!   r   r   rM   r   r   cudaTFr   )Z	attn_maskZ	dropout_pr   )"r   r   r6   rA   r   r   r   r   rq   r   r   r   r   r|   r]   rz   r   rl   r   r   r}   r   r-   r   rZ   r   r'   r   r   Zscaled_dot_product_attentionr   r   r3   r   )r9   r<   r   rb   r   r   r   r!   r   r   r   r   r   r   r_   r`   r   r.   r   r   r:   r/   r0   rA     sf    






&	
zOlmoSdpaAttention.forward)NNNFFN)rB   rC   rD   rE   r'   rG   r   r   r
   r   r   rA   rH   r/   r/   r:   r0   r     s"   
      r   )eagerflash_attention_2sdpac                       s|   e Zd Zeed fddZd	ejeej eej	 ee
 ee ee eej	 eejeeejejf  f dddZ  ZS )
OlmoDecoderLayerr   c                    sL   t    |j| _t|j ||d| _t|| _t|j| _	t|j| _
d S )Nr   )r6   r7   r3   OLMO_ATTENTION_CLASSES_attn_implementation	self_attnrm   mlpr2   input_layernormpost_attention_layernormr   r:   r/   r0   r7   Y  s    

zOlmoDecoderLayer.__init__NFr   c              
   K   s   |}	|  |}| jf |||||||d|\}}
}|	| }|}	| |}| |}|	| }|f}|rp||
f7 }|r~||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            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`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r   )r   r   r   r   )r9   r<   r   rb   r   r   r   r!   r   ZresidualZself_attn_weightsZpresent_key_valueoutputsr/   r/   r0   rA   e  s0    





zOlmoDecoderLayer.forward)NNNFFN)rB   rC   rD   r   rF   r7   r'   rG   r   r   r
   r   r   FloatTensorrA   rH   r/   r/   r:   r0   r   X  s"         r   aI  
    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, pruning heads
    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 ([`OlmoConfig`]):
            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.
zRThe bare Olmo Model outputting raw hidden-states without any specific head on top.c                   @   s@   e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdd ZdS )OlmoPreTrainedModelmodelTr   past_key_valuesc                 C   s|   | j j}t|tjr>|jjjd|d |jd k	rx|jj	  n:t|tj
rx|jjjd|d |jd k	rx|jj|j 	  d S )Nr   )Zmeanstd)rq   Zinitializer_ranger[   r   rr   r   dataZnormal_rp   Zzero_	Embeddingpadding_idx)r9   moduler   r/   r/   r0   _init_weights  s    

z!OlmoPreTrainedModel._init_weightsN)rB   rC   rD   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_quantized_cacheZ_supports_static_cacher   r/   r/   r/   r0   r     s   r   a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` 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)

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

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        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.
        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 [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                       s   e Zd ZdZed fddZdd Zdd Zee	de
jee
j ee
j eeeee
j f  ee
j ee ee ee ee ee
j eeef d
ddZe
je
je
jeedddZ  ZS )	OlmoModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OlmoDecoderLayer`]

    Args:
        config: OlmoConfig
    rq   c                    sp   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j| _d| _|   d S )Nc                    s   g | ]}t  |qS r/   )r   ).0r   r   r/   r0   
<listcomp>0  s     z&OlmoModel.__init__.<locals>.<listcomp>F)r6   r7   Zpad_token_idr   
vocab_sizer   r   r3   embed_tokensZ
ModuleListrangeZnum_hidden_layerslayersr2   normgradient_checkpointing	post_initrw   r:   r   r0   r7   )  s    zOlmoModel.__init__c                 C   s   | j S r5   r   r9   r/   r/   r0   get_input_embeddings8  s    zOlmoModel.get_input_embeddingsc                 C   s
   || _ d S r5   r   r9   valuer/   r/   r0   set_input_embeddings;  s    zOlmoModel.set_input_embeddingsN)	input_idsr   rb   r   inputs_embedsr   r   output_hidden_statesreturn_dictr!   r4   c                 C   sF  |d k	r|n| j j}|d k	r |n| j j}|d k	r4|n| j j}|	d k	rH|	n| j j}	|d k|d k	A rhtd| jr| jr|rt	d d}|d kr| 
|}d}|rt|ts| jsd}t|}t	d |
d kr|d k	r| nd}tj|||jd  |jd}
|d kr|
d}| |||
||}|}|r6d	nd }|rDd	nd }d }| jD ]}|rf||f7 }| jr| jr| |j|||||||
}n||||||||
d
}|d }|r||rdnd }|rR||d f7 }qR| |}|r||f7 }|r|nd }|r| }|	s6tdd ||||fD S t||||dS )NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FTzWe detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)r   r   r$   r/   )r   rb   r   r   r   r!   rM   c                 s   s   | ]}|d k	r|V  qd S r5   r/   )r   vr/   r/   r0   	<genexpr>  s      z$OlmoModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   r<   
attentions)rq   r   r   r   use_return_dictr   r   r   r   r   r   r[   r
   r   Zfrom_legacy_cacheget_seq_lengthr'   r)   r-   r   ri   _update_causal_maskr   Z_gradient_checkpointing_func__call__r   Zto_legacy_cachetupler   )r9   r   r   rb   r   r   r   r   r   r   r!   Zreturn_legacy_cachepast_seen_tokensr.   r<   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheZdecoder_layerZlayer_outputsZ
next_cacher/   r/   r0   rA   >  s    


  

    




zOlmoModel.forward)r   input_tensorr!   r   r   c              
   C   s  | j jdkr$|d k	r d|kr |S d S |d k	r4| nd}t|t}| j jdkrn|sn|sntj|||| jdrnd S |j|j	 }}	t
|j}
|jd }|r| }n"t|t
jr|jd n
|| d }t|||||	|
||jd d}| j jdkr|d k	r|j	jd	kr|st||
}|S )
Nr   r   r   r   )r   Zpast_key_values_lengthZis_trainingr   r%   r   r   r   r   r    r!   r"   r   )rq   r   r   r[   r   r   Z_ignore_causal_mask_sdpar   r   r   r'   finfor   r-   get_max_lengthrG   r1   rZ   Z_unmask_unattended)r9   r   r   r!   r   r   r   Zusing_static_cacher   r   r    r   r   r.   r/   r/   r0   r     sV    






	zOlmoModel._update_causal_mask)
NNNNNNNNNN)rB   rC   rD   rE   r   r7   r   r   r   OLMO_INPUTS_DOCSTRINGr'   r   r   rG   r   r
   r   r   r   r   r   rA   r   rH   r/   r/   r:   r0   r     sD             
yr   c                       s   e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
eeeeeddejeej eej eeej  eej eej ee ee ee ee eej eeef dddZdddZ  ZS )OlmoForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S rn   )
r6   r7   r   r   r   r   rr   r3   lm_headr   rw   r:   r/   r0   r7     s
    
zOlmoForCausalLM.__init__c                 C   s   | j jS r5   r   r   r   r/   r/   r0   r     s    z$OlmoForCausalLM.get_input_embeddingsc                 C   s   || j _d S r5   r   r   r/   r/   r0   r     s    z$OlmoForCausalLM.set_input_embeddingsc                 C   s   | j S r5   r   r   r/   r/   r0   get_output_embeddings  s    z%OlmoForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r5   r   )r9   Znew_embeddingsr/   r/   r0   set_output_embeddings  s    z%OlmoForCausalLM.set_output_embeddingsc                 C   s
   || _ d S r5   r   )r9   decoderr/   r/   r0   set_decoder  s    zOlmoForCausalLM.set_decoderc                 C   s   | j S r5   r   r   r/   r/   r0   get_decoder  s    zOlmoForCausalLM.get_decoder)output_typer   N)r   r   rb   r   r   labelsr   r   r   r   r!   r4   c                 C   s,  |dk	r|n| j j}|	dk	r |	n| j j}	|
dk	r4|
n| j j}
| j||||||||	|
|d
}|d }| |}| }d}|dk	r|dddddf  }|dddf  }t }|	d| j j
}|	d}||j}|||}|
s|f|dd  }|dk	r|f| S |S t|||j|j|jdS )u  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, OlmoForCausalLM

        >>> model = OlmoForCausalLM.from_pretrained("allenai/OLMo-1B-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-1B-hf")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
        ```
        N)
r   r   rb   r   r   r   r   r   r   r!   r   .r%   r   )losslogitsr   r<   r   )rq   r   r   r   r   r   rU   r   r   r   r   r?   r   r   r   r<   r   )r9   r   r   rb   r   r   r   r   r   r   r   r!   r   r<   r  r  Zshift_logitsZshift_labelsZloss_fctoutputr/   r/   r0   rA     sL    +


zOlmoForCausalLM.forwardTc              
   K   sh  |d k	rR|d k	r.|d d |j d  d f }n$|j d |j d krR|d d |f }|d k	r|d kr| dd }||dkd |r|d d |j d  d f }|jtjd}|d k	r|d dkrd|i}	nd|i}	t|trN|j	dkrN|d k	r|j \}
}|j
}n|j \}
}|j
}| jjj}t|j}t||| |||||
d}|	|||||d	 |	S )
Nr   r   r%   )Zmemory_formatr   r   rM   r   )rb   r!   r   r   r   )r-   longZcumsumZmasked_fill_r,   r'   Zcontiguous_formatr[   r   ndimr   r   r   r   r   r   r1   r   r   )r9   r   r   r   r   r!   rb   r   r   Zmodel_inputsr"   r   r   r   r    r/   r/   r0   prepare_inputs_for_generation{  sR    




	z-OlmoForCausalLM.prepare_inputs_for_generation)NNNNNNNNNNN)NNNNNT)rB   rC   rD   Z_tied_weights_keysr7   r   r   r   r   r   r   r   r   r   r   _CONFIG_FOR_DOCr'   r   r   rG   r   r   r   r   r   rA   r  rH   r/   r/   r:   r0   r     sT   	
           
\      r   )Nr   )GrE   r   typingr   r   r   r   r'   Ztorch.nn.functionalr   r   r>   Ztorch.utils.checkpointZtorch.nnr   Zactivationsr	   Zcache_utilsr
   r   r   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   r   Zmodeling_utilsr   Zpytorch_utilsr   utilsr   r   r   r   r   r   Zconfiguration_olmor   Zmodeling_flash_attention_utilsr   Z
get_loggerrB   r   r  rG   rF   r   r   rU   r1   Moduler2   appendrI   rc   re   rh   rl   rm   r}   r~   r   r   r   r   ZOLMO_START_DOCSTRINGr   r   r   r   r/   r/   r/   r0   <module>   sx    
5

 n^MJ a