model_1 / model /model_1.py
hunterfiras's picture
uploaded the main transformer code (inference and training)
36c8734 verified
Raw History Blame Contribute Delete
6.11 kB
try:
import cupy as np
except:
import numpy as np
import sys
import os
sys.path.append("..")
import transformer_block as TB
import pickle
class gradient:
def __init__(self):
self.gradients={}
class weights:
def __init__(self,weights_shapes,file_path,step,opt_path,operation="import"):
if operation!="inference":
self.adam=TB.adam(weights_shapes)
if operation=="create":
self.weights_dict={}
self.step=0
for weight,shape in weights_shapes.items():
if "b" in weight:
self.weights_dict[weight]=np.zeros(shape,dtype=np.float32)
elif "g" in weight:
self.weights_dict[weight]=np.ones(shape,dtype=np.float32)
else:
self.weights_dict[weight]=np.random.randn(*shape).astype(np.float32) * np.sqrt(2/shape[-1])
self.save(file_path,opt_path,step)
elif operation=="import":
self.weights_dict=pickle.load(open(file_path,"rb"))
infos=pickle.load(open(opt_path,"rb"))
self.step=infos["step"]
self.adam.m=infos["m"]
self.adam.v=infos["v"]
elif operation=="inference":
self.weights_dict=pickle.load(open(file_path,"rb"))
def batches_average_and_clip(self,grads,max_norm=1.0):
for weight in grads.keys():
if weight not in {"we","wq","wk","wv"}:
grads[weight]=grads[weight].sum(axis=-3)
Gnorm=np.linalg.norm(np.array([np.linalg.norm(g) for g in grads.values()]))
if Gnorm>max_norm:
for weight in grads.keys():
grads[weight]*=(max_norm/Gnorm)
def update(self,grads,lr,step,eps=1e-5):
B=self.adam.B
self.adam(grads,step)
for weight in self.weights_dict.keys():
self.weights_dict[weight]-=(lr*(self.adam.m[weight]/(1-B[0]**step)))/((np.sqrt(self.adam.v[weight]/(1-B[1]**step)))+eps)
#self.weights_dict[weight]-=lr*grads[weight]
def save(self,file_path,opt_path,step):
pickle.dump(self.weights_dict,open(file_path,"wb"))
pickle.dump({"m":self.adam.m,"v":self.adam.v,"step":step},open(opt_path,"wb"))
class forward:
def __init__(self,seq_len,dmodel,Layers,batches,weights,grads,op="training"):
self.Layers=Layers
w=weights.weights_dict
self.wl=w["wl"]
self.RMSNorm=TB.RMSNorm(w['g'],w['b'],w['fg'],w['fb'],batches,grads,op)
self.MHattention=TB.MHattention(seq_len,batches,w['wq'],w['wk'],w['wv'],w['wo'],grads,op)
self.FeedForward=TB.FFN(w['wu'],w['wd'],w['bu'],w['bd'],batches,grads,op)
self.N1=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
self.MHA=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
self.AE=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
self.N2=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
self.FFN=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
self.layer_output=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
def __call__(self,E):
self.E=E
layer_input=E
for L in range (self.Layers):
self.N1[L]=self.RMSNorm(layer_input,L,1)
self.MHA[L]=self.MHattention.forward(self.N1[L],L)
self.AE[L]=self.MHA[L] + layer_input
self.N2[L]=self.RMSNorm(self.AE[L],L,2)
self.FFN[L]=self.FeedForward.forward(self.N2[L],L)
self.layer_output[L]=self.FFN[L] + self.AE[L]
layer_input=self.layer_output[L]
self.Final_Norm=self.RMSNorm(layer_input,-1,3)
projection=self.Final_Norm @ self.wl
sm=TB.softmax()
result=sm(projection)
return result
class backward:
def __init__(self,forward):
self.forward=forward
self.Layers=forward.Layers
def __call__(self,batches,lookup,grads,tokens,result,output_indices,weights):
w=weights.weights_dict
RMSNorm=self.forward.RMSNorm
MHattention=self.forward.MHattention
FFN=self.forward.FeedForward
SM=TB.softmax()
result[*output_indices]-=1
dprojection=(result) / (batches*result.shape[1])
del result
dFN=dprojection @ w["wl"].T
grads.gradients["wl"]=self.forward.Final_Norm.swapaxes(-1,-2) @ dprojection
del dprojection
dLayer=RMSNorm.backward(self.forward.layer_output[self.Layers-1],dFN,-1,3,grads)
del dFN
for L in range (self.Layers-1,-1,-1):
dFFN=dLayer
dN2=FFN.backward(self.forward.N2[L],L,dFFN,grads)
del dFFN
dAE=RMSNorm.backward(self.forward.AE[L],dN2,L,2,grads) + dLayer
dMHA=dAE
if L>0:
LI=self.forward.layer_output[L-1]
else:
LI=self.forward.E
dN1=MHattention.backward(LI,dMHA,L,grads)
dLayer=RMSNorm.backward(LI,dN1,L,1,grads) + dAE
grads.gradients["we"]=lookup.backward(dLayer,tokens)
def output_tokens(result):
return np.argmax(result,axis=-1)
class inference:
def __init__(self,dmodel,Layers,weights,batches=1,op=None):
self.Layers=Layers
w=weights.weights_dict
self.wl=w["wl"]
self.RMSNorm=TB.RMSNorm(w['g'],w['b'],w['fg'],w['fb'])
self.MHattention=[]
for L in range(Layers):
self.MHattention.append(TB.MHattention(0,batches,w['wq'],w['wk'],w['wv'],w['wo'],op=op,layer=L))
self.FeedForward=TB.FFN(w['wu'],w['wd'],w['bu'],w['bd'])
def __call__(self,E):
layer_input=E
for L in range (self.Layers):
N1=self.RMSNorm(layer_input,L,1)
MHA=self.MHattention[L].forward(N1)
AE=MHA + layer_input
N2=self.RMSNorm(AE,L,2)
FFN=self.FeedForward.forward(N2,L)
layer_input=FFN + AE
Final_Norm=self.RMSNorm(layer_input,-1,3)
projection=Final_Norm @ self.wl
sm=TB.softmax()
result=sm(projection)
return result