o
    i                     @   s,  d dl mZmZ d dlZd dlmZ d dlm  mZ ddl	m
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mZmZmZmZmZ d
dlmZ eeZG dd dejZ G dd deZ!dddZ"G dd deZ#G dd deZ$G dd deZ%G dd deZ&G dd deZ'g dZ(dS )    )CallableOptionalN   )Cache)ALL_ATTENTION_FUNCTIONS)logging)deprecate_kwarg   )LlamaAttentionLlamaDecoderLayerLlamaForCausalLMLlamaMLP
LlamaModelLlamaRotaryEmbeddingeager_attention_forwardrotate_half   )
OlmoConfigc                       s@   e Zd ZdZdeddf fddZdejdejfdd	Z  Z	S )
OlmoLayerNormz/LayerNorm but with no learnable weight or bias.hidden_sizereturnNc                    s   t    |f| _d S )N)super__init__normalized_shape)selfr   	__class__ Y/home/ubuntu/.local/lib/python3.10/site-packages/transformers/models/olmo/modular_olmo.pyr      s   
zOlmoLayerNorm.__init__hidden_statesc                 C   s,   |j }tj|jtjd| jd d dd|S )N)dtypegh㈵>)eps)r    F
layer_normtotorchfloat32r   )r   r   
orig_dtyper   r   r   forward"   s    zOlmoLayerNorm.forward)
__name__
__module____qualname____doc__intr   r%   Tensorr(   __classcell__r   r   r   r   r      s    r   c                       s   e Zd Z fddZ  ZS )OlmoMLPc                    sR   t  | tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _d S )NF)bias)	r   r   nnLinearr   intermediate_size	gate_projup_proj	down_projr   configr   r   r   r   *   s   zOlmoMLP.__init__)r)   r*   r+   r   r/   r   r   r   r   r0   )   s    r0   c           
      C   s^   | j |j }}||}||}| | 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.
    )r    	unsqueezer   r$   )
qkcossinposition_idsunsqueeze_dimq_typek_typeq_embedk_embedr   r   r   apply_rotary_pos_emb1   s   

rE   c                   @   sp   e Zd Zedddd		ddejdeejejf deej dee d	eej	 d
eejeej f fddZ
dS )OlmoAttentionpast_key_valuepast_key_valuesz4.58)new_nameversionNr   position_embeddingsattention_maskcache_positionr   c                 K   s  |j d d }g |d| jR }| |}	| |}
| |}| jjd urJ|	j| jj | jjd |
j| jj | jjd |j| jj | jjd |	|	dd}	|
|	dd}
||	dd}|\}}t
|	|
||\}	}
|d ur|||d}||
|| j|\}
}t}| jjdkrt| jj }|| |	|
||f| jsdn| j| jd|\}}|jg |dR   }| |}||fS )	N)minmaxr   r	   )r>   r=   rM   eagerg        )dropoutscaling)shapehead_dimq_projk_projv_projr9   clip_qkvclamp_view	transposerE   update	layer_idxr   _attn_implementationr   trainingattention_dropoutrS   reshape
contiguouso_proj)r   r   rK   rL   rH   rM   kwargsinput_shapehidden_shapequery_states
key_statesvalue_statesr=   r>   cache_kwargsattention_interfaceattn_outputattn_weightsr   r   r   r(   N   sF   





zOlmoAttention.forward)NN)r)   r*   r+   r   r%   r.   tupler   r   
LongTensorr(   r   r   r   r   rF   M   s"    rF   c                       s&   e Zd Zdedef fddZ  ZS )OlmoDecoderLayerr9   r^   c                    s8   t  || t|j| _t|j| _t||d| _d S )N)r9   r^   )r   r   r   r   input_layernormpost_attention_layernormrF   	self_attn)r   r9   r^   r   r   r   r      s   zOlmoDecoderLayer.__init__)r)   r*   r+   r   r-   r   r/   r   r   r   r   rq      s    rq   c                   @   s   e Zd Zdd ZdS )OlmoRotaryEmbeddingc           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd/ | |  dd}t	j||fdd	}| | j }| | j }	||	fW  d    S 1 sqw   Y  d S )
Nr   rN   r   mpscpuF)device_typeenabledr	   )dim)inv_freqfloatexpandrT   r$   device
isinstancetypestrr%   autocastr\   catr=   attention_scalingr>   )
r   xr?   inv_freq_expandedposition_ids_expandedrx   freqsembr=   r>   r   r   r   r(      s   0&$zOlmoRotaryEmbedding.forwardN)r)   r*   r+   r(   r   r   r   r   ru      s    ru   c                       s"   e Zd Zdef fddZ  ZS )	OlmoModelr9   c                    s<   t    t fddt jD | _t j| _	d S )Nc                    s   g | ]}t  |qS r   )rq   ).0r^   r9   r   r   
<listcomp>   s    z&OlmoModel.__init__.<locals>.<listcomp>)
r   r   r2   
ModuleListrangenum_hidden_layerslayersr   r   normr8   r   r   r   r      s
   zOlmoModel.__init__)r)   r*   r+   r   r   r/   r   r   r   r   r      s    r   c                   @   s   e Zd ZdS )OlmoForCausalLMN)r)   r*   r+   r   r   r   r   r      s    r   )r   r   OlmoPreTrainedModel)Nr   ))typingr   r   r%   torch.nnr2   torch.nn.functional
functionalr"   cache_utilsr   modeling_utilsr   utilsr   utils.deprecationr   llama.modeling_llamar
   r   r   r   r   r   r   r   configuration_olmor   
get_loggerr)   loggerModuler   r0   rE   rF   rq   ru   r   r   __all__r   r   r   r   <module>   s(    (


7
	