-
Notifications
You must be signed in to change notification settings - Fork 25.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add YaRN and Dynamic-YaRN RoPE Scaling Methods #30910
Open
mig-mfreitas
wants to merge
4
commits into
huggingface:main
Choose a base branch
from
mig-mfreitas:yarn-rope-scaling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
cc9b82e
Add YaRN and Dynamic-YaRN RoPE Scaling Methods
mig-mfreitas fc161dd
Merge remote-tracking branch 'upstream/main' into yarn-rope-scaling
miguelm-almeida 1044c7b
Merge remote-tracking branch 'upstream/main' into yarn-rope-scaling
miguelm-almeida 85552b3
Refactor YaRN implementation for LLaMA
miguelm-almeida File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -149,6 +149,140 @@ def forward(self, x, position_ids): | |
return cos, sin | ||
|
||
|
||
class LlamaYarnScalingRotaryEmbedding(LlamaRotaryEmbedding): | ||
def __init__( | ||
self, | ||
dim, | ||
max_position_embeddings=2048, | ||
base=10000, | ||
scaling_factor=1, | ||
original_max_position_embeddings=2048, | ||
attention_factor=None, | ||
beta_fast=32, | ||
beta_slow=1, | ||
device=None, | ||
): | ||
super().__init__(dim, max_position_embeddings, base, device, scaling_factor) | ||
|
||
self.original_max_position_embeddings = original_max_position_embeddings | ||
self.attention_factor = attention_factor | ||
self.beta_fast = beta_fast | ||
self.beta_slow = beta_slow | ||
|
||
if self.attention_factor is None: | ||
self.attention_factor = 0.1 * math.log(scaling_factor) + 1.0 | ||
|
||
self.compute_yarn_scaling(device) | ||
|
||
# Build here to make `torch.jit.trace` work. | ||
self.max_seq_len_cached = max_position_embeddings | ||
emb = self.get_pos_embeddings(device) | ||
|
||
self._cos_cached = (emb.cos() * self.mscale)[None, :, :].to(torch.get_default_dtype()) | ||
self._sin_cached = (emb.sin() * self.mscale)[None, :, :].to(torch.get_default_dtype()) | ||
Comment on lines
+181
to
+182
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The logic to build these tensors was removed in a recent PR (#30743) -- we can delete them as well as all related functions/variables ( This comment applies to the other class too :) |
||
|
||
# Get positional embeddings based on the current max sequence length | ||
def get_pos_embeddings(self, device): | ||
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) | ||
freqs = torch.einsum("i,j->ij", t, self.inv_freq) | ||
emb = torch.cat((freqs, freqs), dim=-1) | ||
return emb | ||
|
||
# Inverse dimension formula to find the dimension based on the number of rotations | ||
def find_correction_dim(self, num_rotations, dim, base=10000, max_position_embeddings=2048): | ||
return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base)) | ||
|
||
# Find dimension range bounds based on rotations | ||
def find_correction_range(self, low_rot, high_rot, dim, base=10000, max_position_embeddings=2048): | ||
low = math.floor(self.find_correction_dim(low_rot, dim, base, max_position_embeddings)) | ||
high = math.ceil(self.find_correction_dim(high_rot, dim, base, max_position_embeddings)) | ||
return max(low, 0), min(high, dim - 1) | ||
|
||
def linear_ramp_mask(self, min, max, dim): | ||
if min == max: | ||
max += 0.001 # Prevent singularity | ||
|
||
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) | ||
ramp_func = torch.clamp(linear_func, 0, 1) | ||
return ramp_func | ||
|
||
def forward(self, x, position_ids=None): | ||
# Difference to the original RoPE: applies a scaling factor computed with | ||
# the YaRN method (NTK-by-Parts + Attn Scaling) | ||
# x: [bs, num_attention_heads, seq_len, head_size] | ||
cos, sin = super().forward(x, position_ids) | ||
cos = cos * self.mscale | ||
sin = sin * self.mscale | ||
return cos, sin | ||
|
||
def compute_yarn_scaling(self, device): | ||
pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) | ||
inv_freq_extrapolation = 1.0 / pos_freqs | ||
inv_freq_interpolation = 1.0 / (self.scaling_factor * pos_freqs) | ||
|
||
low, high = self.find_correction_range( | ||
self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings | ||
) | ||
# Get n-dimensional rotational scaling corrected for extrapolation | ||
inv_freq_mask = 1 - self.linear_ramp_mask(low, high, self.dim // 2).float().to(device) | ||
inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask | ||
|
||
self.register_buffer("inv_freq", inv_freq) | ||
# Get n-dimensional magnitude scaling corrected for interpolation | ||
self.mscale = self.attention_factor | ||
|
||
|
||
class LlamaDynamicYarnScalingRotaryEmbedding(LlamaYarnScalingRotaryEmbedding): | ||
def __init__( | ||
self, | ||
dim, | ||
max_position_embeddings=2048, | ||
base=10000, | ||
scaling_factor=1, | ||
original_max_position_embeddings=2048, | ||
attention_factor=None, | ||
beta_fast=32, | ||
beta_slow=1, | ||
device=None, | ||
): | ||
super().__init__( | ||
dim, | ||
max_position_embeddings, | ||
base, | ||
scaling_factor, | ||
original_max_position_embeddings, | ||
attention_factor, | ||
beta_fast, | ||
beta_slow, | ||
device, | ||
) | ||
|
||
if self.max_position_embeddings != self.original_max_position_embeddings: | ||
self.scaling_factor = self.max_position_embeddings / self.original_max_position_embeddings | ||
self.compute_yarn_scaling(device) | ||
else: | ||
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) | ||
self.register_buffer("inv_freq", inv_freq) | ||
self.mscale = 1 | ||
|
||
# Build here to make `torch.jit.trace` work. | ||
self.max_seq_len_cached = max_position_embeddings | ||
emb = self.get_pos_embeddings(device) | ||
|
||
self._cos_cached = (emb.cos() * self.mscale)[None, :, :].to(torch.get_default_dtype()) | ||
self._sin_cached = (emb.sin() * self.mscale)[None, :, :].to(torch.get_default_dtype()) | ||
|
||
def forward(self, x, position_ids=None): | ||
# Difference to the standard YaRN: the scaling factor is updated when the max sequence length is exceeded | ||
# x: [bs, num_attention_heads, seq_len, head_size] | ||
seq_len = torch.max(position_ids) + 1 | ||
self.scaling_factor = seq_len / self.original_max_position_embeddings | ||
self.compute_yarn_scaling(x.device) | ||
|
||
cos, sin = super().forward(x, position_ids) | ||
return cos, sin | ||
|
||
|
||
def rotate_half(x): | ||
"""Rotates half the hidden dims of the input.""" | ||
x1 = x[..., : x.shape[-1] // 2] | ||
|
@@ -275,6 +409,15 @@ def _init_rope(self): | |
else: | ||
scaling_type = self.config.rope_scaling["type"] | ||
scaling_factor = self.config.rope_scaling["factor"] | ||
# Yarn parameters | ||
kwargs = { | ||
"dim": self.config.rope_scaling.get("original_max_position_embeddings", None), | ||
"max_position_embeddings": self.config.rope_scaling.get("attention_factor", None), | ||
"base": self.config.rope_scaling.get("beta_fast", None), | ||
"scaling_factor": self.config.rope_scaling.get("beta_slow", None), | ||
} | ||
kwargs = {k: v for k, v in kwargs.items() if v is not None} | ||
|
||
if scaling_type == "linear": | ||
self.rotary_emb = LlamaLinearScalingRotaryEmbedding( | ||
self.head_dim, | ||
|
@@ -289,6 +432,22 @@ def _init_rope(self): | |
scaling_factor=scaling_factor, | ||
base=self.rope_theta, | ||
) | ||
elif scaling_type == "yarn": | ||
self.rotary_emb = LlamaYarnScalingRotaryEmbedding( | ||
self.head_dim, | ||
max_position_embeddings=self.max_position_embeddings, | ||
scaling_factor=scaling_factor, | ||
base=self.rope_theta, | ||
**kwargs, | ||
) | ||
elif scaling_type == "dynamic-yarn": | ||
self.rotary_emb = LlamaDynamicYarnScalingRotaryEmbedding( | ||
self.head_dim, | ||
max_position_embeddings=self.max_position_embeddings, | ||
scaling_factor=scaling_factor, | ||
base=self.rope_theta, | ||
**kwargs, | ||
) | ||
else: | ||
raise ValueError(f"Unknown RoPE scaling type {scaling_type}") | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's add a note saying that this is the default value according to the yarn paper, so it doesn't look like a magic number :)