uploaded the main transformer code (inference and training)
Browse filesthe inference code is usable on cpu and gpu, but training code requires 2 gpus for running , one for the actual training and the other for the evaluation , You can modify it to run on one gpu (training only) or to run the evaluation on a part of the cpu (i may do that in the future).
the model is already pretrained on wiki-2 dataset which is included in this repo. the model is small (6.9M parameters) and the training data extracted from the dataset is even smaller (5M+ tokens) so the model doesnt have knowledge for meaning but he can generate good english text and text pattern and will always generate wiki style text.
- model/inference.ipynb +106 -0
- model/model_1.py +157 -0
- model/training.ipynb +207 -0
- model/transformer_architecture.svg +115 -0
model/inference.ipynb
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 4,
|
| 6 |
+
"id": "a8fee3d9",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"prompt= Robert Boulter is an English film , television and theatre actor . He had a \n",
|
| 14 |
+
"P=0.9 (for top-p sampling)\n",
|
| 15 |
+
"tokens generated=989 time to generate:5.9e+01s or 0.059s/token\n",
|
| 16 |
+
"response=\n",
|
| 17 |
+
" Robert Boulter is an English film , television and theatre actor . He had a substitution program on the constituen @-@ fed IVO sequence in a number of critics and writer Narson Short . \n",
|
| 18 |
+
" In its original release for their film in Britain , Olivier received the Award nomination that Olivier had lived \" It 's anime story \" , while he felt that he was \" to become an subject for the whole role and the middle of the book \" . Bernstein describes it \" very hyper music as saying that \" I believe Freem , a statement about which someone who explained we had ever received for the script , with my more shirt . \" Mariana Hugh \" and \" Pride ' Mark Jon \" ( 1998 ) \n",
|
| 19 |
+
" \" Olivier in a bit of me so superple ? \" I Am Not Van Prige 's Lookman Jonathan of Heaven 's Conquered business . Watson described himself as \" more moment ' when turn and Gamel To clare ' knight of the young novel with elposure novel \" . He wrote that Olivier \" was much debated from LiSA 's Lotal Register but more than three years , but that his contemporaries had been impressed with the father who told him a mention from Princeton , but she \" won her , on the main dismissal . \" They later added that he wrote that Olivier was \" good of the ' little young hundred \" in which Nesbitt appeared at a kind of two more years , he had given BBC 's Hughes , as Gielgud , be given to keep another version . There was not an hour , but no piece was like the Hugh Master 's Kieft ' Le ' Was ( 1927 ) . However , Shakespe was the same actor , did not want to end his back with rebelled to watch it as an ambitious . Olivier explained his public work of Fear Shakespe , writing that \" [ there ] I was perceived at a kind of powerful books . \" he enjoyed there not the idea of production , when Olivier is able to learn , and that it was only received , but while staging the fabiered tribute . \n",
|
| 20 |
+
" In an interview , Olivier became a young ' actor @-@ director , Olivier liked meals and impersonation about The Walker 's Independent imagery from the Zombian of Olivier 's Sun 's . The only was much the original novel tie and the period provided his first at the time and was not yet the acting Now In 1959 . Richard Olivier was extras for the \n"
|
| 21 |
+
]
|
| 22 |
+
}
|
| 23 |
+
],
|
| 24 |
+
"source": [
|
| 25 |
+
"try:\n",
|
| 26 |
+
" import cupy as np \n",
|
| 27 |
+
" weights_path=\"weights/minweights.pkl\"\n",
|
| 28 |
+
"except:\n",
|
| 29 |
+
" import numpy as np\n",
|
| 30 |
+
" weights_path=\"weights/cpu_trained_weights.pkl\"\n",
|
| 31 |
+
"import sys\n",
|
| 32 |
+
"import model_1 as model\n",
|
| 33 |
+
"sys.path.append('..')\n",
|
| 34 |
+
"import BPE_training as BPE \n",
|
| 35 |
+
"import pickle\n",
|
| 36 |
+
"import embedings as emb\n",
|
| 37 |
+
"import time\n",
|
| 38 |
+
"import os\n",
|
| 39 |
+
"import gc\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"#model stats:\n",
|
| 42 |
+
"layers=6\n",
|
| 43 |
+
"heads=4\n",
|
| 44 |
+
"dmodel=256\n",
|
| 45 |
+
"dk=dmodel//heads\n",
|
| 46 |
+
"batches=1\n",
|
| 47 |
+
"max_seq_len=1024\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"merges=pickle.load(open(\"../datasets/merges.pkl\",\"rb\"))\n",
|
| 50 |
+
"vocab_len=max(merges.values())+1\n",
|
| 51 |
+
"#weights initialisation\n",
|
| 52 |
+
"operation_type=\"inference\" #\"create\" or \"import\" weights or \"inference\"\n",
|
| 53 |
+
"weights=model.weights(None,weights_path,None,None,operation_type)\n",
|
| 54 |
+
"lookup=emb.lookup(weights.weights_dict[\"we\"])\n",
|
| 55 |
+
"inp=input(\"prompt: \")\n",
|
| 56 |
+
"print(f\"prompt={inp}\")\n",
|
| 57 |
+
"tokens=np.array(BPE.encoder(inp,merges))\n",
|
| 58 |
+
"p=0.9\n",
|
| 59 |
+
"print(f\"P={p} (for top-p sampling)\")\n",
|
| 60 |
+
"start=time.time()\n",
|
| 61 |
+
"gen_len=max_seq_len-len(tokens)\n",
|
| 62 |
+
"fp=model.inference(dmodel,layers,weights)\n",
|
| 63 |
+
"out=np.zeros((gen_len,),dtype=np.int32)\n",
|
| 64 |
+
"for i in range(gen_len):\n",
|
| 65 |
+
" E=lookup(tokens)\n",
|
| 66 |
+
" E=E.reshape(1,*E.shape)\n",
|
| 67 |
+
" result=fp(E)[0,-1]\n",
|
| 68 |
+
" sortedargs=np.argsort(result)[::-1]\n",
|
| 69 |
+
" cumsum=np.cumsum(result[sortedargs])\n",
|
| 70 |
+
" sorted_res=result[sortedargs]\n",
|
| 71 |
+
" p_filter=cumsum<=p\n",
|
| 72 |
+
" p_filter[0]=True\n",
|
| 73 |
+
" p_nucleus=sorted_res[p_filter]\n",
|
| 74 |
+
" p_nucleus/=p_nucleus.sum()\n",
|
| 75 |
+
" choice=np.random.choice(sortedargs[:len(p_nucleus)],size=(1,1),p=p_nucleus)\n",
|
| 76 |
+
" out[i]=(choice.flatten()[0])\n",
|
| 77 |
+
" tokens=choice[0]\n",
|
| 78 |
+
" gc.collect()\n",
|
| 79 |
+
"inp+=BPE.decoder(out,merges)\n",
|
| 80 |
+
"print(f\"tokens generated={gen_len} time to generate:{time.time()-start:.2}s or {(time.time()-start)/gen_len:.2}s/token\")\n",
|
| 81 |
+
"print(f\"response=\\n {inp}\")"
|
| 82 |
+
]
|
| 83 |
+
}
|
| 84 |
+
],
|
| 85 |
+
"metadata": {
|
| 86 |
+
"kernelspec": {
|
| 87 |
+
"display_name": "Python 3",
|
| 88 |
+
"language": "python",
|
| 89 |
+
"name": "python3"
|
| 90 |
+
},
|
| 91 |
+
"language_info": {
|
| 92 |
+
"codemirror_mode": {
|
| 93 |
+
"name": "ipython",
|
| 94 |
+
"version": 3
|
| 95 |
+
},
|
| 96 |
+
"file_extension": ".py",
|
| 97 |
+
"mimetype": "text/x-python",
|
| 98 |
+
"name": "python",
|
| 99 |
+
"nbconvert_exporter": "python",
|
| 100 |
+
"pygments_lexer": "ip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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
import cupy as np
|
| 3 |
+
except:
|
| 4 |
+
import numpy as np
|
| 5 |
+
import sys
|
| 6 |
+
import os
|
| 7 |
+
sys.path.append("..")
|
| 8 |
+
import transformer_block as TB
|
| 9 |
+
import pickle
|
| 10 |
+
class gradient:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.gradients={}
|
| 13 |
+
class weights:
|
| 14 |
+
def __init__(self,weights_shapes,file_path,step,opt_path,operation="import"):
|
| 15 |
+
if operation!="inference":
|
| 16 |
+
self.adam=TB.adam(weights_shapes)
|
| 17 |
+
if operation=="create":
|
| 18 |
+
self.weights_dict={}
|
| 19 |
+
self.step=0
|
| 20 |
+
for weight,shape in weights_shapes.items():
|
| 21 |
+
if "b" in weight:
|
| 22 |
+
self.weights_dict[weight]=np.zeros(shape,dtype=np.float32)
|
| 23 |
+
elif "g" in weight:
|
| 24 |
+
self.weights_dict[weight]=np.ones(shape,dtype=np.float32)
|
| 25 |
+
else:
|
| 26 |
+
self.weights_dict[weight]=np.random.randn(*shape).astype(np.float32) * np.sqrt(2/shape[-1])
|
| 27 |
+
self.save(file_path,opt_path,step)
|
| 28 |
+
elif operation=="import":
|
| 29 |
+
self.weights_dict=pickle.load(open(file_path,"rb"))
|
| 30 |
+
infos=pickle.load(open(opt_path,"rb"))
|
| 31 |
+
self.step=infos["step"]
|
| 32 |
+
self.adam.m=infos["m"]
|
| 33 |
+
self.adam.v=infos["v"]
|
| 34 |
+
elif operation=="inference":
|
| 35 |
+
self.weights_dict=pickle.load(open(file_path,"rb"))
|
| 36 |
+
|
| 37 |
+
def batches_average_and_clip(self,grads,max_norm=1.0):
|
| 38 |
+
for weight in grads.keys():
|
| 39 |
+
if weight not in {"we","wq","wk","wv"}:
|
| 40 |
+
grads[weight]=grads[weight].sum(axis=-3)
|
| 41 |
+
Gnorm=np.linalg.norm(np.array([np.linalg.norm(g) for g in grads.values()]))
|
| 42 |
+
if Gnorm>max_norm:
|
| 43 |
+
for weight in grads.keys():
|
| 44 |
+
grads[weight]*=(max_norm/Gnorm)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def update(self,grads,lr,step,eps=1e-5):
|
| 48 |
+
B=self.adam.B
|
| 49 |
+
self.adam(grads,step)
|
| 50 |
+
for weight in self.weights_dict.keys():
|
| 51 |
+
self.weights_dict[weight]-=(lr*(self.adam.m[weight]/(1-B[0]**step)))/((np.sqrt(self.adam.v[weight]/(1-B[1]**step)))+eps)
|
| 52 |
+
#self.weights_dict[weight]-=lr*grads[weight]
|
| 53 |
+
|
| 54 |
+
def save(self,file_path,opt_path,step):
|
| 55 |
+
pickle.dump(self.weights_dict,open(file_path,"wb"))
|
| 56 |
+
pickle.dump({"m":self.adam.m,"v":self.adam.v,"step":step},open(opt_path,"wb"))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class forward:
|
| 60 |
+
def __init__(self,seq_len,dmodel,Layers,batches,weights,grads,op="training"):
|
| 61 |
+
self.Layers=Layers
|
| 62 |
+
w=weights.weights_dict
|
| 63 |
+
self.wl=w["wl"]
|
| 64 |
+
self.RMSNorm=TB.RMSNorm(w['g'],w['b'],w['fg'],w['fb'],batches,grads,op)
|
| 65 |
+
self.MHattention=TB.MHattention(seq_len,batches,w['wq'],w['wk'],w['wv'],w['wo'],grads,op)
|
| 66 |
+
self.FeedForward=TB.FFN(w['wu'],w['wd'],w['bu'],w['bd'],batches,grads,op)
|
| 67 |
+
self.N1=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 68 |
+
self.MHA=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 69 |
+
self.AE=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 70 |
+
self.N2=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 71 |
+
self.FFN=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 72 |
+
self.layer_output=np.zeros((Layers,batches,seq_len,dmodel),dtype=np.float32)
|
| 73 |
+
|
| 74 |
+
def __call__(self,E):
|
| 75 |
+
self.E=E
|
| 76 |
+
layer_input=E
|
| 77 |
+
for L in range (self.Layers):
|
| 78 |
+
self.N1[L]=self.RMSNorm(layer_input,L,1)
|
| 79 |
+
self.MHA[L]=self.MHattention.forward(self.N1[L],L)
|
| 80 |
+
self.AE[L]=self.MHA[L] + layer_input
|
| 81 |
+
self.N2[L]=self.RMSNorm(self.AE[L],L,2)
|
| 82 |
+
self.FFN[L]=self.FeedForward.forward(self.N2[L],L)
|
| 83 |
+
self.layer_output[L]=self.FFN[L] + self.AE[L]
|
| 84 |
+
layer_input=self.layer_output[L]
|
| 85 |
+
self.Final_Norm=self.RMSNorm(layer_input,-1,3)
|
| 86 |
+
projection=self.Final_Norm @ self.wl
|
| 87 |
+
sm=TB.softmax()
|
| 88 |
+
result=sm(projection)
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class backward:
|
| 94 |
+
def __init__(self,forward):
|
| 95 |
+
self.forward=forward
|
| 96 |
+
self.Layers=forward.Layers
|
| 97 |
+
|
| 98 |
+
def __call__(self,batches,lookup,grads,tokens,result,output_indices,weights):
|
| 99 |
+
w=weights.weights_dict
|
| 100 |
+
RMSNorm=self.forward.RMSNorm
|
| 101 |
+
MHattention=self.forward.MHattention
|
| 102 |
+
FFN=self.forward.FeedForward
|
| 103 |
+
SM=TB.softmax()
|
| 104 |
+
result[*output_indices]-=1
|
| 105 |
+
dprojection=(result) / (batches*result.shape[1])
|
| 106 |
+
del result
|
| 107 |
+
dFN=dprojection @ w["wl"].T
|
| 108 |
+
grads.gradients["wl"]=self.forward.Final_Norm.swapaxes(-1,-2) @ dprojection
|
| 109 |
+
del dprojection
|
| 110 |
+
dLayer=RMSNorm.backward(self.forward.layer_output[self.Layers-1],dFN,-1,3,grads)
|
| 111 |
+
del dFN
|
| 112 |
+
for L in range (self.Layers-1,-1,-1):
|
| 113 |
+
dFFN=dLayer
|
| 114 |
+
dN2=FFN.backward(self.forward.N2[L],L,dFFN,grads)
|
| 115 |
+
del dFFN
|
| 116 |
+
dAE=RMSNorm.backward(self.forward.AE[L],dN2,L,2,grads) + dLayer
|
| 117 |
+
dMHA=dAE
|
| 118 |
+
if L>0:
|
| 119 |
+
LI=self.forward.layer_output[L-1]
|
| 120 |
+
else:
|
| 121 |
+
LI=self.forward.E
|
| 122 |
+
dN1=MHattention.backward(LI,dMHA,L,grads)
|
| 123 |
+
dLayer=RMSNorm.backward(LI,dN1,L,1,grads) + dAE
|
| 124 |
+
grads.gradients["we"]=lookup.backward(dLayer,tokens)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def output_tokens(result):
|
| 130 |
+
return np.argmax(result,axis=-1)
|
| 131 |
+
|
| 132 |
+
class inference:
|
| 133 |
+
def __init__(self,dmodel,Layers,weights,batches=1,op=None):
|
| 134 |
+
self.Layers=Layers
|
| 135 |
+
w=weights.weights_dict
|
| 136 |
+
self.wl=w["wl"]
|
| 137 |
+
self.RMSNorm=TB.RMSNorm(w['g'],w['b'],w['fg'],w['fb'])
|
| 138 |
+
self.MHattention=[]
|
| 139 |
+
for L in range(Layers):
|
| 140 |
+
self.MHattention.append(TB.MHattention(0,batches,w['wq'],w['wk'],w['wv'],w['wo'],op=op,layer=L))
|
| 141 |
+
self.FeedForward=TB.FFN(w['wu'],w['wd'],w['bu'],w['bd'])
|
| 142 |
+
|
| 143 |
+
def __call__(self,E):
|
| 144 |
+
layer_input=E
|
| 145 |
+
for L in range (self.Layers):
|
| 146 |
+
N1=self.RMSNorm(layer_input,L,1)
|
| 147 |
+
MHA=self.MHattention[L].forward(N1)
|
| 148 |
+
AE=MHA + layer_input
|
| 149 |
+
N2=self.RMSNorm(AE,L,2)
|
| 150 |
+
FFN=self.FeedForward.forward(N2,L)
|
| 151 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "9a9c2b2f",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"#training the merges (vocabulary: Byte Pair Encoding) on a dataset\n",
|
| 11 |
+
"try:\n",
|
| 12 |
+
" import cupy as np \n",
|
| 13 |
+
"except:\n",
|
| 14 |
+
" import numpy as np\n",
|
| 15 |
+
"import pickle\n",
|
| 16 |
+
"sys.path.append('..')\n",
|
| 17 |
+
"import BPE_training as BPE\n",
|
| 18 |
+
"merges_save_path=\"../datasets/merges.pkl\"\n",
|
| 19 |
+
"dataset_path=\"../datasets/wikitext-2-raw/wiki.train.raw\"\n",
|
| 20 |
+
"merges_number=4000 #vocabulary size will be merges_number+256\n",
|
| 21 |
+
"BPE.train(dataset_path,merges_number,merges_save_path)"
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"id": "fbc810a0",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"outputs": [],
|
| 30 |
+
"source": [
|
| 31 |
+
"#tokenizing the training and the evaluating data if not already tokenized and saving it in training/validation_tokens.pkl\n",
|
| 32 |
+
"try:\n",
|
| 33 |
+
" import cupy as np \n",
|
| 34 |
+
"except:\n",
|
| 35 |
+
" import numpy as np\n",
|
| 36 |
+
"import pickle\n",
|
| 37 |
+
"sys.path.append('..')\n",
|
| 38 |
+
"import BPE_training as BPE\n",
|
| 39 |
+
"merges_path=\"../datasets/merges.pkl\"\n",
|
| 40 |
+
"validation_data_path=\"../datasets/wikitext-2-raw/wiki.valid.raw\"\n",
|
| 41 |
+
"training_data_path=\"../datasets/wikitext-2-raw/wiki.train.raw\"\n",
|
| 42 |
+
"with open(merges_path,\"rb\") as f: \n",
|
| 43 |
+
" merges=pickle.load(f)\n",
|
| 44 |
+
"with open(training_data_path,\"r\") as f:\n",
|
| 45 |
+
" training_text = f.read()\n",
|
| 46 |
+
"with open(validation_data_path,\"r\") as f:\n",
|
| 47 |
+
" validation_text = f.read()\n",
|
| 48 |
+
"pickle.dump(BPE.encoder(training_text,merges),open(\"../datasets/wikitext-2-raw/training_tokens.pkl\",\"wb\"))\n",
|
| 49 |
+
"pickle.dump(BPE.encoder(validation_text,merges),open(\"../datasets/wikitext-2-raw/validation_tokens.pkl\",\"wb\"))\n"
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"id": "41245672",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"outputs": [],
|
| 58 |
+
"source": [
|
| 59 |
+
"try:\n",
|
| 60 |
+
" import cupy as np \n",
|
| 61 |
+
"except:\n",
|
| 62 |
+
" import numpy as np\n",
|
| 63 |
+
"#the training works on dual Nvidia GPUs one for the training and one for evaluation\n",
|
| 64 |
+
"import sys\n",
|
| 65 |
+
"import model_1 as model\n",
|
| 66 |
+
"sys.path.append('..')\n",
|
| 67 |
+
"import BPE_training as BPE \n",
|
| 68 |
+
"import pickle\n",
|
| 69 |
+
"import embedings as emb\n",
|
| 70 |
+
"import time\n",
|
| 71 |
+
"import os\n",
|
| 72 |
+
"import gc\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"#model stats:\n",
|
| 75 |
+
"layers=6\n",
|
| 76 |
+
"heads=4\n",
|
| 77 |
+
"dmodel=256\n",
|
| 78 |
+
"dk=dmodel//heads\n",
|
| 79 |
+
"batches=16\n",
|
| 80 |
+
"seq_len=1025\n",
|
| 81 |
+
"merges=pickle.load(open(\"../datasets/merges.pkl\",\"rb\"))\n",
|
| 82 |
+
"vocab_len=max(merges.values())+1\n",
|
| 83 |
+
"#weights initialisation\n",
|
| 84 |
+
"weights_shapes={\n",
|
| 85 |
+
" \"we\":(vocab_len,dmodel),\n",
|
| 86 |
+
" \"wk\":(layers,heads,dmodel,dk),\n",
|
| 87 |
+
" \"wq\":(layers,heads,dmodel,dk),\n",
|
| 88 |
+
" \"wv\":(layers,heads,dmodel,dk),\n",
|
| 89 |
+
" \"wo\":(layers,dmodel,dmodel),\n",
|
| 90 |
+
" \"wu\":(layers,dmodel,dmodel*4),\n",
|
| 91 |
+
" \"wd\":(layers,dmodel*4,dmodel),\n",
|
| 92 |
+
" \"wl\":(dmodel,vocab_len),\n",
|
| 93 |
+
" \"bu\":(layers,1,dmodel*4),\n",
|
| 94 |
+
" \"bd\":(layers,1,dmodel),\n",
|
| 95 |
+
" \"g\":(layers,2,dmodel),\n",
|
| 96 |
+
" \"fg\":(1,dmodel),\n",
|
| 97 |
+
" \"b\":(layers,2,dmodel),\n",
|
| 98 |
+
" \"fb\":(1,dmodel)\n",
|
| 99 |
+
"}#{weight:shape}\n",
|
| 100 |
+
"operation_type=\"create\" #\"create\" or \"import\" weights \n",
|
| 101 |
+
"weights=model.weights(weights_shapes,\"weights/weights.pkl\",0,\"weights/adam_weights.pkl\",operation_type)\n",
|
| 102 |
+
"if operation_type==\"create\":\n",
|
| 103 |
+
" print(\"weights created\")\n",
|
| 104 |
+
"step=weights.step\n",
|
| 105 |
+
"warm_up_steps=2000\n",
|
| 106 |
+
"total_params = sum(np.prod(np.array(shape)) for shape in weights_shapes.values())\n",
|
| 107 |
+
"print(f\"total params={total_params:,}\\nvocab_len={vocab_len}\\ndmodel={dmodel},heads={heads},layers={layers}\")\n",
|
| 108 |
+
"saved_embedings=True\n",
|
| 109 |
+
"lookup=emb.lookup(weights.weights_dict[\"we\"])\n",
|
| 110 |
+
"#embeding\n",
|
| 111 |
+
"embedings=emb.embeding_data(\"../datasets/wikitext-2-raw/training_tokens.pkl\",saved_embedings)\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"data=embedings.tokens\n",
|
| 114 |
+
"batched_data=np.array(data[:(seq_len+1)*(len(data)//(seq_len+1))]).reshape(-1,seq_len+1)\n",
|
| 115 |
+
"print(f\"total batches={batched_data.shape[0]}\")\n",
|
| 116 |
+
"batches_indices=np.arange(batched_data.shape[0])\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"with np.cuda.Device(1):\n",
|
| 120 |
+
" eval_batches=32\n",
|
| 121 |
+
" embedings2=emb.embeding_data(\"../datasets/wikitext-2-raw/validation_tokens.pkl\",saved_embedings)\n",
|
| 122 |
+
" evaldata=embedings2.tokens\n",
|
| 123 |
+
" batched_eval_data=(np.array(evaldata[:(seq_len+1)*(len(evaldata)//(seq_len+1))]).reshape(-1,seq_len+1))[:eval_batches]\n",
|
| 124 |
+
" print(f\"eval batches={batched_eval_data.shape[0]}\")\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"min_eval_loss=100\n",
|
| 128 |
+
"start=time.time()\n",
|
| 129 |
+
"while step<((batched_data.shape[0]//batches)*25+1):\n",
|
| 130 |
+
" if step%(batched_data.shape[0]//batches)==0:\n",
|
| 131 |
+
" np.random.shuffle(batches_indices)\n",
|
| 132 |
+
" i=0\n",
|
| 133 |
+
" step_indices=batches_indices[i:i+batches]\n",
|
| 134 |
+
" i+=batches\n",
|
| 135 |
+
" tokens=batched_data[step_indices]\n",
|
| 136 |
+
" E=lookup(tokens[:,:-1])\n",
|
| 137 |
+
" output_indices=[np.arange(batches)[:,None],np.arange(seq_len),tokens[:,1:]]\n",
|
| 138 |
+
" if len(E.shape)<3:\n",
|
| 139 |
+
" E=E.reshape(batches,*E.shape)\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" #gradients storage\n",
|
| 143 |
+
" grads=model.gradient()\n",
|
| 144 |
+
" #forward pass\n",
|
| 145 |
+
" fp=model.forward(seq_len,dmodel,layers,batches,weights,grads)\n",
|
| 146 |
+
" result=fp(E)\n",
|
| 147 |
+
" #loss calculation (loss per token)\n",
|
| 148 |
+
" if step%(batched_data.shape[0]//batches) == 0:\n",
|
| 149 |
+
" loss=-np.sum(np.log(result[np.arange(batches)[:,None],np.arange(seq_len),tokens[:,1:]])) / (batches*seq_len)\n",
|
| 150 |
+
" print(f\"training_loss={loss} , step={step},time={ (time.time()-start)//60}m and {(time.time()-start)%60:.3}s \")\n",
|
| 151 |
+
" with np.cuda.Device(1):\n",
|
| 152 |
+
" class W:\n",
|
| 153 |
+
" def __init__(self,ws):\n",
|
| 154 |
+
" self.weights_dict={k:np.asarray(v) for k,v in weights.weights_dict.items()}\n",
|
| 155 |
+
" weights2=W(weights)\n",
|
| 156 |
+
" lookup2=emb.lookup(weights2.weights_dict[\"we\"])\n",
|
| 157 |
+
" fp2=model.inference(dmodel,layers,weights2,eval_batches,op=\"evaluation\")\n",
|
| 158 |
+
" tokens2=batched_eval_data\n",
|
| 159 |
+
" E2=lookup2(tokens2[:,:-1])\n",
|
| 160 |
+
" result2=fp2(E2)\n",
|
| 161 |
+
" loss2=-np.sum(np.log(result2[np.arange(eval_batches)[:,None],np.arange(seq_len),tokens2[:,1:]])) / (eval_batches*seq_len)\n",
|
| 162 |
+
" del fp2\n",
|
| 163 |
+
" gc.collect()\n",
|
| 164 |
+
" np.get_default_memory_pool().free_all_blocks()\n",
|
| 165 |
+
" print(f\"eval_loss={loss2} , step={step},time={ (time.time()-start)//60}m and {(time.time()-start)%60:.3}s \")\n",
|
| 166 |
+
" l=float(loss2)\n",
|
| 167 |
+
" if l<min_eval_loss and step!=0:\n",
|
| 168 |
+
" weights.save(\"weights/minweights.pkl\",\"weights/minadam_weights.pkl\",step)\n",
|
| 169 |
+
" min_eval_loss=l\n",
|
| 170 |
+
" if step!=0:\n",
|
| 171 |
+
" weights.save(\"weights/weights.pkl\",\"weights/adam_weights.pkl\",step)\n",
|
| 172 |
+
" step+=1\n",
|
| 173 |
+
" bp=model.backward(fp)\n",
|
| 174 |
+
" lr=(dmodel**-0.5)*min((step**-0.5),step*(warm_up_steps**-1.5))\n",
|
| 175 |
+
" bp(batches,lookup,grads,tokens[:,:-1],result,output_indices,weights)\n",
|
| 176 |
+
" weights.batches_average_and_clip(grads.gradients)\n",
|
| 177 |
+
" weights.update(grads.gradients,lr,step)\n",
|
| 178 |
+
" del fp\n",
|
| 179 |
+
" del bp\n",
|
| 180 |
+
" del grads\n",
|
| 181 |
+
" gc.collect()\n",
|
| 182 |
+
" np.get_default_memory_pool().free_all_blocks()"
|
| 183 |
+
]
|
| 184 |
+
}
|
| 185 |
+
],
|
| 186 |
+
"metadata": {
|
| 187 |
+
"kernelspec": {
|
| 188 |
+
"display_name": "Python 3",
|
| 189 |
+
"language": "python",
|
| 190 |
+
"name": "python3"
|
| 191 |
+
},
|
| 192 |
+
"language_info": {
|
| 193 |
+
"codemirror_mode": {
|
| 194 |
+
"name": "ipython",
|
| 195 |
+
"version": 3
|
| 196 |
+
},
|
| 197 |
+
"file_extension": ".py",
|
| 198 |
+
"mimetype": "text/x-python",
|
| 199 |
+
"name": "python",
|
| 200 |
+
"nbconvert_exporter": "python",
|
| 201 |
+
"pygments_lexer": "ipython3",
|
| 202 |
+
"version": "3.13.5"
|
| 203 |
+
}
|
| 204 |
+
},
|
| 205 |
+
"nbformat": 4,
|
| 206 |
+
"nbformat_minor": 5
|
| 207 |
+
}
|
model/transformer_architecture.svg
ADDED
|
|