U
    dip                     @   s  d dl Z d dlmZmZ ddlmZ ddlmZmZ e	e
Ze rLd dlZd(ee ed ee edef dd	d
Zd)ee ed ee edef dddZd*ee ed ee edef dddZd+edee edef dddZd,edee edef dddZd-edee edef dddZeeeeeedZd.eeeee ee dddZd/eee dddZd0eee dddZd1eee dddZd2eee dd d!Zd3eee dd"d#Zd4eee dd$d%ZeeeeeedZd5eee dd&d'Z dS )6    N)OptionalTuple   )PretrainedConfig)is_torch_availableloggingztorch.deviceztorch.Tensor)configdeviceseq_lenreturnc           
      K   s   | dk	r(t |dkr(td| d|  t |dkrF|d }|d }nB| dk	r| j}t| drd| jnd}t| d	| j| j }t|| }d}d|t	j
d|d
t	jd ||   }	|	|fS )a  
    Computes the inverse frequencies according to the original RoPE implementation
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length. Unused for this type of RoPE.
        rope_kwargs (`Dict`, *optional*):
            BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
    Returns:
        Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
        post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
    Nr   zUnexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in `_compute_default_rope_parameters`, got `rope_kwargs`= and `config`=basedimpartial_rotary_factor      ?head_dim   dtype)len
ValueError
rope_thetahasattrr   getattrhidden_sizenum_attention_headsinttorcharangeint64floatto)
r   r	   r
   rope_kwargsr   r   r   r   attention_factorinv_freq r%   D/tmp/pip-unpacked-wheel-bm_b0l5e/transformers/modeling_rope_utils.py _compute_default_rope_parameters   s    
*r'   c                 K   st   | dk	r(t |dkr(td| d|  t |dkr>|d }n| dk	rP| jd }t| ||f|\}}|| }||fS )a  
    Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length. Unused for this type of RoPE.
        rope_kwargs (`Dict`, *optional*):
            BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
    Returns:
        Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
        post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
    Nr   zUnexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in `_compute_linear_scaling_rope_parameters`, got `rope_kwargs`=r   factor)r   r   rope_scalingr'   )r   r	   r
   r"   r(   r$   r#   r%   r%   r&   '_compute_linear_scaling_rope_parametersG   s    

r*   c                 K   s  | dk	r(t |dkr(td| d|  t |dkrV|d }|d }|d }|d }nR| dk	r| j}t| d	rt| jnd
}t| d| j| j }	t|	| }| j	}| j
d }d
}
|dk	r||kr|n|}||| | |d  ||d    }d
|tjd|dtjd ||   }||
fS )a4  
    Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length, used to update the dynamic RoPE at inference time.
        rope_kwargs (`Dict`, *optional*):
            BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
    Returns:
        Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
        post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
    Nr   zUnexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in `_compute_dynamic_ntk_parameters`, got `rope_kwargs`=r   r   r   max_position_embeddingsr(   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r+   r)   r   r   r   r    r!   )r   r	   r
   r"   r   r   r+   r(   r   r   r#   r$   r%   r%   r&   _compute_dynamic_ntk_parametersp   s*    

$*r,   c                    sH  t |dkrtd| | j}t| dr0| jnd}t| d| j| j }t|| }| j	}| j
d }	| j
d}
|
dkrd	t|	 d }
| j
d
pd}| j
dpd}dd   fdd}dd }|td|d ||  }d| }d|	|  }||||||\}}d||||d  | }|d|  ||  }||
fS )a  
    Computes the inverse frequencies with NTK scaling. Please refer to the
    [original paper](https://arxiv.org/abs/2309.00071)
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length. Unused for this type of RoPE.
        rope_kwargs (`Dict`, *optional*):
            BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
    Returns:
        Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
        post-processing scaling factor applied to the computed cos/sin.
    r   zYUnexpected arguments: `**rope_kwargs` should be unset in `_compute_yarn_parameters`, got r   r   r   r(   r#   Ng?	beta_fast    	beta_slowr   c                 S   s*   |t || d t j   dt |  S )zPInverse dimension formula to find the dimension based on the number of rotationsr   )mathlogpi)Znum_rotationsr   r   r+   r%   r%   r&   find_correction_dim   s    z5_compute_yarn_parameters.<locals>.find_correction_dimc                    s@   t  | |||}t  ||||}t|dt||d fS )z.Find dimension range bounds based on rotationsr   r   )r0   floorceilmaxmin)Zlow_rotZhigh_rotr   r   r+   lowhighr3   r%   r&   find_correction_range   s    z7_compute_yarn_parameters.<locals>.find_correction_rangec                 S   s>   | |kr|d7 }t j|t jd|  ||   }t |dd}|S )NgMbP?r   r   r   )r   r   float32clamp)r7   r6   r   Zlinear_funcZ	ramp_funcr%   r%   r&   linear_ramp_factor   s
    z4_compute_yarn_parameters.<locals>.linear_ramp_factorr   )r   r   r   r   r   r   r   r   r   r+   r)   getr0   r1   r   r   r    r!   )r   r	   r
   r"   r   r   r   r   r+   r(   r#   r-   r/   r;   r>   Z	pos_freqsZinv_freq_extrapolationZinv_freq_interpolationr8   r9   Zinv_freq_extrapolation_factorr$   r%   r:   r&   _compute_yarn_parameters   s8    

 
r@   c                 K   s^  t |dkrtd| | j}t| dr0| jnd}t| d| j| j }t|| }| j	d }| j	d }	| j	
d}
| j	
d	}t| d
r|r|| jk r| j}n| j}| j}|| }
n| j}||
 }|dkr|
dkrd}ntdt|
t|  }||krtj|tj|d}ntj|	tj|d}tjd|dtj|d | }d|||   }||fS )a  
    Computes the inverse frequencies with LongRoPE scaling. Please refer to the
    [original implementation](https://github.com/microsoft/LongRoPE)
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length.
        rope_kwargs (`Dict`, *optional*):
            BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
    Returns:
        Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
        post-processing scaling factor applied to the computed cos/sin.
    r   z]Unexpected arguments: `**rope_kwargs` should be unset in `_compute_longrope_parameters`, got r   r   r   long_factorshort_factorr(   r#    original_max_position_embeddingsNr   )r   r	   r   )r   r   r   r   r   r   r   r   r   r)   r?   rC   r+   r0   sqrtr1   r   Ztensorr<   r   r   r    )r   r	   r
   r"   r   r   r   r   rA   rB   r(   r#   Z expanded_max_position_embeddingsr+   Zext_factorsZinv_freq_shaper$   r%   r%   r&   _compute_longrope_parameters   s<    




rE   c                 K   s   t | ||f|\}}| jd }| jd }| jd }| jd }	|	| }
|	| }dtj | }t||
k|| |}|	| | ||  }d| | | ||  }||k  ||
k  }t|||}||fS )a  
    Computes the inverse frequencies for llama 3.1.

    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length. Unused for this type of RoPE.
        rope_kwargs (`Dict`, *optional*):
            BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.
    Returns:
        Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
        post-processing scaling factor applied to the computed cos/sin.
    r(   low_freq_factorhigh_freq_factorrC   r   r   )r'   r)   r0   r2   r   where)r   r	   r
   r"   r$   r#   r(   rF   rG   Zold_context_lenZlow_freq_wavelenZhigh_freq_wavelenZwavelenZinv_freq_llamaZsmooth_factorZsmoothed_inv_freqZis_medium_freqr%   r%   r&   _compute_llama3_parameters6  s    



rI   )defaultZlinearZdynamicZyarnZlongropeZllama3)	rope_typereceived_keysrequired_keysoptional_keysignore_keysc                 C   s   d|kr|dh8 }| d |dk	r,||8 }|| }|rLtd|  d| |dk	rb|| | }n|| }|rtd|  d|  dS )zYCompare the received keys in `config.rope_scaling` against the expected and optional keystyperK   Nz9Missing required keys in `rope_scaling` for 'rope_type'='z': z5Unrecognized keys in `rope_scaling` for 'rope_type'=')addKeyErrorloggerwarning)rK   rL   rM   rN   rO   Zmissing_keysZunused_keysr%   r%   r&   _check_received_keysn  s    	

rU   )r   rO   c                 C   s@   | j }|d|dd }dh}t| }t||||d d S )NrK   rP   rO   )r)   r?   setkeysrU   )r   rO   r)   rK   rM   rL   r%   r%   r&   !_validate_default_rope_parameters  s
    rY   c                 C   st   | j }|d|dd }ddh}t| }t||||d |d }|d ks`t|tr`|dk rptd|  d S )NrK   rP   r(   rV   r   8`rope_scaling`'s factor field must be a float >= 1, got 	r)   r?   rW   rX   rU   
isinstancer    rS   rT   )r   rO   r)   rK   rM   rL   r(   r%   r%   r&   (_validate_linear_scaling_rope_parameters  s    r]   c                 C   s|   | j }|d|dd }ddh}dh}t| }t|||||d |d }|d ksht|trh|dk rxtd|  d S )NrK   rP   r(   rC   rV   r   rZ   r[   )r   rO   r)   rK   rM   rN   rL   r(   r%   r%   r&   )_validate_dynamic_scaling_rope_parameters  s    r^   c                 C   s>  | j }|d|dd }ddh}dddh}t| }t|||||d |d }|d kslt|trl|dk r|td	|  |d}|d k	rt|tr|d
k rtd|  |d}	|	d k	rt|	tstd|	  |d}
|
d k	rt|
tstd|
  |	pd|
pdk r:td|	 d|
 d d S )NrK   rP   r(   r#   r-   r/   rV   r   rZ   r   L`rope_scaling`'s attention_factor field must be a float greater than 0, got z6`rope_scaling`'s beta_fast field must be a float, got z6`rope_scaling`'s beta_slow field must be a float, got r.   r   zO`rope_scaling`'s beta_fast field must be greater than beta_slow, got beta_fast=z( (defaults to 32 if None) and beta_slow=z (defaults to 1 if None)r[   )r   rO   r)   rK   rM   rN   rL   r(   r#   r-   r/   r%   r%   r&   _validate_yarn_parameters  s0    



r`   c                 C   s  | j }|d|dd }dddh}dddh}t| }t|||||d t| d	r\| jnd
}t| d| j| j	 }t
|| }	|d}
t|
tstdd |
D rtd|
  t|
|	d kstd|	d  dt|
  |d}t|tstdd |D rtd|  t||	d ksNtd|	d  dt|  t| drftd n|d}|d krtd n&t|tr|d
k rtd|  |d}|d k	rt|tr|dk rtd|  d S )NrK   rP   rB   rA   r#   r(   rC   rV   r   r   r   c                 s   s   | ]}t |ttfV  qd S Nr\   r   r    .0xr%   r%   r&   	<genexpr>  s     z0_validate_longrope_parameters.<locals>.<genexpr>zC`rope_scaling`'s short_factor field must be a list of numbers, got r   z5`rope_scaling`'s short_factor field must have length z, got c                 s   s   | ]}t |ttfV  qd S ra   rb   rc   r%   r%   r&   rf     s     zB`rope_scaling`'s long_factor field must be a list of numbers, got z4`rope_scaling`'s long_factor field must have length aY  This model has set a `original_max_position_embeddings` field, to be used together with `max_position_embeddings` to determine a scaling factor. Please set the `factor` field of `rope_scaling`with this ratio instead -- we recommend the use of this field over `original_max_position_embeddings`, as it is compatible with most model architectures.z1Missing required keys in `rope_scaling`: 'factor'rZ   g        r_   )r)   r?   rW   rX   rU   r   r   r   r   r   r   r\   listallrS   rT   r   Zwarning_oncer    )r   rO   r)   rK   rM   rN   rL   r   r   r   rB   rA   r(   r#   r%   r%   r&   _validate_longrope_parameters  sD    



 



ri   c           
      C   s>  | j }|d|dd }dddddh}t| }t||||d |d }|d ksft|trf|dk rvtd	|  |d }|d }|d kst|tstd
|  |d kst|tstd|  ||krtd| d|  |d }	|	d kst|	t	std|	  |	| j
kr:td|	 d| j
  d S )NrK   rP   r(   rC   rF   rG   rV   r   rZ   z<`rope_scaling`'s low_freq_factor field must be a float, got z=`rope_scaling`'s high_freq_factor field must be a float, got zc`rope_scaling`'s high_freq_factor field must be greater than low_freq_factor, got high_freq_factor=z and low_freq_factor=zP`rope_scaling`'s original_max_position_embeddings field must be an integer, got zg`rope_scaling`'s original_max_position_embeddings field must be less than max_position_embeddings, got z and max_position_embeddings=)r)   r?   rW   rX   rU   r\   r    rS   rT   r   r+   )
r   rO   r)   rK   rM   rL   r(   rF   rG   rC   r%   r%   r&   _validate_llama3_parameters  s6    rj   c                 C   sb   t | dd}|dkrdS |d|dd}t|}|dk	rL|| |d ntd| d dS )	zO
    Validate the RoPE config arguments, given a `PretrainedConfig` object
    r)   NrK   rP   rJ   rV   zTMissing validation function mapping in `ROPE_VALIDATION_FUNCTIONS` for 'rope_type'='')r   r?   ROPE_VALIDATION_FUNCTIONSrS   rT   )r   rO   r)   rK   Zvalidation_fnr%   r%   r&   rope_config_validation-  s    

rm   )NNN)NNN)NNN)N)N)N)NN)N)N)N)N)N)N)N)!r0   typingr   r   Zconfiguration_utilsr   utilsr   r   Z
get_logger__name__rS   r   r   r    r'   r*   r,   r@   rE   rI   ZROPE_INIT_FUNCTIONSstrrW   rU   rY   r]   r^   r`   ri   rj   rl   rm   r%   r%   r%   r&   <module>   s   
   
+   
*   
4   
P   
E   
/  2&
