-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
65a47a1
commit ebc5e58
Showing
4 changed files
with
42 additions
and
4 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import torch | ||
from torch import nn, einsum | ||
from torch.nn import Module | ||
from torch.cuda.amp import autocast | ||
|
||
class RotaryEmbedding(Module): | ||
def __init__( | ||
self, | ||
dim, | ||
theta = 10000 | ||
): | ||
super().__init__() | ||
inv_freq = theta ** -(torch.arange(0, dim, 2).float() / dim) | ||
self.register_buffer('inv_freq', inv_freq) | ||
|
||
@autocast(enabled = False) | ||
def forward( | ||
self, | ||
seq_len, | ||
offset = 0 | ||
): | ||
t = torch.arange(seq_len + offset, device = self.inv_freq.device).type_as(self.inv_freq) | ||
freqs = torch.einsum('i , j -> i j', t, self.inv_freq) | ||
return torch.cat((freqs, freqs), dim = -1) | ||
|
||
def rotate_half(x): | ||
x1, x2 = x.chunk(2, dim = -1) | ||
return torch.cat((-x2, x1), dim=-1) | ||
|
||
@autocast(enabled = False) | ||
def apply_rotary_pos_emb(pos, t): | ||
return t * pos.cos() + rotate_half(t) * pos.sin() |
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