├── cover.png ├── src ├── readme.md ├── pitresults │ └── readme.md ├── traindata │ └── readme.md ├── ENCODER16k.cs ├── NNSampler.cpp ├── NN_Mokka.h └── Train.ipynb ├── images ├── simplemodel.jpg └── CGZero_Diagram.png ├── old_uncleaned_code ├── readme.md ├── ENCODER16k.cs ├── NNSampler.cpp └── NN_Mokka.h ├── README.md ├── techio.yml ├── markdowns ├── welcome.md ├── intro.md ├── final.md ├── differences.md ├── environment.md └── glossary.md └── LICENSE /cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marchete/CGZero/HEAD/cover.png -------------------------------------------------------------------------------- /src/readme.md: -------------------------------------------------------------------------------- 1 | Source code for CGZero. 2 | 3 | More info at /markdown folder -------------------------------------------------------------------------------- /images/simplemodel.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marchete/CGZero/HEAD/images/simplemodel.jpg -------------------------------------------------------------------------------- /images/CGZero_Diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marchete/CGZero/HEAD/images/CGZero_Diagram.png -------------------------------------------------------------------------------- /src/pitresults/readme.md: -------------------------------------------------------------------------------- 1 | Folder for winrates. 2 | 3 | If you are restarting the training from scratch, remove all `Pit_*.txt` files -------------------------------------------------------------------------------- /src/traindata/readme.md: -------------------------------------------------------------------------------- 1 | Folder for samples. I tweaked it to be a symlink to a shared memory folder `/dev/shm/traindata`. This way file IO is faster, but you'll lose all the samples data if you forget to save them to a real folder. 2 | 3 | If you are restarting the training from scratch, remove all `*.dat` files 4 | -------------------------------------------------------------------------------- /old_uncleaned_code/readme.md: -------------------------------------------------------------------------------- 1 | This is the code I used to get the 6th place bot. I've changed a lot of parameters and code while training the bot, so I can't be sure what was the good hyperparameters for reaching top10. 2 | Trained bots should be similar in strength. Cleaned code has added diversity on first turns, it should be less blind to some moves. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CGZero 2 | AlphaZero like implementation for Oware abapa game, in Codingame (https://www.codingame.com/multiplayer/bot-programming/oware-abapa) 3 | 4 | See https://tech.io/playgrounds/58137/alphazero-like-implementation-for-oware-abapa-game-codingame/alphazero-like-implementation-for-oware-abapa-game 5 | 6 | or https://github.com/marchete/CGZero/tree/master/markdowns for more info. 7 | -------------------------------------------------------------------------------- /techio.yml: -------------------------------------------------------------------------------- 1 | title : AlphaZero like implementation for Oware Abapa game (Codingame) 2 | plan: 3 | - title: "AlphaZero like implementation for Oware Abapa game" 4 | statement: markdowns/welcome.md 5 | - title: "Introduction" 6 | statement: markdowns/intro.md 7 | - title: "Glossary" 8 | statement: markdowns/glossary.md 9 | - title: "Differences between CGZero and Alphazero" 10 | statement: markdowns/differences.md 11 | - title: "Environment Preparation" 12 | statement: markdowns/environment.md 13 | - title: "Final words" 14 | statement: markdowns/final.md 15 | -------------------------------------------------------------------------------- /markdowns/welcome.md: -------------------------------------------------------------------------------- 1 | # AlphaZero like implementation for Oware Abapa game (www.Codingame.com) 2 | 3 | This tutorial can help you implement a working AlphaZero (AZ) like bot for competing on a limited resources environment (1 vCPU, 100KB of total size and 50ms turn time). Most AZ implementations have many Convolutional/Dense layers, and the model can weight more than 20 MB. This code uses just a tiny Neural Network(NN) of about 80KB in size to fit in the 100KB limit. 4 | 5 | See https://github.com/marchete/CGZero for more info and source code. 6 | 7 | ## Difficulty Level: 8 | Very Hard. There are many different components that must be tied together. 9 | 10 | ## Previous Knowledge: 11 | - C++, for the bot part 12 | - Python, for the training part 13 | - Monte Carlo Tree Search 14 | - Experience on AI bot creation (Codingame multiplayer games) 15 | 16 | ## Estimated Time: 17 | 3 hours. Also +5 hours for training the model. Training and doing tests with Neural Networks are time consuming. 18 | 19 | ## What will I learn? 20 | All the components for an AZ like bot. Please note that this implementation isn't exactly a pure AZ bot, it's tweaked to be much simpler. 21 | 22 | ## Why should I learn? 23 | In many games AZ bots are the most powerful right now. 24 | They are interesting because they don't need domain knowledge, they learn from self play. 25 | 26 | ## Main objectives on this playground 27 | 28 | My premises while creating the bot was: 29 | * To be a competitive AI. The bot isn't one of those "it reached 67% winrate vs a random bot!". It's not a fantastic AI but with enough training it reached top 6th at Oware Abapa. That isn't a easy task, top 10 players are the best of the best, high level bots. 30 | * Using a proven Machine Learning (ML) framework for the training part, Tensorflow in my case. 31 | * Don't use domain knowledge, only the Gamestate and valid moves per turn, and a EndGame score (-0.8 or 0.8, with some bonus for early wins and score difference). 32 | * A pure self-learning AI, it only learns by playing against itself (or previous NN versions). For the whole training it never competes against any other AI bot (only itself), neither any kind of expert knowledge, opening books or anything. 33 | * On the documents I'll try to keep it as simple as possible. NN documentation is really hard to understand for some of us. Please keep in mind that this tutorial is aimed for generalistic programmers, not ML experts. 34 | * No external libraries, just C++17 standards. Compilable both in Windows and Linux. 35 | * Fit in 100KB to submit to CG's servers (including binary code and NN weights). 36 | * The code is probably bugged, and not orthodox to Machine Learning standards. But it can be used as an example of different parts that makes a working Alphazero bot. 37 | 38 | I'd like to thank CG people on chat (Jacek, Robostac, Wontonimo and others) for helping me with general NN knowledge. 39 | 40 | ## Disclaimer 41 | The bot is able to learn how to play correctly in about 10 generations (around 4 hrs in a Core-i7 without GPU training). Improved versions of this code was able to reach 5th place with 1hr of training. 42 | -------------------------------------------------------------------------------- /src/ENCODER16k.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.IO; 5 | using System.Runtime.InteropServices; 6 | 7 | class ENCODER16k{ 8 | [DllImport("libc")] 9 | static extern int system(String command); 10 | //From https://github.com/JDanielSmith/Base16k/blob/master/Base16k/Base16k.cs 11 | static string ToBase16KString(byte[] inArray) 12 | { 13 | if (inArray == null) throw new ArgumentNullException(nameof(inArray)); 14 | 15 | int len = inArray.Length; 16 | 17 | var sb = new StringBuilder(len * 6 / 5); 18 | sb.Append(len); 19 | 20 | int code = 0; 21 | 22 | for (int i = 0; i < len; ++i) 23 | { 24 | byte byteValue = inArray[i]; 25 | switch (i % 7) 26 | { 27 | case 0: 28 | code = byteValue << 6; 29 | break; 30 | 31 | case 1: 32 | code |= byteValue >> 2; 33 | code += 0x5000; 34 | sb.Append(System.Convert.ToChar(code)); 35 | code = (byteValue & 3) << 12; 36 | break; 37 | 38 | case 2: 39 | code |= byteValue << 4; 40 | break; 41 | 42 | case 3: 43 | code |= byteValue >> 4; 44 | code += 0x5000; 45 | sb.Append(System.Convert.ToChar(code)); 46 | code = (byteValue & 0xf) << 10; 47 | break; 48 | 49 | case 4: 50 | code |= byteValue << 2; 51 | break; 52 | 53 | case 5: 54 | code |= byteValue >> 6; 55 | code += 0x5000; 56 | sb.Append(System.Convert.ToChar(code)); 57 | code = (byteValue & 0x3f) << 8; 58 | break; 59 | 60 | case 6: 61 | code |= byteValue; 62 | code += 0x5000; 63 | sb.Append(System.Convert.ToChar(code)); 64 | code = 0; 65 | break; 66 | } 67 | } 68 | 69 | // emit a character for remaining bits 70 | if (len % 7 != 0) 71 | { 72 | code += 0x5000; 73 | sb.Append(System.Convert.ToChar(code)); 74 | } 75 | 76 | return sb.ToString(); 77 | } 78 | 79 | static void Main(string[] args) 80 | { 81 | string template= 82 | @"using System; 83 | using System.Text; 84 | using System.IO; 85 | using System.Runtime.InteropServices; 86 | class S{ 87 | [DllImport(""libc"")] 88 | static extern int system(String c); 89 | static byte C(int c){return System.Convert.ToByte(c);} 90 | static byte[] DEC(string s){ 91 | var lE=-1;for(var l=0;l='0'&&s[l]<='9')lE=l;else break; 92 | int L=Int32.Parse(s.Substring(0,lE+1));var F=new System.Collections.Generic.List(L); 93 | int P=0;while((P='0'&&s[P]<='9'))++P; 94 | int i=0;int X=0;byte bV=0; 95 | while(L-->0) 96 | {if (((1<>6);F.Add(bV);bV=C((X&0x3f)<<2);break; 99 | case 1:bV|=C(X>>12);F.Add(bV);break; 100 | case 2:bV=C((X>>4)&0xff);F.Add(bV);bV=C((X&0xf)<<4);break; 101 | case 3:bV|=C(X>>10);F.Add(bV);break; 102 | case 4:bV=C((X>>2)&0xff);F.Add(bV);bV=C((X&3)<<6);break; 103 | case 5:bV|=C(X>>8); F.Add(bV);break; 104 | case 6:bV=C(X&0xff);F.Add(bV);break; 105 | }if (++i==7)i=0;} 106 | return F.ToArray();} 107 | 108 | static void Main(){ 109 | var s=""CODE""; 110 | System.IO.File.WriteAllBytes(""b.zip"",DEC(s)); 111 | system(""unzip b.zip >/dev/null 2>&1;chmod +x Binary >/dev/null 2>&1;./Binary""); 112 | }}"; 113 | 114 | if (args.Length < 2) {Console.Error.WriteLine("Usage: ENCODER16k.exe ");return;} 115 | string tempZIP = args[0]+".zip"; 116 | system("rm "+args[0]+".zip >/dev/null 2>&1"); 117 | system("zip "+String.Join(' ',args).Replace(args[0],tempZIP)+" >/dev/null 2>&1"); 118 | var CODE = ToBase16KString(File.ReadAllBytes(tempZIP)); 119 | CODE = template.Replace("CODE",CODE).Replace("Binary",args[1]); 120 | Console.Error.WriteLine("Compressed CG Size:"+CODE.Length+" "+(CODE.Length>999999?" INVALID! ABOVE CG LIMIT OF 100KB!!!!":"OK FOR CODINGAME")); 121 | File.WriteAllText(args[0],CODE); 122 | system("rm "+tempZIP+" &>/dev/null"); 123 | } 124 | 125 | } -------------------------------------------------------------------------------- /old_uncleaned_code/ENCODER16k.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.IO; 5 | using System.Runtime.InteropServices; 6 | 7 | class ENCODER16k{ 8 | [DllImport("libc")] 9 | static extern int system(String command); 10 | //From https://github.com/JDanielSmith/Base16k/blob/master/Base16k/Base16k.cs 11 | static string ToBase16KString(byte[] inArray) 12 | { 13 | if (inArray == null) throw new ArgumentNullException(nameof(inArray)); 14 | 15 | int len = inArray.Length; 16 | 17 | var sb = new StringBuilder(len * 6 / 5); 18 | sb.Append(len); 19 | 20 | int code = 0; 21 | 22 | for (int i = 0; i < len; ++i) 23 | { 24 | byte byteValue = inArray[i]; 25 | switch (i % 7) 26 | { 27 | case 0: 28 | code = byteValue << 6; 29 | break; 30 | 31 | case 1: 32 | code |= byteValue >> 2; 33 | code += 0x5000; 34 | sb.Append(System.Convert.ToChar(code)); 35 | code = (byteValue & 3) << 12; 36 | break; 37 | 38 | case 2: 39 | code |= byteValue << 4; 40 | break; 41 | 42 | case 3: 43 | code |= byteValue >> 4; 44 | code += 0x5000; 45 | sb.Append(System.Convert.ToChar(code)); 46 | code = (byteValue & 0xf) << 10; 47 | break; 48 | 49 | case 4: 50 | code |= byteValue << 2; 51 | break; 52 | 53 | case 5: 54 | code |= byteValue >> 6; 55 | code += 0x5000; 56 | sb.Append(System.Convert.ToChar(code)); 57 | code = (byteValue & 0x3f) << 8; 58 | break; 59 | 60 | case 6: 61 | code |= byteValue; 62 | code += 0x5000; 63 | sb.Append(System.Convert.ToChar(code)); 64 | code = 0; 65 | break; 66 | } 67 | } 68 | 69 | // emit a character for remaining bits 70 | if (len % 7 != 0) 71 | { 72 | code += 0x5000; 73 | sb.Append(System.Convert.ToChar(code)); 74 | } 75 | 76 | return sb.ToString(); 77 | } 78 | 79 | static void Main(string[] args) 80 | { 81 | string template= 82 | @"using System; 83 | using System.Text; 84 | using System.IO; 85 | using System.Runtime.InteropServices; 86 | class S{ 87 | [DllImport(""libc"")] 88 | static extern int system(String c); 89 | static byte C(int c){return System.Convert.ToByte(c);} 90 | static byte[] DEC(string s){ 91 | var lE=-1;for(var l=0;l='0'&&s[l]<='9')lE=l;else break; 92 | int L=Int32.Parse(s.Substring(0,lE+1));var F=new System.Collections.Generic.List(L); 93 | int P=0;while((P='0'&&s[P]<='9'))++P; 94 | int i=0;int X=0;byte bV=0; 95 | while(L-->0) 96 | {if (((1<>6);F.Add(bV);bV=C((X&0x3f)<<2);break; 99 | case 1:bV|=C(X>>12);F.Add(bV);break; 100 | case 2:bV=C((X>>4)&0xff);F.Add(bV);bV=C((X&0xf)<<4);break; 101 | case 3:bV|=C(X>>10);F.Add(bV);break; 102 | case 4:bV=C((X>>2)&0xff);F.Add(bV);bV=C((X&3)<<6);break; 103 | case 5:bV|=C(X>>8); F.Add(bV);break; 104 | case 6:bV=C(X&0xff);F.Add(bV);break; 105 | }if (++i==7)i=0;} 106 | return F.ToArray();} 107 | 108 | static void Main(){ 109 | var s=""CODE""; 110 | System.IO.File.WriteAllBytes(""b.zip"",DEC(s)); 111 | system(""unzip b.zip >/dev/null 2>&1;chmod +x Binary >/dev/null 2>&1;./Binary""); 112 | }}"; 113 | 114 | if (args.Length < 2) {Console.Error.WriteLine("Usage: ENCODER16k.exe ");return;} 115 | string tempZIP = args[0]+".zip"; 116 | system("rm "+args[0]+".zip >/dev/null 2>&1"); 117 | system("zip "+String.Join(' ',args).Replace(args[0],tempZIP)+" >/dev/null 2>&1"); 118 | var CODE = ToBase16KString(File.ReadAllBytes(tempZIP)); 119 | CODE = template.Replace("CODE",CODE).Replace("Binary",args[1]); 120 | Console.Error.WriteLine("Compressed CG Size:"+CODE.Length+" "+(CODE.Length>999999?" INVALID! ABOVE CG LIMIT OF 100KB!!!!":"OK FOR CODINGAME")); 121 | File.WriteAllText(args[0],CODE); 122 | system("rm "+tempZIP+" &>/dev/null"); 123 | } 124 | 125 | } -------------------------------------------------------------------------------- /markdowns/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | ## Overview: 4 | There is a lot of documentation in Internet about AlphaZero, I won't repeat it. AZ bots get their strength from selfplay, thanks to the statistical nature of MCTS. MCTS rollouts brings information from future turns and give win probabilities, as well as average scoring. These rollouts reinforce the NN model, so on succesive selfplay+train cycles the NN gives better values. Many papers state that doubling the MCTS rollout count per turn (800 to 1600) can increase winrate noticeably. 5 | 6 | This is the design used on CGZero (this AlphaZero implementation). 7 | 8 | ![CGZero Diagram](/images/CGZero_Diagram.png) 9 | 10 | 11 | ## Modules: 12 | The implementation consists on several parts: 13 | 14 | - A game simulator. It's important to have an accurate simulation, It must simulate a turn and give all the legal moves for the current player. Written in C++ 15 | - A modified MCTS tree, that uses the NN as evaluation and exploration. Written in C++ 16 | - Different workers: Selfplay (play games and save states as samples), Pitplay (get winrates between generations), Sampler (prepare samples for training), submit (to send it to CG), written in C++. 17 | - A trainer. Written in Python, it uses Jupyter Notebook and uses Tensorflow as the ML framework. 18 | - A NN model. This is the definition of the Neural Network that will be used both in the C++ and the Python trainer. It has layers (Inputs, Dense Layers, and outputs). 19 | - Some utility to pack the binary and model, to send it to CG for submitting. I have it in C#. 20 | 21 | In my implementation I have 5 main files: 22 | 23 | - `CGZero.cpp`: It does all the C++ roles except the Sampler. 24 | - `NNSampler.cpp`: Sampler Worker. Takes all samples, and average unique gamestates (it reduces samples size count). Right now is game agnostic. It takes inputs+outputs+count from a binary float file. 25 | - `NN_Mokka.h`: NN Inference engine. 26 | - `Train.ipynb`: Jupyter Notebook that does all the training. 27 | - `ENCODER16k.cs`: C# utility. It packs N files and creates a text file that can be pasted in CG IDE. It can compress up to 60%. 28 | 29 | 30 | ## CGZero Pipeline: 31 | 32 | - Define the NN model, both in C++ an Python. Ensure that both codes give the same prediction from the same input. Ensure that the weight fits on the 100KB limit. Recompile the C++ code as it's hardcoded. 33 | - All other steps are completely done at `Train.ipynb` notebook. 34 | - Load parameters for training (number of threads, number of matches per cycle, training parameters, etc) 35 | - Resume previous training state, or create a generation 0 initial state. The trainer will have 2 best models, this is to avoid overfitting against a single model. At any point I have `best1`/`best2`/`candidate` models. All of them are saved on disk. 36 | - Start the training cycle, the whole training is sequential but it uses threads to improve game generation. 37 | - Generate self-plays. It can be between `best1`/`best2` or a random generation. The percentage of matches on each option is defined based on the previous winrate (i.e. if I lose a lot against `best2`, I'll try to focus on creating replays for `best2`). 38 | - Use Sampler to get a random subset of samples. The sampler has intelligence, it averages the samples if they have the same gamestate. I.e. the initial gamestate will be repeated in all games, so the sampler will average all training values to create a single sample for that gamestate. It also adds some decay to older generations, to give more importance to samples of recent generations. Generation 0 is too random, I try to remove its samples as soon as possible. 39 | - Read the samples and train in Tensorflow. I don't do minibatches, but I guess it could be better. 40 | - Save this `candidate` generation as `gen.w32`(weights only for C++ code) and as `gen.h5` (for Tensorflow, to resume training). 41 | - Pit play `candidate` against `best1` and `best2`, get winrates. If winrate `candidate` vs `best1`> 55%, then update best models. `best1` and `best2` are always different. 42 | - Increase Generation (generation++) -------------------------------------------------------------------------------- /markdowns/final.md: -------------------------------------------------------------------------------- 1 | # Final Words 2 | 3 | I started reading ML information since Agade, PB4 and Fenrir "broke" the leaderboard in Coders Strike Back with Neural Network bots (Feb' 2019). These bot achieved 90%+ winrates vs the best bots to date. 4 | I tried reading all the info they gave about ML and NN, but most of the information were very mathematical and complex to me. At this time I did some small parts for a future NN bot (the inference engine), but creating all the pieces and joining them was a complex task. 5 | 6 | Then both Robostac, Recurse and Jacek topped most multiplayer leaderboards with their NN bots. It was clear that NN bots was the new GA (Genetic Algorithms). 7 | 8 | Some final thoughts: 9 | - Hard work and perseverance. Some of us aren't "genius" minds, I need a lot of time to implement stuff and make it work. But hard work usually can overcome your limitations. Keep working on the problem, ask for some help and you'll eventually manage to solve a big task. 10 | - CGZero winrate improves a lot when you optimize the inference CPU time. I passed from 5k sims per turn (sim as number of simulations + NN prediction of that new gamestate) to 10k and the winrate improved noticeably. The more MCTS visits, the better. 11 | - Try to optimize the performance in NN prediction as much as possible. In my profiling tests the bot was using 70% of the CPU time on NN prediction (Dense layer, in calculate output). So any step you can cache, any mathematical operation you can save in the NN inference part it will improve the overall winrate. I did some improvements in NN_Mokka. 12 | - I changed the random move selection from https://github.com/marchete/CGZero/blob/master/src/CGZero.cpp#L1501-L1515 to a weighted random selection, based on visits per child, for the first 20 turns. The random selection was reused from: https://github.com/marchete/RN_Explorer/blob/main/src/solorunner/RN_ExploDiv_7.cpp#L1723 As temperature I use 0.74: `rndWeight[i]=(i==0?0:rndWeight[i-1])+pow((double)(node+i)->visits,1.35)`. This should pick better options than a pure random. This is not in the github code. 13 | - I created a bit bigger network (140+KB in filesize), with 2 hidden layers. I used a float32 to float16 file conversion to reduce the size when sending it to CG. I used the `file32to16` and `file16to32` functions to change from one format to another. The bot in CG does the unpacking with `file16to32` at turn0. It seems that the 32bit to 16bit conversion doesn't degrade the prediction, it seems to have some 1e-4 error in average. 14 | - One-Hot encodings seems good because you can have a big Dense layer without linearly increase the calculation time (you can just set all to bias, then add the weights that comes from the 'ones'). Thanks Robostac and Jacek for this performance improvement. 15 | - Robostac also did a policy + value weight concatenation on the bot (training model remains the same), because that reduces the C++ calculation time of the output layers. But that means many changes, first you need to change the SaveModel() in python, so you `concatenate(policy_weights,value_weights)` and `concatenate(policy_bias,value_bias)` and in the inference engine it calculates as a whole (so it reduces the operations because 6+1 fits in AVX size of 8) without activation (neither tanh or softmax, it must be done "manually"). After predict() you need to manually extract the value float and do the tanh(value). Then for softmax you need to set -999999.9f (any negative big float, in softmax that's a zero) on the position that was the value, and then do a softmax(). 16 | - At my last test I added the valid moves as one-hot inputs. I don't know if that's redundant (because other inputs implies that), but being just 6 inputs it wasn't too heavy to add it. 17 | 18 | On my last tests the training framework learned to play at high level (top 6th) in just 45 minutes of training, starting from scratch. The github code needed about 4hrs to reach the same level of play. Mastering a game in less than 1 hour of training, with a single Core i7 CPU without GPU training it's a great success. 19 | 20 | Even with all, this playground briefly explained how an AlphaZero bot could be for Codingame multiplayers. It's a real, working, competent bot, but don't take it as written in stone, take it just as a reference. 21 | -------------------------------------------------------------------------------- /markdowns/differences.md: -------------------------------------------------------------------------------- 1 | # Differences between CGZero and Alphazero 2 | 3 | ## Simple NN Model 4 | Original AlphaZero NN design has many (80+) Convolutional layers, Fully Connected layers, Batch Normalization layers, skip connection layers (adding inputs again after each residual layer) and more. 5 | CGZero is a toy model. I haven't implemented neither Convolutional nor Batch Normalization layers. I have like 3 or 4 layers of Fully Connected layers, nothing more. 6 | Check https://adspassets.blob.core.windows.net/website/content/alpha_go_zero_cheat_sheet.png for some diagram of Alpha Zero networks. That can't fit on normal competitive games, and it won't have enough CPU time to do anything good. 7 | 8 | ## Synchronous training 9 | 10 | AlphaZero used 4 first-generation [TPUs](https://cloud.google.com/tpu/docs/tpus) and 44 [CPU](https://en.wikipedia.org/wiki/Central_processing_unit) cores. My setup is modest, just a single Intel Core i7, training while I do other stuff at the PC. I don't have distributed workers (can be really simple to delegate selfplay workers to external PC's though). 11 | So all the training pipeline is just linear, one task after another. I use threading to greatly improve selfplay game generation and pitplay winrate results. 12 | 13 | ## Self-play generation 14 | 15 | AlphaZero states 25000 games against itself. I just do around 400-1500 each generation. They always use the best model, I use 3 different options: 16 | 17 | 1. `Best1` vs `Best1` 18 | 2. `Best1` vs `Best2` 19 | 3. `Best1 or Best2` vs `random generation` (a recent one) 20 | 21 | The amount of the third option is always a 10% of the games to generate. **1** and **2** will have variable percentage, depending on the result of the last training. Having `winrate1` and `winrate2` (winrates of candidate vs each best model) I'll generate more games to the lowest winrate. 22 | 23 | ## Samples 24 | Alphazero stores `| Inputs | Policy | EndGame Value |` as a sample. They store samples for the last 500k games, I just store last X00k samples (much less games). 25 | 26 | My Samples have 4 parts: 27 | 28 | | Inputs | SumPolicy | SumValue | Count | 29 | 30 | Samples will be dictionaries with inputs as keys, so I make unique samples and sum the policy and values, and increase the count by 1. Dividing by `Count` will average samples. 31 | AlphaZero always uses EndGame Value for all samples. I mix what you can read on: 32 | https://medium.com/oracledevs/lessons-from-alphazero-part-4-improving-the-training-target-6efba2e71628 33 | In that document they declare **`Z`** and **`Q`** as possible objectives for value training. **`Z`** is the endgame score (-1, 0 or 1) that will be used on all samples (taking into account that samples from the loser player has -endgameScore). **`Q`** is just the sumValue/visits you get while doing MCTS search (i.e. the mean Score of the root node). 34 | I use a mix of both. `SampleValue = k * Z + (1-k)*Q` . **`k`** will linearly increase each turn, so initial samples have some little EndGame Score (because I think it's too far to declare a position as good or bad), and final moves will have a big percentage of EndGame Score (it's more clear that this position is good or bad). 35 | I had many problems with the sign of the Samples value. I struggled to get the correct sign. It seems naive, but to evaluate a game state the root node have a -sum(childrenValues). This is not what I wanted. If as player 0 I have a sure win (1.0), then all children from root will have 1.0 as mean score. But as the way the score backpropagates the root node will have a -1.0 (it's seen as the enemy POV). I neeeded the score for the player 0, so I tested a lot with signs until I got what I expected. 36 | 37 | Alphazero picks random minibatches of 2048 positions from last 500k games. I imagine it's just a random selection of 2048 samples. But according to my samples, without deduplication/averaging of samples you'll end up with a lot of repetitive initial samples, most of them having contradictory training targets. 38 | 39 | My subset selection is much bigger, I take around 200k-800k samples from last 500k-N000k samples as a subset. Also the subset selection is weighted. I order samples by `Count`, on descending order. The 20% of my subset will come from the first 20% of that ordered sample list, the next 20% from the first 40% and so on. This way I ensure that most frequent samples usually appears on the subset. 40 | Finally I add some decay weight to older samples. I get all files, sortered by name descending (so higher generations are read first). For each file I reduce 0.02 the decay factor (starting with 1.0, limited to 0.7 as min decay). So samples from an old generation are counted but they add less to the final `SumPolicy` and `SumValue` 41 | 42 | ## Training 43 | Alphazero uses minibatches of 2048 samples. I use a big subset with M00k samples, and the training function does N passes (EPOCH between 5 and 20, depending on how much it takes). I do it on a synchronized way. 44 | AZ do the evaluation of the network each 1000 minisamples, I do after 1 training call (but that call has N passes as EPOCH). 45 | 46 | The AZ loss function is `Cross entropy loss` + `Mean squared loss` + `regularisation`. I don't know exactly what that regularisation is, or how to calculate it, so I ignored it. 47 | Also the `Cross entropy loss` is completely incorrect for my approach. https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalCrossentropy or any other crossentropy loss in tensorflow seems to work for categorization (i.e. they expect only one true value, with a 1.0 on it and the rest with zero). In my tests I was getting huge losses as categorical crossentropy, even with near perfect predictions (0.0003 differences between the prediction and the expected policy values). 48 | Finally I used https://www.tensorflow.org/api_docs/python/tf/keras/metrics/kl_divergence , that is exactly what I was looking for (a measure of how one probability distribution is different from a second) 49 | 50 | ## Evaluation 51 | I evaluate against two best models, `best1` and `best2`. When a new candidate have a winrate >55%, `best1` is passed to `best2`, and the new candidate is promoted as `best1` 52 | 53 | ## Move selection after MCTS Search ended 54 | While training AlphaZero uses some temperature for selection. It seemed obscure and overly complicated. 55 | 56 | I went to a simpler mode. I rely on dirichlet noise to have some randomness on visit count. Also for the first 11 turns I have some chance to randomly pick a move, regardless its stats. This random move invalidates the sample generation for that position, to avoid breaking the statistics. 57 | I don't pick the move with most visits. I used visits and score (similar to https://tech.io/playgrounds/55004/best-first-minimax-search-with-uct). `SelectMoveScore = move's eval value + log(move's visits)` -------------------------------------------------------------------------------- /markdowns/environment.md: -------------------------------------------------------------------------------- 1 | # Environment Preparation 2 | 3 | ## Overview: 4 | I've used a mixed Linux/Windows environment, using WSL to have Ubuntu on a Windows 10 OS. I installed all the software in Linux except Visual Studio, for personal preference. 5 | 6 | Tools used: 7 | 8 | - Anaconda for Python environments (Linux/Windows) 9 | - Tensorflow 2 and Jupyter notebook (Linux/Windows) 10 | - Dotnet SDK (Linux/Windows), or any C# compiler 11 | - Clang++9 (Linux). This also will be used to export to CG. 12 | - Visual Studio for C++ coding (Windows /Optional) 13 | 14 | You can do all the training pipeline in just one OS, either Windows or linux, sometimes linux binaries are faster than Visual Studio counterpart, measure it. 15 | To export the bot to Codingame you need the CGZero binary in x64 Linux, you can't send a Windows binary. If you strip/codegolf the code maybe it's feasible to send the source .cpp code + weights file as a string in the code. The code has a function to convert float32 weights to float16, that reduces weight file to 50%, with a low accuracy error. So doing that + some compression to Unicode it can probably fit. 16 | 17 | **WARNING! Sending compiled binaries are forbidden on Challenges! Don't use them because you can be disqualified. It's OK tu use it on multi games.** 18 | 19 | ## Steps: 20 | 21 | 1. Install Anaconda 22 | https://docs.anaconda.com/anaconda/user-guide/tasks/tensorflow/ 23 | 24 | 2. Create a Tensorflow environment, including Python, Tensorflow, Numpy and Jupyter Notebook 25 | ``` bash 26 | conda create -n tf tensorflow matplotlib numpy 27 | conda activate tf 28 | conda install -c conda-forge notebook 29 | ``` 30 | For GPU acceleration on tensorflow you'll need additional libraries (check https://www.tensorflow.org/install/gpu ). This is out of scope. 31 | 32 | 3. If you use DotNet SDK you'll need a separate folder to create a project for `ENCODER16k.cs`. Create the folder, then `dotnet new console` inside it, and paste the .cs file there. With mono or other SDK's you can just build a single file "binary" 33 | 4. Create a folder for the Training pipeline. Copy all files (except `ENCODER16k.cs` if you used DotNet SDK): 34 | 35 | **image** 36 | 37 | 5. Compile `NNSampler.cpp` and `CGZero.cpp` binaries. On Linux I use: 38 | 39 | 40 | ``` bash 41 | clang++-9 -std=c++17 -march=core-avx2 -mbmi2 -mpopcnt -mavx2 -mavx -mfma -O3 -fomit-frame-pointer -finline "$AI_Name.cpp" -lpthread -o "$AI_Name" 42 | strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag "$AI_Name" 43 | upx "$AI_Name" -9 --best --ultra-brute --no-backup --force 44 | ``` 45 | In Visual Studio, Release compilation parameters are: 46 | ``` C++ 47 | /JMC /permissive- /GS /W3 /Zc:wchar_t /ZI /Gm- /Od /sdl /Fd"x64\Debug\vc141.pdb" /Zc:inline /fp:precise /D "_DEBUG" /D "_CONSOLE" /D "_CRT_SECURE_NO_WARNINGS" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /arch:AVX2 /Gd /MDd /std:c++17 /FC /Fa"x64\Debug\" /EHsc /nologo /Fo"x64\Debug\" /Fp"x64\Debug\CGZero.pch" /diagnostics:classic 48 | ``` 49 | It needs `AVX2`, `C++17` 50 | 51 | **NOTE: You need to have defined your NN Model before compiling `CGZero.cpp`** , it will fail to compile as it lacks the Create NN Model function. 52 | 53 | 6. Start Jupyter Notebook. 54 | ``` 55 | conda activate tf (only if you aren't in the tf virtual environment) 56 | jupyter notebook 57 | ``` 58 | This will open a browser, if it's not open (like in mixed Windows/Linux environments) you'll see something like: 59 | ``` 60 | [I 13:57:41.110 NotebookApp] Serving notebooks from local directory: /mnt/e/folder 61 | [I 13:57:41.110 NotebookApp] The Jupyter Notebook is running at: 62 | [I 13:57:41.111 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). 63 | [C 13:57:41.470 NotebookApp] 64 | To access the notebook, open this file in a browser: 65 | http://localhost:8889/?token=a5e120ecc047a4d6381fcbd2 66 | ``` 67 | Copy the **`http://localhost:8889/?token=`** URL on a webbrowser, and you'll access Jupyter Notebook. Open `Train.ipynb` file from the browser. 68 | 69 | 7. Click the second cell, and press `Run`, if Tensorflow is correctly installed you'll see: 70 | ``` 71 | Python:3.7.4 (default, Aug 13 2019, 20:35:49) 72 | [GCC 7.3.0] 73 | TF:2.4.1 74 | WARNING:tensorflow:From :24: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version. 75 | Instructions for updating: 76 | Use `tf.config.list_physical_devices('GPU')` instead. 77 | GPU:False CUDA:True 78 | ``` 79 | The warning is for a deprecated call to check if GPU is active, it's irrelevant. 80 | 81 | 8. The next section is the Hyperparameters section, configure values to change training behavior. I can't recommend anything because it's obscure to me, I did trial and error. `THREADS` is important to use multithreading, set up accordly to your CPU. 82 | 83 | 9. Go to the cell with the MODEL DEFINITION. Define your neural network model. Run to compile the model. **This NN Model must match exactly what you have in the .cpp code.** 84 | 85 | 10. Near the end of the script, in auxiliary tools, there is a script for Model Validation between C++ and tensorflow. **Ensure that predicted values are the same. If you don't have this point you'll never be able to train anything.** 86 | 87 | 11. Once you have a correctly installed Tensorflow, your hyperparameters for training, your Model loaded and synchronized between Tensorflow and C++ binary, you are ready to train. Just go to first cell and press Run on all cells until you reach the **MAIN TRAINING LOOP**. At this point the code will run indefinitely until you press stop. It should be safe to stop at any time, but I prefer to cancel it when it's generating selfplays. If you stop on tensorflow training or pit winrate calculation the generation won't get a score. It shouldn't be a problem but it's undesired. Self-play is a safe point to stop, it won't break anything. 88 | 89 | ## Steps for resume training: 90 | 1. On a terminal/console, go to the folder with all the code. 91 | 2. Start Jupyter Notebook, connect to the url. 92 | ``` bash 93 | conda activate tf 94 | jupyter notebook 95 | ``` 96 | 3. In the browser, open `Train.ipynb` file. 97 | 4. Click run until you reach the **MAIN TRAINING LOOP**. 98 | 99 | ## Steps for sending a bot to Codingame. 100 | 1. Copy CGZero binary (compiled as x64 linux) to the folder with the ENCODER16k.cs binary 101 | 2. Copy the best weight generation as best.w32 on that same folder 102 | 3. DotNet SDK: ```dotnet run toSend.txt CGZero best.w32``` This will create a ```toSend.txt``` file. You can copy and paste that code on CG IDE. 103 | 3a. Other compiled binaries the command is like ```mono ENCODER16k.exe toSend.txt CGZero best.w32``` 104 | -------------------------------------------------------------------------------- /markdowns/glossary.md: -------------------------------------------------------------------------------- 1 | # Glossary 2 | 3 | These are simplified descriptions, search on other AlphaZero papers for more formal explanations. I simplified the terms to reflect exactly how I'm using them, they aren't accurate for a ML expert: 4 | 5 | - `Neural Network`/`NN`: It's just a `vector>`. You get some inputs in the 0.0 .. 1.0 range, and you do input * weight + bias = prediction (well, it's very simplified). For the bot the NN is just a big function approximation. It's very similar to heuristics score functions where you apply some coefficients to some data from the gamestate (in CSB it can be angle to checkpoint, speed, checkpoint passed, etc). But the NN does all the paramtuning and function definition by itself. 6 | - `Dense layer` / `MLP Layer`: One of these `vector` 7 | - `One-hot`: A vector with all zeros except one value with 1.0. For inputs a one-hot encoding means the following: Neural Networks expects that inputs values are like gradient, where 0.0 is worse than 1.0. If you have a cell with 3 possible states( empty, white pawn, black pawn) you shouldn't encode it as a single input with values 0.0, 0.5 and 1.0. A black pawn isn't 2x the value of white pawn. So that single cell could be encoded as one-hot encoding with 3 possible activations. Empty: [1.0,0.0,0.0] White[0.0,1.0,0.0] Black [0.0,0.0,1.0]. 8 | - `Value`: Given a gamestate, it's a score evaluating the winning chances for the current player. It's similar to Eval() functions on heuristic bots. But in AlphaZero the function is replaced by the output of a NN prediction. Value will be limited to -1.0 to 1.0 range. 9 | - `Reward`/`Z`: The endgame Value. It should be -1.0 if player loses, 1.0 for winning and 0.0 for a draw. But I've tweaked this to have different winning qualities. In my opinion, if I win faster I need to reflect a better score, or if I win by a big margin. So I give 0.8 as the minimal win score, then I give bonus for turns and score difference. I prefer turns bonus over score difference. The loss score is similar. 10 | - `meanScore`/`Q`: On MCTS you have a sumValue on each MCTS node, coming from the backpropagation of scores. if you divide sumValue/visits you have a mean value. 11 | - `Policy`: Given a gamestate and the legal moves for the current player, it's a vector of probabilities for these legal moves, it's similar to giving a score to the moves or a distribution probability. I.e. Imagine you can do three different actions [Rock,Paper,Scissors], the policy can be [0.333,0.333,0.333]. In this case all moves will be tested similarly, and MCTS will have a similar amount of visits for each move. But if you put [0.1,0.1,0.8] as policy the MCTS search will explore the "Scissors" move much more. A policy should always sum 1.0. 12 | - `NN model`: Definition of the NN structure, Input size, number of Dense layers, and output layers. The CGZero design needs one input layer (the gamestate), and two outputs (value and policy). Some layers are shared between the two outputs. See [1] for a possible diagram. 13 | - `Dirichlet noise`: It's a noise for the policy part. Alphazero uses it on the self-play to create diversity, otherwise the NN will always play exactly the same game over and over (it's deterministic). 14 | You pass a the legal moves count `V` and other parameters (epsilon and alpha), the dirichlet noise will create some random vector of size `V` that sums 1.0. With the parameter called epsilon it will mix the policy and the noise: `final_policy = policy * (1.0-epsilon) + noise * epsilon` . This noise won't change the sum policy, it's just a redistribution. As an example, if the [Rock,Paper,Scissors] policy was [0.1,0.1,0.8], I'd create a dirichlet noise of size 3, that can be [0.3,0.4,0.3]. With an epsilon 0.2 it will end as [0.14,0.16,0.7]. It stills sums 1.0. Alpha on dirichlet noise seems to control how different can be each value of the vector, I use something around 1.0 and 1.5. 15 | - `sample`: It's a single gamestate + Value+Policy+Count. While training I use a count = 1 (I average Value and policy) 16 | - `y_true`: An array with value and policy from samples. This is what I want as the NN output. 17 | - `y_pred`: Predicted array of values and policies. It's the NN output, and after training it should be similar to y_true. 18 | - `loss` and `loss function`. While you are training a NN you need to know how different the `y_true` and `y_pred` are, because the training needs to have some numerical value (gradient) to direct the training. When you are training you'll see that the loss value will decrease, that means the NN is predicting better. 19 | - `cross-entropy loss`: A loss calculation for policies, it gives a single number for the whole vector. Caution at that point, some crossentropy losses are targeted for one-hot policies. In general Alphazero policies aren't one-hot. 20 | - `mean squared loss`: A loss calculation for values. It's squared because it seems it's better for the learning process. 21 | - `hyperparameter`: Some coefficient that changes the NN learning behavior. 22 | - `learning rate` / `LR`: Hyperparameter that controls how fast the NN learns. In a simplified way it's how much the NN weights change to reduce the losses. It's good to have a "big" learning rate at start (like 0.01 or similar) and then reduce it after some training to improve corvengence. 23 | - `epoch`: I use it as 'training iterations on the current sample subset'. The training process can iterate N times over the samples to learn. This is what I define as EPOCH. 24 | - `batch size`: Training steps are done in batches of samples. This define the amount of samples per training step. I don't know what is a good value for this. 25 | - `Temperature`: After reviewing it, I think AZ does the following: For the first 30 turns the move selection is done with a weighted random probability, based on visits. The more visits, the more chance to pick this move. They can tweak the visits by using `pow(childVisit, 1.0/temperature)`. In the github code it wasn't implemented, but I see it logical, so I added it to my code instead my random move selection (it wasn't weighted). I already had a weighted random selection from RN_Explorer, I just reused it. 26 | - `cpuct`: This is the exploration parameter for MCTS Search. Original MCTS uses UCB1 formula with an exploration parameter `C`. In Alphazero the formula is replaced to `Uchild=Qchild + cpuct⋅Pchild⋅(√visitsParent) /(1+visitsChild)` Qchild is `Q` for that child (meanValue), `Pchild` is the Policy value for that child (it's not a vector, but a single value from parent's policy vector). As you see, `cpuct` is similar to `C` in the original UCB1. But guess what? it isn't. According to [2] `cpuct value grows as search progresses!`. In theory `cpuct`should be between 1.0 and 4.0. I have absolutely no idea how to tune it. I don't know if I need a constant, or if I need to change it based on visit count, based on game turn, or based on MCTS depth (i.e. maybe I should reduce exploration after depth 2 on the MCTS Tree to focus more on best moves after some exploration in lower depths). It's another obscure hyperparatemer to me. After reviewing AZ pseudocode, in general the cpuct value changes too little with visits, in CG maybe it affects the first turn (high visit count) but not a lot. 27 | 28 | \[1\] ![Simple NN model](/images/simplemodel.jpg) 29 | 30 | \[2\] https://lczero.org/blog/2018/12/alphazero-paper-and-lc0-v0191/ 31 | -------------------------------------------------------------------------------- /src/NNSampler.cpp: -------------------------------------------------------------------------------- 1 | #include //SSE Extensions 2 | #include //All main STD libraries 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | //#include "fast_double_parser.h" 17 | namespace fs = std::filesystem; 18 | using namespace std; 19 | 20 | const float DECAY_FACTOR = 0.02f; 21 | const float MINIMAL_DECAY =0.65f; 22 | float factor = 1.0f; 23 | //#define DUMP_TXT 24 | struct SampleInfo { 25 | vector I; 26 | vector P; 27 | float N; 28 | int TURN; 29 | int win, draw, loss; 30 | }; 31 | 32 | 33 | #define Now() chrono::high_resolution_clock::now() 34 | struct Stopwatch { 35 | chrono::high_resolution_clock::time_point c_time, c_timeout; 36 | void Start(int us) { c_time = Now(); c_timeout = c_time + chrono::microseconds(us); } 37 | void setTimeout(int us) { c_timeout = c_time + chrono::microseconds(us); } 38 | inline bool Timeout() { 39 | return Now() > c_timeout; 40 | } 41 | long long EllapsedMicroseconds() { return chrono::duration_cast(Now() - c_time).count(); } 42 | long long EllapsedMilliseconds() { return chrono::duration_cast(Now() - c_time).count(); } 43 | } stopwatch; 44 | 45 | 46 | template 47 | inline void hash_combine(std::size_t& seed, T const& v) 48 | { 49 | seed ^= std::hash()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 50 | } 51 | 52 | template 53 | size_t hashVector(vector& in) { 54 | size_t size = in.size(); 55 | size_t seed = 0; 56 | for (size_t i = 0; i < size; i++) 57 | //Combine the hash of the current vector with the hashes of the previous ones 58 | hash_combine(seed, in[i]); 59 | return seed; 60 | } 61 | /*unordered_map samples; 62 | vector hashSamples;*/ 63 | 64 | unordered_map samples; 65 | vector> hashSamples; 66 | 67 | int AVAILABLE_POOL = 0; 68 | 69 | 70 | int PROCESSED_SAMPLES = 0; 71 | float FACTORED_SAMPLES = 0.0f; 72 | bool processFile(fs::path file, const int INPUT_SIZE, const int OUTPUT_SIZE) 73 | { 74 | auto t0 = stopwatch.EllapsedMilliseconds(); 75 | cerr << "Processing " << file.filename(); 76 | //Inputs + POLICY + VALUE 77 | ifstream F(file, std::ios::in | std::ios::binary); 78 | if (!F.good()) 79 | { 80 | cerr << "Error reading file:" << file << endl; 81 | return true; 82 | } 83 | string line; 84 | SampleInfo S; 85 | S.I.resize(INPUT_SIZE); 86 | S.P.resize(OUTPUT_SIZE); 87 | int linesProcessed = 0; 88 | F.seekg(0); 89 | while (!F.eof())// (getline(F, line)) 90 | { 91 | ++linesProcessed; 92 | S.N = 1.0f; 93 | S.TURN=PROCESSED_SAMPLES; 94 | F.read(reinterpret_cast(&S.I[0]), INPUT_SIZE * sizeof(float)); 95 | if (F.eof()) 96 | break; 97 | F.read(reinterpret_cast(&S.P[0]), OUTPUT_SIZE * sizeof(float)); 98 | F.read(reinterpret_cast(&S.N), sizeof(S.N)); 99 | PROCESSED_SAMPLES+=(int)S.N; 100 | S.N *=factor; 101 | FACTORED_SAMPLES+=S.N; 102 | for (auto& spp:S.P) 103 | spp*=S.N; 104 | S.win = 0; 105 | S.loss = 0; 106 | S.draw = 0; 107 | if (S.P.back() > 0.6f) 108 | { 109 | ++S.win; 110 | } 111 | else if (S.P.back() < -0.6f) 112 | { 113 | ++S.loss; 114 | } 115 | else ++S.draw; 116 | /* 117 | 118 | double x; 119 | const char * endptr = line.c_str(); 120 | do { 121 | while (endptr!=nullptr && *endptr == ' ') 122 | { 123 | endptr++; 124 | } 125 | if (endptr == nullptr || *endptr == '\0') 126 | break; 127 | endptr = fast_double_parser::parse_number(endptr, &x); 128 | S.I.emplace_back(x); 129 | } while (endptr != nullptr && *endptr != '\0'); 130 | 131 | 132 | // istringstream iss(line); 133 | //copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter(S.I)); 134 | for (int i = (int) S.I.size() - OUTPUT_SIZE; i < (int)S.I.size(); ++i) 135 | { 136 | S.P.push_back(S.I[i]); 137 | } 138 | if (S.P.size() != OUTPUT_SIZE) 139 | { 140 | cerr << "SIZE ERROR:" << S.P.size() << " != " << OUTPUT_SIZE << endl; 141 | cerr << endl; 142 | } 143 | S.I.resize(S.I.size() - OUTPUT_SIZE); 144 | */ 145 | /*size_t HASH = 0; 146 | for (auto&f : S.I) 147 | { 148 | hash_combine(HASH, f); 149 | }*/ 150 | 151 | size_t HASH = hashVector(S.I); 152 | 153 | 154 | auto hasSample = samples.find(HASH); 155 | if (hasSample == samples.end()) //NEW 156 | { 157 | samples.emplace(HASH, S); 158 | } 159 | else { 160 | hasSample->second.N +=S.N; 161 | for (int i = 0; i < (int)hasSample->second.P.size(); ++i) 162 | { 163 | hasSample->second.P[i] += S.P[i]; 164 | } 165 | hasSample->second.win += S.win; 166 | hasSample->second.loss += S.loss; 167 | hasSample->second.draw += S.draw; 168 | } 169 | 170 | 171 | --AVAILABLE_POOL; 172 | if (AVAILABLE_POOL == 0) 173 | break; 174 | 175 | } 176 | F.close(); 177 | 178 | cerr << " Done. Lines:" << linesProcessed << " PROCESSED:" << PROCESSED_SAMPLES << " Unique:" << samples.size() << " T:" << stopwatch.EllapsedMilliseconds() - t0 <<" Decay Factor:"< 0; 180 | } 181 | 182 | int main(int argc, char* argv[]) 183 | { 184 | stopwatch.Start(0); 185 | if (argc < 8) 186 | { 187 | cerr << "ERROR parameters: " << endl; 188 | return -1; 189 | } 190 | //string folder = argv[1]; 191 | fs::directory_entry directory{ argv[1] }; 192 | string filter = argv[2]; 193 | string oFile = argv[3]; 194 | ofstream outputfile(oFile, std::ios::out | std::ios::binary); 195 | #ifdef DUMP_TXT 196 | ofstream outputF2(oFile + ".txt", std::ios::out); 197 | #endif 198 | if (!outputfile.good()) 199 | { 200 | cerr << "Invalid output file:" << argv[3] << endl; 201 | return -1; 202 | } 203 | 204 | std::regex REG(filter); 205 | int TRAINING_POOL_SIZE = atoi(argv[4]); 206 | int TRAINING_SUBSET_SIZE = atoi(argv[5]); 207 | int INPUT_SIZE = atoi(argv[6]); 208 | int OUTPUT_SIZE = atoi(argv[7]); 209 | int DELETEOLD = atoi(argv[8]); 210 | AVAILABLE_POOL = TRAINING_POOL_SIZE; 211 | 212 | if (TRAINING_SUBSET_SIZE > TRAINING_POOL_SIZE) 213 | { 214 | cerr << "ERROR: TRAINING_SUBSET_SIZE > TRAINING_POOL_SIZE" << endl; 215 | return -1; 216 | } 217 | 218 | vector filenames; 219 | for (const auto& entry : fs::directory_iterator{ directory }) { 220 | if (entry.is_regular_file()) { 221 | string sfile = entry.path().filename().string(); 222 | if (std::regex_match(sfile, REG)) 223 | filenames.push_back(entry.path()); 224 | } 225 | } 226 | //PROCESS FILES 227 | if (filenames.size() == 0) 228 | { 229 | cerr << "ERROR: No files to process, folder:" << argv[1] << " Mask files:" << filter << endl; 230 | return -1; 231 | } 232 | cerr << "Processing " << filenames.size() << " files" << endl; 233 | sort(filenames.begin(), filenames.end(), [](const auto& lhs, const auto& rhs) {return lhs.string() > rhs.string(); }); 234 | bool deletingFiles = false; 235 | for (auto& f : filenames) 236 | { 237 | if (deletingFiles) 238 | { 239 | cerr << "Removing file " << f << endl; 240 | remove(f); 241 | continue; 242 | } 243 | if (!processFile(f, INPUT_SIZE, OUTPUT_SIZE)) 244 | { 245 | if (DELETEOLD == 0) 246 | break; 247 | else 248 | deletingFiles = true; 249 | } 250 | factor = max(MINIMAL_DECAY,factor-DECAY_FACTOR); 251 | } 252 | 253 | for (auto& M : samples) { 254 | hashSamples.push_back(pair(M.first, M.second.N)); 255 | } 256 | //PICK RANDOM SAMPLES 257 | if (samples.size() == 0) 258 | { 259 | cerr << "ERROR: No samples, folder:" << argv[1] << " Mask files:" << filter << endl; 260 | return -1; 261 | } 262 | int uniqueSamples = (int)samples.size(); 263 | if (uniqueSamples > TRAINING_SUBSET_SIZE) 264 | { 265 | 266 | //Keep 20%best 267 | std::sort(hashSamples.begin(), hashSamples.end(), [](auto& a, auto& b) {return a.second > b.second; }); 268 | ofstream st("strats.txt"); 269 | st << "UNIQUE " << uniqueSamples << " PROCESSED:" << PROCESSED_SAMPLES << " Max Count:" << hashSamples[0].second << endl; 270 | for (int i = 0; i < min(200000, uniqueSamples); ++i) { 271 | st << hashSamples[i].second << endl; 272 | } 273 | st.close(); 274 | 275 | int keep20 = TRAINING_SUBSET_SIZE * 20 / 100; 276 | int keep40 = TRAINING_SUBSET_SIZE * 40 / 100; 277 | 278 | int master20 = uniqueSamples * 20 / 100; 279 | int master40 = uniqueSamples * 40 / 100; 280 | 281 | std::random_device rd; 282 | std::mt19937 g(rd()); 283 | 284 | 285 | /* auto rnd1 = std::bind(std::uniform_int_distribution(0,master20), g); 286 | for (int i = 0; i < keep20; ++i) 287 | { 288 | int j = rnd1(); 289 | if (i != j) 290 | { 291 | swap(hashSamples[i], hashSamples[j]); 292 | } 293 | }*/ 294 | auto rnd2 = std::bind(std::uniform_int_distribution(keep20, master40), g); 295 | for (int i = keep20; i < keep40; ++i) 296 | { 297 | int j = rnd2(); 298 | if (i != j) 299 | { 300 | swap(hashSamples[i], hashSamples[j]); 301 | } 302 | } 303 | auto rnd3 = std::bind(std::uniform_int_distribution(keep40, (int)hashSamples.size() - 1), g); 304 | for (int i = keep40; i < TRAINING_SUBSET_SIZE; ++i) 305 | { 306 | int j = rnd3(); 307 | if (i != j) 308 | { 309 | swap(hashSamples[i], hashSamples[j]); 310 | } 311 | } 312 | /* 313 | int master35 = uniqueSamples*35/100; 314 | auto rnd1 = std::bind(std::uniform_int_distribution(keep20,master35), g); 315 | auto rnd2 = std::bind(std::uniform_int_distribution(keep40,(int)hashSamples.size()-1), g); 316 | //Partial shuffle 317 | for (int i = keep20; i < keep40; ++i) 318 | { 319 | int j = rnd1(); 320 | if (i != j) 321 | { 322 | swap(hashSamples[i], hashSamples[j]); 323 | 324 | } 325 | } 326 | for (int i = keep40; i < TRAINING_SUBSET_SIZE; ++i) 327 | { 328 | int j = rnd2(); 329 | if (i != j) 330 | { 331 | swap(hashSamples[i], hashSamples[j]); 332 | } 333 | } 334 | */ 335 | hashSamples.resize(TRAINING_SUBSET_SIZE); 336 | } 337 | //SAVE TO FILE 338 | int totalCovered = 0; 339 | #ifdef _MSC_VER 340 | std::sort(hashSamples.begin(), hashSamples.end(), [](auto& a, auto& b) {return a.second > b.second; }); 341 | #endif 342 | if (PROCESSED_SAMPLES < 850) 343 | std::sort(hashSamples.begin(), hashSamples.end(), [=](auto& a, auto& b) {return samples[a.first].TURN < samples[b.first].TURN; }); 344 | for (auto& ttt : hashSamples) 345 | { 346 | auto& HASH = ttt.first; 347 | SampleInfo& s = samples[HASH]; 348 | totalCovered += s.N; 349 | 350 | outputfile.write(reinterpret_cast(&s.I[0]), (int)s.I.size() * sizeof(float)); 351 | if (s.N > 1.0f) 352 | { 353 | float divide = 1.0f / (float)s.N; 354 | for (auto& f : s.P) { 355 | f *= divide; 356 | } 357 | } 358 | 359 | /* float score = ((float)s.win + 0.5f * (float)s.draw) / (float)(s.win + s.draw + s.loss); 360 | float oriScore = s.P[s.P.size() - 1]; 361 | float FACTOR_WIN= 0.1f; 362 | if (score > 0.53f && score < 0.96f) 363 | { 364 | score *= FACTOR_WIN; 365 | s.P[s.P.size() - 1] = score + (1.0f - score) * s.P.back(); 366 | } 367 | else if (score < 0.47f && score > 0.04f) 368 | { //Loss majority 369 | score = 1.0f - score; 370 | score *= FACTOR_WIN; 371 | s.P[s.P.size() - 1] = -(score + (1.0f - score) * abs(s.P.back())); 372 | } 373 | */ 374 | outputfile.write(reinterpret_cast(&s.P[0]), (int)s.P.size() * sizeof(float)); 375 | outputfile.write(reinterpret_cast(&s.N), (int) sizeof(s.N)); 376 | #ifdef DUMP_TXT 377 | /* if (s.N == 1) 378 | continue;*/ 379 | 380 | for (auto& f : s.I) { 381 | outputF2 << (float)f << " "; 382 | } 383 | 384 | for (auto& f : s.P) { 385 | outputF2 << (float)(f) << " "; 386 | } 387 | 388 | outputF2 << " COUNT:" << s.N << " W:" << s.win << " D:" << s.draw << " L:" << s.loss <<" OriScore:"<< oriScore <<" new:"<< s.P.back()<<" TURN:"< //SSE Extensions 2 | #include //All main STD libraries 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | //#include "fast_double_parser.h" 17 | namespace fs = std::filesystem; 18 | using namespace std; 19 | 20 | const float DECAY_FACTOR = 0.02f; 21 | const float MINIMAL_DECAY =0.65f; 22 | float factor = 1.0f; 23 | //#define DUMP_TXT 24 | struct SampleInfo { 25 | vector I; 26 | vector P; 27 | float N; 28 | int TURN; 29 | int win, draw, loss; 30 | }; 31 | 32 | 33 | #define Now() chrono::high_resolution_clock::now() 34 | struct Stopwatch { 35 | chrono::high_resolution_clock::time_point c_time, c_timeout; 36 | void Start(int us) { c_time = Now(); c_timeout = c_time + chrono::microseconds(us); } 37 | void setTimeout(int us) { c_timeout = c_time + chrono::microseconds(us); } 38 | inline bool Timeout() { 39 | return Now() > c_timeout; 40 | } 41 | long long EllapsedMicroseconds() { return chrono::duration_cast(Now() - c_time).count(); } 42 | long long EllapsedMilliseconds() { return chrono::duration_cast(Now() - c_time).count(); } 43 | } stopwatch; 44 | 45 | 46 | template 47 | inline void hash_combine(std::size_t& seed, T const& v) 48 | { 49 | seed ^= std::hash()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 50 | } 51 | 52 | template 53 | size_t hashVector(vector& in) { 54 | size_t size = in.size(); 55 | size_t seed = 0; 56 | for (size_t i = 0; i < size; i++) 57 | //Combine the hash of the current vector with the hashes of the previous ones 58 | hash_combine(seed, in[i]); 59 | return seed; 60 | } 61 | /*unordered_map samples; 62 | vector hashSamples;*/ 63 | 64 | unordered_map samples; 65 | vector> hashSamples; 66 | 67 | int AVAILABLE_POOL = 0; 68 | 69 | 70 | int PROCESSED_SAMPLES = 0; 71 | float FACTORED_SAMPLES = 0.0f; 72 | bool processFile(fs::path file, const int INPUT_SIZE, const int OUTPUT_SIZE) 73 | { 74 | auto t0 = stopwatch.EllapsedMilliseconds(); 75 | cerr << "Processing " << file.filename(); 76 | //Inputs + POLICY + VALUE 77 | ifstream F(file, std::ios::in | std::ios::binary); 78 | if (!F.good()) 79 | { 80 | cerr << "Error reading file:" << file << endl; 81 | return true; 82 | } 83 | string line; 84 | SampleInfo S; 85 | S.I.resize(INPUT_SIZE); 86 | S.P.resize(OUTPUT_SIZE); 87 | int linesProcessed = 0; 88 | F.seekg(0); 89 | while (!F.eof())// (getline(F, line)) 90 | { 91 | ++linesProcessed; 92 | S.N = 1.0f; 93 | S.TURN=PROCESSED_SAMPLES; 94 | F.read(reinterpret_cast(&S.I[0]), INPUT_SIZE * sizeof(float)); 95 | if (F.eof()) 96 | break; 97 | F.read(reinterpret_cast(&S.P[0]), OUTPUT_SIZE * sizeof(float)); 98 | F.read(reinterpret_cast(&S.N), sizeof(S.N)); 99 | PROCESSED_SAMPLES+=(int)S.N; 100 | S.N *=factor; 101 | FACTORED_SAMPLES+=S.N; 102 | for (auto& spp:S.P) 103 | spp*=S.N; 104 | S.win = 0; 105 | S.loss = 0; 106 | S.draw = 0; 107 | if (S.P.back() > 0.6f) 108 | { 109 | ++S.win; 110 | } 111 | else if (S.P.back() < -0.6f) 112 | { 113 | ++S.loss; 114 | } 115 | else ++S.draw; 116 | /* 117 | 118 | double x; 119 | const char * endptr = line.c_str(); 120 | do { 121 | while (endptr!=nullptr && *endptr == ' ') 122 | { 123 | endptr++; 124 | } 125 | if (endptr == nullptr || *endptr == '\0') 126 | break; 127 | endptr = fast_double_parser::parse_number(endptr, &x); 128 | S.I.emplace_back(x); 129 | } while (endptr != nullptr && *endptr != '\0'); 130 | 131 | 132 | // istringstream iss(line); 133 | //copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter(S.I)); 134 | for (int i = (int) S.I.size() - OUTPUT_SIZE; i < (int)S.I.size(); ++i) 135 | { 136 | S.P.push_back(S.I[i]); 137 | } 138 | if (S.P.size() != OUTPUT_SIZE) 139 | { 140 | cerr << "SIZE ERROR:" << S.P.size() << " != " << OUTPUT_SIZE << endl; 141 | cerr << endl; 142 | } 143 | S.I.resize(S.I.size() - OUTPUT_SIZE); 144 | */ 145 | /*size_t HASH = 0; 146 | for (auto&f : S.I) 147 | { 148 | hash_combine(HASH, f); 149 | }*/ 150 | 151 | size_t HASH = hashVector(S.I); 152 | 153 | 154 | auto hasSample = samples.find(HASH); 155 | if (hasSample == samples.end()) //NEW 156 | { 157 | samples.emplace(HASH, S); 158 | } 159 | else { 160 | hasSample->second.N +=S.N; 161 | for (int i = 0; i < (int)hasSample->second.P.size(); ++i) 162 | { 163 | hasSample->second.P[i] += S.P[i]; 164 | } 165 | hasSample->second.win += S.win; 166 | hasSample->second.loss += S.loss; 167 | hasSample->second.draw += S.draw; 168 | } 169 | 170 | 171 | --AVAILABLE_POOL; 172 | if (AVAILABLE_POOL == 0) 173 | break; 174 | 175 | } 176 | F.close(); 177 | 178 | cerr << " Done. Lines:" << linesProcessed << " PROCESSED:" << PROCESSED_SAMPLES << " Unique:" << samples.size() << " T:" << stopwatch.EllapsedMilliseconds() - t0 <<" Decay Factor:"< 0; 180 | } 181 | 182 | int main(int argc, char* argv[]) 183 | { 184 | stopwatch.Start(0); 185 | if (argc < 8) 186 | { 187 | cerr << "ERROR parameters: " << endl; 188 | return -1; 189 | } 190 | //string folder = argv[1]; 191 | fs::directory_entry directory{ argv[1] }; 192 | string filter = argv[2]; 193 | string oFile = argv[3]; 194 | ofstream outputfile(oFile, std::ios::out | std::ios::binary); 195 | #ifdef DUMP_TXT 196 | ofstream outputF2(oFile + ".txt", std::ios::out); 197 | #endif 198 | if (!outputfile.good()) 199 | { 200 | cerr << "Invalid output file:" << argv[3] << endl; 201 | return -1; 202 | } 203 | 204 | std::regex REG(filter); 205 | int TRAINING_POOL_SIZE = atoi(argv[4]); 206 | int TRAINING_SUBSET_SIZE = atoi(argv[5]); 207 | int INPUT_SIZE = atoi(argv[6]); 208 | int OUTPUT_SIZE = atoi(argv[7]); 209 | int DELETEOLD = atoi(argv[8]); 210 | AVAILABLE_POOL = TRAINING_POOL_SIZE; 211 | 212 | if (TRAINING_SUBSET_SIZE > TRAINING_POOL_SIZE) 213 | { 214 | cerr << "ERROR: TRAINING_SUBSET_SIZE > TRAINING_POOL_SIZE" << endl; 215 | return -1; 216 | } 217 | 218 | vector filenames; 219 | for (const auto& entry : fs::directory_iterator{ directory }) { 220 | if (entry.is_regular_file()) { 221 | string sfile = entry.path().filename().string(); 222 | if (std::regex_match(sfile, REG)) 223 | filenames.push_back(entry.path()); 224 | } 225 | } 226 | //PROCESS FILES 227 | if (filenames.size() == 0) 228 | { 229 | cerr << "ERROR: No files to process, folder:" << argv[1] << " Mask files:" << filter << endl; 230 | return -1; 231 | } 232 | cerr << "Processing " << filenames.size() << " files" << endl; 233 | sort(filenames.begin(), filenames.end(), [](const auto& lhs, const auto& rhs) {return lhs.string() > rhs.string(); }); 234 | bool deletingFiles = false; 235 | for (auto& f : filenames) 236 | { 237 | if (deletingFiles) 238 | { 239 | cerr << "Removing file " << f << endl; 240 | remove(f); 241 | continue; 242 | } 243 | if (!processFile(f, INPUT_SIZE, OUTPUT_SIZE)) 244 | { 245 | if (DELETEOLD == 0) 246 | break; 247 | else 248 | deletingFiles = true; 249 | } 250 | factor = max(MINIMAL_DECAY,factor-DECAY_FACTOR); 251 | } 252 | 253 | for (auto& M : samples) { 254 | hashSamples.push_back(pair(M.first, M.second.N)); 255 | } 256 | //PICK RANDOM SAMPLES 257 | if (samples.size() == 0) 258 | { 259 | cerr << "ERROR: No samples, folder:" << argv[1] << " Mask files:" << filter << endl; 260 | return -1; 261 | } 262 | int uniqueSamples = (int)samples.size(); 263 | if (uniqueSamples > TRAINING_SUBSET_SIZE) 264 | { 265 | 266 | //Keep 20%best 267 | std::sort(hashSamples.begin(), hashSamples.end(), [](auto& a, auto& b) {return a.second > b.second; }); 268 | ofstream st("strats.txt"); 269 | st << "UNIQUE " << uniqueSamples << " PROCESSED:" << PROCESSED_SAMPLES << " Max Count:" << hashSamples[0].second << endl; 270 | for (int i = 0; i < min(200000, uniqueSamples); ++i) { 271 | st << hashSamples[i].second << endl; 272 | } 273 | st.close(); 274 | 275 | int keep20 = TRAINING_SUBSET_SIZE * 20 / 100; 276 | int keep40 = TRAINING_SUBSET_SIZE * 40 / 100; 277 | 278 | int master20 = uniqueSamples * 20 / 100; 279 | int master40 = uniqueSamples * 40 / 100; 280 | 281 | std::random_device rd; 282 | std::mt19937 g(rd()); 283 | 284 | 285 | /* auto rnd1 = std::bind(std::uniform_int_distribution(0,master20), g); 286 | for (int i = 0; i < keep20; ++i) 287 | { 288 | int j = rnd1(); 289 | if (i != j) 290 | { 291 | swap(hashSamples[i], hashSamples[j]); 292 | } 293 | }*/ 294 | auto rnd2 = std::bind(std::uniform_int_distribution(keep20, master40), g); 295 | for (int i = keep20; i < keep40; ++i) 296 | { 297 | int j = rnd2(); 298 | if (i != j) 299 | { 300 | swap(hashSamples[i], hashSamples[j]); 301 | } 302 | } 303 | auto rnd3 = std::bind(std::uniform_int_distribution(keep40, (int)hashSamples.size() - 1), g); 304 | for (int i = keep40; i < TRAINING_SUBSET_SIZE; ++i) 305 | { 306 | int j = rnd3(); 307 | if (i != j) 308 | { 309 | swap(hashSamples[i], hashSamples[j]); 310 | } 311 | } 312 | /* 313 | int master35 = uniqueSamples*35/100; 314 | auto rnd1 = std::bind(std::uniform_int_distribution(keep20,master35), g); 315 | auto rnd2 = std::bind(std::uniform_int_distribution(keep40,(int)hashSamples.size()-1), g); 316 | //Partial shuffle 317 | for (int i = keep20; i < keep40; ++i) 318 | { 319 | int j = rnd1(); 320 | if (i != j) 321 | { 322 | swap(hashSamples[i], hashSamples[j]); 323 | 324 | } 325 | } 326 | for (int i = keep40; i < TRAINING_SUBSET_SIZE; ++i) 327 | { 328 | int j = rnd2(); 329 | if (i != j) 330 | { 331 | swap(hashSamples[i], hashSamples[j]); 332 | } 333 | } 334 | */ 335 | hashSamples.resize(TRAINING_SUBSET_SIZE); 336 | } 337 | //SAVE TO FILE 338 | int totalCovered = 0; 339 | #ifdef _MSC_VER 340 | std::sort(hashSamples.begin(), hashSamples.end(), [](auto& a, auto& b) {return a.second > b.second; }); 341 | #endif 342 | if (PROCESSED_SAMPLES < 850) 343 | std::sort(hashSamples.begin(), hashSamples.end(), [=](auto& a, auto& b) {return samples[a.first].TURN < samples[b.first].TURN; }); 344 | for (auto& ttt : hashSamples) 345 | { 346 | auto& HASH = ttt.first; 347 | SampleInfo& s = samples[HASH]; 348 | totalCovered += s.N; 349 | 350 | outputfile.write(reinterpret_cast(&s.I[0]), (int)s.I.size() * sizeof(float)); 351 | if (s.N > 1.0f) 352 | { 353 | float divide = 1.0f / (float)s.N; 354 | for (auto& f : s.P) { 355 | f *= divide; 356 | } 357 | } 358 | 359 | /* float score = ((float)s.win + 0.5f * (float)s.draw) / (float)(s.win + s.draw + s.loss); 360 | float oriScore = s.P[s.P.size() - 1]; 361 | float FACTOR_WIN= 0.1f; 362 | if (score > 0.53f && score < 0.96f) 363 | { 364 | score *= FACTOR_WIN; 365 | s.P[s.P.size() - 1] = score + (1.0f - score) * s.P.back(); 366 | } 367 | else if (score < 0.47f && score > 0.04f) 368 | { //Loss majority 369 | score = 1.0f - score; 370 | score *= FACTOR_WIN; 371 | s.P[s.P.size() - 1] = -(score + (1.0f - score) * abs(s.P.back())); 372 | } 373 | */ 374 | outputfile.write(reinterpret_cast(&s.P[0]), (int)s.P.size() * sizeof(float)); 375 | outputfile.write(reinterpret_cast(&s.N), (int) sizeof(s.N)); 376 | #ifdef DUMP_TXT 377 | /* if (s.N == 1) 378 | continue;*/ 379 | 380 | for (auto& f : s.I) { 381 | outputF2 << (float)f << " "; 382 | } 383 | 384 | for (auto& f : s.P) { 385 | outputF2 << (float)(f) << " "; 386 | } 387 | 388 | outputF2 << " COUNT:" << s.N << " W:" << s.win << " D:" << s.draw << " L:" << s.loss <<" OriScore:"<< oriScore <<" new:"<< s.P.back()<<" TURN:"< 11 | #include 12 | #ifdef _WIN32 13 | #include 14 | #endif 15 | 16 | #include //map 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include //shared_ptr 31 | #include //memcpy 32 | 33 | //#define DEBUG_MODE 34 | #ifdef DEBUG_MODE 35 | #include 36 | #define ASSERT(x) assert(x) 37 | #else 38 | #define ASSERT(x) 39 | #endif 40 | 41 | union __m256_f { 42 | __m256 v; 43 | float f[8]; 44 | }; 45 | 46 | using namespace std; 47 | 48 | //AVX2 Exponential functions 49 | #define MUL _mm256_mul_ps 50 | #define FMA _mm256_fmadd_ps 51 | #define SET _mm256_set1_ps 52 | const __m256 exp_hi = SET(88.3762626647949f); 53 | const __m256 exp_lo = SET(-88.3762626647949f); 54 | const __m256 cLOG2EF = SET(1.44269504088896341f); 55 | const __m256 cexp_C1 = SET(0.693359375f); 56 | const __m256 cexp_C2 = SET(-2.12194440e-4f); 57 | const __m256 cexp_p0 = SET(1.9875691500E-4f); 58 | const __m256 cexp_p1 = SET(1.3981999507E-3f); 59 | const __m256 cexp_p2 = SET(8.3334519073E-3f); 60 | const __m256 cexp_p3 = SET(4.1665795894E-2f); 61 | const __m256 cexp_p4 = SET(1.6666665459E-1f); 62 | const __m256 cexp_p5 = SET(5.0000001201E-1f); 63 | inline __m256 exp256_ps(const __m256& V) { 64 | __m256 x = V; 65 | __m256 tmp = _mm256_setzero_ps(), fx; 66 | __m256i imm0; 67 | __m256 one = SET(1.0f); 68 | x = _mm256_min_ps(x, exp_hi); 69 | x = _mm256_max_ps(x, exp_lo); 70 | fx = MUL(x, cLOG2EF); 71 | fx = _mm256_add_ps(fx, SET(0.5f)); 72 | tmp = _mm256_floor_ps(fx); 73 | __m256 mask = _mm256_cmp_ps(tmp, fx, _CMP_GT_OS); 74 | mask = _mm256_and_ps(mask, one); 75 | fx = _mm256_sub_ps(tmp, mask); 76 | tmp = MUL(fx, cexp_C1); 77 | __m256 z = MUL(fx, cexp_C2); 78 | x = _mm256_sub_ps(x, tmp); 79 | x = _mm256_sub_ps(x, z); 80 | z = MUL(x, x); 81 | __m256 y = cexp_p0; 82 | y = FMA(y, x, cexp_p1); 83 | y = FMA(y, x, cexp_p2); 84 | y = FMA(y, x, cexp_p3); 85 | y = FMA(y, x, cexp_p4); 86 | y = FMA(y, x, cexp_p5); 87 | y = FMA(y, z, x); 88 | y = _mm256_add_ps(y, one); 89 | imm0 = _mm256_cvttps_epi32(fx); 90 | imm0 = _mm256_add_epi32(imm0, _mm256_set1_epi32(0x7f)); 91 | imm0 = _mm256_slli_epi32(imm0, 23); 92 | __m256 pow2n = _mm256_castsi256_ps(imm0); 93 | y = MUL(y, pow2n); 94 | return y; 95 | } 96 | //AVX2 Faster Exponential functions 97 | inline __m256 fast_exp256_ps(const __m256& V) { 98 | const __m256 C1 = _mm256_set1_ps(1064872507.1541044f); 99 | const __m256 C2 = _mm256_set1_ps(12102203.161561485f); 100 | return _mm256_castsi256_ps(_mm256_cvttps_epi32(_mm256_fmadd_ps(C2, V, C1))); 101 | } 102 | 103 | #undef SET 104 | #undef MUL 105 | #undef FMA 106 | 107 | template 108 | class aligned_allocator { 109 | public: 110 | typedef T *pointer; 111 | typedef const T *const_pointer; 112 | typedef T &reference; 113 | typedef const T &const_reference; 114 | typedef T value_type; 115 | typedef std::size_t size_type; 116 | typedef ptrdiff_t difference_type; 117 | 118 | T *address(T &r) const { 119 | return &r; 120 | } 121 | 122 | const T *address(const T &s) const { 123 | return &s; 124 | } 125 | 126 | std::size_t max_size() const { 127 | return (static_cast(0) - static_cast(1)) / sizeof(T); 128 | } 129 | template 130 | struct rebind { 131 | typedef aligned_allocator other; 132 | }; 133 | 134 | bool operator!=(const aligned_allocator &other) const { 135 | return !(*this == other); 136 | } 137 | 138 | void construct(T *const p, const T &t) const { 139 | void *const pv = static_cast(p); 140 | 141 | new(pv) T(t); 142 | } 143 | 144 | void destroy(T *const p) const { 145 | p->~T(); 146 | } 147 | 148 | bool operator==(const aligned_allocator &other) const { 149 | return true; 150 | } 151 | 152 | 153 | aligned_allocator() {} 154 | 155 | aligned_allocator(const aligned_allocator &) {} 156 | 157 | template 158 | aligned_allocator(const aligned_allocator &) {} 159 | 160 | ~aligned_allocator() {} 161 | 162 | T *allocate(const std::size_t n) const { 163 | if (n == 0) { 164 | return NULL; 165 | } 166 | if (n > max_size()) { 167 | throw std::length_error("aligned_allocator::allocate() - Integer overflow."); 168 | } 169 | void *const pv = _mm_malloc(n * sizeof(T), Alignment); 170 | if (pv == NULL) { 171 | throw std::bad_alloc(); 172 | } 173 | return static_cast(pv); 174 | } 175 | 176 | void deallocate(T *const p, const std::size_t n) const { 177 | _mm_free(p); 178 | } 179 | 180 | template 181 | T *allocate(const std::size_t n, const U * /* const hint */) const { 182 | return allocate(n); 183 | } 184 | 185 | private: 186 | aligned_allocator &operator=(const aligned_allocator &); 187 | }; 188 | 189 | 190 | typedef std::vector<__m256_f, aligned_allocator<__m256_f, sizeof(__m256_f)> > aligned_vector; 191 | 192 | class Tensor { 193 | public: 194 | aligned_vector xmm; 195 | uint64_t xmm_size; 196 | uint64_t size; 197 | std::vector shape; 198 | 199 | explicit Tensor(std::vector shape) : shape(shape) { 200 | size = 1; 201 | 202 | for (int x : shape) 203 | size *= x; 204 | 205 | xmm_size = static_cast(std::ceil(size / 8.0f)); 206 | 207 | xmm.resize(xmm_size); 208 | 209 | for (int i = 0; i < xmm_size; i++) { 210 | xmm[i].v = _mm256_setzero_ps(); 211 | } 212 | } 213 | 214 | explicit Tensor(aligned_vector xmm, std::vector shape) : shape(shape), xmm(std::move(xmm)) { 215 | size = 1; 216 | 217 | for (int x : shape) 218 | size *= x; 219 | 220 | xmm_size = static_cast(std::ceil(size / 8.0f)); 221 | } 222 | 223 | Tensor() : shape({ 0 }), size(0) {} 224 | ~Tensor() { 225 | xmm.clear(); 226 | shape.clear(); 227 | } 228 | /* __m256 operator[](const uint32_t& index) const { 229 | return xmm[index >>3].f[index & 7]; 230 | }*/ 231 | 232 | void load(std::vector &vec) { 233 | xmm.resize(xmm_size); 234 | xmm[xmm_size - 1].v = _mm256_setzero_ps(); //Last one to zero because it can be partially loaded 235 | memcpy(reinterpret_cast(xmm.data()), reinterpret_cast(vec.data()), size * sizeof(float)); 236 | }; 237 | explicit Tensor(std::vector &vec, std::vector shape) : shape(shape) { 238 | size = 1; 239 | 240 | for (int x : shape) 241 | size *= x; 242 | 243 | xmm_size = static_cast(std::ceil(size / 8.0f)); 244 | load(vec); 245 | 246 | }; 247 | // Get a single element (float value) from the matrix 248 | inline float getElement(const uint32_t& index) const { 249 | return xmm[index >> 3].f[index & 7]; 250 | } 251 | 252 | // Set a single element (float value) into the matrix 253 | // Caution: This might be an expensive operation if called multiple times. Use setChunk instead 254 | inline void setElement(const uint32_t& index, const float& value) { 255 | xmm[index >> 3].f[index & 7] = value; 256 | } 257 | 258 | // Set a whole chunk (8 float values) into the matrix 259 | // This is prefered over setElement 260 | inline void setChunk(const uint32_t& index, float *chunk) { 261 | ASSERT(index < xmm_size && index >= 0); 262 | xmm[index].v = _mm256_load_ps(chunk); 263 | } 264 | // Sets eight numbers together (__m256). 265 | inline void setChunk(const uint32_t& index, const __m256& chunk) { 266 | ASSERT(index < xmm_size && index >= 0); 267 | xmm[index].v = chunk; 268 | } 269 | 270 | // Retrieve a chunk from the matrix 271 | __m256 getChunk(const uint32_t& index) const { 272 | return xmm[index].v; 273 | } 274 | // Adds two matrices together, mainly for the bias. 275 | void add(Tensor &bias, Tensor &out) { 276 | 277 | ASSERT(((int)size) != ((int)bias.size)); 278 | for (int i = 0; i < bias.xmm_size; ++i) { 279 | out.setChunk(i, _mm256_add_ps(xmm[i].v, bias.xmm[i].v)); 280 | } 281 | } 282 | //Subtract two matrices. 283 | void sub(const Tensor &a, Tensor &out) { 284 | ASSERT((int)size != (int)a.size); 285 | for (uint32_t i = 0; i < xmm_size; i++) { 286 | out.setChunk(i, _mm256_sub_ps(xmm[i].v, a.xmm[i].v)); 287 | } 288 | } 289 | 290 | // Sub that takes a single value instead of an entire matrix 291 | void sub(const float &a, Tensor &out) { 292 | __m256 sub_chunk = _mm256_set1_ps(a); 293 | for (uint32_t i = 0; i < xmm_size; i++) { 294 | out.xmm[i].v = _mm256_sub_ps(xmm[i].v, sub_chunk); 295 | } 296 | } 297 | 298 | void mul(const float &a, Tensor &out) { 299 | __m256 mul_chunk = _mm256_set1_ps(a); 300 | for (uint32_t i = 0; i < xmm_size; i++) { 301 | out.xmm[i].v = _mm256_mul_ps(xmm[i].v, mul_chunk); 302 | } 303 | } 304 | 305 | // Calculates dot product of two matrices 306 | // Out is expected to be initialized with its xmm vector already resized to the correct length 307 | void dot_product(int kept_dim, const std::vector &big_matrix_vec, uint32_t big_reserve_size, 308 | const Tensor &small, uint32_t chunk_range, Tensor &out) { 309 | uint32_t out_index = 0; 310 | for (uint32_t small_chunk = 0; small_chunk < small.xmm_size; small_chunk += chunk_range) { 311 | for (uint32_t big_chunk = 0; big_chunk < xmm_size; big_chunk += chunk_range) { 312 | __m256 FMA = _mm256_setzero_ps(); 313 | for (uint32_t partial_index = 0; partial_index < chunk_range; ++partial_index) { 314 | FMA = _mm256_fmadd_ps(xmm[big_chunk + partial_index].v, small.xmm[small_chunk + partial_index].v, FMA); 315 | } 316 | out.setElement(out_index++, _mm_cvtss_f32(_mm256_castps256_ps128(hsums(FMA)))); 317 | } 318 | } 319 | } 320 | // Prints the shape. 321 | std::string shape_str() const { 322 | std::string shape_str = "(None, "; 323 | 324 | for (int i = 0; i < shape.size() - 1; i++) { 325 | shape_str += std::to_string(shape[i]) + ", "; 326 | } 327 | shape_str += std::to_string(shape[shape.size() - 1]) + ")"; 328 | return shape_str; 329 | } 330 | // reshapes the matrix. 331 | void reshape(const std::vector &new_shape) { 332 | uint64_t new_size = 1; 333 | 334 | for (int x : new_shape) { 335 | new_size *= x; 336 | } 337 | ASSERT(size == new_size); 338 | shape = new_shape; 339 | } 340 | 341 | // Does horizontal sum of a chunk v 342 | // Only works if v is __m256, __m128 requires less instructions 343 | static inline __m256 hsums(__m256 const &v) { 344 | auto x = _mm256_permute2f128_ps(v, v, 1); 345 | auto y = _mm256_add_ps(v, x); 346 | x = _mm256_shuffle_ps(y, y, _MM_SHUFFLE(2, 3, 0, 1)); 347 | x = _mm256_add_ps(x, y); 348 | y = _mm256_shuffle_ps(x, x, _MM_SHUFFLE(1, 0, 3, 2)); 349 | return _mm256_add_ps(x, y); 350 | }; 351 | 352 | // operator << : Displays contents of matrix 353 | friend std::ostream &operator<<(std::ostream &stream, const Tensor &matrix) { 354 | for (uint32_t i = 0; i < matrix.xmm_size; i++) { 355 | stream << std::to_string(i * 8) + " - ["; 356 | for (uint32_t j = 0; j < 7; j++) 357 | stream << std::to_string(matrix.xmm[i].f[j]) + " "; 358 | stream << std::to_string(matrix.xmm[i].f[7]); 359 | stream << "]\n"; 360 | } 361 | return stream; 362 | } 363 | 364 | 365 | 366 | void load(std::istream& is) { 367 | xmm.resize(xmm_size); 368 | xmm[xmm_size - 1].v = _mm256_setzero_ps(); //Last one to zero because it can be partially loaded 369 | is.read(reinterpret_cast(xmm.data()), size * sizeof(float)); 370 | }; 371 | void save(std::ostream& os) { 372 | os.write(reinterpret_cast(xmm.data()), size * sizeof(float)); 373 | }; 374 | 375 | }; 376 | 377 | std::vector extractValues(const std::string &file_path) { 378 | char c; 379 | float val; 380 | 381 | std::ifstream file; 382 | file.open(file_path); 383 | 384 | std::vector values; 385 | 386 | // Loop until beginning of array (openining '[') 387 | while ((file >> c) && (c != '[')) {} 388 | 389 | // Keep reading values until closing ']' is met 390 | while ((file >> val >> c) && ((c == ',') || (c == ']'))) { 391 | values.push_back(val); 392 | } 393 | 394 | return values; 395 | } 396 | 397 | // Loads the matrices. 398 | Tensor loadMatrix(const std::string &matrix_dir, const std::string &matrix_name) { 399 | std::vector image_vec(extractValues(matrix_dir + "/" + matrix_name + ".ahsf")); 400 | std::vector image_shape(3); 401 | 402 | std::ifstream shape_file; 403 | shape_file.open(matrix_dir + "/" + matrix_name + "_shape.ahsf"); 404 | shape_file >> image_shape[0] >> image_shape[1] >> image_shape[2]; 405 | 406 | return Tensor(image_vec, image_shape); 407 | } 408 | 409 | // Change the image shape to make it in columns depending on the size of the filter. 410 | 411 | //std::function function 412 | void Activation_Identity(const Tensor& input, Tensor& output) { 413 | if (&input != &output) { 414 | output = input; 415 | } 416 | } 417 | void Activation_ReLU(const Tensor& input, Tensor& output) { 418 | __m256 zero = _mm256_setzero_ps(); 419 | for (uint32_t i = 0; i < output.xmm_size; ++i) 420 | { 421 | output.xmm[i].v = _mm256_max_ps(input.xmm[i].v, zero); 422 | } 423 | } 424 | template //can't pass a float as template 425 | void Activation_LeakyReLU(const Tensor& input, Tensor& output) { 426 | const __m256 zero = _mm256_setzero_ps(); 427 | const __m256 vAlpha = _mm256_set1_ps((float)N / (float)D); 428 | for (uint32_t i = 0; i < output.xmm_size; ++i) 429 | { 430 | output.xmm[i].v = _mm256_add_ps(_mm256_max_ps(input.xmm[i].v, zero), _mm256_min_ps(_mm256_mul_ps(input.xmm[i].v, vAlpha), zero)); 431 | } 432 | } 433 | 434 | void Activation_Softmax(const Tensor& input, Tensor& output) { 435 | float sum = 0.0f; 436 | int rem = 8-(output.size % 8); 437 | if (rem != 0) 438 | { 439 | for (int i = 0; i < rem; ++i) 440 | { 441 | output.setElement( (uint32_t)(output.xmm_size * 8 - i - 1),-99999999.99f); 442 | } 443 | } 444 | for (uint32_t i = 0; i < output.xmm_size; ++i) 445 | { 446 | output.xmm[i].v = exp256_ps(input.xmm[i].v); 447 | #ifdef _MSC_VER 448 | sum += output.hsums(output.xmm[i].v).m256_f32[0]; 449 | #else 450 | sum += output.hsums(output.xmm[i].v)[0]; 451 | #endif 452 | } 453 | sum = 1.0f / sum; 454 | output.mul(sum, output); 455 | } 456 | 457 | void Activation_Tanh(const Tensor& input, Tensor& output) { 458 | for (uint32_t i = 0; i < output.size; ++i) { 459 | output.setElement(i, tanh(input.getElement(i))); 460 | } 461 | } 462 | void Activation_Sigmoid(const Tensor& input, Tensor& output) { 463 | const __m256 one = _mm256_set1_ps(1.0f); 464 | for (uint32_t i = 0; i < output.xmm_size; ++i) 465 | { 466 | output.xmm[i].v = exp256_ps(input.xmm[i].v); 467 | auto divisor = _mm256_add_ps(output.xmm[i].v, one); 468 | output.xmm[i].v = _mm256_div_ps(output.xmm[i].v, divisor); 469 | } 470 | } 471 | typedef std::function Activators; 472 | const Activators NONE = Activation_Identity; 473 | const Activators RELU = Activation_ReLU; 474 | const Activators TANH = Activation_Tanh; 475 | const Activators SIGMOID = Activation_Sigmoid; 476 | const Activators SOFTMAX = Activation_Softmax; 477 | 478 | class Layer : public std::enable_shared_from_this { 479 | public: 480 | shared_ptr inputLayer = nullptr; 481 | vector> outputLayers; 482 | 483 | Tensor output; 484 | Activators activator; 485 | std::string name; 486 | 487 | shared_ptr link(shared_ptr _linkLayer) 488 | { 489 | ASSERT(_linkLayer->output.size > 0); 490 | ASSERT(inputLayer == nullptr); //Cannot connect to multiple inputs 491 | inputLayer = _linkLayer; 492 | inputLayer->outputLayers.push_back(shared_from_this()); 493 | //Redimension based on input Weights and Bias 494 | initialize(inputLayer->output.shape); 495 | return shared_from_this(); //return this Layer for future connections 496 | } 497 | inline shared_ptr operator()(shared_ptr _linkLayer) 498 | { 499 | return link(_linkLayer); 500 | } 501 | 502 | 503 | 504 | int rem; 505 | 506 | explicit Layer(std::string name, Activators activator = NONE) : name(std::move(name)), activator(activator) {}; 507 | 508 | virtual ~Layer() = default; 509 | // Calculate output is the function that computes the output of this layer. 510 | virtual void calculateOutput(Tensor &input_mat) = 0; 511 | virtual void predict() = 0; 512 | // Precomute sets up the required matrices and variables required for calculateOutput to work. 513 | virtual void initialize(vector& Dim) = 0; 514 | virtual void precompute() = 0; 515 | virtual void load(std::istream& is) = 0; 516 | virtual void save(std::ostream& os) = 0; 517 | virtual string getType() = 0; 518 | virtual int countParams() = 0; 519 | virtual int summary() { 520 | int trainableParams = countParams(); 521 | cerr << left << setw(28) << setfill(' ') << (name + " (" + getType() + ")") << setw(26) << output.shape_str() << trainableParams << endl; 522 | return trainableParams; 523 | }; 524 | }; 525 | 526 | class ActivateLayer : public Layer { 527 | public: 528 | ActivateLayer(std::string name, Activators act) : Layer(name, act) {} 529 | inline void calculateOutput(Tensor &input_mat) override { 530 | activator(input_mat, output); 531 | }; 532 | inline void predict()override { 533 | ASSERT(inputLayer != nullptr); 534 | calculateOutput(inputLayer->output); 535 | }; 536 | void initialize(vector& Dim) override { 537 | output = Tensor(Dim); 538 | } 539 | void precompute()override { 540 | ASSERT(inputLayer != nullptr); 541 | output = inputLayer->output; //Same Tensor 542 | }; 543 | void load(std::istream& is)override {}; 544 | void save(std::ostream& os)override {}; 545 | inline int countParams() override { return 0; }; 546 | }; 547 | class Softmax : public ActivateLayer { 548 | public: 549 | Softmax(std::string name = "Softmax") :ActivateLayer(name, SOFTMAX) {} 550 | string getType() override { return "Softmax"; }; 551 | }; 552 | class Tanh : public ActivateLayer { 553 | public: 554 | Tanh(std::string name = "Tanh") :ActivateLayer(name, TANH) {} 555 | string getType() override { return "Tanh"; }; 556 | }; 557 | class ReLU : public ActivateLayer { 558 | public: 559 | ReLU(std::string name = "ReLU") :ActivateLayer(name, RELU) {} 560 | string getType() override { return "ReLU"; }; 561 | }; 562 | class Sigmoid : public ActivateLayer { 563 | public: 564 | Sigmoid(std::string name = "Sigmoid") :ActivateLayer(name, SIGMOID) {} 565 | string getType() override { return "Sigmoid"; }; 566 | }; 567 | class WeightBiasLayer : public Layer { //WeightBiasLayer 568 | protected: 569 | vector weights; 570 | Tensor bias; 571 | int num_of_outputs; 572 | public: 573 | WeightBiasLayer(std::string name, Activators activator, int num_of_outputs) 574 | : Layer(name, activator), num_of_outputs(num_of_outputs){}; 575 | 576 | ~WeightBiasLayer() {}; 577 | //virtual void calculateOutput(Tensor &inputMat) = 0; 578 | 579 | inline void predict()override { 580 | ASSERT(inputLayer != nullptr); 581 | calculateOutput(inputLayer->output); 582 | }; 583 | 584 | void load(std::istream& is)override { 585 | for (auto&w: weights) 586 | w.load(is); 587 | bias.load(is); 588 | }; 589 | void save(std::ostream& os)override { 590 | for (auto& w : weights) 591 | w.save(os); 592 | bias.save(os); 593 | }; 594 | inline int countParams() override { return (int)(weights.size()*weights[0].size + bias.size); }; 595 | }; 596 | 597 | class Input : public Layer { 598 | public: 599 | //std::vector input_dim; 600 | Input(std::string name, std::vector input_dim) : Layer(name)//, input_dim(input_dim) 601 | { 602 | output = Tensor(input_dim); 603 | }; 604 | Input(std::vector input_dim) : Layer("Input")//, input_dim(input_dim) 605 | { 606 | output = Tensor(input_dim); 607 | }; 608 | ~Input() {}; 609 | void calculateOutput(Tensor &input_mat) override { 610 | if (&output != &input_mat) 611 | { 612 | output = input_mat; 613 | } 614 | }; 615 | //Somebody took care to update output to the correct inputs.... 616 | inline void predict()override {}; 617 | void initialize(vector& Dim) override {}//Already done at constructor 618 | void precompute()override { 619 | //Already done at constructor 620 | } 621 | void load(std::istream& is)override {}; 622 | void save(std::ostream& os)override {}; 623 | string getType() override { return "Input"; }; 624 | inline int countParams() override { return 0; }; 625 | int summary() override { return 0; }; 626 | 627 | virtual Tensor* getInputTensor(){ 628 | return &output; 629 | } 630 | virtual void RestartInputs() { 631 | for (int i = 0; i < output.xmm_size; ++i) 632 | { 633 | output.xmm[i].v = _mm256_setzero_ps(); 634 | } 635 | } 636 | virtual void SetBit(int N) { 637 | output.xmm[0].f[N] = 1.0f; 638 | } 639 | virtual void UnsetBit(int N) { 640 | output.xmm[0].f[N] = 0.0f; 641 | } 642 | virtual void SetFloat(int N,float val) { 643 | output.xmm[0].f[N] = val; 644 | } 645 | virtual void UnsetFloat(int N) { 646 | output.xmm[0].f[N] = 0.0f; 647 | } 648 | }; 649 | 650 | class Dense : public WeightBiasLayer { 651 | public: 652 | Dense(std::string name, int num_of_outputs, Activators activator) 653 | : WeightBiasLayer(name, activator, num_of_outputs) { }; 654 | Dense(int num_of_outputs, Activators activator = NONE) 655 | : WeightBiasLayer("Dense", activator, num_of_outputs) { }; 656 | 657 | ~Dense() {}; 658 | 659 | void calculateOutput(Tensor &input_mat) override { 660 | for (int i = 0; i < output.xmm_size; ++i) { 661 | output.xmm[i].v = bias.xmm[i].v; 662 | } 663 | for (size_t N = 0; N < input_mat.size; N++) { 664 | float val = input_mat.xmm[0].f[N]; 665 | if (val == 0.0f) 666 | continue; 667 | else if (val == 1.0f) { 668 | for (int i = 0; i < output.xmm_size; ++i) { 669 | output.xmm[i].v = _mm256_add_ps(weights[N].xmm[i].v, output.xmm[i].v); 670 | } 671 | } 672 | else { 673 | auto fm = _mm256_set1_ps(val); 674 | for (int i = 0; i < output.xmm_size; ++i) { 675 | output.xmm[i].v = _mm256_fmadd_ps(fm, weights[N].xmm[i].v, output.xmm[i].v); 676 | } 677 | } 678 | } 679 | activator(output, output); 680 | }; 681 | 682 | // Sets up the Dense layer, it takes the shape of the matrix before it to compute its own matrices. 683 | void initialize(vector& Dim) override { 684 | int totalSize = 1; 685 | for (int& n : Dim) 686 | totalSize *= n; 687 | output = Tensor(vector{num_of_outputs}); 688 | for (int i = 0; i < totalSize; ++i) 689 | weights.emplace_back(Tensor(vector{num_of_outputs})); 690 | bias = Tensor(vector{num_of_outputs}); 691 | #ifdef DEBUG_MODE 692 | cerr << "***** LAYER " << name << "******" << endl; 693 | //cerr << "Output " << ":" << output.shape_str()<> inputs; 708 | vector> outputs; 709 | bool Loaded = false; 710 | Model(vector> inputs, vector> outputs) 711 | : inputs(inputs) 712 | , outputs(outputs) 713 | { 714 | ASSERT(!inputs.empty()); 715 | buildPath(); 716 | } 717 | Model() {} 718 | ~Model() { 719 | inputs.clear(); 720 | outputs.clear(); 721 | m_forwardPath.clear(); 722 | }; 723 | void predict(); 724 | void predictSingleOutput(shared_ptr output); 725 | void summary(); 726 | void loadWeights(const std::string& f); 727 | void saveWeights(const std::string& f); 728 | private: 729 | void buildPath(); 730 | vector m_forwardPath; //Predicts all outputs 731 | map> m_forwardSingle; //For single output predictions 732 | }; 733 | void Model::summary() { 734 | int trainableParams = 0; 735 | const string line = "_________________________________________________________________"; 736 | const string line2 = "================================================================="; 737 | cout << line << endl; 738 | cout << "Layer (type) Output Shape Param # " << endl; 739 | for (size_t i = 1; i < m_forwardPath.size(); ++i) 740 | { 741 | cout << (i == 1 ? line2 : line) << endl; //Skip 1st layer, input 742 | trainableParams += m_forwardPath[i]->summary(); 743 | } 744 | cout << line2 << endl; 745 | cout << "Total params : " << trainableParams << endl; 746 | cout << "Trainable params : " << trainableParams << endl; 747 | cout << "Non - trainable params : 0" << endl; 748 | cout << line << endl; 749 | } 750 | 751 | //NOTE: prediction assumes that Input Layers are properly loaded 752 | void Model::predict() { 753 | if (!Loaded) 754 | throw std::invalid_argument("Model weights not loaded"); 755 | for (auto&& m : m_forwardPath) { 756 | m->predict(); 757 | } 758 | } 759 | 760 | void Model::predictSingleOutput(shared_ptr output) { 761 | if (!Loaded) 762 | throw std::invalid_argument("Model weights not loaded"); 763 | for (auto&& m : m_forwardSingle[output.get()]) { 764 | m->predict(); 765 | } 766 | } 767 | 768 | map> m_forwardSingle; //For single output predictions 769 | 770 | void Model::loadWeights(const std::string& f) { 771 | std::ifstream is(f, std::ifstream::in | std::ios::binary); 772 | if (is.good()) 773 | { 774 | for (auto& m : m_forwardPath) { 775 | m->load(is); 776 | } 777 | for (auto& m : m_forwardPath) { 778 | m->precompute(); 779 | } 780 | Loaded = true; 781 | } 782 | } 783 | void Model::saveWeights(const std::string& f) { 784 | ofstream os(f, std::ifstream::out | std::ios::binary); 785 | for (auto&& m : m_forwardPath) { 786 | m->save(os); 787 | } 788 | } 789 | void Model::buildPath() { 790 | // build forward path by taking dependencies into account (topological sort) 791 | m_forwardPath.clear(); 792 | map deps; 793 | 794 | for (auto l : inputs) 795 | { 796 | m_forwardPath.push_back(l.get()); 797 | } 798 | 799 | for (uint32_t i = 0; i < m_forwardPath.size(); i++) 800 | { 801 | auto layer = m_forwardPath[i]; 802 | for (auto wp : layer->outputLayers) 803 | { 804 | auto next = wp.lock().get(); 805 | const size_t n = 1;//next->inputs.size(); 806 | if (n > 1) 807 | deps[layer]++; 808 | 809 | if (n == 1 || n == deps[next]) 810 | m_forwardPath.push_back(next); 811 | } 812 | } 813 | //Create path for single outputs. I.e. one path for policy and another for value 814 | m_forwardSingle.clear(); 815 | deps.clear(); 816 | for (auto&& O : outputs) { 817 | Layer* layer = O.get(); 818 | m_forwardSingle[layer].clear(); 819 | auto& V = m_forwardSingle[layer]; 820 | while (layer != nullptr && deps[layer] == 0) { 821 | V.insert(V.begin(), layer); 822 | deps[layer]++; 823 | layer = layer->inputLayer.get(); 824 | } 825 | } 826 | 827 | 828 | 829 | } 830 | -------------------------------------------------------------------------------- /old_uncleaned_code/NN_Mokka.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | //Compile with -O3 -march=core-avx2 -mavx2 -mfma 3 | //#define LOW_MEMORY_USE 4 | 5 | #ifndef _MSC_VER 6 | #pragma GCC optimize("O3","omit-frame-pointer","inline") 7 | //#pragma GCC option("arch=native","tune=native","no-zeroupper") 8 | #pragma GCC target("avx2,fma") 9 | #endif 10 | #include 11 | #include 12 | #ifdef _WIN32 13 | #include 14 | #endif 15 | 16 | #include //map 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include //shared_ptr 31 | #include //memcpy 32 | 33 | //#define DEBUG_MODE 34 | #ifdef DEBUG_MODE 35 | #include 36 | #define ASSERT(x) assert(x) 37 | #else 38 | #define ASSERT(x) 39 | #endif 40 | 41 | union __m256_f { 42 | __m256 v; 43 | float f[8]; 44 | }; 45 | 46 | using namespace std; 47 | 48 | //AVX2 Exponential functions 49 | #define MUL _mm256_mul_ps 50 | #define FMA _mm256_fmadd_ps 51 | #define SET _mm256_set1_ps 52 | const __m256 exp_hi = SET(88.3762626647949f); 53 | const __m256 exp_lo = SET(-88.3762626647949f); 54 | const __m256 cLOG2EF = SET(1.44269504088896341f); 55 | const __m256 cexp_C1 = SET(0.693359375f); 56 | const __m256 cexp_C2 = SET(-2.12194440e-4f); 57 | const __m256 cexp_p0 = SET(1.9875691500E-4f); 58 | const __m256 cexp_p1 = SET(1.3981999507E-3f); 59 | const __m256 cexp_p2 = SET(8.3334519073E-3f); 60 | const __m256 cexp_p3 = SET(4.1665795894E-2f); 61 | const __m256 cexp_p4 = SET(1.6666665459E-1f); 62 | const __m256 cexp_p5 = SET(5.0000001201E-1f); 63 | inline __m256 exp256_ps(const __m256& V) { 64 | __m256 x = V; 65 | __m256 tmp = _mm256_setzero_ps(), fx; 66 | __m256i imm0; 67 | __m256 one = SET(1.0f); 68 | x = _mm256_min_ps(x, exp_hi); 69 | x = _mm256_max_ps(x, exp_lo); 70 | fx = MUL(x, cLOG2EF); 71 | fx = _mm256_add_ps(fx, SET(0.5f)); 72 | tmp = _mm256_floor_ps(fx); 73 | __m256 mask = _mm256_cmp_ps(tmp, fx, _CMP_GT_OS); 74 | mask = _mm256_and_ps(mask, one); 75 | fx = _mm256_sub_ps(tmp, mask); 76 | tmp = MUL(fx, cexp_C1); 77 | __m256 z = MUL(fx, cexp_C2); 78 | x = _mm256_sub_ps(x, tmp); 79 | x = _mm256_sub_ps(x, z); 80 | z = MUL(x, x); 81 | __m256 y = cexp_p0; 82 | y = FMA(y, x, cexp_p1); 83 | y = FMA(y, x, cexp_p2); 84 | y = FMA(y, x, cexp_p3); 85 | y = FMA(y, x, cexp_p4); 86 | y = FMA(y, x, cexp_p5); 87 | y = FMA(y, z, x); 88 | y = _mm256_add_ps(y, one); 89 | imm0 = _mm256_cvttps_epi32(fx); 90 | imm0 = _mm256_add_epi32(imm0, _mm256_set1_epi32(0x7f)); 91 | imm0 = _mm256_slli_epi32(imm0, 23); 92 | __m256 pow2n = _mm256_castsi256_ps(imm0); 93 | y = MUL(y, pow2n); 94 | return y; 95 | } 96 | //AVX2 Faster Exponential functions 97 | inline __m256 fast_exp256_ps(const __m256& V) { 98 | const __m256 C1 = _mm256_set1_ps(1064872507.1541044f); 99 | const __m256 C2 = _mm256_set1_ps(12102203.161561485f); 100 | return _mm256_castsi256_ps(_mm256_cvttps_epi32(_mm256_fmadd_ps(C2, V, C1))); 101 | } 102 | 103 | #undef SET 104 | #undef MUL 105 | #undef FMA 106 | 107 | template 108 | class aligned_allocator { 109 | public: 110 | typedef T *pointer; 111 | typedef const T *const_pointer; 112 | typedef T &reference; 113 | typedef const T &const_reference; 114 | typedef T value_type; 115 | typedef std::size_t size_type; 116 | typedef ptrdiff_t difference_type; 117 | 118 | T *address(T &r) const { 119 | return &r; 120 | } 121 | 122 | const T *address(const T &s) const { 123 | return &s; 124 | } 125 | 126 | std::size_t max_size() const { 127 | return (static_cast(0) - static_cast(1)) / sizeof(T); 128 | } 129 | template 130 | struct rebind { 131 | typedef aligned_allocator other; 132 | }; 133 | 134 | bool operator!=(const aligned_allocator &other) const { 135 | return !(*this == other); 136 | } 137 | 138 | void construct(T *const p, const T &t) const { 139 | void *const pv = static_cast(p); 140 | 141 | new(pv) T(t); 142 | } 143 | 144 | void destroy(T *const p) const { 145 | p->~T(); 146 | } 147 | 148 | bool operator==(const aligned_allocator &other) const { 149 | return true; 150 | } 151 | 152 | 153 | aligned_allocator() {} 154 | 155 | aligned_allocator(const aligned_allocator &) {} 156 | 157 | template 158 | aligned_allocator(const aligned_allocator &) {} 159 | 160 | ~aligned_allocator() {} 161 | 162 | T *allocate(const std::size_t n) const { 163 | if (n == 0) { 164 | return NULL; 165 | } 166 | if (n > max_size()) { 167 | throw std::length_error("aligned_allocator::allocate() - Integer overflow."); 168 | } 169 | void *const pv = _mm_malloc(n * sizeof(T), Alignment); 170 | if (pv == NULL) { 171 | throw std::bad_alloc(); 172 | } 173 | return static_cast(pv); 174 | } 175 | 176 | void deallocate(T *const p, const std::size_t n) const { 177 | _mm_free(p); 178 | } 179 | 180 | template 181 | T *allocate(const std::size_t n, const U * /* const hint */) const { 182 | return allocate(n); 183 | } 184 | 185 | private: 186 | aligned_allocator &operator=(const aligned_allocator &); 187 | }; 188 | 189 | 190 | typedef std::vector<__m256_f, aligned_allocator<__m256_f, sizeof(__m256_f)> > aligned_vector; 191 | 192 | class Tensor { 193 | public: 194 | aligned_vector xmm; 195 | uint64_t xmm_size; 196 | uint64_t size; 197 | std::vector shape; 198 | 199 | explicit Tensor(std::vector shape) : shape(shape) { 200 | size = 1; 201 | 202 | for (int x : shape) 203 | size *= x; 204 | 205 | xmm_size = static_cast(std::ceil(size / 8.0f)); 206 | 207 | xmm.resize(xmm_size); 208 | 209 | for (int i = 0; i < xmm_size; i++) { 210 | xmm[i].v = _mm256_setzero_ps(); 211 | } 212 | } 213 | 214 | explicit Tensor(aligned_vector xmm, std::vector shape) : shape(shape), xmm(std::move(xmm)) { 215 | size = 1; 216 | 217 | for (int x : shape) 218 | size *= x; 219 | 220 | xmm_size = static_cast(std::ceil(size / 8.0f)); 221 | } 222 | 223 | Tensor() : shape({ 0 }), size(0) {} 224 | ~Tensor() { 225 | xmm.clear(); 226 | shape.clear(); 227 | } 228 | /* __m256 operator[](const uint32_t& index) const { 229 | return xmm[index >>3].f[index & 7]; 230 | }*/ 231 | 232 | void load(std::vector &vec) { 233 | xmm.resize(xmm_size); 234 | xmm[xmm_size - 1].v = _mm256_setzero_ps(); //Last one to zero because it can be partially loaded 235 | memcpy(reinterpret_cast(xmm.data()), reinterpret_cast(vec.data()), size * sizeof(float)); 236 | }; 237 | explicit Tensor(std::vector &vec, std::vector shape) : shape(shape) { 238 | size = 1; 239 | 240 | for (int x : shape) 241 | size *= x; 242 | 243 | xmm_size = static_cast(std::ceil(size / 8.0f)); 244 | load(vec); 245 | 246 | }; 247 | // Get a single element (float value) from the matrix 248 | inline float getElement(const uint32_t& index) const { 249 | return xmm[index >> 3].f[index & 7]; 250 | } 251 | 252 | // Set a single element (float value) into the matrix 253 | // Caution: This might be an expensive operation if called multiple times. Use setChunk instead 254 | inline void setElement(const uint32_t& index, const float& sumScore) { 255 | xmm[index >> 3].f[index & 7] = sumScore; 256 | } 257 | 258 | // Set a whole chunk (8 float values) into the matrix 259 | // This is prefered over setElement 260 | inline void setChunk(const uint32_t& index, float *chunk) { 261 | ASSERT(index < xmm_size && index >= 0); 262 | xmm[index].v = _mm256_load_ps(chunk); 263 | } 264 | // Sets eight numbers together (__m256). 265 | inline void setChunk(const uint32_t& index, const __m256& chunk) { 266 | ASSERT(index < xmm_size && index >= 0); 267 | xmm[index].v = chunk; 268 | } 269 | 270 | // Retrieve a chunk from the matrix 271 | __m256 getChunk(const uint32_t& index) const { 272 | return xmm[index].v; 273 | } 274 | // Adds two matrices together, mainly for the bias. 275 | void add(Tensor bias, Tensor &out) { 276 | 277 | ASSERT(((int)size) != ((int)bias.size)); 278 | for (int i = 0; i < bias.xmm_size; ++i) { 279 | out.setChunk(i, _mm256_add_ps(xmm[i].v, bias.xmm[i].v)); 280 | } 281 | } 282 | //Subtract two matrices. 283 | void sub(const Tensor &a, Tensor &out) { 284 | ASSERT((int)size != (int)a.size); 285 | for (uint32_t i = 0; i < xmm_size; i++) { 286 | out.setChunk(i, _mm256_sub_ps(xmm[i].v, a.xmm[i].v)); 287 | } 288 | } 289 | 290 | // Sub that takes a single value instead of an entire matrix 291 | void sub(const float &a, Tensor &out) { 292 | __m256 sub_chunk = _mm256_set1_ps(a); 293 | for (uint32_t i = 0; i < xmm_size; i++) { 294 | out.xmm[i].v = _mm256_sub_ps(xmm[i].v, sub_chunk); 295 | } 296 | } 297 | 298 | void mul(const float &a, Tensor &out) { 299 | __m256 mul_chunk = _mm256_set1_ps(a); 300 | for (uint32_t i = 0; i < xmm_size; i++) { 301 | out.xmm[i].v = _mm256_mul_ps(xmm[i].v, mul_chunk); 302 | } 303 | } 304 | 305 | // Calculates dot product of two matrices 306 | // Out is expected to be initialized with its xmm vector already resized to the correct length 307 | void dot_product(int kept_dim, const std::vector &big_matrix_vec, uint32_t big_reserve_size, 308 | const Tensor &small, uint32_t chunk_range, Tensor &out) { 309 | uint32_t out_index = 0; 310 | for (uint32_t small_chunk = 0; small_chunk < small.xmm_size; small_chunk += chunk_range) { 311 | for (uint32_t big_chunk = 0; big_chunk < xmm_size; big_chunk += chunk_range) { 312 | __m256 FMA = _mm256_setzero_ps(); 313 | for (uint32_t partial_index = 0; partial_index < chunk_range; ++partial_index) { 314 | FMA = _mm256_fmadd_ps(xmm[big_chunk + partial_index].v, small.xmm[small_chunk + partial_index].v, FMA); 315 | } 316 | out.setElement(out_index++, _mm_cvtss_f32(_mm256_castps256_ps128(hsums(FMA)))); 317 | } 318 | } 319 | } 320 | // Prints the shape. 321 | std::string shape_str() const { 322 | std::string shape_str = "(None, "; 323 | 324 | for (int i = 0; i < shape.size() - 1; i++) { 325 | shape_str += std::to_string(shape[i]) + ", "; 326 | } 327 | shape_str += std::to_string(shape[shape.size() - 1]) + ")"; 328 | return shape_str; 329 | } 330 | // reshapes the matrix. 331 | void reshape(const std::vector &new_shape) { 332 | uint64_t new_size = 1; 333 | 334 | for (int x : new_shape) { 335 | new_size *= x; 336 | } 337 | ASSERT(size == new_size); 338 | shape = new_shape; 339 | } 340 | 341 | // Does horizontal sum of a chunk v 342 | // Only works if v is __m256, __m128 requires less instructions 343 | static inline __m256 hsums(__m256 const &v) { 344 | auto x = _mm256_permute2f128_ps(v, v, 1); 345 | auto y = _mm256_add_ps(v, x); 346 | x = _mm256_shuffle_ps(y, y, _MM_SHUFFLE(2, 3, 0, 1)); 347 | x = _mm256_add_ps(x, y); 348 | y = _mm256_shuffle_ps(x, x, _MM_SHUFFLE(1, 0, 3, 2)); 349 | return _mm256_add_ps(x, y); 350 | }; 351 | 352 | // operator << : Displays contents of matrix 353 | friend std::ostream &operator<<(std::ostream &stream, const Tensor &matrix) { 354 | for (uint32_t i = 0; i < matrix.xmm_size; i++) { 355 | stream << std::to_string(i * 8) + " - ["; 356 | for (uint32_t j = 0; j < 7; j++) 357 | stream << std::to_string(matrix.xmm[i].f[j]) + " "; 358 | stream << std::to_string(matrix.xmm[i].f[7]); 359 | stream << "]\n"; 360 | } 361 | return stream; 362 | } 363 | 364 | 365 | 366 | void load(std::istream& is) { 367 | xmm.resize(xmm_size); 368 | xmm[xmm_size - 1].v = _mm256_setzero_ps(); //Last one to zero because it can be partially loaded 369 | is.read(reinterpret_cast(xmm.data()), size * sizeof(float)); 370 | }; 371 | void save(std::ostream& os) { 372 | os.write(reinterpret_cast(xmm.data()), size * sizeof(float)); 373 | }; 374 | 375 | }; 376 | 377 | std::vector extractValues(const std::string &file_path) { 378 | char c; 379 | float val; 380 | 381 | std::ifstream file; 382 | file.open(file_path); 383 | 384 | std::vector values; 385 | 386 | // Loop until beginning of array (openining '[') 387 | while ((file >> c) && (c != '[')) {} 388 | 389 | // Keep reading values until closing ']' is met 390 | while ((file >> val >> c) && ((c == ',') || (c == ']'))) { 391 | values.push_back(val); 392 | } 393 | 394 | return values; 395 | } 396 | 397 | // Loads the matrices. 398 | Tensor loadMatrix(const std::string &matrix_dir, const std::string &matrix_name) { 399 | std::vector image_vec(extractValues(matrix_dir + "/" + matrix_name + ".ahsf")); 400 | std::vector image_shape(3); 401 | 402 | std::ifstream shape_file; 403 | shape_file.open(matrix_dir + "/" + matrix_name + "_shape.ahsf"); 404 | shape_file >> image_shape[0] >> image_shape[1] >> image_shape[2]; 405 | 406 | return Tensor(image_vec, image_shape); 407 | } 408 | 409 | // Change the image shape to make it in columns depending on the size of the filter. 410 | void im2col(Tensor &input_mat, const std::vector &filterShape, Tensor &out, int s, int pad) { 411 | int index = 0; 412 | int count = 0; 413 | int filter_size = filterShape[0] * filterShape[1] * filterShape[2]; 414 | int kernel_size = filterShape[0]; 415 | int tt, yy, tem1, tem2; 416 | int x, y, z; 417 | if (input_mat.shape.size() == 1) 418 | { 419 | y = 1; x = 1; z = input_mat.shape[0]; 420 | 421 | } 422 | else if (input_mat.shape.size() == 2) 423 | { 424 | y = input_mat.shape[0]; x = 1; z = input_mat.shape[1]; 425 | } 426 | else 427 | { 428 | y = input_mat.shape[1]; x = input_mat.shape[0]; z = input_mat.shape[2]; 429 | } 430 | 431 | for (int i = 0; i < y; i = i + s) { //length y 432 | for (int k = 0; k < x; k = k + s) { //width x 433 | for (int j = 0; j < z; j++) { // depth z 434 | tt = k - pad + kernel_size - 1; 435 | yy = i - pad + kernel_size - 1; 436 | if (tt < x + pad && yy < x + pad) { 437 | for (int l = i - pad; l < i - pad + kernel_size && l < y + pad; l++) { // for i 438 | for (int m = k - pad; m < k - pad + kernel_size && m < x + pad; m++) { //for j 439 | tem1 = m; 440 | tem2 = l; 441 | if (tem1 >= 0 && tem2 >= 0 && tem1 < x && tem2 < y) { 442 | out.setElement(static_cast(index), input_mat.getElement( 443 | static_cast(tem1 + tem2 * x + j * x * y))); 444 | } 445 | index++; 446 | count++; 447 | if (count >= filter_size) { 448 | index += 8 - (filter_size % 8); 449 | count = 0; 450 | } 451 | } 452 | } 453 | } 454 | } 455 | } 456 | } 457 | } 458 | 459 | 460 | //std::function function 461 | void Activation_Identity(const Tensor& input, Tensor& output) { 462 | if (&input != &output) { 463 | output = input; 464 | } 465 | } 466 | void Activation_ReLU(const Tensor& input, Tensor& output) { 467 | __m256 zero = _mm256_setzero_ps(); 468 | for (uint32_t i = 0; i < output.xmm_size; ++i) 469 | { 470 | output.xmm[i].v = _mm256_max_ps(input.xmm[i].v, zero); 471 | } 472 | } 473 | template //can't pass a float as template 474 | void Activation_LeakyReLU(const Tensor& input, Tensor& output) { 475 | const __m256 zero = _mm256_setzero_ps(); 476 | const __m256 vAlpha = _mm256_set1_ps((float)N / (float)D); 477 | for (uint32_t i = 0; i < output.xmm_size; ++i) 478 | { 479 | output.xmm[i].v = _mm256_add_ps(_mm256_max_ps(input.xmm[i].v, zero), _mm256_min_ps(_mm256_mul_ps(input.xmm[i].v, vAlpha), zero)); 480 | } 481 | } 482 | 483 | void Activation_Softmax(const Tensor& input, Tensor& output) { 484 | float sum = 0.0f; 485 | int rem = 8-(output.size % 8); 486 | if (rem != 0) 487 | { 488 | for (int i = 0; i < rem; ++i) 489 | { 490 | output.setElement( (uint32_t)(output.xmm_size * 8 - i - 1),-99999999.99f); 491 | } 492 | } 493 | for (uint32_t i = 0; i < output.xmm_size; ++i) 494 | { 495 | output.xmm[i].v = exp256_ps(input.xmm[i].v); 496 | #ifdef _MSC_VER 497 | sum += output.hsums(output.xmm[i].v).m256_f32[0]; 498 | #else 499 | sum += output.hsums(output.xmm[i].v)[0]; 500 | #endif 501 | } 502 | sum = 1.0f / sum; 503 | output.mul(sum, output); 504 | } 505 | 506 | void Activation_Tanh(const Tensor& input, Tensor& output) { 507 | for (uint32_t i = 0; i < output.size; ++i) { 508 | output.setElement(i, tanh(input.getElement(i))); 509 | } 510 | } 511 | void Activation_Sigmoid(const Tensor& input, Tensor& output) { 512 | const __m256 one = _mm256_set1_ps(1.0f); 513 | for (uint32_t i = 0; i < output.xmm_size; ++i) 514 | { 515 | output.xmm[i].v = exp256_ps(input.xmm[i].v); 516 | auto divisor = _mm256_add_ps(output.xmm[i].v, one); 517 | output.xmm[i].v = _mm256_div_ps(output.xmm[i].v, divisor); 518 | } 519 | } 520 | typedef std::function Activators; 521 | const Activators NONE = Activation_Identity; 522 | const Activators RELU = Activation_ReLU; 523 | const Activators TANH = Activation_Tanh; 524 | const Activators SIGMOID = Activation_Sigmoid; 525 | const Activators SOFTMAX = Activation_Softmax; 526 | 527 | class Layer : public std::enable_shared_from_this { 528 | public: 529 | shared_ptr inputLayer = nullptr; 530 | vector> outputLayers; 531 | 532 | Tensor output; 533 | Activators activator; 534 | std::string name; 535 | 536 | shared_ptr link(shared_ptr _linkLayer) 537 | { 538 | ASSERT(_linkLayer->output.size > 0); 539 | ASSERT(inputLayer == nullptr); //Cannot connect to multiple inputs 540 | inputLayer = _linkLayer; 541 | inputLayer->outputLayers.push_back(shared_from_this()); 542 | //Redimension based on input Weights and Bias 543 | initialize(inputLayer->output.shape); 544 | return shared_from_this(); //return this Layer for future connections 545 | } 546 | inline shared_ptr operator()(shared_ptr _linkLayer) 547 | { 548 | return link(_linkLayer); 549 | } 550 | 551 | 552 | 553 | int rem; 554 | 555 | explicit Layer(std::string name, Activators activator = NONE) : name(std::move(name)), activator(activator) {}; 556 | 557 | virtual ~Layer() = default; 558 | // Calculate output is the function that computes the output of this layer. 559 | virtual void calculateOutput(Tensor &input_mat) = 0; 560 | virtual void predict() = 0; 561 | // Precomute sets up the required matrices and variables required for calculateOutput to work. 562 | virtual void initialize(vector& Dim) = 0; 563 | virtual void precompute() = 0; 564 | virtual void load(std::istream& is) = 0; 565 | virtual void save(std::ostream& os) = 0; 566 | virtual string getType() = 0; 567 | virtual int countParams() = 0; 568 | virtual int summary() { 569 | int trainableParams = countParams(); 570 | cerr << left << setw(28) << setfill(' ') << (name + " (" + getType() + ")") << setw(26) << output.shape_str() << trainableParams << endl; 571 | return trainableParams; 572 | }; 573 | }; 574 | 575 | class ActivateLayer : public Layer { 576 | public: 577 | ActivateLayer(std::string name, Activators act) : Layer(name, act) {} 578 | inline void calculateOutput(Tensor &input_mat) override { 579 | activator(input_mat, output); 580 | }; 581 | inline void predict()override { 582 | ASSERT(inputLayer != nullptr); 583 | calculateOutput(inputLayer->output); 584 | }; 585 | void initialize(vector& Dim) override { 586 | output = Tensor(Dim); 587 | } 588 | void precompute()override { 589 | ASSERT(inputLayer != nullptr); 590 | output = inputLayer->output; //Same Tensor 591 | }; 592 | void load(std::istream& is)override {}; 593 | void save(std::ostream& os)override {}; 594 | inline int countParams() override { return 0; }; 595 | }; 596 | class Softmax : public ActivateLayer { 597 | public: 598 | Softmax(std::string name = "Softmax") :ActivateLayer(name, SOFTMAX) {} 599 | string getType() override { return "Softmax"; }; 600 | }; 601 | class Tanh : public ActivateLayer { 602 | public: 603 | Tanh(std::string name = "Tanh") :ActivateLayer(name, TANH) {} 604 | string getType() override { return "Tanh"; }; 605 | }; 606 | class ReLU : public ActivateLayer { 607 | public: 608 | ReLU(std::string name = "ReLU") :ActivateLayer(name, RELU) {} 609 | string getType() override { return "ReLU"; }; 610 | }; 611 | class Sigmoid : public ActivateLayer { 612 | public: 613 | Sigmoid(std::string name = "Sigmoid") :ActivateLayer(name, SIGMOID) {} 614 | string getType() override { return "Sigmoid"; }; 615 | }; 616 | class WeightBiasLayer : public Layer { //WeightBiasLayer 617 | protected: 618 | Tensor weights; 619 | Tensor bias; 620 | int num_of_outputs; 621 | public: 622 | WeightBiasLayer(std::string name, Activators activator, int num_of_outputs) 623 | : Layer(name, activator), num_of_outputs(num_of_outputs) {}; 624 | 625 | ~WeightBiasLayer() {}; 626 | //virtual void calculateOutput(Tensor &inputMat) = 0; 627 | 628 | inline void predict()override { 629 | ASSERT(inputLayer != nullptr); 630 | calculateOutput(inputLayer->output); 631 | }; 632 | 633 | void load(std::istream& is)override { 634 | weights.load(is); 635 | bias.load(is); 636 | }; 637 | void save(std::ostream& os)override { 638 | weights.save(os); 639 | bias.save(os); 640 | }; 641 | inline int countParams() override { return (int)(weights.size + bias.size); }; 642 | }; 643 | 644 | class Input : public Layer { 645 | public: 646 | //std::vector input_dim; 647 | Input(std::string name, std::vector input_dim) : Layer(name)//, input_dim(input_dim) 648 | { 649 | output = Tensor(input_dim); 650 | }; 651 | Input(std::vector input_dim) : Layer("Input")//, input_dim(input_dim) 652 | { 653 | output = Tensor(input_dim); 654 | }; 655 | ~Input() {}; 656 | void calculateOutput(Tensor &input_mat) override { 657 | if (&output != &input_mat) 658 | { 659 | output = input_mat; 660 | } 661 | }; 662 | //Somebody took care to update output to the correct inputs.... 663 | inline void predict()override {}; 664 | void initialize(vector& Dim) override {}//Already done at constructor 665 | void precompute()override { 666 | //Already done at constructor 667 | } 668 | void load(std::istream& is)override {}; 669 | void save(std::ostream& os)override {}; 670 | string getType() override { return "Input"; }; 671 | inline int countParams() override { return 0; }; 672 | int summary() override { return 0; }; 673 | }; 674 | 675 | class Dense : public WeightBiasLayer { 676 | public: 677 | Tensor kernelMatrix; 678 | Dense(std::string name, int num_of_outputs, Activators activator) 679 | : WeightBiasLayer(name, activator, num_of_outputs) {}; 680 | Dense(int num_of_outputs, Activators activator = NONE) 681 | : WeightBiasLayer("Dense", activator, num_of_outputs) {}; 682 | 683 | ~Dense() {}; 684 | 685 | void calculateOutput(Tensor &input_mat) override { 686 | //right now it couldn't be parallelized, 687 | __m256* w = &kernelMatrix.xmm[0].v; 688 | for (size_t n = 0; n < output.xmm_size; ++n) { 689 | float* initData = &input_mat.xmm[0].f[0]; 690 | __m256 accum = _mm256_setzero_ps(); 691 | for (size_t i = 0; i < input_mat.size; i++) { 692 | accum = _mm256_fmadd_ps(*w++, _mm256_set1_ps(*initData++), accum); 693 | } 694 | output.xmm[n].v = accum; 695 | } 696 | output.add(bias, output); 697 | activator(output, output); 698 | 699 | }; 700 | 701 | // Sets up the Dense layer, it takes the shape of the matrix before it to compute its own matrices. 702 | void initialize(vector& Dim) override { 703 | int totalSize = 1; 704 | for (int& n : Dim) 705 | totalSize *= n; 706 | output = Tensor(vector{num_of_outputs}); 707 | weights = Tensor(vector{totalSize, num_of_outputs}); 708 | bias = Tensor(vector{num_of_outputs}); 709 | #ifdef DEBUG_MODE 710 | cerr << "***** LAYER " << name << "******" << endl; 711 | //cerr << "Output " << ":" << output.shape_str()<{ (int)(weights.shape[0] * output.xmm_size * 8)}); 719 | int CountT = 0; 720 | for (size_t n = 0; n < num_of_outputs; n += 8) { 721 | for (size_t i = 0; i < inputLayer->output.size; i++) { 722 | auto Tf = i * num_of_outputs + n; 723 | kernelMatrix.xmm[CountT++].v = _mm256_loadu_ps(&weights.xmm[Tf >> 3].f[Tf & 7]); 724 | } 725 | } 726 | } 727 | 728 | string getType() override { return "Dense"; }; 729 | }; 730 | 731 | 732 | //#TODO 733 | class Conv : public WeightBiasLayer { 734 | 735 | private: 736 | int kernel_size; 737 | int stride; 738 | int padding; 739 | 740 | public: 741 | Tensor biasMat; 742 | //Tensor smaller_mat; 743 | uint32_t chunk_range; 744 | uint32_t big_reserve_size; 745 | uint32_t small_reserve_size; 746 | Tensor s, b; 747 | std::vector big_matrix_vec; 748 | int kept_dim; 749 | std::vector biases; 750 | std::vector X_col_shape; 751 | std::vector W_row_shape; 752 | Tensor kernelMatrix; 753 | Conv(std::string name, int num_of_outputs, 754 | int kernel_size, int stride, int padding, Activators activator = NONE) : WeightBiasLayer(name, activator, num_of_outputs), 755 | kernel_size(kernel_size), stride(stride), 756 | padding(padding) {}; 757 | Conv(int num_of_outputs, 758 | int kernel_size, int stride, int padding, Activators activator = NONE) : WeightBiasLayer("Conv", activator, num_of_outputs), 759 | kernel_size(kernel_size), stride(stride), 760 | padding(padding) {}; 761 | 762 | ~Conv() {}; 763 | // Calculates the output of the convolution layer. 764 | void calculateOutput(Tensor &input_mat) override { 765 | im2col(input_mat, weights.shape, kernelMatrix, stride, padding); 766 | std::vector oldShape = weights.shape; 767 | weights.reshape({ W_row_shape[1], W_row_shape[0] }); 768 | kernelMatrix.dot_product(kept_dim, big_matrix_vec, big_reserve_size, s, chunk_range, output); 769 | output.add(biasMat, output); 770 | activator(output, output); 771 | weights.reshape(oldShape); 772 | }; 773 | 774 | void initialize(vector& inDim) override { 775 | 776 | vector outDim; 777 | outDim.resize(3); 778 | outDim[0] = (uint32_t)std::floor(((float)inDim[0] + padding * 2 - kernel_size) / stride + 1); 779 | outDim[1] = (uint32_t)std::floor(((float)inDim[1] + padding * 2 - kernel_size) / stride + 1); 780 | outDim[2] = num_of_outputs; 781 | output = Tensor(outDim); 782 | vector wDim = { kernel_size ,kernel_size ,inDim[2],outDim[2] }; 783 | weights = Tensor(wDim); 784 | vector bDim = { num_of_outputs }; 785 | bias = Tensor(bDim); 786 | #ifdef DEBUG_MODE 787 | cerr << "***** LAYER " << name << "******" << endl; 788 | //cerr << "Output " << ":" << output.shape_str()<output.shape; 796 | //vector in_mat = { 28,28,1 }; 797 | //Setting the padding. 798 | int pad = padding; 799 | 800 | // Compute the size output of the im2col function, the X col, and W row matrices. 801 | std::vector filter_shape = this->weights.shape; 802 | /* int x = in_mat[0]; 803 | x = x - filter_shape[0] + 2 * pad; 804 | x = (int)floor(float(x) / float(stride)); 805 | x = x + 1;*/ 806 | int x = output.shape[0]; 807 | // Computes the output size of the matrix of the dot product function and of the add bias. 808 | /*std::vector out_shape = {x, x, this->weights.shape[3]}; 809 | Tensor out(out_shape); 810 | output = out;*/ 811 | //int x = output.shape[0]; 812 | int x_row = x * x; 813 | int x_col = 1; 814 | 815 | for (int i = 0; i < filter_shape.size() - 1; i++) { 816 | x_col *= filter_shape[i]; 817 | } 818 | X_col_shape.push_back(x_col); 819 | X_col_shape.push_back(x_row); 820 | int xx = filter_shape.at(filter_shape.size() - 1); 821 | W_row_shape.push_back(xx); 822 | W_row_shape.push_back(x_col); 823 | 824 | std::vector im_shape = { X_col_shape.at(0), X_col_shape.at(1) }; 825 | Tensor im(im_shape); 826 | kernelMatrix = im; 827 | 828 | // Set up the bias matrix so that its ready to be added to the output after the dot product. 829 | for (int j = 0; j < output.shape.at(2); ++j) { 830 | for (int i = 0; i < output.shape.at(0) * output.shape.at(1); ++i) { 831 | biases.push_back(bias.getElement(j)); 832 | } 833 | } 834 | biasMat = Tensor(biases, output.shape); 835 | 836 | // Setting up the weights matrix and reshaping it to the desired shape for the dot product. 837 | std::vector oldShape = weights.shape; 838 | weights.reshape({ W_row_shape[1], W_row_shape[0] }); 839 | 840 | kept_dim = weights.shape[0]; 841 | auto other_dim = weights.shape[1]; 842 | auto repeated_dim = kernelMatrix.shape[1]; 843 | const auto& smaller_mat = weights; 844 | 845 | chunk_range = (uint32_t)std::ceil(kept_dim / 8.0); 846 | big_reserve_size = chunk_range * 8 * repeated_dim; 847 | small_reserve_size = chunk_range * 8 * other_dim; 848 | 849 | auto small_matrix_vec = std::vector(small_reserve_size, 0.0f); 850 | big_matrix_vec = std::vector(big_reserve_size, 0.0f); 851 | 852 | uint32_t i = 0; 853 | uint32_t vec_index = 0; 854 | 855 | while (i < smaller_mat.size) { 856 | for (int j = 0; j < kept_dim; j++) { 857 | small_matrix_vec[vec_index + j] = smaller_mat.getElement(i + j); 858 | } 859 | vec_index += kept_dim; 860 | i += kept_dim; 861 | 862 | while (vec_index % 8 != 0) 863 | ++vec_index; 864 | } 865 | 866 | Tensor small(small_matrix_vec, { (int)small_reserve_size, 1 }); 867 | 868 | s = small; 869 | weights.reshape(oldShape); 870 | 871 | // Reshaping the im2col to be padded same as the weights matrix. 872 | Tensor mat(big_matrix_vec, { (int)big_reserve_size, 1 }); 873 | kernelMatrix = mat; 874 | 875 | } 876 | string getType() override { return "Conv2D"; }; 877 | }; 878 | 879 | class Model { 880 | public: 881 | vector> inputs; 882 | vector> outputs; 883 | bool Loaded = false; 884 | Model(vector> inputs, vector> outputs) 885 | : inputs(inputs) 886 | , outputs(outputs) 887 | { 888 | ASSERT(!inputs.empty()); 889 | buildPath(); 890 | } 891 | Model() {} 892 | ~Model() { 893 | inputs.clear(); 894 | outputs.clear(); 895 | m_forwardPath.clear(); 896 | }; 897 | void predict(); 898 | void predictSingleOutput(shared_ptr output); 899 | void summary(); 900 | void loadWeights(const std::string& f); 901 | void saveWeights(const std::string& f); 902 | private: 903 | void buildPath(); 904 | vector m_forwardPath; //Predicts all outputs 905 | map> m_forwardSingle; //For single output predictions 906 | }; 907 | void Model::summary() { 908 | int trainableParams = 0; 909 | const string line = "_________________________________________________________________"; 910 | const string line2 = "================================================================="; 911 | cout << line << endl; 912 | cout << "Layer (type) Output Shape Param # " << endl; 913 | for (size_t i = 1; i < m_forwardPath.size(); ++i) 914 | { 915 | cout << (i == 1 ? line2 : line) << endl; //Skip 1st layer, input 916 | trainableParams += m_forwardPath[i]->summary(); 917 | } 918 | cout << line2 << endl; 919 | cout << "Total params : " << trainableParams << endl; 920 | cout << "Trainable params : " << trainableParams << endl; 921 | cout << "Non - trainable params : 0" << endl; 922 | cout << line << endl; 923 | } 924 | 925 | //NOTE: prediction assumes that Input Layers are properly loaded 926 | void Model::predict() { 927 | if (!Loaded) 928 | throw std::invalid_argument("Model weights not loaded"); 929 | for (auto&& m : m_forwardPath) { 930 | m->predict(); 931 | } 932 | } 933 | 934 | void Model::predictSingleOutput(shared_ptr output) { 935 | if (!Loaded) 936 | throw std::invalid_argument("Model weights not loaded"); 937 | for (auto&& m : m_forwardSingle[output.get()]) { 938 | m->predict(); 939 | } 940 | } 941 | 942 | map> m_forwardSingle; //For single output predictions 943 | 944 | void Model::loadWeights(const std::string& f) { 945 | std::ifstream is(f, std::ifstream::in | std::ios::binary); 946 | if (is.good()) 947 | { 948 | for (auto& m : m_forwardPath) { 949 | m->load(is); 950 | } 951 | for (auto& m : m_forwardPath) { 952 | m->precompute(); 953 | } 954 | Loaded = true; 955 | } 956 | } 957 | void Model::saveWeights(const std::string& f) { 958 | ofstream os(f, std::ifstream::out | std::ios::binary); 959 | for (auto&& m : m_forwardPath) { 960 | m->save(os); 961 | } 962 | } 963 | void Model::buildPath() { 964 | // build forward path by taking dependencies into account (topological sort) 965 | m_forwardPath.clear(); 966 | map deps; 967 | 968 | for (auto l : inputs) 969 | { 970 | m_forwardPath.push_back(l.get()); 971 | } 972 | 973 | for (uint32_t i = 0; i < m_forwardPath.size(); i++) 974 | { 975 | auto layer = m_forwardPath[i]; 976 | for (auto wp : layer->outputLayers) 977 | { 978 | auto next = wp.lock().get(); 979 | const size_t n = 1;//next->inputs.size(); 980 | if (n > 1) 981 | deps[layer]++; 982 | 983 | if (n == 1 || n == deps[next]) 984 | m_forwardPath.push_back(next); 985 | } 986 | } 987 | //Create path for single outputs. I.e. one path for policy and another for value 988 | m_forwardSingle.clear(); 989 | deps.clear(); 990 | for (auto&& O : outputs) { 991 | Layer* layer = O.get(); 992 | m_forwardSingle[layer].clear(); 993 | auto& V = m_forwardSingle[layer]; 994 | while (layer != nullptr && deps[layer] == 0) { 995 | V.insert(V.begin(), layer); 996 | deps[layer]++; 997 | layer = layer->inputLayer.get(); 998 | } 999 | } 1000 | 1001 | 1002 | 1003 | } -------------------------------------------------------------------------------- /src/Train.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "######################################### INITIALIZATION #####################################" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": { 16 | "colab": { 17 | "base_uri": "https://localhost:8080/" 18 | }, 19 | "executionInfo": { 20 | "elapsed": 2064, 21 | "status": "ok", 22 | "timestamp": 1622443062342, 23 | "user": { 24 | "displayName": "Marchete", 25 | "photoUrl": "", 26 | "userId": "00000078181859324609" 27 | }, 28 | "user_tz": -120 29 | }, 30 | "id": "xJqDIgorJBbK", 31 | "outputId": "91ab953e-8c83-4a48-b029-5418aa1261ac" 32 | }, 33 | "outputs": [], 34 | "source": [ 35 | "from __future__ import absolute_import, division, print_function, unicode_literals\n", 36 | "# Install TensorFlow\n", 37 | "\n", 38 | "import tensorflow as tf\n", 39 | "#THREADS=3\n", 40 | "#tf.config.threading.set_intra_op_parallelism_threads(THREADS)\n", 41 | "#tf.config.threading.set_inter_op_parallelism_threads(THREADS)\n", 42 | "import random\n", 43 | "import numpy as np\n", 44 | "from numpy import genfromtxt\n", 45 | "import pandas as pd\n", 46 | "import base64\n", 47 | "import sys\n", 48 | "import glob, os\n", 49 | "import re\n", 50 | "import gc\n", 51 | "import subprocess\n", 52 | "import datetime\n", 53 | "import queue\n", 54 | "from IPython.display import clear_output\n", 55 | "from tensorflow.python.client import device_lib\n", 56 | "\n", 57 | "print(\"Python:\"+sys.version)\n", 58 | "print(\"TF:\"+tf.__version__)\n", 59 | "print(\"GPU:\"+str(tf.test.is_gpu_available())+\" CUDA:\"+str(tf.test.is_built_with_cuda()))\n", 60 | "#print(device_lib.list_local_devices())\n", 61 | "import os\n", 62 | "if not os.path.exists('/run/shm/traindata'):\n", 63 | " os.makedirs('/run/shm/traindata')\n" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": { 70 | "id": "crkTUlVwJBbO" 71 | }, 72 | "outputs": [], 73 | "source": [ 74 | "######################################### HYPERPARAMETERS AND CONFIGS #####################################\n", 75 | "\n", 76 | "#Don't touch INPUT_SIZE UNLESS YOU ARE CHANGING THE NN INPUTS DEFINITION. POLICY_SIZE IS THE NUMBER OF LEGAL MOVES ON THE GAME.\n", 77 | "#INPUT_SIZE must match what CGZero.cpp says in function:\n", 78 | "# int _Game::getInputDimensions() {...}\n", 79 | "INPUT_SIZE=6*2*24+2*27\n", 80 | "#The same than CGZero.cpp function: int getPolicySize() {...}\n", 81 | "POLICY_SIZE=6\n", 82 | "\n", 83 | "\n", 84 | "#HYPERPARAMETERS. You MUST assign them a value.\n", 85 | "#DISCLAIMER: I have ABSOLUTELY no idea what are good hyperparameters. Most AZ documentation is confusing or even contradictory.\n", 86 | "MATCHES_PER_GENERATION= #Something around 400 and 3000\n", 87 | "PIT_MATCHES= #I have about 400, too little matches will not be enough to know if a candidate is best.\n", 88 | "THREADS=6 #CPU dependant, on a Core i7-8700K I can set it to 9. With 6 I can use the PC for other purposes, like gaming.\n", 89 | "TRAINING_POOL_SIZE= #At least 500000, but can be millions. 500k-2M I'd say\n", 90 | " #If it's too small there won't be enough samples.\n", 91 | " #If it's too big it will use very old samples that might not have good values to learn.\n", 92 | "TRAINING_SUBSET_SIZE= #I noticed better learning with more samples. 200k is not enough, 500k and up seemed a better value\n", 93 | "K_BATCH_SIZE= #I have no idea what to use, I used 64 in last tests, but on others I put bigger batch sizes, like 512 or 1024\n", 94 | "K_ITERATIONS= #Unused, this was for the minibatch approach from original Alphazero. There is commented code in the training loop about that\n", 95 | "K_EPOCH= #Number of full learning passes the Tensorflow will do with the samples subset, from 1 to 60 I guess. If the learning process is slow I put a lower value.\n", 96 | "\n", 97 | "K_WEIGHT_POLICY=1.0 #Give more importance to Policy losses\n", 98 | "K_WEIGHT_VALUE=1.0 \n", 99 | "\n", 100 | "WINRATE_ACCEPTED=55.6 #Or 55.0, what you prefer\n", 101 | "\n", 102 | "K_LEARNING_RATE=0.001 #I imagine that at some point it must be lowered, I have no idea exactly when.\n", 103 | "K_MOMENTUM=0.87 #Some hyperparameter for the training part. See https://distill.pub/2017/momentum/ \n", 104 | "\n", 105 | "#Parameters that controls how the endgame score is backpropagated to the samples.\n", 106 | "#https://medium.com/oracledevs/lessons-from-alphazero-part-4-improving-the-training-target-6efba2e71628\n", 107 | "#For each sample the value I use is= B * ENDGAME_SCORE + (1.0 - B)*MeanScore\n", 108 | "#Where B is B = PROPAGATE_BASE + PROPAGATE_INC * (seenMoves / totalMovesInReplayBuffer)\n", 109 | "# and MeanScore is the MCTS mean value (Q).\n", 110 | "#Alphazero uses z: PROPAGATE_BASE = 1.0 and PROPAGATE_INC = 0.0\n", 111 | "#Others use q: PROPAGATE_BASE = 0.0 and PROPAGATE_INC = 0.0\n", 112 | "#I'm using a mix of z and q, something like PROPAGATE_BASE = 0.45 and PROPAGATE_INC = 1.0-PROPAGATE_BASE\n", 113 | "PROPAGATE_BASE= # 0.0 to 1.0. Percentage of endgame Score (-1 for loss and +1 for win) that the sample on turn 0 will have.\n", 114 | "PROPAGATE_INC=1.0-PROPAGATE_BASE #Percentage of endgame score at end.\n", 115 | "\n", 116 | "#I've used the same idea for the policy part. I dislike the \"temperature\" thing on Alphazero, I just tweak samples to be\n", 117 | "# POLICY = B * VisitsPOLICY + (1.0 - B)*OneHotPOLICY\n", 118 | "#VisitsPOLICY is calculated by dividing visitsChildren/visitsParent, so you have a 100% distribution\n", 119 | "#OneHotPOLICY is all zeros except the selected move that it's a 1.0. It's also a 100% distribution\n", 120 | "POLICY_BACKP_FIRST=10 #; //Similarly , but with percentage of turns, first 10% of turns doesn't have any \"temperature\",\n", 121 | "POLICY_BACKP_LAST=5 #; //from (100-5=95%) I linearly sharpen policy to get only the best move, a one-hot policy\n", 122 | "\n", 123 | "#TRAINING PARAMETERS\n", 124 | "#I literally have no idea what's going on with the cpuct hyperparameter. It controls the exploration part on the MCTS search.\n", 125 | "#But the problem is that I don't see any consensus about what's the best way to control it.\n", 126 | "#https://lczero.org/blog/2018/12/alphazero-paper-and-lc0-v0191/ Cpuct is not a constant!!!!!!!\n", 127 | "#https://medium.com/oracledevs/lessons-from-alpha-zero-part-6-hyperparameter-tuning-b1cfcbe4ca9a Trial and error way\n", 128 | "TRAIN_CPUCT_MIN= #Maybe something between 2.0 and 3.0, but I'm clueless. 1.0 was \"good\" (>70% winrate) on pit, but not that good when submitted to CG\n", 129 | "TRAIN_CPUCT_INC=0.00\n", 130 | "TRAIN_CPUCT_MAX=TRAIN_CPUCT_MIN\n", 131 | "\n", 132 | "TRAIN_NOISE_DIR_EPSILON= #it gives diversity, something between 0.10 and 0.30 can be good for selfplay\n", 133 | "TRAIN_NOISE_DIR_ALPHA= #More than 1.0 always, maybe in the 1.0-1.6 range.\n", 134 | "TRAIN_NOISE_DIR_DECAY=0.0 #Reduce noise each turn. Maybe it's not good to have much noise at endgame.\n", 135 | "TRAIN_MCTS_ITER= #At least 800, but the more, the better quality of predictions but slower sample generation. 2k or 4k works fine too\n", 136 | "TRAIN_NOISE_RANDOM= #Simplistic random noise to NN value. 0.03 means a randomFloat(0.97,1.03)*NNvalue\n", 137 | "#Don't touch that\n", 138 | "TRAIN_PARAMS = f\"{TRAIN_CPUCT_MIN} {TRAIN_CPUCT_INC} {TRAIN_CPUCT_MAX} {TRAIN_MCTS_ITER} {TRAIN_NOISE_DIR_EPSILON} {TRAIN_NOISE_DIR_ALPHA} {TRAIN_NOISE_DIR_DECAY} {TRAIN_NOISE_RANDOM} {PROPAGATE_BASE} {PROPAGATE_INC} {POLICY_BACKP_FIRST} {POLICY_BACKP_LAST}\"\n", 139 | "\n", 140 | "#PIT PARAMETERS\n", 141 | "PIT_CPUCT_MIN=TRAIN_CPUCT_MIN\n", 142 | "PIT_CPUCT_INC=0.00\n", 143 | "PIT_CPUCT_MAX=PIT_CPUCT_MIN\n", 144 | "\n", 145 | "PIT_NOISE_DIR_EPSILON=0.03 #Use much lower dirichlet noise than in selfplay. We need diversity but not noise.\n", 146 | "PIT_NOISE_DIR_ALPHA=1.0\n", 147 | "PIT_NOISE_DIR_DECAY=0.0006\n", 148 | "PIT_MCTS_ITER=TRAIN_MCTS_ITER\n", 149 | "PIT_NOISE_RANDOM=0.02\n", 150 | "#Don't touch that\n", 151 | "PIT_PARAM_THREAD= f\"{THREADS} {PIT_MATCHES}\"\n", 152 | "PIT_PARAM_MCTS = f\"{PIT_CPUCT_MIN} {PIT_CPUCT_INC} {PIT_CPUCT_MAX} {PIT_MCTS_ITER} {PIT_NOISE_DIR_EPSILON} {PIT_NOISE_DIR_ALPHA} {PIT_NOISE_DIR_DECAY} {PIT_NOISE_RANDOM} {PROPAGATE_BASE} {PROPAGATE_INC} {POLICY_BACKP_FIRST} {POLICY_BACKP_LAST}\"\n", 153 | "SAMPLES_FILE=os.path.join(\".\",\"traindata\",\"samples.dat\")\n", 154 | "sampler_process=os.path.join(\".\",\"NNSampler\")+\" \"+os.path.join(\".\",\"traindata\")+\" Replay.*.dat \"+SAMPLES_FILE+\" \"+str(TRAINING_POOL_SIZE)+\" \"+str(TRAINING_SUBSET_SIZE)+\" \"+str(INPUT_SIZE)+\" \"+str(1+POLICY_SIZE)+\" 1\"\n" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "######################################### FUNCTIONS USED FOR TRAINING #####################################\n", 164 | "def adjustLR():\n", 165 | " if generation == 0:\n", 166 | " return 8*K_LEARNING_RATE\n", 167 | " elif generation < 5:\n", 168 | " return 6*K_LEARNING_RATE\n", 169 | " elif generation < 10:\n", 170 | " return 2*K_LEARNING_RATE\n", 171 | " else:\n", 172 | " return K_LEARNING_RATE\n", 173 | "\n", 174 | "#Save weights, non trainable layers must be named \"IGNORE_*\"\n", 175 | "def SaveModel(my_model,fileSTR):\n", 176 | " totalbytes=0\n", 177 | " data=[]\n", 178 | " Wmodel = open(\"./\"+fileSTR, \"wb\")\n", 179 | " for x in my_model.weights:\n", 180 | " if (\"IGNORE_\" in x.name):\n", 181 | " #print(\"Ignoring layer \"+x.name)\n", 182 | " continue\n", 183 | " nn = x.numpy()\n", 184 | " T = nn\n", 185 | " v = np.ndarray.tobytes(T)\n", 186 | " Wmodel.write(bytearray(v))\n", 187 | " totalbytes+=len(v)\n", 188 | " data.append(base64.b64encode(v).decode(\"utf-8\"))\n", 189 | " Wmodel.close()\n", 190 | "def readWinrate(candidatefile,bestfile):\n", 191 | " files=sorted(glob.glob(os.path.join('pitresults','Pit_'+candidatefile+'_'+bestfile+'_*.txt')),reverse=True)\n", 192 | " for file in files:\n", 193 | " with open(file, 'r') as f:\n", 194 | " strvalue=f.read().strip()\n", 195 | " return float(strvalue)\n", 196 | " return -1.0\n", 197 | "def readAndDeleteWinrate(candidatefile,bestfile):\n", 198 | " files=sorted(glob.glob(os.path.join('pitresults','Pit_'+candidatefile+'_'+bestfile+'_*.txt')),reverse=True)\n", 199 | " valor=-1.0\n", 200 | " for file in files:\n", 201 | " if (valor == -1.0):\n", 202 | " with open(file, 'r') as f:\n", 203 | " valor=float(f.read().strip())\n", 204 | " os.remove(file)\n", 205 | " return valor\n", 206 | "\n", 207 | "#LR_decay = tf.keras.callbacks.LearningRateScheduler(tf.keras.optimizers.schedules.ExponentialDecay(initial_learning_rate=1e-3,decay_steps=20000,decay_rate=0.9))" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "######################################### MODEL DEFINITION #####################################\n", 217 | "## Must match the model you have in CGZero.cpp, in function\n", 218 | "## Model _Game::CreateNNModel(bool activeSoftMax) {" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": null, 224 | "metadata": { 225 | "id": "nEr5GjiJJBbP" 226 | }, 227 | "outputs": [], 228 | "source": [ 229 | "#It's INCOMPLETE, YOU MUST CREATE YOUR OWN MODEL!!\n", 230 | "#Order is important! You must take into account that this model and C++ counterpart must be synchronized, so layer orders must be the same between languages.\n", 231 | "\n", 232 | "#Input layer\n", 233 | "inputs = tf.keras.Input(shape=(INPUT_SIZE,), name='input')\n", 234 | "#Common part of the Model, both policy and value use these layers\n", 235 | "x = tf.keras.layers.Dense(TODOTODOTODOT,activation='relu',name='Dense1')(inputs)\n", 236 | "#x = tf.keras.layers.Dense(TODOTODOTODOT,activation='relu')(x)\n", 237 | "\n", 238 | "#Split part 1, P1 layers are for the policy part. If you don't want extra layers for p1, I guess you can do p1=x\n", 239 | "p1 = tf.keras.layers.Dense(TODOTODOTODOT,activation='relu',name='p1')(x)\n", 240 | "#p1 = tf.keras.layers.Dense(TODOTODOTODOT,activation='relu')(p1)\n", 241 | "\n", 242 | "#Split part, v1 layers are for the value part. If you don't want extra layers for v1, I guess you can do v1=x\n", 243 | "v1 = tf.keras.layers.Dense(TODOTODOTODOT,activation='relu',name='v1')(x)\n", 244 | "#v1 = tf.keras.layers.Dense(TODOTODOTODOT,activation='relu')(v1)\n", 245 | "#Output layers, don't touch them if you don't know what are you doing.\n", 246 | "value = tf.keras.layers.Dense(1, activation='tanh',name='value')(v1)\n", 247 | "policy = tf.keras.layers.Dense(POLICY_SIZE, activation='softmax',name='policy')(p1)\n", 248 | "model = tf.keras.Model(inputs=inputs, outputs=[value, policy])\n", 249 | "#Others use Adam as optimizer, I just used SGD because I'm clueless and I saw some others using SGD.\n", 250 | "opt = tf.keras.optimizers.SGD(learning_rate=K_LEARNING_RATE, momentum=K_MOMENTUM)\n", 251 | "#Keep a file with losses history\n", 252 | "csv_logger = tf.keras.callbacks.CSVLogger('gen_train.log',append=True)\n", 253 | "\n", 254 | "model.compile(loss={'value': 'mean_squared_error',\n", 255 | " 'policy':tf.keras.losses.KLD },\n", 256 | " optimizer=opt,\n", 257 | " loss_weights = {'value':K_WEIGHT_VALUE,\n", 258 | " 'policy':K_WEIGHT_POLICY}\n", 259 | " ,metrics={'value':'mean_absolute_percentage_error',\n", 260 | " 'policy': 'categorical_accuracy' }\n", 261 | " )" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": { 268 | "id": "Kbz3qqCMJBbQ", 269 | "scrolled": true 270 | }, 271 | "outputs": [], 272 | "source": [ 273 | "if not os.path.exists('gen0000.h5'):\n", 274 | " model.save('gen0000.h5')\n", 275 | " SaveModel(model,\"gen0000.w32\")\n", 276 | " model.summary()" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "######################################### RESUME TRAINING #####################################\n", 286 | "# load best models, load last generation number" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "metadata": { 293 | "id": "1I1ex_D8JBbS", 294 | "outputId": "fd3d4b2c-00dc-44a2-d88b-77ba3f51b487" 295 | }, 296 | "outputs": [], 297 | "source": [ 298 | "generation=0\n", 299 | "gen_name=\"gen\"+str(generation).zfill(4)\n", 300 | "if os.path.exists('generation.txt'):\n", 301 | " with open('generation.txt', 'r') as f:\n", 302 | " generation = int(f.read().strip())\n", 303 | " gen_name=\"gen\"+str(generation).zfill(4)\n", 304 | " print(\"Generation is :\"+gen_name+\" \"+str(generation)) \n", 305 | " if (generation > 0):\n", 306 | " #model = tf.keras.models.load_model(gen_name+'.h5', custom_objects={\"policy_loss\": policy_loss})\n", 307 | " model = tf.keras.models.load_model(gen_name+'.h5')\n", 308 | "if not os.path.exists(gen_name+\".w32\"):\n", 309 | " SaveModel(model,gen_name+\".w32\")\n", 310 | " model.save(gen_name+'.h5')\n", 311 | "gen_best1=gen_name\n", 312 | "if os.path.exists('gen_best1.txt'):\n", 313 | " with open('gen_best1.txt', 'r') as f:\n", 314 | " gen_best1 = f.read().strip()\n", 315 | "gen_best2=gen_name\n", 316 | "if os.path.exists('gen_best2.txt'):\n", 317 | " with open('gen_best2.txt', 'r') as f:\n", 318 | " gen_best2 = f.read().strip() \n", 319 | "model=tf.keras.models.load_model(gen_name+'.h5')\n", 320 | "print(\"Best Model1:\"+gen_best1+\" + \"+gen_best2+\". Current generation:\"+gen_name+\" loaded\")\n" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": null, 326 | "metadata": {}, 327 | "outputs": [], 328 | "source": [ 329 | "######################################### MAIN TRAINING LOOP #####################################\n", 330 | "# 1- Creates self plays between best models (and also some random generation to give diversity)\n", 331 | "# 2- Creates a random sample dataset from selfplay\n", 332 | "# 3- Train the current model\n", 333 | "# 4- Save candidate as a new generation (useful to resume later, or return back to a previous train state)\n", 334 | "# 5- Pit play vs best1 and best2, promote candidate as best if winrate is good" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": null, 340 | "metadata": { 341 | "id": "zULZ7RjSJBbT", 342 | "outputId": "93c0f940-cecf-41cf-ae95-e337af017d60", 343 | "scrolled": false 344 | }, 345 | "outputs": [], 346 | "source": [ 347 | "clear_output(wait=True)\n", 348 | "try:\n", 349 | " pit_winrate2\n", 350 | "except NameError:\n", 351 | " pit_winrate2=70.0\n", 352 | "try:\n", 353 | " pit_winrate\n", 354 | "except NameError:\n", 355 | " pit_winrate=max(0,100.0-pit_winrate2)\n", 356 | " \n", 357 | "while True:\n", 358 | " model.optimizer.learning_rate.assign(adjustLR())\n", 359 | " if (generation % 10 == 0):\n", 360 | " clear_output(wait=True)\n", 361 | " samplescount=0\n", 362 | " #if (generation == 0):\n", 363 | " # csv_data = np.fromfile(SAMPLES_FILE, dtype=np.float32)\n", 364 | " # csv_data=np.reshape(csv_data, (-1,INPUT_SIZE+POLICY_SIZE+2))\n", 365 | " # samplescount =(csv_data.shape)[0]\n", 366 | "\n", 367 | " #Remove generation 0 data once we have samples with more quality\n", 368 | " if (generation > 4 and generation < 6):\n", 369 | " gen0=\"gen\"+str(0).zfill(4)\n", 370 | " remove0=glob.glob(os.path.join('traindata','Replay_'+'*'+gen0+\"*\"+'.dat'))\n", 371 | " for filePath in remove0:\n", 372 | " try:\n", 373 | " os.remove(filePath)\n", 374 | " except:\n", 375 | " pass\n", 376 | " # 1- Creates self plays between best models (and also some random generation to give diversity)\n", 377 | " # The code will repeat until it has enough samples (only after generation 10, lower ones are of bad quality).\n", 378 | " while samplescount < TRAINING_SUBSET_SIZE/3:\n", 379 | " if (generation<=1):\n", 380 | " random_enemy=gen_name\n", 381 | " else:\n", 382 | " random_enemy=\"gen\"+str(random.randint(max(1,generation-5), generation)).zfill(4)\n", 383 | " \n", 384 | " if (generation==0 and (len(glob.glob(os.path.join('traindata','Replay_'+'*'+gen_name+\"vs\"+gen_name+'.dat')))>0)):\n", 385 | " print('Replay_'+'*'+gen_name+'.txt already exists') \n", 386 | " else:\n", 387 | " pFirst=max(0.2,0.9*(1.0-(pit_winrate/(pit_winrate+pit_winrate2))))\n", 388 | " pSecond=0.9-pFirst\n", 389 | " print(f\" **** Doing samples. Count:{samplescount}. pBest1:{100.0*pFirst}% p2:{100.0*pSecond}% {pit_winrate} {pit_winrate2}\")\n", 390 | " p70=int(pFirst*MATCHES_PER_GENERATION)\n", 391 | " p20=int(pSecond*MATCHES_PER_GENERATION)\n", 392 | " p5=MATCHES_PER_GENERATION-p70-p20\n", 393 | " selfplay_process=os.path.join(\".\",\"CGZero\")+\" selfplay \"+f\"{THREADS} {p70} \"+gen_best1+\" \"+TRAIN_PARAMS+\" \"+gen_best1+\" \"+TRAIN_PARAMS\n", 394 | " print(selfplay_process)\n", 395 | " subprocess.run(selfplay_process, shell=True)\n", 396 | " if (gen_best1 != gen_best2):\n", 397 | " selfplay_process=os.path.join(\".\",\"CGZero\")+\" selfplay \"+f\"{THREADS} {p20} \"+gen_best1+\" \"+TRAIN_PARAMS+\" \"+gen_best2+\" \"+TRAIN_PARAMS\n", 398 | " print(selfplay_process)\n", 399 | " subprocess.run(selfplay_process, shell=True)\n", 400 | " if (p70 >= p20):\n", 401 | " A=gen_best1 if (gen_best1 >= random_enemy) else random_enemy\n", 402 | " B=gen_best1 if (A == random_enemy) else random_enemy\n", 403 | " else:\n", 404 | " A=gen_best2 if (gen_best2 >= random_enemy) else random_enemy\n", 405 | " B=gen_best2 if (A == random_enemy) else random_enemy\n", 406 | " selfplay_process=os.path.join(\".\",\"CGZero\")+\" selfplay \"+f\"{THREADS} {p5} \"+A+\" \"+TRAIN_PARAMS+\" \"+B+\" \"+TRAIN_PARAMS\n", 407 | " print(selfplay_process)\n", 408 | " subprocess.run(selfplay_process, shell=True)\n", 409 | " print('Reading training data')\n", 410 | " # 2- Creates a random sample dataset from selfplay\n", 411 | " print(sampler_process)\n", 412 | " subprocess.run(sampler_process, shell=True)\n", 413 | " csv_data = np.fromfile(SAMPLES_FILE, dtype=np.float32)\n", 414 | " csv_data=np.reshape(csv_data, (-1,INPUT_SIZE+POLICY_SIZE+2))\n", 415 | " gc.collect()\n", 416 | " samplescount =(csv_data.shape)[0]\n", 417 | " if (generation < 10):\n", 418 | " break\n", 419 | " #Cut samples to inputs , policy , value , countVisits\n", 420 | " np.random.shuffle(csv_data)\n", 421 | " cut_index = [(csv_data.shape)[1]-POLICY_SIZE-2, (csv_data.shape)[1]-2,(csv_data.shape)[1]-1]\n", 422 | " samples,policy,value,countVisits=np.split(csv_data, cut_index,axis=1)\n", 423 | " \n", 424 | " #mask= np.where(policy < 0, -999999999.99, policy) #not used, it was a test to remove invalid moves, not needed\n", 425 | " policy= np.where(policy < 0, 0, policy) \n", 426 | " csv_data=None\n", 427 | " gc.collect()\n", 428 | " # 3- Train the current model\n", 429 | " ####Minibatches learning: This is for doing minibatches, but I prefer to simply feed all the samples subset.\n", 430 | " #for loop in range(K_ITERATIONS):\n", 431 | " # print(\"Batch \"+str(loop)+\":\",end='')\n", 432 | " # indices = np.random.choice(value.shape[0], K_BATCH_SIZE, replace=False)\n", 433 | " # S=samples[indices]\n", 434 | " # P=policy[indices]\n", 435 | " # V=value[indices]\n", 436 | " # #model.optimizer.learning_rate.assign(learning_rate_scheduler(loop, 0.0))\n", 437 | " # #model.optimizer.learning_rate.assign(K_LEARNING_RATE)\n", 438 | " # model.fit({'input':S}, {'policy': P, 'value':V},verbose=2, epochs=K_EPOCH,callbacks=[csv_logger],batch_size=int(K_BATCH_SIZE/4))\n", 439 | " \n", 440 | " ####Simple learning, just learn from all the subset. If you activate the former, disable this line\n", 441 | " model.fit({'input':samples}, {'policy': policy, 'value':value},verbose=2, epochs=min(generation+1,K_EPOCH),callbacks=[csv_logger],batch_size=int(K_BATCH_SIZE))\n", 442 | " gc.collect()\n", 443 | " #new generation\n", 444 | " print('New generation '+gen_name+' -> '+\"gen\"+str(generation+1).zfill(4))\n", 445 | " generation=generation+1\n", 446 | " gen_name=\"gen\"+str(generation).zfill(4)\n", 447 | " # 4- Save candidate as a new generation (useful to resume later, or return back to a previous train state)\n", 448 | " print('Save Model '+gen_name+'.h5')\n", 449 | " model.save(gen_name+'.h5')\n", 450 | " SaveModel(model,gen_name+\".w32\")\n", 451 | " with open('generation.txt', 'w') as f:\n", 452 | " f.write(str(generation)) \n", 453 | " \n", 454 | " # 5- Pit play vs best1 and best2, promote candidate as best if winrate is good\n", 455 | " pitplay_process=os.path.join(\".\",\"CGZero\")+\" pitplay \"+PIT_PARAM_THREAD+\" \"+gen_name+\" \"+PIT_PARAM_MCTS+\" \"+gen_best1+\" \"+PIT_PARAM_MCTS\n", 456 | " print('subprocess.run('+pitplay_process+', shell=True)')\n", 457 | " subprocess.run(pitplay_process, shell=True)\n", 458 | " pit_winrate=readWinrate(gen_name,gen_best1)\n", 459 | " if gen_best1 == gen_best2:\n", 460 | " pit_winrate2=pit_winrate\n", 461 | " else:\n", 462 | " pitplay_process=os.path.join(\".\",\"CGZero\")+\" pitplay \"+PIT_PARAM_THREAD+\" \"+gen_name+\" \"+PIT_PARAM_MCTS+\" \"+gen_best2+\" \"+PIT_PARAM_MCTS\n", 463 | " subprocess.run(pitplay_process, shell=True)\n", 464 | " pit_winrate2=readWinrate(gen_name,gen_best2)\n", 465 | " print('Winrate '+str(pit_winrate)+' '+str(pit_winrate2))\n", 466 | " #Check if it's a new best, update bests\n", 467 | " if (pit_winrate>=WINRATE_ACCEPTED):\n", 468 | " print(\"New best:\"+gen_name+\" vs \"+gen_best1+\": Winrate1:\"+str(pit_winrate)+\"%\")\n", 469 | " print(\" :\"+gen_name+\" vs \"+gen_best2+\": Winrate2:\"+str(pit_winrate2)+\"%\")\n", 470 | " tmpgenbest1=gen_best1\n", 471 | " gen_best1=gen_name\n", 472 | " with open('gen_best1.txt', 'w') as f:\n", 473 | " f.write(gen_best1)\n", 474 | " if (pit_winrate2>=50.0 and tmpgenbest1 != gen_best2):\n", 475 | " gen_best2=tmpgenbest1\n", 476 | " with open('gen_best2.txt', 'w') as f:\n", 477 | " f.write(gen_best2)" 478 | ] 479 | }, 480 | { 481 | "cell_type": "code", 482 | "execution_count": null, 483 | "metadata": {}, 484 | "outputs": [], 485 | "source": [ 486 | "######################################### AUXILIARY TOOLBOX #####################################" 487 | ] 488 | }, 489 | { 490 | "cell_type": "code", 491 | "execution_count": null, 492 | "metadata": { 493 | "scrolled": false 494 | }, 495 | "outputs": [], 496 | "source": [ 497 | "###################### MODEL VALIDATION ###########################\n", 498 | "#Run this script, then copy the output to C++ main() function to print a Model prediction in C++. Both must be the same\n", 499 | "print(\"//########################## ZERO TEST\")\n", 500 | "test_zero=np.zeros([1,INPUT_SIZE], dtype=np.float32)\n", 501 | "predictions = model.predict(test_zero)\n", 502 | "model.save('validate.h5')\n", 503 | "SaveModel(model,\"validate.w32\")\n", 504 | "print(\"//Use the following code in C++ to validate Model consistency\")\n", 505 | "print('ValidateModel(\"validate.w32\",\tR\"('+f\"{' '.join(map(str, test_zero[0]))})\\\");\")\n", 506 | "\n", 507 | "print(\"//Value Predicted:\",end='')\n", 508 | "print(predictions[0][0])\n", 509 | "\n", 510 | "print(\"//Policy Predicted:\",end='')\n", 511 | "print(predictions[1][0])\n", 512 | "print(\"//Ensure that Value and Policy values are the same\")\n", 513 | "print(\"//########################## RANDOM TEST\")\n", 514 | "test_random=np.random.rand(1,INPUT_SIZE)\n", 515 | "predictions = model.predict(test_random)\n", 516 | "print(\"//Use the following code in C++ to validate Model consistency\")\n", 517 | "print('ValidateModel(\"validate.w32\",\tR\"('+f\"{' '.join(map(str, test_random[0]))})\\\");\")\n", 518 | "\n", 519 | "print(\"//Value Predicted:\",end='')\n", 520 | "print(predictions[0][0])\n", 521 | "\n", 522 | "print(\"//Policy Predicted:\",end='')\n", 523 | "print(predictions[1][0])\n", 524 | "print(\"//Ensure that Value and Policy values are the same\")" 525 | ] 526 | }, 527 | { 528 | "cell_type": "code", 529 | "execution_count": null, 530 | "metadata": {}, 531 | "outputs": [], 532 | "source": [ 533 | "#Search a new CPUCT, it pits the same NN model with different coeffs, and keep a report on best_upct.txt file\n", 534 | "import shutil\n", 535 | "shutil.copyfile(gen_best1+'.w32', 'A.w32')\n", 536 | "shutil.copyfile(gen_best2+'.w32', 'B.w32')\n", 537 | "#cpupt optimizer\n", 538 | "BEST_CPUCT_MAX=1.00+random.random()*5.0 \n", 539 | "BEST_CPUCT_MIN=(BEST_CPUCT_MAX-0.40)*random.random()+0.40\n", 540 | "BEST_CPUCT_INC=0.001+0.035*random.random()\n", 541 | "TEST_PARAM_THREAD= f\"{THREADS} 150\"\n", 542 | "try:\n", 543 | " bestWinrate\n", 544 | "except NameError:\n", 545 | " bestWinrate=0.0\n", 546 | "with open('best_upct.txt', 'a') as f:\n", 547 | " f.write(\"Searching on best:\"+gen_best1+\"\\n\")\n", 548 | "for upt in range(100):\n", 549 | " TEST_CPUCT_INC=0.001+0.035*random.random()\n", 550 | " TEST_CPUCT_MAX=1.00+random.random()*5.0 \n", 551 | " TEST_CPUCT_MIN=(TEST_CPUCT_MAX-1.00)*random.random()+1.00 \n", 552 | " if (random.random() < 0.5):\n", 553 | " TEST_CPUCT_INC=-TEST_CPUCT_INC\n", 554 | " T=TEST_CPUCT_MIN\n", 555 | " TEST_CPUCT_MIN=TEST_CPUCT_MAX\n", 556 | " TEST_CPUCT_MAX=T\n", 557 | " #pit\n", 558 | " #TEST_CPUCT_MAX=1.00+random.random()*5.0 \n", 559 | " #TEST_CPUCT_MIN=(TEST_CPUCT_MAX-1.00)*random.random()+1.00\n", 560 | " #TEST_CPUCT_INC=0.001+0.035*random.random()\n", 561 | " TEST_CPUCT_MIN=3.0-0.30+2.0*0.30*random.random()\n", 562 | " TEST_CPUCT_MAX=TEST_CPUCT_MIN+2.0*0.05*random.random()\n", 563 | " TEST_CPUCT_INC=0.00360-0.00080+2.0*0.00080*random.random()\n", 564 | " \n", 565 | "\n", 566 | " UPT_CC = f\"{TEST_CPUCT_MIN} {TEST_CPUCT_INC} {TEST_CPUCT_MAX} {PIT_MCTS_ITER} {PIT_NOISE_DIR_EPSILON} {PIT_NOISE_DIR_ALPHA} {PIT_NOISE_DIR_DECAY} {PIT_NOISE_RANDOM} {PROPAGATE_BASE} {PROPAGATE_INC} {POLICY_BACKP_FIRST} {POLICY_BACKP_LAST}\" \n", 567 | " pitplay_process=os.path.join(\".\",\"CGZero\")+\" pitplay \"+TEST_PARAM_THREAD+\" A \"+UPT_CC+\" A \"+PIT_PARAM_MCTS\n", 568 | " print('subprocess.run('+pitplay_process+', shell=True)')\n", 569 | " subprocess.run(pitplay_process, shell=True)\n", 570 | " pit_winrate=readAndDeleteWinrate(\"A\",\"A\")\n", 571 | " if (pit_winrate > 50.0 and pit_winrate > bestWinrate-5.0):\n", 572 | " pitplay_process=os.path.join(\".\",\"CGZero\")+\" pitplay \"+TEST_PARAM_THREAD+\" A \"+UPT_CC+\" B \"+PIT_PARAM_MCTS\n", 573 | " subprocess.run(pitplay_process, shell=True)\n", 574 | " pit_winrate+=readAndDeleteWinrate(\"A\",\"B\")\n", 575 | " pit_winrate*=0.5\n", 576 | " with open('best_upct.txt', 'a') as f:\n", 577 | " f.write(f\"{pit_winrate} | {TEST_CPUCT_MIN} {TEST_CPUCT_INC} {TEST_CPUCT_MAX} \"+\"\\n\") \n", 578 | " print('Winrate '+str(pit_winrate))\n", 579 | " if (pit_winrate > bestWinrate):\n", 580 | " bestWinrate = pit_winrate\n", 581 | " BEST_CPUCT_MAX=TEST_CPUCT_MAX \n", 582 | " BEST_CPUCT_MIN=TEST_CPUCT_MIN\n", 583 | " BEST_CPUCT_INC=TEST_CPUCT_INC\n", 584 | " print(f\"New best {TEST_CPUCT_MIN} {TEST_CPUCT_INC} {TEST_CPUCT_MAX} {bestWinrate}% \")\n", 585 | " with open('best_upct.txt', 'a') as f:\n", 586 | " f.write(f\"New best {bestWinrate}% | {TEST_CPUCT_MIN} {TEST_CPUCT_INC} {TEST_CPUCT_MAX}\"+\"\\n\") " 587 | ] 588 | }, 589 | { 590 | "cell_type": "code", 591 | "execution_count": null, 592 | "metadata": {}, 593 | "outputs": [], 594 | "source": [ 595 | "csv_data = np.fromfile(SAMPLES_FILE, dtype=np.float32)\n", 596 | "csv_data=np.reshape(csv_data, (-1,INPUT_SIZE+POLICY_SIZE+2))\n", 597 | "cut_index = [(csv_data.shape)[1]-POLICY_SIZE-2, (csv_data.shape)[1]-2,(csv_data.shape)[1]-1]\n", 598 | "samples,policy,value=np.split(csv_data, cut_index,axis=1)\n", 599 | "\n", 600 | "mask= np.where(policy < 0, -999999999.99, policy)\n", 601 | "policy= np.where(policy < 0, 0, policy) " 602 | ] 603 | }, 604 | { 605 | "cell_type": "code", 606 | "execution_count": null, 607 | "metadata": {}, 608 | "outputs": [], 609 | "source": [ 610 | "model.optimizer.learning_rate.assign(0.003)\n", 611 | "model.fit({'input':samples}, {'policy': policy, 'value':value},verbose=2, epochs=int(20),callbacks=[csv_logger],batch_size=64) " 612 | ] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": null, 617 | "metadata": {}, 618 | "outputs": [], 619 | "source": [ 620 | "model.save(gen_name+'.h5')\n", 621 | "SaveModel(model,gen_name+\".w32\")" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": null, 627 | "metadata": {}, 628 | "outputs": [], 629 | "source": [ 630 | "pitplay_process=os.path.join(\".\",\"CGZero\")+\" pitplay \"+PIT_PARAM_THREAD+\" \"+gen_name+\" \"+PIT_PARAM_MCTS+\" \"+gen_best2+\" \"+PIT_PARAM_MCTS\n", 631 | "print('subprocess.run('+pitplay_process+', shell=True)')\n", 632 | "subprocess.run(pitplay_process, shell=True)" 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": null, 638 | "metadata": {}, 639 | "outputs": [], 640 | "source": [ 641 | "selfplay_process=os.path.join(\".\",\"CGZero\")+\" selfplay \"+f\"{THREADS} 500 \"+gen_best1+\" \"+TRAIN_PARAMS+\" \"+gen_best2+\" \"+TRAIN_PARAMS\n", 642 | "print(selfplay_process)\n", 643 | "subprocess.run(selfplay_process, shell=True)\n", 644 | "\n", 645 | "selfplay_process=os.path.join(\".\",\"CGZero\")+\" selfplay \"+f\"{THREADS} 500 \"+gen_best2+\" \"+TRAIN_PARAMS+\" \"+gen_best2+\" \"+TRAIN_PARAMS\n", 646 | "print(selfplay_process)\n", 647 | "subprocess.run(selfplay_process, shell=True)\n", 648 | "print(\"Done\")" 649 | ] 650 | }, 651 | { 652 | "cell_type": "code", 653 | "execution_count": null, 654 | "metadata": {}, 655 | "outputs": [], 656 | "source": [ 657 | "csv_data = np.fromfile(SAMPLES_FILE, dtype=np.float32)\n", 658 | "csv_data=np.reshape(csv_data, (-1,INPUT_SIZE+POLICY_SIZE+2))\n", 659 | "cut_index = [(csv_data.shape)[1]-POLICY_SIZE-2, (csv_data.shape)[1]-2,(csv_data.shape)[1]-1]\n", 660 | "samples,policy,value,countVisits=np.split(csv_data, cut_index,axis=1)" 661 | ] 662 | }, 663 | { 664 | "cell_type": "code", 665 | "execution_count": null, 666 | "metadata": {}, 667 | "outputs": [], 668 | "source": [ 669 | "nn_1=\"gen0242\"\n", 670 | "nn_2=\"gen0239\"\n", 671 | "no_matches=300\n", 672 | "custom=f\"./CGZero selfplay {THREADS} {no_matches} {nn_1} 4.0 0.0034086042277349836 4.0 2000 0.24 1.3 0.0 0.05 0.9 0.1 20 5 {nn_2} 4.0 0.0034086042277349836 4.0 2000 0.24 1.3 0.0 0.05 0.9 0.1 20 5\"\n", 673 | "print(custom)\n", 674 | "subprocess.run(custom, shell=True)" 675 | ] 676 | }, 677 | { 678 | "cell_type": "code", 679 | "execution_count": null, 680 | "metadata": {}, 681 | "outputs": [], 682 | "source": [ 683 | "model=tf.keras.models.load_model(\"gen\"+str(36).zfill(4)+'.h5')" 684 | ] 685 | }, 686 | { 687 | "cell_type": "code", 688 | "execution_count": null, 689 | "metadata": {}, 690 | "outputs": [], 691 | "source": [ 692 | "pitplay_process=os.path.join(\".\",\"CGZero\")+\" pitplay \"+PIT_PARAM_THREAD+\" \"+gen_name+\" \"+PIT_PARAM_MCTS+\" \"+gen_best2+\" \"+PIT_PARAM_MCTS\n", 693 | "print('subprocess.run('+pitplay_process+', shell=True)')\n", 694 | "subprocess.run(pitplay_process, shell=True)" 695 | ] 696 | } 697 | ], 698 | "metadata": { 699 | "colab": { 700 | "name": "AlphaZero.ipynb", 701 | "provenance": [] 702 | }, 703 | "kernelspec": { 704 | "display_name": "Python 3", 705 | "language": "python", 706 | "name": "python3" 707 | }, 708 | "language_info": { 709 | "codemirror_mode": { 710 | "name": "ipython", 711 | "version": 3 712 | }, 713 | "file_extension": ".py", 714 | "mimetype": "text/x-python", 715 | "name": "python", 716 | "nbconvert_exporter": "python", 717 | "pygments_lexer": "ipython3", 718 | "version": "3.7.4" 719 | } 720 | }, 721 | "nbformat": 4, 722 | "nbformat_minor": 1 723 | } 724 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------