File size: 6,114 Bytes
36c8734
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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