a
    h                     @   s4  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	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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)selfr   	__class__ a/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/olmo/modular_olmo.pyr      s    
zOlmoLayerNorm.__init__)hidden_statesr   c                 C   s,   |j }tj|jtjd| jd d dd|S )N)dtypegh㈵>)eps)r    FZ
layer_normtotorchZfloat32r   )r   r   Z
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)Zbias)	r   r   nnZLinearr   Zintermediate_sizeZ	gate_projZup_projZ	down_projr   configr   r   r   r   +   s    zOlmoMLP.__init__)r&   r'   r(   r   r,   r   r   r   r   r-   *   s   r-   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    Z	unsqueezer   r#   )
qkcossinposition_idsZunsqueeze_dimZq_typeZk_typeZq_embedZk_embedr   r   r   apply_rotary_pos_emb2   s    

r6   c                   @   sb   e Zd Zeddddd	ejeejejf eej ee eej	 eejeej f dddZ
dS )
OlmoAttentionZpast_key_valuepast_key_valuesz4.58)new_nameversionN)r   position_embeddingsattention_maskr8   cache_positionr   c                 K   s  |j d d }g |d| jR }| |}	| |}
| |}| jjd ur|	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r.t| jj }|| |	|
||f| jsHdn| j| jd|\}}|jg |dR   }| |}||fS )	N)minmaxr   r	   )r4   r3   r=   eagerg        )Zdropoutscaling)shapeZhead_dimZq_projZk_projZv_projr0   Zclip_qkvZclamp_view	transposer6   update	layer_idxr   Z_attn_implementationr   ZtrainingZattention_dropoutrB   Zreshape
contiguousZo_proj)r   r   r;   r<   r8   r=   kwargsZinput_shapeZhidden_shapeZquery_statesZ
key_statesZvalue_statesr3   r4   Zcache_kwargsZattention_interfaceZattn_outputZattn_weightsr   r   r   r%   O   sF    






zOlmoAttention.forward)NN)r&   r'   r(   r   r$   r+   tupler   r   Z
LongTensorr%   r   r   r   r   r7   N   s     r7   c                       s$   e Zd Zeed fddZ  ZS )OlmoDecoderLayerr0   rG   c                    s8   t  || t|j| _t|j| _t||d| _d S )NrL   )r   r   r   r   Zinput_layernormZpost_attention_layernormr7   Z	self_attn)r   r0   rG   r   r   r   r      s    zOlmoDecoderLayer.__init__)r&   r'   r(   r   r*   r   r,   r   r   r   r   rK      s   rK   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rl|jjdkrl|jjnd}t	j
|dd^ | |  dd}t	j||fdd	}| | j }| | j }	||	fW  d    S 1 s0    Y  d S )
Nr   r>   r   ZmpscpuF)device_typeZenabledr	   )dim)Zinv_freqfloatexpandrC   r#   Zdevice
isinstancetypestrr$   ZautocastrE   catr3   Zattention_scalingr4   )
r   xr5   Zinv_freq_expandedZposition_ids_expandedrO   ZfreqsZembr3   r4   r   r   r   r%      s    0&zOlmoRotaryEmbedding.forwardN)r&   r'   r(   r%   r   r   r   r   rM      s   rM   c                       s"   e Zd Zed fddZ  ZS )	OlmoModelr0   c                    s<   t    t fddt jD | _t j| _	d S )Nc                    s   g | ]}t  |qS r   )rK   ).0rG   rY   r   r   
<listcomp>       z&OlmoModel.__init__.<locals>.<listcomp>)
r   r   r.   Z
ModuleListrangeZnum_hidden_layersZlayersr   r   Znormr/   r   rY   r   r      s
    zOlmoModel.__init__)r&   r'   r(   r   r   r,   r   r   r   r   rX      s   rX   c                   @   s   e Zd ZdS )OlmoForCausalLMN)r&   r'   r(   r   r   r   r   r^      s   r^   )r^   rX   ZOlmoPreTrainedModel)Nr   )*typingr   r   r$   Ztorch.nnr.   Ztorch.nn.functionalZ
functionalr"   Ztorch.utils.checkpointZcache_utilsr   Zmodeling_utilsr   utilsr   Zutils.deprecationr   Zllama.modeling_llamar
   r   r   r   r   r   r   r   Zconfiguration_olmor   Z
get_loggerr&   loggerModuler   r-   r6   r7   rK   rM   rX   r^   __all__r   r   r   r   <module>   s(   (


7
	