Download transformer_block.py from hunterfiras/model_1: direct link, hf CLI and curl.
- Browser
- Download file 9.82 kB
-
https://huggingface.co/hunterfiras/model_1/resolve/main/transformer_block.py
- Command line
-
hf download hf://hunterfiras/model_1/transformer_block.py
-
curl -L -o transformer_block.py https://huggingface.co/hunterfiras/model_1/resolve/main/transformer_block.py
9.82 kB
| try: | |
| import cupy as np | |
| except: | |
| import numpy as np | |
| import embedings as em | |
| class softmax: | |
| def __init__(self): | |
| pass | |
| def __call__(self,x): | |
| m=np.max(x,axis=-1,keepdims=True) | |
| exp=np.exp(x-m) | |
| return exp / np.sum(exp,axis=-1,keepdims=True) | |
| def backward(self,dSM,SM): | |
| return SM * (dSM - np.sum(dSM * SM,axis=-1,keepdims=True)) | |
| def RELU(x): | |
| return x * (x>0) | |
| class MHattention: | |
| def __init__(self,seq_len,batches,wq,wk,wv,wo,grads=None,op=None,layer=None): | |
| """normal MHA attention from "attention is all you need" paper with KV cache for inference | |
| Note:set seq_len to 0 and batches to 1 for inference | |
| 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) | |
| if op and grads left default it will be considered for inference | |
| for training pass the grads dict and set op='training'""" | |
| self.wq=wq | |
| self.wk=wk | |
| self.wv=wv | |
| self.wo=wo | |
| layers=wv.shape[0] | |
| heads=wv.shape[1] ; dmodel=wv.shape[2] ; self.dk=wv.shape[3] | |
| self.heads=heads | |
| self.layer=layer | |
| self.training=(op=="training") | |
| self.eval=(op=="evaluation") | |
| if self.training: | |
| grads.gradients["wq"]=np.zeros((layers,*wq.shape[1:]),dtype=np.float32) | |
| grads.gradients["wk"]=np.zeros((layers,*wk.shape[1:]),dtype=np.float32) | |
| grads.gradients["wv"]=np.zeros((layers,*wv.shape[1:]),dtype=np.float32) | |
| grads.gradients["wo"]=np.zeros((layers,batches,*wo.shape[1:]),dtype=np.float32) | |
| self.V=np.zeros((layers,batches,heads,seq_len,self.dk),dtype=np.float32) | |
| self.RQ=np.zeros((layers,batches,heads,seq_len,self.dk),dtype=np.float32) | |
| self.RK=np.zeros((layers,batches,heads,seq_len,self.dk),dtype=np.float32) | |
| self.SM=np.zeros((layers,batches,heads,seq_len,seq_len),dtype=np.float32) | |
| self.con=np.zeros((layers,batches,seq_len,dmodel),dtype=np.float32) | |
| self.RoPE=em.RoPE(self.dk,seq_len) | |
| else: | |
| self.V=np.empty((batches,heads,0,self.dk),dtype=np.float32) | |
| self.RK=np.empty((batches,heads,0,self.dk),dtype=np.float32) | |
| self.pos=0 | |
| def forward(self,E,L=None): | |
| """for training you must set L as the layer number | |
| for inference the instance has already the layer number as self.layer """ | |
| if self.training: | |
| Q=E[:,None,:,:] @ self.wq[L] | |
| K=E[:,None,:,:] @ self.wk[L] | |
| self.V[L]=E[:,None,:,:] @ self.wv[L] | |
| self.RQ[L]=self.RoPE(Q) | |
| self.RK[L]=self.RoPE(K) | |
| score=(self.RQ[L] @ np.swapaxes(self.RK[L],-2,-1))* (1/self.dk) | |
| score[:,:,*np.triu_indices(score.shape[2],1)]=-1e10 #masking the attention score | |
| sm=softmax() | |
| self.SM[L]=sm(score) | |
| As=self.SM[L] @ self.V[L] | |
| self.con[L]=As.swapaxes(1,2).reshape((Q.shape[0],Q.shape[2],Q.shape[1]*Q.shape[3])) | |
| A=self.con[L] @ self.wo[L] | |
| else: | |
| L=self.layer | |
| if self.RK.shape[-2]==0: | |
| Rp=em.RoPE(self.dk,seq_len=E.shape[-2]) | |
| self.pos+=E.shape[-2] | |
| else: | |
| Rp=em.RoPE(self.dk,pos=self.pos) | |
| self.pos+=1 | |
| Q=E[:,None,:,:] @ self.wq[L] | |
| nK=E[:,None,:,:] @ self.wk[L] | |
| nV=E[:,None,:,:] @ self.wv[L] | |
| self.V=np.append(self.V,nV,axis=-2) | |
| nRK=Rp(nK) | |
| self.RK=np.append(self.RK,nRK,axis=-2) | |
| if self.eval: | |
| RQ=Rp(Q) | |
| score=(RQ @ np.swapaxes(self.RK,-2,-1))* (1/self.dk) | |
| score[:,:,*np.triu_indices(score.shape[2],1)]=-1e10 #masking the attention score | |
| else: | |
| RQ=Rp(Q)[-1] | |
| score=(RQ @ np.swapaxes(self.RK,-2,-1))* (1/self.dk) | |
| sm=softmax() | |
| As=sm(score) @ self.V | |
| con=As.swapaxes(1,2).reshape((Q.shape[0],Q.shape[2],Q.shape[1]*Q.shape[3])) | |
| A=con @ self.wo[L] | |
| return A | |
| def backward(self,E,dMHA,L,grads): | |
| dcon=dMHA @ self.wo[L].swapaxes(-1,-2) | |
| dAs=np.array(np.split(dcon,self.heads,axis=-1)).swapaxes(0,1) | |
| dSM=dAs @ self.V[L].swapaxes(-1,-2) | |
| sm=softmax() | |
| dscore=sm.backward(dSM,self.SM[L]) | |
| dRQ=(1/self.dk) * (dscore @ self.RK[L]) | |
| dRK=(1/self.dk) * (dscore.swapaxes(-1,-2) @ self.RQ[L]) | |
| dQ=self.RoPE.backward(dRQ) | |
| dK=self.RoPE.backward(dRK) | |
| dV=self.SM[L].swapaxes(-1,-2) @ dAs | |
| dEq=dQ @ self.wq[L].swapaxes(-1,-2) | |
| dEk=dK @ self.wk[L].swapaxes(-1,-2) | |
| dEv=dV @ self.wv[L].swapaxes(-1,-2) | |
| dE=(dEq + dEk + dEv).sum(axis=1) | |
| grads.gradients["wq"][L]=(E[:,None,:,:].swapaxes(-1,-2) @ dQ).sum(axis=0) | |
| grads.gradients["wk"][L]=(E[:,None,:,:].swapaxes(-1,-2) @ dK).sum(axis=0) | |
| grads.gradients["wv"][L]=(E[:,None,:,:].swapaxes(-1,-2) @ dV).sum(axis=0) | |
| grads.gradients["wo"][L]=self.con[L].swapaxes(-1,-2) @ dMHA | |
| return dE | |
| class RMSNorm: | |
| """RMSNorm (Root mean square normalisation) | |
| here I passed g (gamma) and b (beta) as matrices that has all the gammas and betas of all layers and normalization steps | |
| L:Layer , n:the part you will do prenorm for (n=1 : attention ;; n=2: feed forward) | |
| fg and fb are the paremeters for the last normalization after all the transformer block layers before the linear operation | |
| i havent included them in g and b for memory efficiency | |
| just pass n==3 in the call parameters for the last norm | |
| """ | |
| def __init__ (self,g,b,fg,fb,batches=None,grads=None,op=None): | |
| self.g=g | |
| self.b=b | |
| self.fg=fg | |
| self.fb=fb | |
| layers=g.shape[0] | |
| if op=="training": | |
| grads.gradients["g"]=np.zeros((layers,batches,2,g.shape[-1]),dtype=np.float32) | |
| grads.gradients["b"]=np.zeros((layers,batches,2,b.shape[-1]),dtype=np.float32) | |
| def RMS(self,x): | |
| return np.sqrt((1/x.shape[-1]) * np.sum(x**2,axis=-1,keepdims=True)) | |
| def __call__(self,x,L,n): | |
| if n==3: | |
| return (x/self.RMS(x)) * self.fg + self.fb | |
| else: | |
| return (x/self.RMS(x)) * self.g[L,n-1] + self.b[L,n-1] | |
| def backward(self,x,dN,L,n,grads): | |
| rms=self.RMS(x) | |
| if n==3: | |
| g=self.fg | |
| b=self.fb | |
| grads.gradients["fg"]=(dN * (x/rms)).sum(axis=1,keepdims=True,dtype=np.float32) | |
| grads.gradients["fb"]=dN.sum(axis=1,keepdims=True,dtype=np.float32) | |
| else: | |
| g=self.g[L,n-1] | |
| b=self.b[L,n-1] | |
| grads.gradients["g"][L,:,n-1]=(dN * (x/rms)).sum(axis=1) | |
| grads.gradients["b"][L,:,n-1]=dN.sum(axis=1) | |
| S=np.sum(x**2,axis=-1,keepdims=True) | |
| dx= (dN/rms)*g-(x/(S*rms))*np.sum(dN*g*x,axis=-1,keepdims=True) | |
| return dx | |
| class FFN: | |
| def __init__(self,wu,wd,bu,bd,batches=None,grads=None,op=None): | |
| self.wu=wu | |
| self.wd=wd | |
| self.bu=bu | |
| self.bd=bd | |
| layers=wu.shape[0] | |
| self.training=(op=="training") | |
| if self.training: | |
| grads.gradients["wu"]=np.zeros((layers,batches,*wu.shape[1:]),dtype=np.float32) | |
| grads.gradients["wd"]=np.zeros((layers,batches,*wd.shape[1:]),dtype=np.float32) | |
| grads.gradients["bu"]=np.zeros((layers,batches,*bu.shape[1:]),dtype=np.float32) | |
| grads.gradients["bd"]=np.zeros((layers,batches,*bd.shape[1:]),dtype=np.float32) | |
| def forward(self,x,L): | |
| xu=x @ self.wu[L] + self.bu[L] | |
| if self.training: | |
| self.activation=np.zeros((self.wu.shape[0],*xu.shape)) | |
| self.activation[L]=RELU(xu) | |
| xd=self.activation[L] @ self.wd[L] + self.bd[L] | |
| else: | |
| xd=RELU(xu) @ self.wd[L] + self.bd[L] | |
| return xd | |
| def backward(self,FFN_input,L,dFFN,grads): | |
| dactivation= dFFN @ self.wd[L].swapaxes(-1,-2) | |
| dxu=dactivation * (self.activation[L]>0) | |
| dx=dxu @ self.wu[L].swapaxes(-1,-2) | |
| grads.gradients["wu"][L]=(FFN_input.swapaxes(-1,-2) @ dxu) | |
| grads.gradients["wd"][L]=(self.activation[L].swapaxes(-1,-2) @ dFFN) | |
| grads.gradients["bu"][L]=np.sum(dxu,axis=-2,keepdims=True) | |
| grads.gradients["bd"][L]=np.sum(dFFN,axis=-2,keepdims=True) | |
| return dx | |
| class adam: | |
| """adam optimizer""" | |
| def __init__(self,weights_shapes,B=None): | |
| """weights_shapes is a dict with the format {weight_name:shape} | |
| 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 | |
| initializing the class create automatically the moment vectors and sets them to 0 for all weights | |
| """ | |
| self.m={} | |
| self.v={} | |
| if B is None: | |
| B=np.array([0.9,0.999]) | |
| self.B=B | |
| for weight,shape in weights_shapes.items(): | |
| self.m[weight]=np.zeros(shape).astype(np.float32) | |
| self.v[weight]=np.zeros(shape).astype(np.float32) | |
| def moment_hat(self,m,g,power,step): | |
| """this function calculates the moment vector for adam optimizer | |
| use this same function to creat both moments (m and v) | |
| to calculate m set the power to 1 | |
| to calculate g set the power to 2 | |
| """ | |
| m_new=self.B[power-1] * m + (1-self.B[power-1]) * (g**power) | |
| return m_new | |
| def __call__(self,grads,step): | |
| "calling the instance will update the moment vectors for the step for all weights" | |
| for weight in grads.keys(): | |
| self.m[weight]=self.moment_hat(self.m[weight],grads[weight],1,step) | |
| self.v[weight]=self.moment_hat(self.v[weight],grads[weight],2,step) | |