o
    ei                     @   s4  d dl 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 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"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Z)dS )    )CallableN   )Cache)dynamic_rope_update)ALL_ATTENTION_FUNCTIONS)logging)maybe_autocast   )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__ c/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/olmo/modular_olmo.pyr   2   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   forward6   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                   @   s    e Zd Ze e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	|dd. | |  
dd}tj||fdd	}| | j }| | j }	W d    ||	fS 1 sow   Y  ||	fS )
Nr   r   mpscpuF)device_typeenabledr	   )dim)inv_freqfloatexpandshaper$   device
isinstancetypestrr   	transposer%   catcosattention_scalingsin)
r   xposition_idsinv_freq_expandedposition_ids_expandedr>   freqsembrK   rM   r   r   r   r(   H   s   0&
zOlmoRotaryEmbedding.forwardN)r)   r*   r+   r%   no_gradr   r(   r   r   r   r   r:   G   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.
        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krK   rM   unsqueeze_dimq_typek_typeq_embedk_embedr   r   r   apply_rotary_pos_embW   s   

r]   c                   @   sb   e Zd Z		d
dejdeejejf dejdB dedB dejdB deejejdB f fdd	ZdS )OlmoAttentionNr   position_embeddingsattention_maskpast_key_valuescache_positionr   c                 K   sx  |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t}|| |	|
||f| jsdn| j| jd|\}}|jg |dR   }| |}||fS )Nr;   )minmaxr   r	   )rM   rK   rb   g        )dropoutscaling)rD   head_dimq_projk_projv_projr9   clip_qkvclamp_viewrI   r]   update	layer_idxr   get_interface_attn_implementationr   trainingattention_dropoutrf   reshape
contiguouso_proj)r   r   r_   r`   ra   rb   kwargsinput_shapehidden_shapequery_states
key_statesvalue_statesrK   rM   cache_kwargsattention_interfaceattn_outputattn_weightsr   r   r   r(   r   sF   	




zOlmoAttention.forward)NN)	r)   r*   r+   r%   r.   tupler   
LongTensorr(   r   r   r   r   r^   q   s     r^   c                       s&   e Zd Zdedef fddZ  ZS )OlmoDecoderLayerr9   ro   c                    s8   t  || t|j| _t|j| _t||d| _d S )N)r9   ro   )r   r   r   r   input_layernormpost_attention_layernormr^   	self_attn)r   r9   ro   r   r   r   r      s   zOlmoDecoderLayer.__init__)r)   r*   r+   r   r-   r   r/   r   r   r   r   r      s    r   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   )r   ).0ro   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)r   )*collections.abcr   r%   torch.nnr2   torch.nn.functional
functionalr"   cache_utilsr   modeling_rope_utilsr   modeling_utilsr   utilsr   utils.genericr   llama.modeling_llamar
   r   r   r   r   r   r   r   configuration_olmor   
get_loggerr)   loggerModuler   r0   r:   r]   r^   r   r   r   __all__r   r   r   r   <module>   s*   (



6	