DebasishDhal99 commited on
Commit
f2aabc6
·
1 Parent(s): 8038560

Added rope implementation code with explanation

Browse files
rope_implementation/rope_implementation.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ def apply_rope(x, base=10000):
4
+ """
5
+ x.shape = (seq_len, dim)
6
+
7
+ In simple words, do this
8
+ x = [x0,
9
+ x1,
10
+ x2,
11
+ .
12
+ .
13
+ x_seq_len]
14
+
15
+ x1 = [x10, x11, x12, x13,...., x_1dim]
16
+
17
+ Take pairwise embedding values, rotate them by a certain angle, stich them back together
18
+
19
+ theta[k, i] = k * omega[i] # this is the rotation angle
20
+ omega[i] = 1 / 10000^(2i/d) # frequency for dimension pair r
21
+ theta[k, i] = k / (10000 ** (2 * i / d))
22
+
23
+
24
+ """
25
+
26
+ seq_len, dim = x.shape
27
+ assert dim%2 == 0
28
+
29
+ positions = np.arange(seq_len) # [0,1,2,..,seq_len]
30
+
31
+ positions = positions[:, None] #simple broadcasting into columns
32
+ #[[0], [1], [2]...[seq_len]]
33
+
34
+ pair_indices = np.arange(start=0, stop=dim, step=2) # [0, 2, ..., dim]
35
+
36
+ inv_freq = 1 / (
37
+ base ** (pair_indices / dim)
38
+ )
39
+
40
+ angles = positions * inv_freq # (seq_len, seq_len)
41
+
42
+ cos = np.cos(angles)
43
+ sin = np.sin(angles)
44
+
45
+ x_even = x[:, 0::2] # every second col starting from 0, simple
46
+ x_odd = x[:, 1::2] # ditto but starting from 1
47
+
48
+ rotated_even = (x_even * cos) - (x_odd * sin) # new_x0 = x0*cos(theta) - x1*sin(theta), simple rotation formula
49
+ rotated_odd = (x_even * sin) + (x_odd * cos) # new_x1 = x0*sin(theta) + x1*cost(theta)
50
+
51
+ output = np.empty_like(x)
52
+
53
+ output[:, 0::2] = rotated_even
54
+ output[:, 1::2] = rotated_odd
55
+
56
+ return output