DebasishDhal99 commited on
Commit
db4dc58
·
1 Parent(s): 32067df

feat: added bare mimimum implementation of absolute sinusoidal positional encoding

Browse files
absolute_sinusoidal_position_embedding/abs_pos_embedding.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Bare minimum implementation of absolute sinusoidal position embedding. NOT PRODUCTION READY. WILL IMPROVE IT STEP BY STEP.
2
+
3
+ import numpy as np
4
+
5
+ np.random.seed(42)
6
+
7
+ # Sinusoidal Position Embedding Formula
8
+
9
+ # p(k,i) = sin(k/10000^(2i/d)) if i is even, else cost(k/10000^(2i/d))
10
+
11
+ # k is the position of the token (2nd token, 3rd token etc. in a sequence of sentences)
12
+ # i is the dimension index (1st dimension, 2nd dimension etc. in a vector of embeddings)
13
+ # d is the dimension of the embedding
14
+
15
+
16
+ total_tokens = 3 # 3 words
17
+ d = 5 # 5 dimensions . ex. embedding = [0.1, 0.2, 0.3, 0.4, 0.5]
18
+
19
+ base_embedding = np.random.randn(total_tokens, d)
20
+
21
+ print(f"Base embedding: shape = {base_embedding.shape}\n{base_embedding}")
22
+
23
+ assert base_embedding.shape == (total_tokens, d)
24
+
25
+ def pos_embedding(k, i, d):
26
+ if i%2 == 0:
27
+ pos_embedding_offset = np.sin(k/10000**(i/d))
28
+ else:
29
+ pos_embedding_offset = np.cos(k/10000**((i-1)/d)) # The logic is that for a given position k, the even dimensions are sin and the odd dimensions are cos of the same frequency..
30
+
31
+ return pos_embedding_offset
32
+
33
+ sample_pos_embedding_offset = pos_embedding(k=5, i=5, d=d)
34
+ print(f"Pos embedding offset: {sample_pos_embedding_offset}")
35
+
36
+
37
+ def abs_pos_embedding(d, total_tokens):
38
+ pos_embedding_matrix = np.zeros((total_tokens, d))
39
+ for k in range(total_tokens):
40
+ for i in range(d):
41
+ pos_embedding_matrix[k][i] = pos_embedding(k=k, i=i, d=d)
42
+
43
+ return pos_embedding_matrix
44
+
45
+ abs_pos_embedding = abs_pos_embedding(d=d, total_tokens=total_tokens)
46
+
47
+ embedding_with_pos = base_embedding + abs_pos_embedding
48
+ print(f"Position embedding: shape = {abs_pos_embedding.shape}\n{abs_pos_embedding}")
49
+
50
+ print(f"Embedding with pos: shape = {embedding_with_pos.shape}\n{embedding_with_pos}")