
    GJje                     r    d dl Z d dlmZ d dlmZ d dlmZ  G d de      Z G d de      Z	 G d d	e      Z
y)
    N)Optional)Modulec            	       P     e Zd ZdZ	 	 	 d
dedededef fdZd Zddefd	Z	 xZ
S )RoPEa  Implements the rotary positional encoding.

    The traditional implementation rotates consecutive pairs of elements in the
    feature dimension while the default implementation rotates pairs with
    stride half the feature dimensions for efficiency.

    For more details see `RoFormer: Enhanced Transformer with Rotary Position
    Embedding <https://arxiv.org/abs/2104.09864>`_.

    Args:
        dims (int): The feature dimensions to be rotated. If the input feature
            is larger than dims then the rest is left unchanged.
        traditional (bool, optional): If set to ``True`` choose the traditional
            implementation which is slightly less efficient. Default: ``False``.
        base (float, optional): The base used to compute angular frequency for
            each dimension in the positional encodings. Default: ``10000``.
        scale (float, optional): The scale used to scale the positions. Default: ``1.0``.
    dimstraditionalbasescalec                 Z    t         |           || _        || _        || _        || _        y )N)super__init__r   r   r	   r
   )selfr   r   r	   r
   	__class__s        k/Users/ahmed/devFolder/claude-voice/.venv/lib/python3.12/site-packages/mlx/nn/layers/positional_encoding.pyr   zRoPE.__init__   s-     		&	
    c                 8    | j                    d| j                   S )Nz, traditional=)r   r   )r   s    r   _extra_reprzRoPE._extra_repr+   s    ))N4+;+;*<==r   offsetc                     t         j                  j                  || j                  | j                  | j
                  | j                  |      S )N)r   r	   r
   r   )mxfastroper   r   r	   r
   )r   xr   s      r   __call__zRoPE.__call__.   s@    ww||II((**  
 	
r   )Fi'  g      ?)r   )__name__
__module____qualname____doc__intboolfloatr   r   r   __classcell__r   s   @r   r   r   
   sO    , "  	
 >
# 
r   r   c                   T     e Zd ZdZ	 	 	 	 	 d
dedededee   dedef fdZd	 Z	 xZ
S )SinusoidalPositionalEncodinga0  Implements sinusoidal positional encoding.

    For more details see the paper `Attention Is All You Need
    <https://arxiv.org/abs/1706.03762>`_.

    Args:
        dims (int): The dimensionality of the resulting positional embeddings.
        min_freq (float, optional): The minimum frequency expected. Default:
            ``0.0001``.
        max_freq (float, optional): The maximum frequency expected. Default:
            ``1``.
        scale (float, optional): A multiplicative scale for the embeddings.
            Default: ``sqrt(2/dims)``.
        cos_first (bool, optional): If ``True`` embed using ``[cos(x); sin(x)]``
            instead of the reverse. Default: ``False``.
        full_turns (bool, optional): If ``True`` multiply the frequencies with
            :math:`2\pi`. Default: ``False``.
    r   min_freqmax_freqr
   	cos_first
full_turnsc                    t         |           dt        j                  d|dz        |dz  dz
  z  z
  }t	        j
                  |      }t	        j
                  |      }t        j                  |||z
  z  |z         | _        |r%| j                  dt        j                  z  z  | _        |xs d|z  dz  | _	        || _
        y )N   r      g      ?)r   r   r   arangemathlogexp_sigmaspir
   r(   )	r   r   r&   r'   r
   r(   r)   one_zeror   s	           r   r   z%SinusoidalPositionalEncoding.__init__M   s     	ryyDAI.$!)a-@@88H%88H% vvh(X*=>IJ<<1tww;7DL /q4xC/
"r   c                 8   |d   | j                   z  }t        j                  |      }t        j                  |      }| j                  rt        j
                  ||gd      }nt        j
                  ||gd      }| j                  dk7  r|| j                  z  }|S )N).Naxisr+   )r1   r   cossinr(   concatenater
   )r   r   ycosysinys        r   r   z%SinusoidalPositionalEncoding.__call__e   sz    iL4<<'vvayvvay>>d|"5Ad|"5A::?DJJAr   )g-C6?r+   NFF)r   r   r   r   r   r!   r   r    r   r   r"   r#   s   @r   r%   r%   9   sa    , !!% ## # 	#
 # # #0r   r%   c            
       ^    e Zd Zeej
                  fdedededefd       Zed        Zd	dZ	y)
ALiBiq_sequence_lengthk_sequence_length	num_headsr   c           	      ,   t        j                  ||       }t        j                  d|      }t        j                  t        j                  |d d d f   |d d d f   z
  d             }t        j                  ||      }||z  j                  |      }	|	S )Nr   )r   r+   r6   )rB   dtype)r   r-   absexpand_dimsr?   create_alibi_slopeastype)
r@   rA   rB   r   rD   x1x2distance_matrixalibi_slope
alibi_masks
             r   create_alibi_matrixzALiBi.create_alibi_matrixv   s     YYv01YYq+,66NN2ag;D!G46B
 
 ..%.P%3;;EB
r   c                     dt         ffd |       }t        j                  ||      }t        j                  |d      S )Nnc                 h   t        j                  |       j                         r?ddt        j                  |       dz
   z   z  }t        |       D cg c]
  }|||z  z   c}S dt        j                  t        j                  |             z  } |       d|z        dd d   d | |z
   z   S c c}w )Nr,      r   )r.   log2
is_integerrangefloor)rP   starticlosest_power_of_2
get_slopess       r   rZ   z,ALiBi.create_alibi_slope.<locals>.get_slopes   s    yy|&&(tyy|a'7%8 89:27(;(Qq((;;%&$**TYYq\*B%B"12 %7!78A>?WEWAWXY <s   B/)rD   )r5   r6   )r   r   arrayrF   )rB   rD   slopesoutrZ   s       @r   rG   zALiBi.create_alibi_slope   s<    		# 		 I&hhvU+~~c11r   Nc                     t         j                  |j                  d   |z   |j                  d   |j                  d   ||j                        }|||z   }||z   S )Nr[   r5   r+   )r@   rA   rB   r   rD   )r?   rN   shaperD   )r   attention_scoresr   maskrM   s        r   r   zALiBi.__call__   so    ...44R86A.44R8&,,Q/"(( / 

 #d*J*,,r   )r   N)
r   r   r   staticmethodr   float32r   rN   rG   r    r   r   r?   r?   u   sZ     jj  	   2 2 
-r   r?   )r.   typingr   mlx.corecorer   mlx.nn.layers.baser   r   r%   r?   re   r   r   <module>rj      s9       %,
6 ,
^96 9x--F --r   