uploaded the custom written libraries that will be imported by the model code.
Browse files- BPE_training.py +105 -0
- README.md +0 -3
- __init__.py +0 -0
- embedings.py +74 -0
- transformer_block.py +233 -0
BPE_training.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import collections as col
|
| 3 |
+
import time
|
| 4 |
+
import pickle
|
| 5 |
+
try:
|
| 6 |
+
import cupy as np
|
| 7 |
+
except:
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_pair(voc):
|
| 12 |
+
pairs=col.defaultdict(int)
|
| 13 |
+
for word,freq in voc.items():
|
| 14 |
+
for i in range (len(word)-1):
|
| 15 |
+
pairs[(word[i],word[i+1])]+=freq
|
| 16 |
+
return max(pairs,key=pairs.get)
|
| 17 |
+
|
| 18 |
+
def merge(voc,pair,idx):
|
| 19 |
+
new_voc={}
|
| 20 |
+
for word,freq in voc.items():
|
| 21 |
+
if len(word)<2 or pair[0] not in word or pair[1] not in word:
|
| 22 |
+
new_voc[word]=freq
|
| 23 |
+
else:
|
| 24 |
+
i=0
|
| 25 |
+
new_word=()
|
| 26 |
+
while i<len(word):
|
| 27 |
+
if word[i]==pair[0] and i<len(word)-1 and word[i+1]==pair[1]:
|
| 28 |
+
new_word+=(idx,)
|
| 29 |
+
i+=2
|
| 30 |
+
else:
|
| 31 |
+
new_word+=(word[i],)
|
| 32 |
+
i+=1
|
| 33 |
+
new_voc[new_word]=freq
|
| 34 |
+
return new_voc
|
| 35 |
+
|
| 36 |
+
def train(text_path,merges_number,merges_path):
|
| 37 |
+
start = time.time()
|
| 38 |
+
print(f"pretokenization: {time.time()-start:.3f}s")
|
| 39 |
+
with open(text_path,"r") as f:
|
| 40 |
+
text=f.read()
|
| 41 |
+
text=text.encode("UTF-8")
|
| 42 |
+
pattern=r"\w+| +|[^\w\s]|\n+|\t+".encode("UTF-8")
|
| 43 |
+
tokens=re.findall(pattern,text)
|
| 44 |
+
tokens=list(map(tuple,tokens))
|
| 45 |
+
a=[i for i in tokens if len(i)>1]
|
| 46 |
+
words=col.Counter(a)
|
| 47 |
+
merges={}
|
| 48 |
+
start = time.time()
|
| 49 |
+
for n in range(merges_number):
|
| 50 |
+
idx=256+n
|
| 51 |
+
best=get_pair(words)
|
| 52 |
+
merges[best]=idx
|
| 53 |
+
words=merge(words,best,idx)
|
| 54 |
+
pickle.dump(merges,open(merges_path,"wb"))
|
| 55 |
+
print(f"merges: {time.time()-start:.3f}s")
|
| 56 |
+
|
| 57 |
+
def encoder(text,merges):
|
| 58 |
+
seq=list(text.encode("UTF-8"))
|
| 59 |
+
for pair,idx in merges.items():
|
| 60 |
+
if pair[0] not in seq or pair[1] not in seq :
|
| 61 |
+
pass
|
| 62 |
+
else:
|
| 63 |
+
new_seq=[]
|
| 64 |
+
i=0
|
| 65 |
+
while i<len(seq):
|
| 66 |
+
if pair[0]==seq[i] and i<len(seq)-1 and pair[1]==seq[i+1]:
|
| 67 |
+
new_seq.append(idx)
|
| 68 |
+
i+=2
|
| 69 |
+
else:
|
| 70 |
+
new_seq.append(seq[i])
|
| 71 |
+
i+=1
|
| 72 |
+
seq=new_seq
|
| 73 |
+
return seq
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def unmerge(seq,pair,idx):
|
| 80 |
+
if idx not in seq :
|
| 81 |
+
return seq
|
| 82 |
+
else:
|
| 83 |
+
new_seq=[]
|
| 84 |
+
i=0
|
| 85 |
+
while i<len(seq):
|
| 86 |
+
if seq[i]==idx:
|
| 87 |
+
new_seq+=list(pair)
|
| 88 |
+
i+=1
|
| 89 |
+
else:
|
| 90 |
+
new_seq.append(seq[i])
|
| 91 |
+
i+=1
|
| 92 |
+
return new_seq
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def decoder(seq,merges):
|
| 96 |
+
decoded=seq
|
| 97 |
+
pairs=list(merges.keys())
|
| 98 |
+
idxes=list(merges.values())
|
| 99 |
+
pairs.reverse();idxes.reverse()
|
| 100 |
+
for i in range (len (pairs)):
|
| 101 |
+
decoded=unmerge(decoded,pairs[i],idxes[i])
|
| 102 |
+
return bytes(decoded).decode("UTF-8")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
|
README.md
CHANGED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
__init__.py
ADDED
|
File without changes
|
embedings.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
import cupy as np
|
| 3 |
+
except:
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pickle
|
| 6 |
+
import BPE_training as BPE
|
| 7 |
+
class RoPE:
|
| 8 |
+
def __init__(self,d,seq_len=None,pos=None):
|
| 9 |
+
""" Rotatory positional embeding
|
| 10 |
+
it rotates each pair of dimensions in the vector by an angle=pos * theta to give it position information
|
| 11 |
+
theta=10000**(-2*i/d) i is the dimention pair number and d is the last dimention of the input matrix
|
| 12 |
+
"""
|
| 13 |
+
self.d=d
|
| 14 |
+
if pos is None:
|
| 15 |
+
pos=np.arange(seq_len).reshape(-1,1)
|
| 16 |
+
else:
|
| 17 |
+
pos=np.array([pos]).reshape(1,1)
|
| 18 |
+
i=np.arange(d//2)
|
| 19 |
+
theta=10000**(-2*i/d)
|
| 20 |
+
angles=pos * theta
|
| 21 |
+
|
| 22 |
+
self.cos_=np.repeat(np.cos(angles),2,axis=1)
|
| 23 |
+
self.sin_=np.repeat(np.sin(angles),2,axis=1)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def rotate_half(self,X):
|
| 27 |
+
res=np.zeros((X.shape))
|
| 28 |
+
res[:,:,:,1::2]=X[:,:,:,::2]
|
| 29 |
+
res[:,:,:,::2]=X[:,:,:,1::2]*-1
|
| 30 |
+
return res
|
| 31 |
+
|
| 32 |
+
def __call__(self,X):
|
| 33 |
+
return (X*self.cos_ + self.rotate_half(X)*self.sin_)
|
| 34 |
+
|
| 35 |
+
def backward(self,dRotated):
|
| 36 |
+
"""
|
| 37 |
+
As RoPE rotates the input matrix's pairs of dimensions by theta[dims_pair]
|
| 38 |
+
RoPE(X)=R@X so the derivative of it is the function rotating it by the opposit angle so basically its RoPE with -theta
|
| 39 |
+
"""
|
| 40 |
+
return (dRotated*self.cos_ - self.rotate_half(dRotated)*self.sin_)
|
| 41 |
+
|
| 42 |
+
class lookup:
|
| 43 |
+
def __init__(self,We):
|
| 44 |
+
self.ET=We
|
| 45 |
+
def __call__(self,tokens):
|
| 46 |
+
return self.ET[tokens]
|
| 47 |
+
def backward(self,dE,tokens):
|
| 48 |
+
dmodel=dE.shape[-1]
|
| 49 |
+
dwe=np.zeros_like(self.ET)
|
| 50 |
+
try:
|
| 51 |
+
np.add.at(dwe,tokens.ravel(),dE.reshape(-1,dmodel))
|
| 52 |
+
except:
|
| 53 |
+
import cupyx
|
| 54 |
+
cupyx.scatter_add(dwe,tokens.ravel(),dE.reshape(-1,dmodel))
|
| 55 |
+
return dwe
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class embeding_data:
|
| 59 |
+
def __init__(self,save_path,saved=True,data_path=None,merges=None):
|
| 60 |
+
if not saved:
|
| 61 |
+
self.tokens=self.save_embeds(data_path,save_path,merges)
|
| 62 |
+
else:
|
| 63 |
+
self.tokens=self.load_embeds(save_path)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def save_embeds(self,data_path,save_path,merges):
|
| 67 |
+
with open(data_path,"r") as file:
|
| 68 |
+
text=file.read()
|
| 69 |
+
tokens=BPE.encoder(text,merges)
|
| 70 |
+
pickle.dump(tokens,open(save_path,"bw"))
|
| 71 |
+
|
| 72 |
+
def load_embeds(self,save_path):
|
| 73 |
+
return pickle.load(open(save_path,"br"))
|
| 74 |
+
|
transformer_block.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
import cupy as np
|
| 3 |
+
except:
|
| 4 |
+
import numpy as np
|
| 5 |
+
import embedings as em
|
| 6 |
+
|
| 7 |
+
class softmax:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
pass
|
| 10 |
+
def __call__(self,x):
|
| 11 |
+
m=np.max(x,axis=-1,keepdims=True)
|
| 12 |
+
exp=np.exp(x-m)
|
| 13 |
+
return exp / np.sum(exp,axis=-1,keepdims=True)
|
| 14 |
+
|
| 15 |
+
def backward(self,dSM,SM):
|
| 16 |
+
return SM * (dSM - np.sum(dSM * SM,axis=-1,keepdims=True))
|
| 17 |
+
|
| 18 |
+
def RELU(x):
|
| 19 |
+
return x * (x>0)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class MHattention:
|
| 23 |
+
|
| 24 |
+
def __init__(self,seq_len,batches,wq,wk,wv,wo,grads=None,op=None,layer=None):
|
| 25 |
+
"""normal MHA attention from "attention is all you need" paper with KV cache for inference
|
| 26 |
+
Note:set seq_len to 0 and batches to 1 for inference
|
| 27 |
+
for inference the class instance present only one layer (set as layer parameter) so each layer should have a separate class instance (with the same parameters)
|
| 28 |
+
if op and grads left default it will be considered for inference
|
| 29 |
+
for training pass the grads dict and set op='training'"""
|
| 30 |
+
self.wq=wq
|
| 31 |
+
self.wk=wk
|
| 32 |
+
self.wv=wv
|
| 33 |
+
self.wo=wo
|
| 34 |
+
layers=wv.shape[0]
|
| 35 |
+
heads=wv.shape[1] ; dmodel=wv.shape[2] ; self.dk=wv.shape[3]
|
| 36 |
+
self.heads=heads
|
| 37 |
+
self.layer=layer
|
| 38 |
+
self.training=(op=="training")
|
| 39 |
+
self.eval=(op=="evaluation")
|
| 40 |
+
if self.training:
|
| 41 |
+
grads.gradients["wq"]=np.zeros((layers,*wq.shape[1:]),dtype=np.float32)
|
| 42 |
+
grads.gradients["wk"]=np.zeros((layers,*wk.shape[1:]),dtype=np.float32)
|
| 43 |
+
grads.gradients["wv"]=np.zeros((layers,*wv.shape[1:]),dtype=np.float32)
|
| 44 |
+
grads.gradients["wo"]=np.zeros((layers,batches,*wo.shape[1:]),dtype=np.float32)
|
| 45 |
+
|
| 46 |
+
self.V=np.zeros((layers,batches,heads,seq_len,self.dk),dtype=np.float32)
|
| 47 |
+
self.RQ=np.zeros((layers,batches,heads,seq_len,self.dk),dtype=np.float32)
|
| 48 |
+
self.RK=np.zeros((layers,batches,heads,seq_len,self.dk),dtype=np.float32)
|
| 49 |
+
self.SM=np.zeros((layers,batches,heads,seq_len,seq_len),dtype=np.float32)
|
| 50 |
+
self.con=np.zeros((layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 51 |
+
self.RoPE=em.RoPE(self.dk,seq_len)
|
| 52 |
+
else:
|
| 53 |
+
self.V=np.empty((batches,heads,0,self.dk),dtype=np.float32)
|
| 54 |
+
self.RK=np.empty((batches,heads,0,self.dk),dtype=np.float32)
|
| 55 |
+
self.pos=0
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def forward(self,E,L=None):
|
| 59 |
+
"""for training you must set L as the layer number
|
| 60 |
+
for inference the instance has already the layer number as self.layer """
|
| 61 |
+
if self.training:
|
| 62 |
+
Q=E[:,None,:,:] @ self.wq[L]
|
| 63 |
+
K=E[:,None,:,:] @ self.wk[L]
|
| 64 |
+
self.V[L]=E[:,None,:,:] @ self.wv[L]
|
| 65 |
+
self.RQ[L]=self.RoPE(Q)
|
| 66 |
+
self.RK[L]=self.RoPE(K)
|
| 67 |
+
score=(self.RQ[L] @ np.swapaxes(self.RK[L],-2,-1))* (1/self.dk)
|
| 68 |
+
score[:,:,*np.triu_indices(score.shape[2],1)]=-1e10 #masking the attention score
|
| 69 |
+
sm=softmax()
|
| 70 |
+
self.SM[L]=sm(score)
|
| 71 |
+
As=self.SM[L] @ self.V[L]
|
| 72 |
+
self.con[L]=As.swapaxes(1,2).reshape((Q.shape[0],Q.shape[2],Q.shape[1]*Q.shape[3]))
|
| 73 |
+
A=self.con[L] @ self.wo[L]
|
| 74 |
+
else:
|
| 75 |
+
L=self.layer
|
| 76 |
+
if self.RK.shape[-2]==0:
|
| 77 |
+
Rp=em.RoPE(self.dk,seq_len=E.shape[-2])
|
| 78 |
+
self.pos+=E.shape[-2]
|
| 79 |
+
else:
|
| 80 |
+
Rp=em.RoPE(self.dk,pos=self.pos)
|
| 81 |
+
self.pos+=1
|
| 82 |
+
Q=E[:,None,:,:] @ self.wq[L]
|
| 83 |
+
nK=E[:,None,:,:] @ self.wk[L]
|
| 84 |
+
nV=E[:,None,:,:] @ self.wv[L]
|
| 85 |
+
self.V=np.append(self.V,nV,axis=-2)
|
| 86 |
+
nRK=Rp(nK)
|
| 87 |
+
self.RK=np.append(self.RK,nRK,axis=-2)
|
| 88 |
+
if self.eval:
|
| 89 |
+
RQ=Rp(Q)
|
| 90 |
+
score=(RQ @ np.swapaxes(self.RK,-2,-1))* (1/self.dk)
|
| 91 |
+
score[:,:,*np.triu_indices(score.shape[2],1)]=-1e10 #masking the attention score
|
| 92 |
+
else:
|
| 93 |
+
RQ=Rp(Q)[-1]
|
| 94 |
+
score=(RQ @ np.swapaxes(self.RK,-2,-1))* (1/self.dk)
|
| 95 |
+
sm=softmax()
|
| 96 |
+
As=sm(score) @ self.V
|
| 97 |
+
con=As.swapaxes(1,2).reshape((Q.shape[0],Q.shape[2],Q.shape[1]*Q.shape[3]))
|
| 98 |
+
A=con @ self.wo[L]
|
| 99 |
+
return A
|
| 100 |
+
|
| 101 |
+
def backward(self,E,dMHA,L,grads):
|
| 102 |
+
dcon=dMHA @ self.wo[L].swapaxes(-1,-2)
|
| 103 |
+
dAs=np.array(np.split(dcon,self.heads,axis=-1)).swapaxes(0,1)
|
| 104 |
+
dSM=dAs @ self.V[L].swapaxes(-1,-2)
|
| 105 |
+
sm=softmax()
|
| 106 |
+
dscore=sm.backward(dSM,self.SM[L])
|
| 107 |
+
dRQ=(1/self.dk) * (dscore @ self.RK[L])
|
| 108 |
+
dRK=(1/self.dk) * (dscore.swapaxes(-1,-2) @ self.RQ[L])
|
| 109 |
+
dQ=self.RoPE.backward(dRQ)
|
| 110 |
+
dK=self.RoPE.backward(dRK)
|
| 111 |
+
dV=self.SM[L].swapaxes(-1,-2) @ dAs
|
| 112 |
+
dEq=dQ @ self.wq[L].swapaxes(-1,-2)
|
| 113 |
+
dEk=dK @ self.wk[L].swapaxes(-1,-2)
|
| 114 |
+
dEv=dV @ self.wv[L].swapaxes(-1,-2)
|
| 115 |
+
dE=(dEq + dEk + dEv).sum(axis=1)
|
| 116 |
+
grads.gradients["wq"][L]=(E[:,None,:,:].swapaxes(-1,-2) @ dQ).sum(axis=0)
|
| 117 |
+
grads.gradients["wk"][L]=(E[:,None,:,:].swapaxes(-1,-2) @ dK).sum(axis=0)
|
| 118 |
+
grads.gradients["wv"][L]=(E[:,None,:,:].swapaxes(-1,-2) @ dV).sum(axis=0)
|
| 119 |
+
grads.gradients["wo"][L]=self.con[L].swapaxes(-1,-2) @ dMHA
|
| 120 |
+
return dE
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class RMSNorm:
|
| 126 |
+
"""RMSNorm (Root mean square normalisation)
|
| 127 |
+
here I passed g (gamma) and b (beta) as matrices that has all the gammas and betas of all layers and normalization steps
|
| 128 |
+
L:Layer , n:the part you will do prenorm for (n=1 : attention ;; n=2: feed forward)
|
| 129 |
+
fg and fb are the paremeters for the last normalization after all the transformer block layers before the linear operation
|
| 130 |
+
i havent included them in g and b for memory efficiency
|
| 131 |
+
just pass n==3 in the call parameters for the last norm
|
| 132 |
+
"""
|
| 133 |
+
def __init__ (self,g,b,fg,fb,batches=None,grads=None,op=None):
|
| 134 |
+
self.g=g
|
| 135 |
+
self.b=b
|
| 136 |
+
self.fg=fg
|
| 137 |
+
self.fb=fb
|
| 138 |
+
layers=g.shape[0]
|
| 139 |
+
if op=="training":
|
| 140 |
+
grads.gradients["g"]=np.zeros((layers,batches,2,g.shape[-1]),dtype=np.float32)
|
| 141 |
+
grads.gradients["b"]=np.zeros((layers,batches,2,b.shape[-1]),dtype=np.float32)
|
| 142 |
+
|
| 143 |
+
def RMS(self,x):
|
| 144 |
+
return np.sqrt((1/x.shape[-1]) * np.sum(x**2,axis=-1,keepdims=True))
|
| 145 |
+
|
| 146 |
+
def __call__(self,x,L,n):
|
| 147 |
+
if n==3:
|
| 148 |
+
return (x/self.RMS(x)) * self.fg + self.fb
|
| 149 |
+
else:
|
| 150 |
+
return (x/self.RMS(x)) * self.g[L,n-1] + self.b[L,n-1]
|
| 151 |
+
|
| 152 |
+
def backward(self,x,dN,L,n,grads):
|
| 153 |
+
rms=self.RMS(x)
|
| 154 |
+
if n==3:
|
| 155 |
+
g=self.fg
|
| 156 |
+
b=self.fb
|
| 157 |
+
grads.gradients["fg"]=(dN * (x/rms)).sum(axis=1,keepdims=True,dtype=np.float32)
|
| 158 |
+
grads.gradients["fb"]=dN.sum(axis=1,keepdims=True,dtype=np.float32)
|
| 159 |
+
else:
|
| 160 |
+
g=self.g[L,n-1]
|
| 161 |
+
b=self.b[L,n-1]
|
| 162 |
+
grads.gradients["g"][L,:,n-1]=(dN * (x/rms)).sum(axis=1)
|
| 163 |
+
grads.gradients["b"][L,:,n-1]=dN.sum(axis=1)
|
| 164 |
+
S=np.sum(x**2,axis=-1,keepdims=True)
|
| 165 |
+
dx= (dN/rms)*g-(x/(S*rms))*np.sum(dN*g*x,axis=-1,keepdims=True)
|
| 166 |
+
return dx
|
| 167 |
+
|
| 168 |
+
class FFN:
|
| 169 |
+
def __init__(self,wu,wd,bu,bd,batches=None,grads=None,op=None):
|
| 170 |
+
self.wu=wu
|
| 171 |
+
self.wd=wd
|
| 172 |
+
self.bu=bu
|
| 173 |
+
self.bd=bd
|
| 174 |
+
layers=wu.shape[0]
|
| 175 |
+
self.training=(op=="training")
|
| 176 |
+
if self.training:
|
| 177 |
+
grads.gradients["wu"]=np.zeros((layers,batches,*wu.shape[1:]),dtype=np.float32)
|
| 178 |
+
grads.gradients["wd"]=np.zeros((layers,batches,*wd.shape[1:]),dtype=np.float32)
|
| 179 |
+
grads.gradients["bu"]=np.zeros((layers,batches,*bu.shape[1:]),dtype=np.float32)
|
| 180 |
+
grads.gradients["bd"]=np.zeros((layers,batches,*bd.shape[1:]),dtype=np.float32)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def forward(self,x,L):
|
| 184 |
+
xu=x @ self.wu[L] + self.bu[L]
|
| 185 |
+
if self.training:
|
| 186 |
+
self.activation=np.zeros((self.wu.shape[0],*xu.shape))
|
| 187 |
+
self.activation[L]=RELU(xu)
|
| 188 |
+
xd=self.activation[L] @ self.wd[L] + self.bd[L]
|
| 189 |
+
else:
|
| 190 |
+
xd=RELU(xu) @ self.wd[L] + self.bd[L]
|
| 191 |
+
return xd
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def backward(self,FFN_input,L,dFFN,grads):
|
| 195 |
+
dactivation= dFFN @ self.wd[L].swapaxes(-1,-2)
|
| 196 |
+
dxu=dactivation * (self.activation[L]>0)
|
| 197 |
+
dx=dxu @ self.wu[L].swapaxes(-1,-2)
|
| 198 |
+
grads.gradients["wu"][L]=(FFN_input.swapaxes(-1,-2) @ dxu)
|
| 199 |
+
grads.gradients["wd"][L]=(self.activation[L].swapaxes(-1,-2) @ dFFN)
|
| 200 |
+
grads.gradients["bu"][L]=np.sum(dxu,axis=-2,keepdims=True)
|
| 201 |
+
grads.gradients["bd"][L]=np.sum(dFFN,axis=-2,keepdims=True)
|
| 202 |
+
return dx
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class adam:
|
| 206 |
+
"""adam optimizer"""
|
| 207 |
+
def __init__(self,weights_shapes,B=None):
|
| 208 |
+
"""weights_shapes is a dict with the format {weight_name:shape}
|
| 209 |
+
B is a (2,) array containing B1 (B[0]) and B2 (B[1]) its set to B1=0.9 and B2=0.999 by default
|
| 210 |
+
initializing the class create automatically the moment vectors and sets them to 0 for all weights
|
| 211 |
+
"""
|
| 212 |
+
self.m={}
|
| 213 |
+
self.v={}
|
| 214 |
+
if B is None:
|
| 215 |
+
B=np.array([0.9,0.999])
|
| 216 |
+
self.B=B
|
| 217 |
+
for weight,shape in weights_shapes.items():
|
| 218 |
+
self.m[weight]=np.zeros(shape).astype(np.float32)
|
| 219 |
+
self.v[weight]=np.zeros(shape).astype(np.float32)
|
| 220 |
+
def moment_hat(self,m,g,power,step):
|
| 221 |
+
"""this function calculates the moment vector for adam optimizer
|
| 222 |
+
use this same function to creat both moments (m and v)
|
| 223 |
+
to calculate m set the power to 1
|
| 224 |
+
to calculate g set the power to 2
|
| 225 |
+
"""
|
| 226 |
+
m_new=self.B[power-1] * m + (1-self.B[power-1]) * (g**power)
|
| 227 |
+
return m_new
|
| 228 |
+
def __call__(self,grads,step):
|
| 229 |
+
"calling the instance will update the moment vectors for the step for all weights"
|
| 230 |
+
for weight in grads.keys():
|
| 231 |
+
self.m[weight]=self.moment_hat(self.m[weight],grads[weight],1,step)
|
| 232 |
+
self.v[weight]=self.moment_hat(self.v[weight],grads[weight],2,step)
|
| 233 |
+
|