Ë
    îÍ:j¸¨  ã                   ó²  — d dl Z d dlmZ d dlmZ ddlmZ ddlmZm	Z	  e	j                  e«      Z e«       rd dlZd„ Z	 	 	 d"dee   d	ed
   dee   dedef   fd„Z	 	 	 d"dee   d	ed
   dee   dedef   fd„Z	 	 	 d"dee   d	ed
   dee   dedef   fd„Z	 d#ded	d
dee   dedef   fd„Z	 d#ded	d
dee   dedef   fd„Z	 d#ded	d
dee   dedef   fd„ZeeeeeedœZ	 	 d$dedededee   dee   f
d„Zd#dedee   fd„Zd#dedee   fd„Zd#dedee   fd„Zd#dedee   fd„Zd#dedee   fd„Z d#dedee   fd „Z!eeeee e!dœZ"d#dedee   fd!„Z#y)%é    N©Úwraps)ÚOptionalé   )ÚPretrainedConfig)Úis_torch_availableÚloggingc                 óB   ‡ ‡‡— d„ Šd„ Št        ‰ «      ˆˆˆ fd„«       }|S )ad  
    Decorator function to update the RoPE parameters in the forward pass, if the model is using a dynamic RoPE
    (i.e. a RoPE implementation that may recompute its frequencies in the forward pass).

    Args:
        rope_forward (Callable):
            The forward pass of the RoPE implementation.

    Returns:
        The decorated forward pass.
    c                 óè  — t        j                  |«      dz   }t        | j                  d«      r| j                  j                  }n| j                  j
                  }||kD  rTt        | d«      s)| j                  | j                  ||dz   ¬«      \  | _        }| j                  d| j                  d¬«       y| j                  j                  |«      | _	        | j                  d| j                  d¬«       y)	zbLongrope uses long factor if sequence is larger than original pretraining length, short otherwise.r   Ú original_max_position_embeddingsÚlong_inv_freq©Úseq_lenÚinv_freqF©Ú
persistentN)ÚtorchÚmaxÚhasattrÚconfigr   Úmax_position_embeddingsÚrope_init_fnr   Úregister_bufferÚoriginal_inv_freqÚto)ÚselfÚposition_idsÚdevicer   r   Ú_s         úu/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/transformers/modeling_rope_utils.pyÚlongrope_frequency_updatez6dynamic_rope_update.<locals>.longrope_frequency_update+   sÚ   € ä—)‘)˜LÓ)¨AÑ-ˆÜ�4—;‘;Ð BÔCØ/3¯{©{×/[Ñ/[Ñ,à/3¯{©{×/RÑ/RÐ,ØÐ5Ò5Ü˜4 Ô1Ø(,×(9Ñ(9Ø—K‘K Ð1QÐTUÑ1Uð ):ó )Ñ%�Ô" Að × Ñ  ¨T×-?Ñ-?ÈEÐ ÕRð &*×%;Ñ%;×%>Ñ%>¸vÓ%FˆDÔ"Ø× Ñ  ¨T×-CÑ-CÐPUÐ ÕVó    c                 óÆ  — t        j                  |«      dz   }|| j                  kD  rA| j                  | j                  ||¬«      \  }| _        | j                  d|d¬«       || _        || j                  k  rj| j                  | j                  kD  rP| j                  j                  |«      | _        | j                  d| j                  d¬«       | j                  | _        yyy)a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   r   r   Fr   N)
r   r   Úmax_seq_len_cachedr   r   Úattention_scalingr   Úoriginal_max_seq_lenr   r   )r   r   r   r   r   s        r    Údynamic_frequency_updatez5dynamic_rope_update.<locals>.dynamic_frequency_update>   sÕ   € ô —)‘)˜LÓ)¨AÑ-ˆØ�T×,Ñ,Ò,Ø/3×/@Ñ/@ÀÇÁÈfÐ^eÐ/@Ó/fÑ,ˆH�dÔ,Ø× Ñ  ¨XÀ%Ð ÔHØ&-ˆDÔ#à�T×.Ñ.Ò.°4×3JÑ3JÈT×MfÑMfÒ3fð &*×%;Ñ%;×%>Ñ%>¸vÓ%FˆDÔ"Ø× Ñ  ¨T×-CÑ-CÐPUÐ ÔVØ&*×&?Ñ&?ˆDÕ#ð 4gÐ.r"   c                 ó¨   •— d| j                   v r ‰| ||j                  ¬«       n$| j                   dk(  r ‰| ||j                  ¬«        ‰| ||«      S )NÚdynamic)r   Úlongrope)Ú	rope_typer   )r   Úxr   r'   r!   Úrope_forwards      €€€r    Úwrapperz$dynamic_rope_update.<locals>.wrapperQ   sJ   ø€ à˜Ÿ™Ñ&Ù$ T¨<ÀÇÁÖIØ�^‰^˜zÒ)Ù% d¨LÀÇÁÕJÙ˜D ! \Ó2Ð2r"   r   )r-   r.   r'   r!   s   ` @@r    Údynamic_rope_updater/      s/   ú€ òWò&@ô& ˆ<Óõ3ó ð3ð €Nr"   r   r   ztorch.devicer   Úreturnztorch.Tensorc                 óJ  — | j                   }t        | dd«      }t        | dd«      xs | j                  | j                  z  }t	        ||z  «      }d}d|t        j                  d|dt
        j                  ¬«      j                  |t
        j                  ¬«      |z  z  z  }||fS )	a  
    Computes the inverse frequencies according to the original RoPE implementation
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration. This function assumes that the config will provide at least the following
            properties:

            *   rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
            *   hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
            *   num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.

            Additionally, this function will make use of the following properties if they are found in the config:

            *   head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
                derived as hidden_size // num_attention_heads.
            *   partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
                the first fraction of the head_dim. Defaults to 1.0.
        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.

    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).
    Úpartial_rotary_factorç      ð?Úhead_dimNr   é   ©Údtype©r   r7   )
Ú
rope_thetaÚgetattrÚhidden_sizeÚnum_attention_headsÚintr   ÚarangeÚint64r   Úfloat)	r   r   r   Úbaser2   r4   ÚdimÚattention_factorr   s	            r    Ú _compute_default_rope_parametersrD   \   s§   € ð> ×Ñ€DÜ# FÐ,CÀSÓIÐÜ�v˜z¨4Ó0Òd°F×4FÑ4FÈ&×JdÑJdÑ4d€HÜ
ˆhÐ.Ñ.Ó
/€CàÐð �dœuŸ|™|¨A¨s°A¼U¿[¹[ÔI×LÑLÐTZÔbg×bmÑbmÐLÓnÐqtÑtÑuÑv€HØÐ%Ð%Ð%r"   c                 óR   — | j                   d   }t        | ||«      \  }}||z  }||fS )a  
    Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev
    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration. This function assumes that the config will provide at least the following
            properties:

            *   rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
            *   hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
            *   num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.

            Additionally, this function will make use of the following properties if they are found in the config:

            *   head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
                derived as hidden_size // num_attention_heads.
            *   partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
                the first fraction of the head_dim. Defaults to 1.0.
        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.

    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).
    Úfactor)Úrope_scalingrD   )r   r   r   rF   r   rC   s         r    Ú'_compute_linear_scaling_rope_parametersrH   ‡   sD   € ð> × Ñ  Ñ*€Fô "BÀ&È&ÐRYÓ!ZÑ€HÐð
 �Ñ€HØÐ%Ð%Ð%r"   c                 ó„  — | j                   }t        | dd«      }t        | d| j                  | j                  z  «      }t	        ||z  «      }| j
                  }| j                  d   }d}	|€|}ngt        |t        j                  «      rAt        j                  |t        j                  ||j                  |j                  ¬«      «      }nt        ||«      }|||z  |z  |dz
  z
  ||dz
  z  z  z  }d|t        j                  d|dt        j                   ¬	«      j#                  |t        j$                  ¬
«      |z  z  z  }
|
|	fS )aÈ	  
    Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla

    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration. This function assumes that the config will provide at least the following
            properties:

            *   rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
            *   hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
            *   num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
            *   max_position_embeddings (`int`): The default sequence length used to update the dynamic RoPE at
                inference time
            *   rope_scaling (`dict[str, float]`): The standard RoPE scaling parameters, from which `factor`
                will be accessed. The value of `factor` is used to determine the new base frequency, along with the
                current sequence length (seq_len), the maximum positional embeddings (max_position_embeddings), and the
                computed dimensionality (dim) of the rotary embeddings. If seq_len <= max_position_embeddings, this
                factor has no effect. If seq_len <= max_position_embeddings, this factor effectively stretches the
                context window using an exponent derived from `dim`.

            Additionally, this function will make use of the following properties if they are found in the config:

            *   head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
                derived as hidden_size // num_attention_heads.
            *   partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
                the first fraction of the head_dim. Defaults to 1.0.
        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. If `None` or shorter than
            max_position_embeddings, this value will be overridden by max_position_embeddings.

    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).
    r2   r3   r4   rF   ©r7   r   r   r5   r   r6   r8   )r9   r:   r;   r<   r=   r   rG   Ú
isinstancer   ÚTensorÚmaximumÚtensorr7   r   r   r>   r?   r   r@   )r   r   r   rA   r2   r4   rB   r   rF   rC   r   s              r    Ú_compute_dynamic_ntk_parametersrO   ²   sB  € ðT ×Ñ€DÜ# FÐ,CÀSÓIÐÜ�v˜z¨6×+=Ñ+=À×A[ÑA[Ñ+[Ó\€HÜ
ˆhÐ.Ñ.Ó
/€CØ$×<Ñ<ÐØ× Ñ  Ñ*€FàÐð €Ø)‰Ü	�GœUŸ\™\Ô	*Ü—-‘-ØÜ�L‰LÐ0¸¿¹ÈgÏnÉnÔ]ó
‰ô
 �gÐ6Ó7ˆð �F˜WÑ$Ð'>Ñ>À6ÈAÁ:ÑNÐTWÐ[^ÐabÑ[bÑTcÑdÑd€DØ�dœuŸ|™|¨A¨s°A¼U¿[¹[ÔI×LÑLÐTZÔbg×bmÑbmÐLÓnÐqtÑtÑuÑv€HØÐ%Ð%Ð%r"   c                 ó  ‡— | j                   }t        | dd«      }t        | d| j                  | j                  z  «      }t	        ||z  «      }| j
                  d   }| j
                  j                  d«      }| j
                  j                  d«      }	| j
                  j                  d«      }
| j
                  j                  d«      xs | j                  }dd
„}|€)|	r|
rt         |||	«       |||
«      z  «      }n ||«      }| j
                  j                  d«      xs d}| j
                  j                  d«      xs d	}d„ Šˆfd„}d„ }|t        j                  d|d«      j                  |t        j                  ¬«      |z  z  }d|z  }d||z  z  }| j
                  j                  dd«      } |||||||«      \  }}d	 ||||dz  «      j                  |t        j                  ¬«      z
  }|d	|z
  z  ||z  z   }||fS )ak  
    Computes the inverse frequencies with NTK scaling. Please refer to the
    [original paper](https://huggingface.co/papers/2309.00071)

    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration. This function assumes that the config will provide at least the following
            properties:

            *   rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
            *   hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
            *   num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
            *   max_position_embeddings (`int`): The maximum length of the positional embeddings.
            *   rope_scaling (`dict[str, float | int]`): The standard RoPE scaling parameters, from which the following
                keys will be accessed:
                *   `attention_factor` (`float`, *optional*): The scaling factor to be applied to the computed cos/sin.
                    If None, the value is inferred from `factor`, `mscale`, and `mscale_all_dim` as avaialble.
                *   `beta_fast` (`float`, *optional*, defaults to 32): Parameter to set the boundary for extrapolation
                    (only) in the linear ramp function.
                *   `beta_slow` (`float`, *optional*, defaults to 1): Parameter to set the boundary for interpolation
                    (only) in the linear ramp function.
                *   `factor` (`float`, *optional*): The scaling factor applied when interpolating the position IDs to
                    extend the possible context length. Additionally, if `attention_factor` is None, the log of this
                    value is used to compute a value for `attention_factor`, possibly in conjunciton with `mscale` and
                    `mscale_all_dim`, if provided.
                *   `mscale` (`float`, *optional*): If `attention_factor` is None and both `mscale` and
                    `mscale_all_dim` are provided, `mscale` acts scalar augmenting `log(factor)` when computing the
                    numerator for the inferred value of `attention_factor`. If not provided, `attention_factor` will be
                    calculated based on `factor` only.
                *   `mscale_all_dim` (`float`, *optional*): If `attention_factor` is None and both `mscale` and
                    `mscale_all_dim` are provided, `mscale_all_dim` acts scalar augmenting `log(factor)` when computing
                    the denominator for the inferred value of `attention_factor`. If not provided, `attention_factor`
                    will be calculated based on `factor` only.
                *   `original_max_position_embeddings` (`int`, *optional*): The original max position embeddings used
                    during pretraining. If not provided, the function falls back to `max_position_embeddings`.
                *   `truncate` (`bool`, *optional*): Whether to truncate the correction range.

            Additionally, this function will make use of the following properties if they are found in the config:

            *   head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
                derived as hidden_size // num_attention_heads.
            *   partial_rotary_factor (`float`, *optional*, defaults to 1.0): If less than 1.0, inverse frequencies
                will be returned for the first fraction of the head_dim.
        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.

    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.
    r2   r3   r4   rF   rC   ÚmscaleÚmscale_all_dimr   r   c                 óJ   — | dk  ryd|z  t        j                  | «      z  dz   S )Nr   r3   gš™™™™™¹?)ÚmathÚlog)ÚscalerQ   s     r    Ú
get_mscalez,_compute_yarn_parameters.<locals>.get_mscale:  s(   € Ø�AŠ:ØØ�V‰|œdŸh™h u›oÑ-°Ñ3Ð3r"   Ú	beta_fasté    Ú	beta_slowc                 ó’   — |t        j                  || dz  t         j                  z  z  «      z  dt        j                  |«      z  z  S )zPInverse dimension formula to find the dimension based on the number of rotationsr5   )rT   rU   Úpi)Únum_rotationsrB   rA   r   s       r    Úfind_correction_dimz5_compute_yarn_parameters.<locals>.find_correction_dimL  sB   € à”d—h‘hÐ6¸-È!Ñ:KÌdÏgÉgÑ:UÑVÓWÑWÐ\]Ô`d×`hÑ`hÐimÓ`nÑ\nÑoÐor"   c                 ó¾   •—  ‰| |||«      } ‰||||«      }|r*t        j                  |«      }t        j                  |«      }t        |d«      t	        ||dz
  «      fS )z.Find dimension range bounds based on rotationsr   r   )rT   ÚfloorÚceilr   Úmin)	Úlow_rotÚhigh_rotrB   rA   r   ÚtruncateÚlowÚhighr^   s	           €r    Úfind_correction_rangez7_compute_yarn_parameters.<locals>.find_correction_rangeP  s^   ø€ á! '¨3°Ð6MÓNˆÙ" 8¨S°$Ð8OÓPˆÙÜ—*‘*˜S“/ˆCÜ—9‘9˜T“?ˆDÜ�3˜‹{œC  c¨A¡gÓ.Ð.Ð.r"   c                 ó¤   — | |k(  r|dz  }t        j                  |t         j                  ¬«      | z
  || z
  z  }t        j                  |dd«      }|S )Ngü©ñÒMbP?r6   r   r   )r   r>   Úfloat32Úclamp)rb   r   rB   Úlinear_funcÚ	ramp_funcs        r    Úlinear_ramp_factorz4_compute_yarn_parameters.<locals>.linear_ramp_factorY  sL   € Ø�#Š:Ø�5‰LˆCä—|‘| C¬u¯}©}Ô=ÀÑCÈÈcÉ	ÑRˆÜ—K‘K ¨Q°Ó2ˆ	ØÐr"   r   r5   r8   re   T)r   )r9   r:   r;   r<   r=   rG   Úgetr   r@   r   r>   r   )r   r   r   rA   r2   r4   rB   rF   rC   rQ   rR   r   rW   rX   rZ   rh   rn   Ú	pos_freqsÚinv_freq_extrapolationÚinv_freq_interpolationre   rf   rg   Úinv_freq_extrapolation_factorr   r^   s                            @r    Ú_compute_yarn_parametersrt   ö   s0  ø€ ðp ×Ñ€DÜ# FÐ,CÀSÓIÐÜ�v˜z¨6×+=Ñ+=À×A[ÑA[Ñ+[Ó\€HÜ
ˆhÐ.Ñ.Ó
/€CØ× Ñ  Ñ*€FØ×*Ñ*×.Ñ.Ð/AÓBÐØ× Ñ ×$Ñ$ XÓ.€FØ×(Ñ(×,Ñ,Ð-=Ó>€Nà×Ñ×ÑÐ BÓCÒeÀv×GeÑGeð %ó4ð ÐÙ‘nÜ$¡Z°¸Ó%?Á*ÈVÐUcÓBdÑ%dÓeÑá)¨&Ó1Ðð ×#Ñ#×'Ñ'¨Ó4Ò:¸€IØ×#Ñ#×'Ñ'¨Ó4Ò9¸€Iòpô/òð œŸ™ a¨¨aÓ0×3Ñ3¸6ÌÏÉÐ3ÓUÐX[Ñ[Ñ\€IØ  9™_ÐØ  F¨YÑ$6Ñ7Ðà×"Ñ"×&Ñ& z°4Ó8€HÙ% i°¸CÀÐGgÐiqÓr�I€Cˆð %&Ñ(:¸3ÀÀcÈQÁhÓ(O×(RÑ(RÐZ`Ôhm×hsÑhsÐ(RÓ(tÑ$tÐ!à !Ð&CÑ"CÑDØ
 Ð#@Ñ
@ñ	Að ð Ð%Ð%Ð%r"   c                 ód  — | j                   }t        | dd«      }t        | d| j                  | j                  z  «      }t	        ||z  «      }| j
                  d   }| j
                  d   }| j
                  j                  d«      }	| j
                  j                  d«      }
t        | dd	«      x}r| j                  |z  }	n| j                  }|
€I|	dk  rd}
nAt        j                  d
t        j                  |	«      t        j                  |«      z  z   «      }
|r,||kD  r't        j                  |t        j                  |¬«      }n&t        j                  |t        j                  |¬«      }t        j                  d|dt        j                  |¬«      j!                  «       |z  }d|||z  z  z  }||
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. This function assumes that the config will provide at least the following
            properties:

            *   rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
            *   hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
            *   num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
            *   max_position_embeddings (`int`): The maximum length of the positional embeddings.
            *   original_max_position_embeddings (`int`, *optional*): The original max position embeddings used during
                pretraining. If not provided, defaults to `max_position_embeddings`.
            *   rope_scaling (`dict[str, float]`): The standard RoPE scaling parameters, from which the following keys
                will be accessed:
                *   `attention_factor` (`float`, *optional*): The scaling factor to be applied on the attention
                    computation. If unspecified, it defaults to value recommended by the implementation, inferred from
                    the value of `factor`.
                *   `factor` (`float`, *optional*): The scaling factor to apply to the RoPE embeddings. If both
                    `max_position_embeddings` and `original_max_position_embeddings` are provided, this value will be
                    overridden s the ratio between those values.
                *   `long_factor` (`float`, *optional*): The scale factor applied when computing the inverse
                    frequencies if `seq_len` is provided and greater than `original_max_position_embeddings`.
                *   `short_factor` (`float`, *optional*): The scale factor applied when computing the inverse
                    frequencies if `seq_len` is None or less-than-or-equal-to `original_max_position_embeddings`.

            Additionally, this function will make use of the following properties if they are found in the config:

            *   head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
                derived as hidden_size // num_attention_heads.
            *   partial_rotary_factor (`float`, *optional*, defaults to 1.0): If less than 1.0, inverse frequencies
                will be returned for the first fraction of the head_dim.
        device (`torch.device`):
            The device to use for initialization of the inverse frequencies.
        seq_len (`int`, *optional*):
            The current sequence length.

    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.
    r2   r3   r4   Úlong_factorÚshort_factorrF   rC   r   Nr   rJ   r   r5   )r9   r:   r;   r<   r=   rG   ro   r   rT   ÚsqrtrU   r   rN   rj   r>   r?   r@   )r   r   r   rA   r2   r4   rB   rv   rw   rF   rC   r   Úext_factorsÚinv_freq_shaper   s                  r    Ú_compute_longrope_parametersr{   s  s–  € ð^ ×Ñ€DÜ# FÐ,CÀSÓIÐÜ�v˜z¨6×+=Ñ+=À×A[ÑA[Ñ+[Ó\€HÜ
ˆhÐ.Ñ.Ó
/€CØ×%Ñ% mÑ4€KØ×&Ñ& ~Ñ6€LØ× Ñ ×$Ñ$ XÓ.€FØ×*Ñ*×.Ñ.Ð/AÓBÐô
 ,3°6Ð;]Ð_cÓ+dÐdÐ'ÐdØ×/Ñ/Ð2RÑR‰à+1×+IÑ+IÐ(ð ÐØ�SŠ=Ø"Ñä#Ÿy™y¨¬T¯X©X°fÓ-=ÄÇÁÐIiÓ@jÑ-jÑ)jÓkÐñ �7Ð=Ò=Ü—l‘l ;´e·m±mÈFÔS‰ä—l‘l <´u·}±}ÈVÔTˆÜ—\‘\ ! S¨!´5·;±;ÀvÔN×TÑTÓVÐY\Ñ\€NØ�k D¨.Ñ$8Ñ8Ñ9€HàÐ%Ð%Ð%r"   c                 ó¢  — t        | ||«      \  }}| j                  d   }| j                  d   }| j                  d   }| j                  d   }||z  }	||z  }
dt        j                  z  |z  }t	        j
                  ||	kD  ||z  |«      }||z  |z
  ||z
  z  }d|z
  |z  |z  ||z  z   }||
k   ||	kD   z  }t	        j
                  |||«      }||fS )ap
  
    Computes the inverse frequencies for llama 3.1.

    Args:
        config ([`~transformers.PretrainedConfig`]):
            The model configuration. This function assumes that the config will provide at least the following
            properties:

            *   rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived.
            *   hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly.
            *   num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly.
            *   rope_scaling (`dict[str, float | int]`): The standard RoPE scaling parameters, from which the following
                keys will be accessed:
                *   `factor` (`float`, *optional*): The scaling factor applied to the inverse frequencies when 1) the
                    wavelength is greater than `low_freq_wavelen` prior to smoothing, and 2) to all inverse frequencies
                    during smoothing.
                *   `high_freq_factor` (`float`): The scale factor used to compute `high_freq_wavelen` and
                    the value for the denominator of the smoothing factor prior to the `low_freq_factor` shift.
                *   `low_freq_factor` (`float`): The scale factor used to compute `low_freq_wavelen` and
                    the shift applied to the numerator and denominator of the smoothing factor.
                    frequencies if `seq_len` is None or less-than-or-equal-to `original_max_position_embeddings`.
                *   `original_max_position_embeddings` (`int`): The original max position embeddings used
                    during pretraining. If not provided, the function falls back to `max_position_embeddings`.

            Additionally, this function will make use of the following properties if they are found in the config:

            *   head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be
                derived as hidden_size // num_attention_heads.
            *   partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for
                the first fraction of the head_dim. Defaults to 1.0.
        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.
    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.
    rF   Úlow_freq_factorÚhigh_freq_factorr   r5   r   )rD   rG   rT   r\   r   Úwhere)r   r   r   r   rC   rF   r}   r~   Úold_context_lenÚlow_freq_wavelenÚhigh_freq_wavelenÚwavelenÚinv_freq_llamaÚsmooth_factorÚsmoothed_inv_freqÚis_medium_freqs                   r    Ú_compute_llama3_parametersrˆ   Å  s  € ôT "BÀ&È&ÐRYÓ!ZÑ€HÐà× Ñ  Ñ*€FØ×)Ñ)Ð*;Ñ<€OØ×*Ñ*Ð+=Ñ>ÐØ×)Ñ)Ð*LÑM€Oà&¨Ñ8ÐØ'Ð*:Ñ:Ðà”$—'‘'‰k˜HÑ$€Gô —[‘[ Ð+;Ñ!;¸XÈÑ=NÐPXÓY€Nà$ wÑ.°Ñ@ÐEUÐXgÑEgÑh€MØ˜]Ñ*¨nÑ<¸vÑEÈÐXfÑHfÑfÐØÐ!2Ñ2Ð3¸ÐBRÑ8RÐ6SÑS€NÜ—[‘[ Ð1BÀNÓS€NàÐ+Ð+Ð+r"   )ÚdefaultÚlinearr)   Úyarnr*   Úllama3r+   Úreceived_keysÚrequired_keysÚoptional_keysÚignore_keysc                 óÔ   — d|v r|dhz  }|j                  d«       |�||z  }||z
  }|rt        d| › d|› �«      ‚|�	||z
  |z
  }n||z
  }|rt        j                  d| › d|› �«       yy)zYCompare the received keys in `config.rope_scaling` against the expected and optional keysÚtyper+   Nz9Missing required keys in `rope_scaling` for 'rope_type'='z': z5Unrecognized keys in `rope_scaling` for 'rope_type'=')ÚaddÚKeyErrorÚloggerÚwarning)r+   r�   rŽ   r�   r�   Úmissing_keysÚunused_keyss          r    Ú_check_received_keysr™     s§   € ð �ÑØ˜&˜Ñ!ˆØ×Ñ˜+Ô&ð ÐØ˜Ñ$ˆà  =Ñ0€LÙÜÐRÐS\ÐR]Ð]`ÐamÐ`nÐoÓpÐpàÐ Ø# mÑ3°mÑC‰à# mÑ3ˆÙÜ�‰ÐNÈyÈkÐY\Ð]hÐ\iÐjÕkð r"   c                 ó¶   — | j                   }|j                  d|j                  dd «      «      }dh}t        |j                  «       «      }t	        ||||¬«       y )Nr+   r’   ©r�   )rG   ro   ÚsetÚkeysr™   )r   r�   rG   r+   rŽ   r�   s         r    Ú!_validate_default_rope_parametersrž   0  sT   € Ø×&Ñ&€LØ× Ñ  ¨l×.>Ñ.>¸vÀtÓ.LÓM€IØ �M€MÜ˜×)Ñ)Ó+Ó,€MÜ˜ M°=ÈkÖZr"   c                 ó"  — | j                   }|j                  d|j                  dd «      «      }ddh}t        |j                  «       «      }t	        ||||¬«       |d   }|�t        |t        «      r|dk  rt        j                  d|› �«       y y )Nr+   r’   rF   r›   r3   ú8`rope_scaling`'s factor field must be a float >= 1, got ©	rG   ro   rœ   r�   r™   rK   r@   r•   r–   )r   r�   rG   r+   rŽ   r�   rF   s          r    Ú(_validate_linear_scaling_rope_parametersr¢   8  s‘   € Ø×&Ñ&€LØ× Ñ  ¨l×.>Ñ.>¸vÀtÓ.LÓM€IØ  (Ð+€MÜ˜×)Ñ)Ó+Ó,€MÜ˜ M°=ÈkÕZà˜(Ñ#€FØ€~œZ¨´Ô6¸&À3º,Ü�‰ÐQÐRXÐQYÐZÕ[ð ;Gr"   c                 ó*  — | j                   }|j                  d|j                  dd «      «      }ddh}dh}t        |j                  «       «      }t	        |||||¬«       |d   }|�t        |t        «      r|dk  rt        j                  d|› �«       y y )Nr+   r’   rF   r   r›   r3   r    r¡   )r   r�   rG   r+   rŽ   r�   r�   rF   s           r    Ú)_validate_dynamic_scaling_rope_parametersr¤   D  sœ   € Ø×&Ñ&€LØ× Ñ  ¨l×.>Ñ.>¸vÀtÓ.LÓM€IØ  (Ð+€Mà7Ð8€MÜ˜×)Ñ)Ó+Ó,€MÜ˜ M°=À-Ð]hÕià˜(Ñ#€FØ€~œZ¨´Ô6¸&À3º,Ü�‰ÐQÐRXÐQYÐZÕ[ð ;Gr"   c           	      ó¶  — | j                   }|j                  d|j                  dd «      «      }ddh}h d£}t        |j                  «       «      }t	        |||||¬«       |d   }|�t        |t        «      r|dk  rt        j                  d|› �«       |j                  d«      }|�-t        |t        «      r|d	k  rt        j                  d
|› �«       |j                  d«      }	|	�(t        |	t        «      st        j                  d|	› �«       |j                  d«      }
|
�(t        |
t        «      st        j                  d|
› �«       |	xs d|
xs dk  rt        j                  d|	› d|
› d�«       | j                   j                  d«      }|�5| j                  |z  }||k7  r t        j                  d|› d|› d|› d�«       y y t        j                  d«       y )Nr+   r’   rF   >   rQ   re   rX   rZ   rR   rC   r   r›   r3   r    rC   r   úL`rope_scaling`'s attention_factor field must be a float greater than 0, got rX   z6`rope_scaling`'s beta_fast field must be a float, got rZ   z6`rope_scaling`'s beta_slow field must be a float, got rY   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   zHThe explicitly set RoPE scaling factor (config.rope_scaling['factor'] = zá) does not match the ratio implicitly set by other parameters (implicit factor = post-yarn context length / pre-yarn context length = config.max_position_embeddings / config.rope_scaling['original_max_position_embeddings'] = z). Using the explicit factor (z‡) in YaRN. This may cause unexpected behaviour in model usage, please correct the 'max_position_embeddings' fields in the model config.a~  config.rope_scaling['original_max_position_embeddings'], the pre-yarn context length, is unset. We will **assume** config.max_position_embeddings holds the pre-yarn context length. Some use cases may expect config.max_position_embeddings to hold the post-yarn context length (pre-yarn context length * factor) -- we recommend updating both fields for optimal downstream model usage.)rG   ro   rœ   r�   r™   rK   r@   r•   r–   r   Úwarning_once)r   r�   rG   r+   rŽ   r�   r�   rF   rC   rX   rZ   r   Úimplicit_factors                r    Ú_validate_yarn_parametersr©   R  s  € Ø×&Ñ&€LØ× Ñ  ¨l×.>Ñ.>¸vÀtÓ.LÓM€IØ  (Ð+€Mò€Mô ˜×)Ñ)Ó+Ó,€MÜ˜ M°=À-Ð]hÕià˜(Ñ#€FØ€~œZ¨´Ô6¸&À3º,Ü�‰ÐQÐRXÐQYÐZÔ[à#×'Ñ'Ð(:Ó;ÐØÐ#¬ZÐ8HÌ%Ô-PÐTdÐghÒThÜ�‰ØZÐ[kÐZlÐmô	
ð × Ñ  Ó-€IØÐ¤Z°	¼5Ô%AÜ�‰ÐOÐPYÈ{Ð[Ô\Ø× Ñ  Ó-€IØÐ¤Z°	¼5Ô%AÜ�‰ÐOÐPYÈ{Ð[Ô\àŠ�R˜IšN¨Ò+Ü�‰Ø]Ð^gÐ]hð i6Ø6?°[Ð@XðZô	
ð (.×':Ñ':×'>Ñ'>Ð?aÓ'bÐ$Ø'Ð3à ×8Ñ8Ð;[Ñ[ˆØ˜fÒ$Ü×ÑØZÐ[aÐZbð cnð #Ð#Ð#AÀ&Àð Juð	uõð %ô 	×Ñð_õ	
r"   c                 óÀ  — | j                   }|j                  d|j                  dd «      «      }h d£}h d£}t        |j                  «       «      }t	        |||||¬«       t        | dd«      }t        | d| j                  | j                  z  «      }t        ||z  «      }	|j                  d	«      }
t        |
t        «      s*t        d
„ |
D «       «      rt        j                  d|
› �«       t        |
«      |	dz  k7  r't        j                  d|	dz  › dt        |
«      › �«       |j                  d«      }t        |t        «      s*t        d„ |D «       «      rt        j                  d|› �«       t        |«      |	dz  k7  r't        j                  d|	dz  › dt        |«      › �«       t        | d«      rt        j!                  d«       y |j                  d«      }|€t        j                  d«       n-t        |t"        «      r|dk  rt        j                  d|› �«       |j                  d«      }|�/t        |t"        «      r|dk  rt        j                  d|› �«       y y y )Nr+   r’   >   r+   rv   rw   >   rF   rC   r   r›   r2   r3   r4   rw   c              3   óH   K  — | ]  }t        |t        t        f«      –— Œ y ­w©N©rK   r=   r@   ©Ú.0r,   s     r    ú	<genexpr>z0_validate_longrope_parameters.<locals>.<genexpr>¢  s   è ø€ Ò1dÐRS´*¸QÄÄeÀ×2MÑ1dùó   ‚ "zC`rope_scaling`'s short_factor field must be a list of numbers, got r5   z5`rope_scaling`'s short_factor field must have length z, got rv   c              3   óH   K  — | ]  }t        |t        t        f«      –— Œ y ­wr¬   r­   r®   s     r    r°   z0_validate_longrope_parameters.<locals>.<genexpr>¨  s   è ø€ Ò0bÐQR´¸AÄÄU¸|×1LÑ0bùr±   zB`rope_scaling`'s long_factor field must be a list of numbers, got z4`rope_scaling`'s long_factor field must have length r   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.rF   z1Missing required keys in `rope_scaling`: 'factor'r    rC   g        r¦   )rG   ro   rœ   r�   r™   r:   r;   r<   r=   rK   ÚlistÚallr•   r–   Úlenr   r§   r@   )r   r�   rG   r+   rŽ   r�   r�   r2   r4   rB   rw   rv   rF   rC   s                 r    Ú_validate_longrope_parametersr¶   ”  s@  € Ø×&Ñ&€LØ× Ñ  ¨l×.>Ñ.>¸vÀtÓ.LÓM€IÚ@€MâV€MÜ˜×)Ñ)Ó+Ó,€MÜ˜ M°=À-Ð]hÕiä# FÐ,CÀSÓIÐÜ�v˜z¨6×+=Ñ+=À×A[ÑA[Ñ+[Ó\€HÜ
ˆhÐ.Ñ.Ó
/€Cà×#Ñ# NÓ3€LÜ�l¤DÔ)¬cÑ1dÐWcÔ1dÔ.dÜ�‰Ð\Ð]iÐ\jÐkÔlÜ
ˆ<Ó˜C 1™HÒ$Ü�‰ÐNÈsÐVWÉxÈjÐX^Ô_bÐcoÓ_pÐ^qÐrÔsà×"Ñ" =Ó1€KÜ�k¤4Ô(¬SÑ0bÐVaÔ0bÔ-bÜ�‰Ð[Ð\gÐ[hÐiÔjÜ
ˆ;Ó˜3 !™8Ò#Ü�‰ÐMÈcÐUVÉhÈZÐW]Ô^aÐbmÓ^nÐ]oÐpÔqô
 ˆvÐ9Ô:Ü×ÑðAõ	
ð ×!Ñ! (Ó+ˆØˆ>Ü�N‰NÐNÕOÜ˜F¤EÔ*¨f°sªlÜ�N‰NÐUÐV\ÐU]Ð^Ô_à'×+Ñ+Ð,>Ó?ÐØÐ'ÜÐ.´Ô6Ð:JÈSÒ:PÜ—‘ØbÐcsÐbtÐuõð ;Qð (r"   c                 óä  — | j                   }|j                  d|j                  dd «      «      }h d£}t        |j                  «       «      }t	        ||||¬«       |d   }|�t        |t        «      r|dk  rt        j                  d|› �«       |d   }|d	   }|�t        |t        «      st        j                  d
|› �«       |�t        |t        «      st        j                  d|› �«       ||k  rt        j                  d|› d|› �«       |d   }	|	�t        |	t        «      st        j                  d|	› �«       |	| j                  k\  r&t        j                  d|	› d| j                  › �«       y y )Nr+   r’   >   rF   r+   r}   r~   r   r›   rF   r3   r    r}   r~   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=r   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=)rG   ro   rœ   r�   r™   rK   r@   r•   r–   r=   r   )
r   r�   rG   r+   rŽ   r�   rF   r}   r~   r   s
             r    Ú_validate_llama3_parametersr¸   Æ  s‹  € Ø×&Ñ&€LØ× Ñ  ¨l×.>Ñ.>¸vÀtÓ.LÓM€IÚv€MÜ˜×)Ñ)Ó+Ó,€MÜ˜ M°=ÈkÕZà˜(Ñ#€FØ€~œZ¨´Ô6¸&À3º,Ü�‰ÐQÐRXÐQYÐZÔ[à"Ð#4Ñ5€OØ#Ð$6Ñ7ÐØÐ¤j°Ä%Ô&HÜ�‰ÐUÐVeÐUfÐgÔhØÐ¤zÐ2BÄEÔ'JÜ�‰ÐVÐWgÐVhÐiÔjØ˜?Ò*Ü�‰ØqØÐ Ð 5°oÐ5FðHô	
ð
 (4Ð4VÑ'WÐ$Ø'Ð/´zÐBbÔdgÔ7hÜ�‰Ø^Ø/Ð0ð2ô	
ð (¨6×+IÑ+IÒIÜ�‰ØuØ/Ð0Ð0MÈf×NlÑNlÐMmðoõ	
ð Jr"   c                 óÞ   — t        | dd«      }|€y|j                  d|j                  dd«      «      }t        j                  |«      }|� || |¬«       yt        j	                  d|› d�«       y)	zO
    Validate the RoPE config arguments, given a `PretrainedConfig` object
    rG   Nr+   r’   r‰   r›   zTMissing validation function mapping in `ROPE_VALIDATION_FUNCTIONS` for 'rope_type'='ú')r:   ro   ÚROPE_VALIDATION_FUNCTIONSr•   r–   )r   r�   rG   r+   Úvalidation_fns        r    Úrope_config_validationr½   õ  sw   € ô ˜6 >°4Ó8€LØÐØð × Ñ  ¨l×.>Ñ.>¸vÀyÓ.QÓR€IÜ-×1Ñ1°)Ó<€MØÐ Ù�f¨+Ö6ä�‰ØbÐclÐbmÐmnÐoõ	
r"   )NNNr¬   )NN)$rT   Ú	functoolsr   Útypingr   Úconfiguration_utilsr   Úutilsr   r	   Ú
get_loggerÚ__name__r•   r   r/   r=   Útupler@   rD   rH   rO   rt   r{   rˆ   ÚROPE_INIT_FUNCTIONSÚstrrœ   r™   rž   r¢   r¤   r©   r¶   r¸   r»   r½   © r"   r    ú<module>rÈ      s#  ðó Ý Ý å 1ß .ð 
ˆ×	Ñ	˜HÓ	%€ñ ÔÛò;ð~ *.Ø'+Ø!ñ(&ØÐ%Ñ&ð(&à�^Ñ$ð(&ð �c‰]ð(&ð ˆ>˜5Ð Ñ!ó	(&ðX *.Ø'+Ø!ñ(&ØÐ%Ñ&ð(&à�^Ñ$ð(&ð �c‰]ð(&ð ˆ>˜5Ð Ñ!ó	(&ðX *.Ø'+Ø!ñA&ØÐ%Ñ&ðA&à�^Ñ$ðA&ð �c‰]ðA&ð ˆ>˜5Ð Ñ!ó	A&ðJ PTñz&Øðz&Ø&4ðz&Ø?GÈ¹}ðz&à
ˆ>˜5Ð Ñ!óz&ð| PTñO&ØðO&Ø&4ðO&Ø?GÈ¹}ðO&à
ˆ>˜5Ð Ñ!óO&ðf PTñ>,Øð>,Ø&4ð>,Ø?GÈ¹}ð>,à
ˆ>˜5Ð Ñ!ó>,ðJ 0Ø5Ø.Ø$Ø,Ø(ñÐ ð $(Ø!%ñlØðlàðlð ðlð ˜C‘=ð	lð
 ˜#‘ólñ:[Ð.>ð [ÈXÐVYÉ]ó [ñ	\Ð5Eð 	\ÐT\Ð]`ÑTaó 	\ñ\Ð6Fð \ÐU]Ð^aÑUbó \ñ?
Ð&6ð ?
ÀXÈcÁ]ó ?
ñD/Ð*:ð /ÈÐRUÉó /ñd!
Ð(8ð !
ÀxÐPSÁ}ó !
ðL 1Ø6Ø8Ø%Ø-Ø)ñÐ ñ
Ð#3ð 
À(È3Á-ô 
r"   