diff --git a/Projects/Cortex_test/cortex_test.sln b/Projects/Cortex_test/cortex_test.sln new file mode 100644 index 00000000..ee99ef25 --- /dev/null +++ b/Projects/Cortex_test/cortex_test.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cortex_test", "cortex_test\cortex_test.vcxproj", "{CB0601AE-A104-40CF-83D1-DA66736E8322}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CB0601AE-A104-40CF-83D1-DA66736E8322}.Debug|Win32.ActiveCfg = Debug|Win32 + {CB0601AE-A104-40CF-83D1-DA66736E8322}.Debug|Win32.Build.0 = Debug|Win32 + {CB0601AE-A104-40CF-83D1-DA66736E8322}.Release|Win32.ActiveCfg = Release|Win32 + {CB0601AE-A104-40CF-83D1-DA66736E8322}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Projects/Cortex_test/cortex_test/ReadMe.txt b/Projects/Cortex_test/cortex_test/ReadMe.txt new file mode 100644 index 00000000..f645b350 --- /dev/null +++ b/Projects/Cortex_test/cortex_test/ReadMe.txt @@ -0,0 +1,40 @@ +======================================================================== + CONSOLE APPLICATION : cortex_test Project Overview +======================================================================== + +AppWizard has created this cortex_test application for you. + +This file contains a summary of what you will find in each of the files that +make up your cortex_test application. + + +cortex_test.vcxproj + This is the main project file for VC++ projects generated using an Application Wizard. + It contains information about the version of Visual C++ that generated the file, and + information about the platforms, configurations, and project features selected with the + Application Wizard. + +cortex_test.vcxproj.filters + This is the filters file for VC++ projects generated using an Application Wizard. + It contains information about the association between the files in your project + and the filters. This association is used in the IDE to show grouping of files with + similar extensions under a specific node (for e.g. ".cpp" files are associated with the + "Source Files" filter). + +cortex_test.cpp + This is the main application source file. + +///////////////////////////////////////////////////////////////////////////// +Other standard files: + +StdAfx.h, StdAfx.cpp + These files are used to build a precompiled header (PCH) file + named cortex_test.pch and a precompiled types file named StdAfx.obj. + +///////////////////////////////////////////////////////////////////////////// +Other notes: + +AppWizard uses "TODO:" comments to indicate parts of the source code you +should add to or customize. + +///////////////////////////////////////////////////////////////////////////// diff --git a/Projects/Cortex_test/cortex_test/cortex_test.cpp b/Projects/Cortex_test/cortex_test/cortex_test.cpp new file mode 100644 index 00000000..aebf2458 --- /dev/null +++ b/Projects/Cortex_test/cortex_test/cortex_test.cpp @@ -0,0 +1,70 @@ +// cortex_test.cpp : Defines the entry point for the console application. +// + +#include "stdafx.h" + + +int _tmain(int argc, _TCHAR* argv[]){ + objectConsoleLoggingService CL; + cortexLayersFactory * mFACTORY; + classGUI_SDL * mGUI; + sdlProgressBar * mPBar; + sdlLog * mLog; + basicLogCollection::getInstance()->addHandler(&CL); + mGUI = classGUI_SDL::getInstance(); + mLog = new sdlLog( 10,300,600,200); + basicLogCollection::getInstance()->addHandler(mLog); + + mFACTORY = cortexLayersFactory::getInstance(); + mPBar = new sdlProgressBar(120, 120, 500, 40); + mPBar->attachStatusProvider(mFACTORY); + mFACTORY->setGpuUsageMode(false); + mFACTORY->setPushPullMode(true); + float detectionThreshold = 0.5f; + basicCortex * Net; + Net = mFACTORY->parseConfigCustom("C:\\FruchtSystems\\darknet-master\\cfg\\tiny-yolo.cfg", 1 ); + //Net = mFACTORY->parseConfig("C:\\FruchtSystems\\dn_vs13\\x64\\Debug\\cfg\\yolo-obj.cfg"); + //Net = mFACTORY->parseConfig("C:\\FruchtSystems\\darknet-master\\cfg\\darknet.cfg"); + if( Net != NULL ){ + //delete(mPBar); + Net->loadWeights("C:\\FruchtSystems\\dn_vs13\\x64\\Debug\\yolo-obj.backup"); + Net->setBatch(1); + + regionLayer *RL; + RL = (regionLayer*)Net->getLayer(Net->getLayersCount() - 1); + + float nms = .4f; + uint32_t box_cnt; + uint32_t cls_cnt; + box_cnt = RL->getBoxesCount(); + cls_cnt = RL->getClassesCount(); + cortexBOXLABEL *boxes = (cortexBOXLABEL*)calloc(box_cnt, sizeof(cortexBOXLABEL)); + float **probs = (float**)calloc(box_cnt, sizeof(float*)); + for (uint32_t j = 0; j < box_cnt; ++j){ + memset(boxes, 0, box_cnt*sizeof(cortexBOXLABEL)); + probs[j] = (float*)calloc(cls_cnt, sizeof(float)); + memset(probs[j], 0, cls_cnt*sizeof(float)); + }; + cv::Mat img; + cv::Mat r_img; + char *tPath = "C:\\FruchtSystems\\darknet-master\\data\\dog.jpg"; + img = cv::imread(tPath, CV_LOAD_IMAGE_COLOR);//CV_LOAD_IMAGE_GRAYSCALE + basicLogCollection::getInstance()->Log("Main", NULL, tPath ); + // Check for invalid input + if( !img.data ){ + basicLogCollection::getInstance()->Log("Main", NULL, "Could not open or find the image!"); + } else { + cv::resize(img, r_img, cv::Size(Net->getInputWidth(), Net->getInputHeight()), 0, 0, CV_INTER_LINEAR); + cortexImage image(&r_img); + Net->predict(image.data); + RL->get_region_boxes(1, 1, detectionThreshold, probs, boxes, 0, 0 ); + + }; + mGUI->waitThreadEnd(); + delete(Net); + } else { + basicLogCollection::getInstance()->Log("Main", NULL, "Error Loading Network Configuration!"); + }; + return 0; +} + diff --git a/Projects/Cortex_test/cortex_test/stdafx.cpp b/Projects/Cortex_test/cortex_test/stdafx.cpp new file mode 100644 index 00000000..6c62e2f6 --- /dev/null +++ b/Projects/Cortex_test/cortex_test/stdafx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : source file that includes just the standard includes +// cortex_test.pch will be the pre-compiled header +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/Projects/Cortex_test/cortex_test/stdafx.h b/Projects/Cortex_test/cortex_test/stdafx.h new file mode 100644 index 00000000..902b447f --- /dev/null +++ b/Projects/Cortex_test/cortex_test/stdafx.h @@ -0,0 +1,30 @@ +// stdafx.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +#include "targetver.h" + +#include +#include + +//#include +//#include +//#include +//#include + +//#include + +#include "../../lib/data/cortex/cpu/cpu.h" +#include "../../lib/data/cortex/cuda/cuda.h" +#include "../../lib/components/object/objectConsoleLoggingService.h" +#include "../../lib/data/cortex/layers/layersFactory.h" +#include "../../lib/data/cortex/layers/regionLayer.h" +//#include "../../lib/sdl/gui_sdl.h" +#include "../../lib/sdl/widgets/progressBar.h" +#include "../../lib/sdl/widgets/logWidget.h" + + +// TODO: reference additional headers your program requires here diff --git a/Projects/Cortex_test/cortex_test/targetver.h b/Projects/Cortex_test/cortex_test/targetver.h new file mode 100644 index 00000000..87c0086d --- /dev/null +++ b/Projects/Cortex_test/cortex_test/targetver.h @@ -0,0 +1,8 @@ +#pragma once + +// Including SDKDDKVer.h defines the highest available Windows platform. + +// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and +// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. + +#include diff --git a/lib/data/cortex/base/basicCortex.cpp b/lib/data/cortex/base/basicCortex.cpp index 06181b20..bea51533 100644 --- a/lib/data/cortex/base/basicCortex.cpp +++ b/lib/data/cortex/base/basicCortex.cpp @@ -16,6 +16,9 @@ #include "../layers/routeLayer.h" #include "../layers/detectionLayer.h" +#define LOG( X ) m_pLog->Log( "basicCortex", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "basicCortex", this, _LOG_ERROR, X ) + basicCortex::basicCortex(LEARNING_POLICY Policy, bool useGPU){ m_pLog = basicLogCollection::getInstance(); m_bUseGPU = useGPU; @@ -86,6 +89,7 @@ basicCortex::~basicCortex(){ }; bool basicCortex::create(int n){ + m_nN = n; return true; }; @@ -138,6 +142,7 @@ float basicCortex::getCurrentRate( void ){ }; void basicCortex::forward( cortexSTATE state ){ + state.workspace = m_pWorkspace; state.index = 0; for( layerHeap::iterator index = m_vLayerHeap.begin(); index < m_vLayerHeap.end(); @@ -404,6 +409,20 @@ uint32_t basicCortex::getInputSize(void){ return 0; }; +uint32_t basicCortex::getInputWidth(void){ + if (m_vLayerHeap.size()){ + m_nWidth = m_vLayerHeap[0]->m_nIn_Width; + }; + return m_nWidth; +}; + +uint32_t basicCortex::getInputHeight(void){ + if (m_vLayerHeap.size()){ + m_nHeight = m_vLayerHeap[0]->m_nIn_Height; + }; + return m_nHeight; +}; + uint32_t basicCortex::getOutputSize(void){ cortexLayer *tL; tL = getOutputLayer(); @@ -475,17 +494,238 @@ void basicCortex::parseConfig(char * filename){ }; void basicCortex::parseConfigCustom(char * filename, int batch){ }; -void basicCortex::save(char * filename){ +*/ + +void basicCortex::save(char *filename){ }; -void basicCortex::saveWeights(char * filename){ +void basicCortex::saveWeights(char *filename){ }; -void basicCortex::saveWeightsUpto(char * filename, int cutoff){ +void basicCortex::saveWeightsUpto(char *filename, int cutoff){ }; -void basicCortex::saveWeightsDouble(char * filename){ +void basicCortex::saveWeightsDouble(char *filename){ }; -void basicCortex::loadWeights(char * filename){ +void basicCortex::loadWeights(char *filename){ + loadWeightsUpto(filename, m_nN); }; -void basicCortex::loadWeightsUpto(char * filename, int cutoff){ + +void basicCortex::loadWeightsUpto(char *filename, int cutoff){ +#ifdef GPU + if( m_nGpuIndex >= 0 ){ + m_pPU->setDevice( m_nGpuIndex ); + }; +#endif + char tBuffer[256]; + sprintf( tBuffer, "Loading weights from %s...", filename ); + LOG(tBuffer); + FILE *fp = fopen(filename, "rb"); + if (!fp) file_error(filename); + + uint32_t major; + uint32_t minor; + uint32_t revision; + fread(&major, sizeof(uint32_t), 1, fp); + fread(&minor, sizeof(uint32_t), 1, fp); + fread(&revision, sizeof(uint32_t), 1, fp); + + sprintf(tBuffer, "Revision:%d Major:%d Minor:%d", revision, major, minor); + LOG(tBuffer); + + if ((major * 10 + minor) >= 2) { + LOG("Seen 64 bit"); + uint64_t iseen = 0; + fread(&m_nSeen, sizeof(uint64_t), 1, fp); + } else { + LOG("Seen 32 bit"); + uint32_t iseen = 0; + fread(&iseen, sizeof(uint32_t), 1, fp); + m_nSeen = (uint64_t)iseen; + }; + bool transpose = (major > 1000) || (minor > 1000); + //for (uint32_t i = 0; ( i < m_nN ) && ( i < cutoff); ++i){ + for (uint32_t i = 0; (i < m_vLayerHeap.size()) && (i < cutoff); ++i){ + cortexLayer *l = m_vLayerHeap.at(i); + if( l->m_bDontLoad )continue; + switch (l->m_eType){ + case BATCHNORM: + case RNN: + case CRNN: + case LOCAL: + case CONVOLUTIONAL: l->loadWeights(fp); break; + case GRU: + case CONNECTED: l->loadWeights(fp, transpose); break; + default: break; + }; + }; + LOG("Done!"); + fclose(fp); }; -*/ +void basicCortex::visualize(void){ + /*image *prev = 0; + int i; + char buff[256]; + for (i = 0; i < m_vLayerHeap.size(); ++i){ + sprintf(buff, "Layer %d", i); + layer l = net.layers[i]; + if (l.type == CONVOLUTIONAL){ + prev = visualize_convolutional_layer(l, buff, prev); + }; + };*/ +}; + +void basicCortex::topPredictions( int k, int *index){ + //int size = get_network_output_size(net); + //float *out = get_network_output(net); + //top_k(out, m_nOutput size, k, index); + top_k( m_pOutput, m_nOutput, k, index); +}; + + +float *basicCortex::predict(float *input){ +//#ifdef GPU +// if (gpu_index >= 0) return network_predict_gpu(net, input); +//#endif + + cortexSTATE state; + state.net = this; + state.index = 0; + state.input = input; + state.truth = 0; + state.train = 0; + state.delta = 0; + state.workspace = 0; + forward( state ); + //float *out = get_network_output(net); + //return out; + return m_pOutput; +}; + +cortexMATRIX basicCortex::predictDataMulti(cortexDATA test, int n){ + int i, j, b, m; + //int k = get_network_output_size(net); + int k = m_nOutput; + cortexMATRIX pred = make_matrix(test.X.rows, k); + float *X = (float*)calloc(m_nBatch*test.X.rows, sizeof(float)); + for (i = 0; i < test.X.rows; i += m_nBatch){ + for (b = 0; b < m_nBatch; ++b){ + if (i + b == test.X.rows) break; + memcpy(X + b*test.X.cols, test.X.values[i + b], test.X.cols*sizeof(float)); + }; + for (m = 0; m < n; ++m){ + float *out = predict(X); + for (b = 0; b < m_nBatch; ++b){ + if (i + b == test.X.rows) break; + for (j = 0; j < k; ++j){ + pred.values[i + b][j] += out[j + b*k] / n; + }; + }; + }; + }; + free(X); + return pred; +}; + +cortexMATRIX basicCortex::predictData(cortexDATA test){ + int i, j, b; + //int k = get_network_output_size(net); + int k = m_nOutput; + cortexMATRIX pred = make_matrix(test.X.rows, k); + float *X = (float*)calloc(m_nBatch*test.X.cols, sizeof(float)); + for (i = 0; i < test.X.rows; i += m_nBatch){ + for (b = 0; b < m_nBatch; ++b){ + if (i + b == test.X.rows) break; + memcpy(X + b*test.X.cols, test.X.values[i + b], test.X.cols*sizeof(float)); + }; + float *out = predict(X); + for (b = 0; b < m_nBatch; ++b){ + if (i + b == test.X.rows) break; + for (j = 0; j < k; ++j){ + pred.values[i + b][j] = out[j + b*k]; + }; + }; + }; + free(X); + return pred; +}; + +void basicCortex::print( void ){ + for (size_t i = 0; i < m_nBatch; ++i){ + cortexLayer *l = m_vLayerHeap.at(i); + float *output = l->m_pOutput; + int n = l->m_nOutput; + float mean = m_pPU->calcMeanArray(output, n); + float vari = m_pPU->calcVarianceArray(output, n); + fprintf(stderr, "Layer %d - Mean: %f, Variance: %f\n", i, mean, vari); + if (n > 100) n = 100; + for (size_t j = 0; j < n; ++j) fprintf(stderr, "%f, ", output[j]); + if (n == 100)fprintf(stderr, ".....\n"); + fprintf(stderr, "\n"); + }; +}; + +void basicCortex::compareNetworks(basicCortex n1, basicCortex n2, cortexDATA test){ + cortexMATRIX g1 = n1.predictData(test); + cortexMATRIX g2 = n2.predictData(test); + int i; + int a, b, c, d; + a = b = c = d = 0; + for (i = 0; i < g1.rows; ++i){ + int truth = m_pPU->calcMaxIndex(test.Y.values[i], test.Y.cols); + int p1 = m_pPU->calcMaxIndex(g1.values[i], g1.cols); + int p2 = m_pPU->calcMaxIndex(g2.values[i], g2.cols); + if (p1 == truth){ + if (p2 == truth) ++d; + else ++c; + } else{ + if (p2 == truth) ++b; + else ++a; + }; + }; + printf("%5d %5d\n%5d %5d\n", a, b, c, d); + float num = (float)pow((abs(b - c) - 1.), 2.); + float den = (float)(b + c); + printf("%f\n", num / den); +}; + +float basicCortex::accuracy(cortexDATA d){ + cortexMATRIX guess = predictData(d); + float acc = matrix_topk_accuracy(d.Y, guess, 1); + free_matrix(guess); + return acc; +}; + +float *basicCortex::accuracies(cortexDATA d, int n){ + static float acc[2]; + cortexMATRIX guess = predictData(d); + acc[0] = matrix_topk_accuracy(d.Y, guess, 1); + acc[1] = matrix_topk_accuracy(d.Y, guess, n); + free_matrix(guess); + return acc; +}; + +float basicCortex::accuracyMulti(cortexDATA d, int n){ + cortexMATRIX guess = predictDataMulti(d, n); + float acc = matrix_topk_accuracy(d.Y, guess, 1); + free_matrix(guess); + return acc; +}; + +void basicCortex::freeNetwork( void ){ + for (uint32_t i = 0; i < m_vLayerHeap.size(); ++i) { + //ToDo: Must issue delete to a type of layer + delete(m_vLayerHeap.at(i)); + }; + m_vLayerHeap.clear(); +#ifdef GPU + if ( m_pGpuWorkspace!= NULL ) m_pPU->freeMem(m_pGpuWorkspace); + //if (*net.input_gpu) cuda_free(*net.input_gpu); + //if (*net.truth_gpu) cuda_free(*net.truth_gpu); + //if (net.input_gpu) free(net.input_gpu); + //if (net.truth_gpu) free(net.truth_gpu); +#endif + if (m_pWorkspace != NULL)free(m_pWorkspace); +}; + + +#undef LOG +#undef LOG_ERROR \ No newline at end of file diff --git a/lib/data/cortex/base/basicCortex.h b/lib/data/cortex/base/basicCortex.h index 80882790..3e03ea7d 100644 --- a/lib/data/cortex/base/basicCortex.h +++ b/lib/data/cortex/base/basicCortex.h @@ -32,6 +32,7 @@ class basicCortex{ float m_fPower; float m_fEpoch; float m_fCost; + uint32_t m_nN; uint32_t m_nGpuIndex; uint16_t m_nWidth; uint16_t m_nHeight; @@ -98,6 +99,8 @@ class basicCortex{ uint32_t getLayersCount(void); cv::Mat * getImageOfLayer(uint32_t i); uint32_t getInputSize(void); + uint32_t getInputWidth(void); + uint32_t getInputHeight(void); float getMomentum(void){ return m_fMomentum; }; uint32_t getOtputSize(void){ return m_nOutput; }; float * getOutput(void); @@ -138,19 +141,30 @@ class basicCortex{ void setGpuState(cortexSTATE &State){ memcpy(&m_sGpuState, &State, sizeof(cortexSTATE)); }; */ uint32_t getGpuIndex(void){ return m_nGpuIndex; }; - float *getGpuInput(void){ return m_pGpuInput; }; - float *getGpuTruth(void){ return m_pGpuTruth; }; + float * getGpuInput(void){ return m_pGpuInput; }; + float * getGpuTruth(void){ return m_pGpuTruth; }; void setGpuInput(float *ptr); void setGpuTruth(float *ptr); #endif //void parseConfig( char * filename ); //void parseConfigCustom( char * filename, int batch ); - //void save( char * filename ); - //void saveWeights( char * filename ); - //void saveWeightsUpto( char * filename, int cutoff ); - //void saveWeightsDouble( char * filename ); - //void loadWeights( char * filename ); - //void loadWeightsUpto( char * filename, int cutoff ); + void save( char * filename ); + void saveWeights( char * filename ); + void saveWeightsUpto( char * filename, int cutoff ); + void saveWeightsDouble( char * filename ); + void loadWeights( char * filename ); + void loadWeightsUpto( char * filename, int cutoff ); + void visualize( void); + void topPredictions( int k, int *index); + float * predict( float * input); + cortexMATRIX predictDataMulti( cortexDATA test, int n); + cortexMATRIX predictData( cortexDATA test); + void print( void ); + void compareNetworks( basicCortex n1, basicCortex n2, cortexDATA test ); + float accuracy( cortexDATA d); + float * accuracies( cortexDATA d, int n); + float accuracyMulti( cortexDATA d, int n); + void freeNetwork( void ); friend class cortexProcessingUnit; friend class cortexLayersFactory; }; diff --git a/lib/data/cortex/base/basicImage.cpp b/lib/data/cortex/base/basicImage.cpp index 5a2ae384..8b135de0 100644 --- a/lib/data/cortex/base/basicImage.cpp +++ b/lib/data/cortex/base/basicImage.cpp @@ -53,6 +53,7 @@ cortexImage::cortexImage(IplImage* src){ c = src->nChannels; step = src->widthStep; data = (float*)calloc(h*w*c, sizeof(float)); + size = h*w*c; if( data != NULL ) { int i, j, k; for(i = 0; i < h; ++i){ @@ -63,15 +64,17 @@ cortexImage::cortexImage(IplImage* src){ }; }; } else { - h=0; - w=0; - c=0; + h = 0; + w = 0; + c = 0; + size = 0; step = 0; }; } else { - h=0; - w=0; - c=0; + h = 0; + w = 0; + c = 0; + size = 0; step = 0; }; }; @@ -82,6 +85,7 @@ cortexImage::cortexImage(cv::Mat* src){ w= src->cols; c= src->channels(); step = w*c; + size = h*w*c; data = (float*)calloc(h*w*c, sizeof(float)); if( data != NULL ) { int i, j, k; @@ -96,12 +100,14 @@ cortexImage::cortexImage(cv::Mat* src){ h=0; w=0; c=0; + size = 0; step = 0; }; } else { h=0; w=0; c=0; + size = 0; step = 0; }; }; @@ -129,6 +135,7 @@ cortexImage::cortexImage( const cortexImage &CC ){ w=CC.w; c=CC.c; step=CC.step; + size = CC.size; data = (float*)calloc(h*w*c, sizeof(float)); if( data != NULL ) { memcpy( data, CC.data, h*w*c*sizeof(float)); @@ -136,6 +143,7 @@ cortexImage::cortexImage( const cortexImage &CC ){ h=0; w=0; c=0; + size = 0; step = 0; }; }; @@ -145,6 +153,7 @@ cortexImage::cortexImage( const cortexImage *CC ){ w = CC->w; c = CC->c; step = CC->step; + size = CC->size; data = (float*)calloc(h*w*c, sizeof(float)); if (data != NULL) { memcpy(data, CC->data, h*w*c*sizeof(float)); @@ -153,6 +162,7 @@ cortexImage::cortexImage( const cortexImage *CC ){ w = 0; c = 0; step = 0; + size = 0; }; }; @@ -191,7 +201,7 @@ cortexImage::cortexImage( cortexImage *CC ){ */ cortexImage::~cortexImage(){ - + freeData(); }; float cortexImage::getColor(uint32_t c, uint32_t x, uint32_t max){ @@ -631,6 +641,8 @@ void cortexImage::normalize2( void ){ void cortexImage::copyInto(cortexImage *dest){ if (dest->data != NULL) free(dest->data); dest->data = (float*)calloc(h*w*c, sizeof(float)); + dest->size = h*w*c; + dest->step = w*c; if (dest->data != NULL){ dest->h = h; dest->w = w; @@ -640,6 +652,8 @@ void cortexImage::copyInto(cortexImage *dest){ dest->h = 0; dest->w = 0; dest->c = 0; + dest->size = 0; + dest->step = 0; }; }; @@ -759,6 +773,8 @@ void cortexImage::makeEmpty(uint32_t ww, uint32_t hh, uint32_t cc){ h = hh; w = ww; c = cc; + step = 0; + size = 0; }; void cortexImage::freeData(void){ @@ -767,13 +783,14 @@ void cortexImage::freeData(void){ void cortexImage::makeWithData(uint32_t ww, uint32_t hh, uint32_t cc){ makeEmpty( ww, hh, cc ); - data = (float*)calloc(h*w*c, sizeof(float)); + size = h*w*c; + data = (float*)calloc(size, sizeof(float)); }; void cortexImage::fillRandom(void){ freeData(); - data = (float*)calloc(h*w*c, sizeof(float)); - for (uint16_t i = 0; i < w*h*c; ++i){ + data = (float*)calloc(size, sizeof(float)); + for (uint16_t i = 0; i < size; ++i){ data[i] = (float)((rand_normal() * .25) + .5); }; }; diff --git a/lib/data/cortex/base/basicImage.h b/lib/data/cortex/base/basicImage.h index 67fb7d44..c00b7925 100644 --- a/lib/data/cortex/base/basicImage.h +++ b/lib/data/cortex/base/basicImage.h @@ -97,11 +97,12 @@ class cortexImage{ //cortexImage( cortexImage *CC ); /* */ - uint16_t w; - uint16_t h; - uint16_t c; - uint16_t step; - float *data; + uint16_t w; + uint16_t h; + uint16_t c; + uint16_t step; + float * data; + size_t size; /*Methods*/ bool fillFromMat( cv::Mat* src ); bool fillFromVoid( uint32_t width, uint32_t height, uint32_t c){ return true; }; diff --git a/lib/data/cortex/base/basicLayer.cpp b/lib/data/cortex/base/basicLayer.cpp index 464f2f07..110bd68d 100644 --- a/lib/data/cortex/base/basicLayer.cpp +++ b/lib/data/cortex/base/basicLayer.cpp @@ -16,6 +16,8 @@ cortexLayer::cortexLayer(LAYER_TYPE type, bool useGPU){ m_pPU = cpuHOST::getInstance(); #endif m_eType = type; + m_eActivation = LEAKY; + m_eCost_type = SMOOTH; MUTEX_INIT(m_mOutputProtector); MUTEX_INIT(m_mInputProtector); MUTEX_INIT(m_mTruthProtector); @@ -27,12 +29,12 @@ cortexLayer::cortexLayer(LAYER_TYPE type, bool useGPU){ m_sClassFix = 0; - m_nBackground = m_nBatch = m_nBias = m_nClasses = m_nCoords = m_nDelta = m_nGroups = m_nIn_Width = m_nIn_Height = m_nIn_Channels = m_nIndexes = m_nInput \ + m_nBackground = m_nBatch = m_nBias = m_nClasses = m_nCoords = m_nDelta = m_nHidden = m_nGroups = m_nIn_Width = m_nIn_Height = m_nIn_Channels = m_nIndexes = m_nInput \ = m_nLog = m_nMaxBoxes = m_nN = m_nObjectness = m_nOut_Width = m_nOut_Height = m_nOut_Channels = m_nOutput = m_nPad = m_nRescore = m_nScale = m_nShortcut = m_nSide \ = m_nSize = m_nSteps = m_nStride = m_nT = m_nTruth = m_nWeight = m_nWorkspace = m_nRollingMeanSize = m_nRollingVarianceSize = 0; m_fAlpha = m_fAngle = m_fB1 = m_fB2 = m_fBetta = m_fClassScale = m_fCoordScale = m_fCost = m_fDelta = m_fDOT = m_fEpsilon = m_fExposure = m_fJitter \ - = m_fKappa = m_fNoObjectScale = m_fObjectScale = m_fRatio = m_fSaturation = m_fScale = m_fShift = m_fTemperature = 0.f; + = m_fKappa = m_fNoObjectScale = m_fObjectScale = m_fRatio = m_fSaturation = m_fScale = m_fShift = m_fTemperature = m_fThreshold = 0.f; m_pBias = m_pBiasUpdate = m_pBinaryInput = m_pBinaryWeight = m_pDelta = m_pConcat = m_pConcatDelta = m_pHostH = m_pHostM = m_pHostR = m_pHostV = m_pHostZ \ = m_pInput = /*m_pNormX =*/ m_pMean = m_pMeanDelta = m_pMeanSpatial = m_pOutput = m_pRand = m_pRollingMean = m_pRollingVariance = m_pScale = m_pScaleUpdate \ @@ -40,8 +42,9 @@ cortexLayer::cortexLayer(LAYER_TYPE type, bool useGPU){ m_pCharWeight = NULL; m_pHostIndexes = NULL; m_pGpuIndexes = NULL; + m_pMap = m_pIndexes = NULL; - m_pGpuZ = m_pGpuR = m_pGpuH = m_pGpuM = m_pGpuV = m_pGpuX = m_pGpuPrevState = m_pGpuForgotState = m_pGpuForgotDelta /*= m_pGpuState = m_pGpuStateDelta*/ \ + m_pGpuZ = m_pGpuR = m_pGpuH = m_pGpuM = m_pGpuV = m_pGpuX = m_pGpuXNorm = m_pGpuPrevState = m_pGpuForgotState = m_pGpuForgotDelta /*= m_pGpuState = m_pGpuStateDelta*/ \ = m_pGpuGate = m_pGpuGateDelta = m_pGpuSave = m_pGpuSaveDelta = m_pGpuConcat = m_pGpuConcatDelta = m_pGpuMean = m_pGpuVariance = m_pGpuRollingMean \ = m_pGpuRollingVariance = m_pGpuVarianceDelta = m_pGpuMeanDelta = /*m_pGpuNormX =*/ m_pGpuWeight = m_pGpuWeightUpdate = m_pGpuBias = m_pGpuBiasUpdate \ = m_pGpuScale = m_pGpuScaleUpdate = m_pGpuOutput = m_pGpuDelta = m_pGpuRand = m_pGpuBinaryWeight = m_pGpuBinaryInput = NULL; @@ -68,7 +71,8 @@ cortexLayer::~cortexLayer(){ FREE_HOST(m_pHostV); FREE_HOST(m_pHostZ); FREE_HOST(m_pInput); - //FREE_HOST(m_pNormX); + FREE_HOST(m_pIndexes); + FREE_HOST(m_pMap); FREE_HOST(m_pMean); FREE_HOST(m_pMeanDelta); FREE_HOST(m_pMeanSpatial); @@ -113,7 +117,7 @@ cortexLayer::~cortexLayer(){ FREE_PU(m_pGpuRollingVariance); FREE_PU(m_pGpuVarianceDelta); FREE_PU(m_pGpuMeanDelta); - //FREE_PU(m_pGpuNormX); + FREE_PU(m_pGpuXNorm); FREE_PU(m_pGpuWeight); FREE_PU(m_pGpuWeightUpdate); FREE_PU(m_pGpuBias); diff --git a/lib/data/cortex/base/basicLayer.h b/lib/data/cortex/base/basicLayer.h index aad5dc6f..29737da6 100644 --- a/lib/data/cortex/base/basicLayer.h +++ b/lib/data/cortex/base/basicLayer.h @@ -36,8 +36,7 @@ class cortexLayer{ bool m_bAdam; bool m_bBatchNormalize; bool m_bBinary; - bool m_bBiasMatch; - //bool m_bClassFix; + bool m_bBiasMatch; bool m_bDoesCost; bool m_bDontLoad; bool m_bDontLoadScales; @@ -221,64 +220,19 @@ class cortexLayer{ explicit cortexLayer( LAYER_TYPE type = BLANK, bool useGPU = true ); virtual ~cortexLayer(); /* Virtual Methods */ - virtual void forward( cortexSTATE state){}; virtual void backward( cortexSTATE state){}; virtual void backwardBias( float * bias_updates, float *delta, uint32_t batch, uint32_t n, uint32_t size){}; + virtual void loadWeights( FILE * Ptr, bool trans = false){}; virtual void update( uint32_t batch, float learning_rate, float momentum, float decay){}; virtual bool resize( uint32_t w, uint32_t h){ return false; }; virtual void push(void){}; virtual void pull(void){}; /* regular methods */ char * getString(void); - //void resetState(uint32_t b); - /*LAYER_TYPE getType(void){ return m_eType; }; - ACTIVATION getActivation(void){ return m_eActivation; }; - void setInputDimentions(uint32_t Width, uint32_t Height, uint32_t Channels){ m_nIn_Height = Height; m_nIn_Width = Width; m_nIn_Channels = Channels; }; - void setOutputDimentions(uint32_t Width, uint32_t Height, uint32_t Channels){ m_nOut_Height = Height; m_nOut_Width = Width; m_nOut_Channels = Channels; }; - uint32_t getBatch(void){ return m_nBatch; }; - void setBatch(uint32_t b){ m_nBatch = b; }; - uint32_t getIn_Width(void){ return m_nIn_Width; }; - uint32_t getIn_Height(void){ return m_nIn_Height; }; - uint32_t getIn_Channels(void){ return m_nIn_Channels; }; - uint32_t getOut_Width(void){ return m_nOut_Width; }; - uint32_t getOut_Height(void){ return m_nOut_Height; }; - uint32_t getOut_Channels(void){ return m_nOut_Channels; }; - uint32_t computeOut_Width(void){ return 0; }; - uint32_t computeOut_Height(void){ return 0; }; - uint32_t computeOut_Channels(void){ return 0; }; - - float getCost(void){ return m_fCost; }; - - float * getOutput(void){ return m_pOutput; }; - uint32_t getOutputSize(void){ return m_nOutput; }; - float * getInput(void){ return m_pInput; }; - uint32_t getInputSize(void){ return m_nInput; }; - float * getTruth(void){ return m_pTruth; }; - uint32_t getTruthSize(void){ return m_nTruth; }; - float * getDelta(void){ return m_pDelta; }; - uint32_t getDeltaSize(void){ return m_nDelta; }; - float * getWorkspace(void){ return m_pWorkspace; }; - uint32_t getWorkspaceSize(void){ return m_nWorkspace; }; - - - void setB1(float a){ m_fB1 = a; }; - void setB2(float a){ m_fB2 = a; }; - void setDot(float a){ m_fDOT = a; }; - void setEPS(float a){ m_fEpsilon = a; }; - void setFlipped(bool a){ m_bFlipped = a; }; - void setShortcut(uint32_t a){ m_nShortcut = a; }; - */ #ifdef GPU - /* CUDA functionality */ - //virtual void forward_gpu( cortexSTATE state){}; - //virtual void backward_gpu( cortexSTATE state){}; - //virtual void update_gpu( int batch, float learning_rate, float momentum, float decay){}; - - friend class gpuCUDA; #endif - friend class cpuHOST; friend class basicCortex; friend class routeLayer; diff --git a/lib/data/cortex/base/basicList.cpp b/lib/data/cortex/base/basicList.cpp index efb0b7eb..0ab36a01 100644 --- a/lib/data/cortex/base/basicList.cpp +++ b/lib/data/cortex/base/basicList.cpp @@ -150,14 +150,15 @@ char *fgetl( FILE *fp ){ return line; }; */ -cortexRList *readDataÑfg(char *filename){ +cortexRList *readDataÑfg(char *filename, uint8_t *cnt ){ FILE *file = fopen( filename, "r" ); if( file == NULL ) return NULL; //file_error(filename); char *line; int nu = 0; + if(cnt )*cnt = 0; cortexRList * RetVal = createList(); paramSection * cSection = createSection(); - cortexRList * opts;// = createList(); + cortexRList * opts = NULL;// = createList(); while ((line = fgetl(file)) != 0){ ++nu; strip(line); @@ -173,6 +174,7 @@ cortexRList *readData opts = createList(); cSection->opts = opts; listInsert(RetVal, cSection); + if (cnt)*cnt++; //optionInsert(RetVal, line, (char*)opts); cSection = createSection(); //opts = createList(); @@ -185,6 +187,7 @@ cortexRList *readData break; }; }; + free(cSection); fclose(file); return RetVal; }; diff --git a/lib/data/cortex/base/basicList.h b/lib/data/cortex/base/basicList.h index a842c28a..8dc793a9 100644 --- a/lib/data/cortex/base/basicList.h +++ b/lib/data/cortex/base/basicList.h @@ -26,7 +26,7 @@ typedef struct S_Section{ } paramSection; -cortexRList * readDataÑfg( char * filename); +cortexRList * readDataÑfg( char * filename, unsigned char *cnt = 0 ); bool readOption( char * s, cortexRList * opt); void optionInsert( cortexRList * l, char * key, char *val); char * optionFind( cortexRList * l, char * key); diff --git a/lib/data/cortex/base/basicProcessingUnit.cpp b/lib/data/cortex/base/basicProcessingUnit.cpp index 3a8a298b..4fd04f66 100644 --- a/lib/data/cortex/base/basicProcessingUnit.cpp +++ b/lib/data/cortex/base/basicProcessingUnit.cpp @@ -92,17 +92,15 @@ void *cortexProcessingUnit::load_thread(void *ptr){ return NULL; }; -#ifdef __linux__ -pthread_t cortexProcessingUnit::load_data_in_thread(cortexTHREAD_ARGS args){ -#else -HANDLE cortexProcessingUnit::load_data_in_thread(cortexTHREAD_ARGS args){ - HANDLE thread; +THREAD_HANDLE cortexProcessingUnit::load_data_in_thread(cortexTHREAD_ARGS args){ + THREAD_HANDLE thread; +#ifdef WIN_THREAD DWORD m_dwThreadID; #endif cortexTHREAD_ARGS *ptr = (cortexTHREAD_ARGS*)malloc(sizeof(cortexTHREAD_ARGS)); if (ptr != NULL){ *ptr = args; -#ifdef __linux__ +#ifdef PTHREAD if(pthread_create(&thread, 0, load_thread, ptr)) LOG_ERROR("Thread creation failed"); #else thread = CreateThread( @@ -113,9 +111,8 @@ HANDLE cortexProcessingUnit::load_data_in_thread(cortexTHREAD_ARGS args){ 0, &m_dwThreadID); #endif - return thread; }; - return NULL; + return thread; }; void cortexProcessingUnit::load_data_blocking(cortexTHREAD_ARGS *args){ @@ -1451,6 +1448,156 @@ bool cortexProcessingUnit::makeGradientArray(float *x, uint32_t n, ACTIVATION a, return true; }; +void cortexProcessingUnit::transposeMatrix(float *a, int rows, int cols){ + float *transpose = (float*)calloc(rows*cols, sizeof(float)); + int x, y; + for (x = 0; x < rows; ++x){ + for (y = 0; y < cols; ++y){ + transpose[y*rows + x] = a[x*cols + y]; + } + } + memcpy(a, transpose, rows*cols*sizeof(float)); + free(transpose); +} + +float cortexProcessingUnit::calcSumArray(float *a, size_t n){ + float sum = 0; + for (size_t i = 0; i < n; ++i) sum += a[i]; + return sum; +}; + +float cortexProcessingUnit::calcMeanArray(float *a, size_t n){ + return calcSumArray(a, n) / n; +}; + +float cortexProcessingUnit::calcVarianceArray(float *a, size_t n){ + float sum = 0; + float mean = calcMeanArray( a, n ); + for (size_t i = 0; i < n; ++i) sum += (a[i] - mean)*(a[i] - mean); + return sum / n; +}; + +inline int cortexProcessingUnit::calcConstrain(int a, int min, int max){ + if (a < min) return min; + if (a > max) return max; + return a; +}; + +inline float cortexProcessingUnit::calcConstrain(float a, float min, float max){ + if (a < min) return min; + if (a > max) return max; + return a; +}; + +size_t cortexProcessingUnit::calcMaxIndex(float *a, size_t n){ + if (n <= 0) return -1; + int i, max_i = 0; + float max = a[0]; + for (i = 1; i < n; ++i){ + if (a[i] > max){ + max = a[i]; + max_i = i; + } + } + return max_i; +}; + +int cortexProcessingUnit::calcRandInt(int min, int max){ + if (max < min){ + int s = min; + min = max; + max = s; + } + int r = (rand() % (max - min + 1)) + min; + return r; +}; + + +// From http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform + +float cortexProcessingUnit::calcRandNormal(void){ + static int haveSpare = 0; + static double rand1, rand2; + + if (haveSpare){ + haveSpare = 0; + return (float)(sqrt(rand1) * sin(rand2)); + }; + + haveSpare = 1; + + rand1 = rand() / ((double)RAND_MAX); + if (rand1 < 1e-100) rand1 = 1e-100; + rand1 = -2 * log(rand1); + rand2 = (rand() / ((double)RAND_MAX)) * TWO_PI; + + return (float)(sqrt(rand1) * cos(rand2)); +}; + +/* +float rand_normal() +{ +int n = 12; +int i; +float sum= 0; +for(i = 0; i < n; ++i) sum += (float)rand()/RAND_MAX; +return sum-n/2.; +} +*/ + +size_t cortexProcessingUnit::calcRandIndex(void){ + return ((size_t)(rand() & 0xff) << 56) | + ((size_t)(rand() & 0xff) << 48) | + ((size_t)(rand() & 0xff) << 40) | + ((size_t)(rand() & 0xff) << 32) | + ((size_t)(rand() & 0xff) << 24) | + ((size_t)(rand() & 0xff) << 16) | + ((size_t)(rand() & 0xff) << 8) | + ((size_t)(rand() & 0xff) << 0); +}; + +float cortexProcessingUnit::calcRandUniform(float min, float max){ + if (max < min){ + float swap = min; + min = max; + max = swap; + } + return ((float)rand() / RAND_MAX * (max - min)) + min; +}; + +float cortexProcessingUnit::calcRandScale(float s){ + float scale = calcRandUniformStrong(1, s); + if( calcRandomGen() % 2 ) return scale; + return 1.f / scale; +}; + +float cortexProcessingUnit::calcRandUniformStrong(float min, float max){ + if (max < min) { + float swap = min; + min = max; + max = swap; + }; + return (calcRandomFloat() * (max - min)) + min; +}; + +uint32_t cortexProcessingUnit::calcRandomGen(void){ + unsigned int rnd = 0; +#ifndef WIN32 + rand_s(&rnd); +#else + rnd = rand(); +#endif + return rnd; +}; + +float cortexProcessingUnit::calcRandomFloat(void){ +#ifdef WIN32 + return ((float)calcRandomGen() / (float)UINT_MAX); +#else + return ((float)calcRandomGen() / (float)RAND_MAX); +#endif +}; + #undef LOG #undef LOG_ERROR #undef SLOG diff --git a/lib/data/cortex/base/basicProcessingUnit.h b/lib/data/cortex/base/basicProcessingUnit.h index 9a9036bf..37ca9e9d 100644 --- a/lib/data/cortex/base/basicProcessingUnit.h +++ b/lib/data/cortex/base/basicProcessingUnit.h @@ -71,6 +71,7 @@ class cortexProcessingUnit{ virtual bool binarizeWeights(float *weights, uint32_t n, uint32_t size, float *binary){ return false; }; virtual void printMatrix(uint32_t M, uint32_t N, float *A){}; + void transposeMatrix(float *a, int rows, int cols); virtual bool calcAxpy(uint32_t N, float ALPHA, float * X, uint32_t INCX, float * Y, uint32_t INCY){ return false; }; virtual bool calcAxpyOffset(uint32_t N, float ALPHA, float * X, uint32_t OFFX, uint32_t INCX, float * Y, uint32_t OFFY, uint32_t INCY){ return false; }; @@ -86,6 +87,22 @@ class cortexProcessingUnit{ virtual bool calcWeightedDelta(float *a, float *b, float *s, float *da, float *db, float *ds, uint32_t num, float *dc){ return false; }; virtual bool calcWeightedSum(float *a, float *b, float *s, uint32_t num, float *c){ return false; }; + float calcSumArray(float *a, size_t n); + float calcMeanArray(float *a, size_t n); + float calcVarianceArray(float *a, size_t n); + int calcConstrain(int a, int min, int max); + float calcConstrain(float a, float min, float max); + size_t calcMaxIndex(float *a, size_t n); + int calcRandInt(int min, int max); + float calcRandNormal(void); + size_t calcRandIndex(void); + float calcRandUniform(float min, float max); + float calcRandUniformStrong(float min, float max); + uint32_t calcRandomGen(void); + float calcRandomFloat(void); + float calcRandScale(float s); + + virtual bool makeConstrain(uint32_t N, float ALPHA, float * X, uint32_t INCX){ return false; }; virtual bool makeConst(uint32_t N, float ALPHA, float * X, uint32_t INCX){ return false; }; virtual float makeActivated(float x, ACTIVATION a); @@ -146,7 +163,6 @@ class cortexProcessingUnit{ float mag_array(float *a, uint32_t n); float mag2_array(float *a, uint32_t n); - // CPU + GPU virtual void forward_layer( avgpoolLayer *layer, cortexSTATE state){}; virtual void backward_layer(avgpoolLayer *layer, cortexSTATE state){}; @@ -222,11 +238,7 @@ class cortexProcessingUnit{ private: static void * load_thread( void *ptr); -#ifdef __linnux__ - pthread_t load_data_in_thread( cortexTHREAD_ARGS args); -#else - HANDLE load_data_in_thread( cortexTHREAD_ARGS args); -#endif + THREAD_HANDLE load_data_in_thread(cortexTHREAD_ARGS args); protected: void print_letters(float *pred, uint32_t n); diff --git a/lib/data/cortex/cpu/cpuBatchnormLayer.cpp b/lib/data/cortex/cpu/cpuBatchnormLayer.cpp index a0cf5e01..b2ded77a 100644 --- a/lib/data/cortex/cpu/cpuBatchnormLayer.cpp +++ b/lib/data/cortex/cpu/cpuBatchnormLayer.cpp @@ -13,7 +13,7 @@ void cpuHOST::forward_layer(batchnormLayer *layer, cortexSTATE state){ calcAxpy(layer->m_nOut_Channels, .01f, layer->m_pVariance, 1, layer->m_pRollingVariance, 1); makeCopy(layer->m_nOutputVol, layer->m_pOutput, 1, layer->m_pX, 1); makeNormalized(layer->m_pOutput, layer->m_pMean, layer->m_pVariance, layer->m_nBatch, layer->m_nOut_Channels, Area); - makeCopy(layer->m_nOutputVol, layer->m_pOutput, 1, layer->m_pNormX, 1); + makeCopy(layer->m_nOutputVol, layer->m_pOutput, 1, layer->m_pXNorm, 1); } else { makeNormalized(layer->m_pOutput, layer->m_pRollingMean, layer->m_pRollingVariance, layer->m_nBatch, layer->m_nOut_Channels, Area); }; @@ -22,7 +22,7 @@ void cpuHOST::forward_layer(batchnormLayer *layer, cortexSTATE state){ void cpuHOST::backward_layer(batchnormLayer *layer, cortexSTATE state){ uint32_t Area = layer->m_nOut_Height*layer->m_nOut_Width; - makeBackwardScale(layer->m_pNormX, layer->m_pDelta, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pScaleUpdate); + makeBackwardScale(layer->m_pXNorm, layer->m_pDelta, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pScaleUpdate); calcScaleBias(layer->m_pDelta, layer->m_pScale, layer->m_nBatch, layer->m_nOut_Channels, Area); makeMeanDelta(layer->m_pDelta, layer->m_pVariance, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pMeanDelta); makeVarianceDelta(layer->m_pX, layer->m_pDelta, layer->m_pMean, layer->m_pVariance, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pVarianceDelta); diff --git a/lib/data/cortex/cpu/cpuConvolutionalLayer.cpp b/lib/data/cortex/cpu/cpuConvolutionalLayer.cpp index 3cfd6bdd..1845c044 100644 --- a/lib/data/cortex/cpu/cpuConvolutionalLayer.cpp +++ b/lib/data/cortex/cpu/cpuConvolutionalLayer.cpp @@ -19,14 +19,34 @@ void cpuHOST::forward_layer(convolutionalLayer *layer, cortexSTATE state){ float *a = layer->m_pWeight; float *b = state.workspace; float *c = layer->m_pOutput; - + float *d = state.input; for( uint32_t i = 0; i < layer->m_nBatch; ++i){ - im2col(state.input, layer->m_nIn_Channels, layer->m_nIn_Height, layer->m_nIn_Width, layer->m_nSize, layer->m_nStride, layer->m_nPad, b); + im2col( d, layer->m_nIn_Channels, layer->m_nIn_Height, layer->m_nIn_Width, layer->m_nSize, layer->m_nStride, layer->m_nPad, b); gemm(0, 0, m, n, CC, 1, a, CC, b, n, 1, c, n); c += n*m; - state.input += VV; + d += VV; + }; + if (layer->m_bBatchNormalize){ + //forward_layer(((batchnormLayer*)layer), state); + uint32_t Area = layer->m_nOut_Height*layer->m_nOut_Width; + //makeCopy(layer->m_nOutputVol, state.input, 1, layer->m_pOutput, 1); + makeCopy(layer->m_nInput, state.input, 1, layer->m_pOutput, 1); + if (state.train) { + makeMean(layer->m_pOutput, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pMean); + makeVariance(layer->m_pOutput, layer->m_pMean, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pVariance); + calcScal(layer->m_nOut_Channels, .99f, layer->m_pRollingMean, 1); + calcAxpy(layer->m_nOut_Channels, .01f, layer->m_pMean, 1, layer->m_pRollingMean, 1); + calcScal(layer->m_nOut_Channels, .99f, layer->m_pRollingVariance, 1); + calcAxpy(layer->m_nOut_Channels, .01f, layer->m_pVariance, 1, layer->m_pRollingVariance, 1); + makeCopy(layer->m_nOutputVol, layer->m_pOutput, 1, layer->m_pX, 1); + makeNormalized(layer->m_pOutput, layer->m_pMean, layer->m_pVariance, layer->m_nBatch, layer->m_nOut_Channels, Area); + makeCopy(layer->m_nOutputVol, layer->m_pOutput, 1, layer->m_pXNorm, 1); + } + else { + makeNormalized(layer->m_pOutput, layer->m_pRollingMean, layer->m_pRollingVariance, layer->m_nBatch, layer->m_nOut_Channels, Area); + }; + calcScaleBias(layer->m_pOutput, layer->m_pScale, layer->m_nBatch, layer->m_nOut_Channels, Area); }; - if (layer->m_bBatchNormalize) forward_layer(((batchnormLayer*)layer), state); addBias(layer->m_pOutput, layer->m_pBias, layer->m_nBatch, layer->m_nN, n); makeActivatedArray(layer->m_pOutput, m*n*layer->m_nBatch, layer->m_eActivation); if (layer->m_bBinary || layer->m_bXNOR) layer->swapBinary(); diff --git a/lib/data/cortex/cuda/col2im_kernels.cu b/lib/data/cortex/cuda/col2im_kernels.cu index 6d418c9d..2456fd14 100644 --- a/lib/data/cortex/cuda/col2im_kernels.cu +++ b/lib/data/cortex/cuda/col2im_kernels.cu @@ -41,9 +41,9 @@ __global__ void col2im_gpu_kernel(const int n, const float* data_col, } } -void gpuCUDA::col2im_ongpu(float *data_col, - int channels, int height, int width, - int ksize, int stride, int pad, float *data_im){ +void gpuCUDA::col2im(float *data_col, + uint32_t channels, uint32_t height, uint32_t width, + uint32_t ksize, uint32_t stride, uint32_t pad, float *data_im){ // We are going to launch channels * height_col * width_col kernels, each // kernel responsible for copying a single-channel grid. int height_col = (height + 2 * pad - ksize) / stride + 1; diff --git a/lib/data/cortex/cuda/convolutional_kernels.cu b/lib/data/cortex/cuda/convolutional_kernels.cu index 50100101..1fb3ba0a 100644 --- a/lib/data/cortex/cuda/convolutional_kernels.cu +++ b/lib/data/cortex/cuda/convolutional_kernels.cu @@ -279,7 +279,7 @@ void gpuCUDA::push_layer( convolutionalLayer *l ){ pushFloatArray(l->m_pGpuV, l->m_pHostV, l->m_nIn_Channels * l->m_nOut_Channels * l->m_nSize * l->m_nSize ); }; }; - +/* void gpuCUDA::update_layer( convolutionalLayer *l, int batch, float learning_rate, float momentum, float decay){ if( CONVOLUTIONAL != l->m_eType ) return; int size = l->m_nSize * l->m_nSize * l->m_nIn_Channels * l->m_nOut_Channels; @@ -305,7 +305,7 @@ void gpuCUDA::update_layer( convolutionalLayer *l, int batch, float learning_rat scal_ongpu( size, momentum, l->m_pGpuWeightUpdate, 1); }; }; - +*/ #undef LOG #undef LOG_ERROR diff --git a/lib/data/cortex/cuda/cudaBatchnormLayer.cpp b/lib/data/cortex/cuda/cudaBatchnormLayer.cpp index 4965d620..c414969d 100644 --- a/lib/data/cortex/cuda/cudaBatchnormLayer.cpp +++ b/lib/data/cortex/cuda/cudaBatchnormLayer.cpp @@ -13,7 +13,7 @@ void gpuCUDA::forward_layer(batchnormLayer *layer, cortexSTATE state){ calcAxpy(layer->m_nOut_Channels, .01f, layer->m_pGpuVariance, 1, layer->m_pGpuRollingVariance, 1); makeCopy(layer->m_nOutputVol, layer->m_pGpuOutput, 1, layer->m_pGpuX, 1); makeNormalized(layer->m_pGpuOutput, layer->m_pGpuMean, layer->m_pGpuVariance, layer->m_nBatch, layer->m_nOut_Channels, Area); - makeCopy(layer->m_nOutputVol, layer->m_pGpuOutput, 1, layer->m_pGpuNormX, 1); + makeCopy(layer->m_nOutputVol, layer->m_pGpuOutput, 1, layer->m_pGpuXNorm, 1); } else { makeNormalized(layer->m_pGpuOutput, layer->m_pGpuRollingMean, layer->m_pGpuRollingVariance, layer->m_nBatch, layer->m_nOut_Channels, Area); }; @@ -22,7 +22,7 @@ void gpuCUDA::forward_layer(batchnormLayer *layer, cortexSTATE state){ void gpuCUDA::backward_layer(batchnormLayer *layer, cortexSTATE state){ uint32_t Area = layer->m_nOut_Height*layer->m_nOut_Width; - makeBackwardScale(layer->m_pGpuNormX, layer->m_pGpuDelta, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pGpuScaleUpdate); + makeBackwardScale(layer->m_pGpuXNorm, layer->m_pGpuDelta, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pGpuScaleUpdate); calcScaleBias(layer->m_pGpuDelta, layer->m_pGpuScale, layer->m_nBatch, layer->m_nOut_Channels, Area); makeMeanDelta(layer->m_pGpuDelta, layer->m_pGpuVariance, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pGpuMeanDelta); makeFastVarianceDelta(layer->m_pGpuX, layer->m_pGpuDelta, layer->m_pGpuMean, layer->m_pGpuVariance, layer->m_nBatch, layer->m_nOut_Channels, Area, layer->m_pGpuVarianceDelta); diff --git a/lib/data/cortex/cuda/im2col_kernels.cu b/lib/data/cortex/cuda/im2col_kernels.cu index 325190b9..7529feac 100644 --- a/lib/data/cortex/cuda/im2col_kernels.cu +++ b/lib/data/cortex/cuda/im2col_kernels.cu @@ -45,9 +45,9 @@ __global__ void im2col_gpu_kernel(const int n, const float* data_im, } } -void gpuCUDA::im2col_ongpu(float *im, - int channels, int height, int width, - int ksize, int stride, int pad, float *data_col){ +void gpuCUDA::im2col(float *im, + uint32_t channels, uint32_t height, uint32_t width, + uint32_t ksize, uint32_t stride, uint32_t pad, float *data_col){ // We are going to launch channels * height_col * width_col kernels, each // kernel responsible for copying a single-channel grid. int height_col = (height + 2 * pad - ksize) / stride + 1; diff --git a/lib/data/cortex/cuda/network_kernels.cu b/lib/data/cortex/cuda/network_kernels.cu index 09a6fc86..7eba5eca 100644 --- a/lib/data/cortex/cuda/network_kernels.cu +++ b/lib/data/cortex/cuda/network_kernels.cu @@ -63,19 +63,19 @@ void gpuCUDA::forwardNetwork(basicCortex *net, cortexSTATE tState ){ snprintf(buffer, 256,"FillOnGPU %d", index); LOG(buffer); # endif - fill( tLayer->m_nOutput * tLayer->m_nBatch, 0, tLayer->m_pGpuDelta, 1 ); + makeFill( tLayer->m_nOutput * tLayer->m_nBatch, 0, tLayer->m_pGpuDelta, 1 ); # ifdef _DEBUG snprintf(buffer, 256,"FillOnGPU %d Done", index); LOG(buffer); # endif }; # ifdef _DEBUG - snprintf(buffer, 256, "FillForwardGPU %d Layer Type: %d\n", index, tLayer->getType()); + snprintf(buffer, 256, "FillForwardGPU %d Layer Type: %d\n", index, tLayer->m_eType); LOG(buffer); # endif //?? //tLayer->setGpuState(tState); - tLayer->forward_gpu(tState); + tLayer->forward(tState); # ifdef _DEBUG snprintf(buffer, 256, "FillOnGPU %d Done\n", index); LOG(buffer); @@ -101,7 +101,33 @@ void gpuCUDA::backwardNetwork(basicCortex *net, cortexSTATE tState){ tState.input = tPrev->m_pGpuOutput; tState.delta = tPrev->m_pGpuDelta; }; - tLayer->backward_gpu(tState); + switch (tLayer->m_eType){ + case CONVOLUTIONAL: backward_layer((convolutionalLayer *)tLayer, tState); break; + case DECONVOLUTIONAL: backward_layer((deconvolutionalLayer *)tLayer, tState); break; + case CONNECTED: backward_layer((convolutionalLayer *)tLayer, tState); break; + case MAXPOOL: backward_layer((convolutionalLayer *)tLayer, tState); break; + case SOFTMAX: backward_layer((convolutionalLayer *)tLayer, tState); break; + case DETECTION: backward_layer((convolutionalLayer *)tLayer, tState); break; + case DROPOUT: backward_layer((convolutionalLayer *)tLayer, tState); break; + case CROP: backward_layer((convolutionalLayer *)tLayer, tState); break; + case ROUTE: backward_layer((convolutionalLayer *)tLayer, tState); break; + case COST: backward_layer((convolutionalLayer *)tLayer, tState); break; + case NORMALIZATION: backward_layer((convolutionalLayer *)tLayer, tState); break; + case AVGPOOL: backward_layer((convolutionalLayer *)tLayer, tState); break; + case LOCAL: backward_layer((convolutionalLayer *)tLayer, tState); break; + case SHORTCUT: backward_layer((convolutionalLayer *)tLayer, tState); break; + case ACTIVE: backward_layer((convolutionalLayer *)tLayer, tState); break; + case RNN: backward_layer((convolutionalLayer *)tLayer, tState); break; + case GRU: backward_layer((convolutionalLayer *)tLayer, tState); break; + case LSTM: backward_layer((convolutionalLayer *)tLayer, tState); break; + case CRNN: backward_layer((convolutionalLayer *)tLayer, tState); break; + case BATCHNORM: backward_layer((convolutionalLayer *)tLayer, tState); break; + case NETWORK: backward_layer((convolutionalLayer *)tLayer, tState); break; + case XNOR: backward_layer((convolutionalLayer *)tLayer, tState); break; + case REGION: backward_layer((convolutionalLayer *)tLayer, tState); break; + case REORG: backward_layer((convolutionalLayer *)tLayer, tState); break; + case BLANK: backward_layer((convolutionalLayer *)tLayer, tState); break; + }; }; }; @@ -114,7 +140,8 @@ void gpuCUDA::updateNetwork(basicCortex *net){ cortexLayer *tLayer = net->getLayer(index); tLayer->m_nT=net->getCurrentBatch();// get_current_batch(net); //if ( tLayer->update_gpu != NULL ){ - tLayer->update_gpu( update_batch, rate, net->getMomentum(), net->getDecay() ); + //tLayer->update_gpu( update_batch, rate, net->getMomentum(), net->getDecay() ); + tLayer->update(update_batch, rate, net->getMomentum(), net->getDecay()); //}; }; }; @@ -126,7 +153,7 @@ void gpuCUDA::propogateForwardBackwardNetwork( basicCortex *net, float *x, float tState.workspace = net->getWorkspace(); size_t x_size = net->getInputSize() * net->getBatch(); size_t y_size = net->getOtputSize() * net->getBatch(); - if ( net->getLayer(net->getLayersCount() - 1)->getTruth() != NULL ) y_size = net->getLayer(net->getLayersCount() - 1)->getTruthSize()*net->getBatch(); + if ( net->getLayer(net->getLayersCount() - 1)->m_pTruth != NULL ) y_size = net->getLayer(net->getLayersCount() - 1)->m_nTruth * net->getBatch(); if ( net->getGpuInput() == NULL ){ // If GPU mem not binded net->setGpuInput(makeFloatArray(x_size, x)); @@ -167,9 +194,9 @@ void *gpuCUDA::train_thread(void *ptr){ return 0; }; -pthread_t gpuCUDA::trainNetworkMT(basicCortex *net, cortexDATA d, float *err){ - pthread_t thread; - memset(&thread, 0, sizeof(pthread_t)); +THREAD_HANDLE gpuCUDA::trainNetworkMT(basicCortex *net, cortexDATA d, float *err){ + THREAD_HANDLE thread; + memset(&thread, 0, sizeof(THREAD_HANDLE)); train_args *ptr = (train_args *)calloc(1, sizeof(train_args)); if (ptr != NULL){ ptr->mGPU = this; @@ -210,7 +237,7 @@ void gpuCUDA::updateLayer( cortexLayer *l, basicCortex *net ){ float rate = net->getCurrentRate(); l->m_nT = net->getCurrentBatch(); //if( l->update_gpu != NULL ){ - l->update_gpu( update_batch, rate, net->getMomentum(), net->getDecay() ); + l->update( update_batch, rate, net->getMomentum(), net->getDecay() ); //}; }; @@ -233,7 +260,7 @@ void gpuCUDA::mergeWeights( cortexLayer * l, cortexLayer * base ){ }; void gpuCUDA::scaleWeights(cortexLayer *l, float s){ - if (CONVOLUTIONAL == l->getType()) { + if (CONVOLUTIONAL == l->m_eType) { //scal_cpu(l->getBiasSize(), s, l->getBiases(), 1); calcScal( l->m_nBias, s, l->m_pBias, 1 ); //scal_cpu(l->getWeightSize(), s, l->getWeights(), 1);//l.n*l.size*l.size*l.c @@ -312,21 +339,20 @@ void gpuCUDA::distributeUpdates(cortexLayer *l, cortexLayer *base){ }; }; -void gpuCUDA::syncLayers(basicCortex **nets, int n, int j){ +void gpuCUDA::syncLayers(basicCortex **nets, uint32_t n, uint32_t j){ //printf("Syncing layer %d\n", j); - int i; basicCortex *net = nets[0]; cortexLayer *base = net->getLayer(j); setDevice(net->getGpuIndex()); pullWeights( base ); - for (i = 1; i < n; ++i) { + for (uint32_t i = 1; i < n; ++i) { setDevice(nets[i]->getGpuIndex()); cortexLayer *l = nets[i]->getLayer(j); pullWeights(l); mergeWeights(l, base); } scaleWeights(base, 1.f/n); - for (i = 0; i < n; ++i) { + for (uint32_t i = 0; i < n; ++i) { setDevice(nets[i]->getGpuIndex()); cortexLayer *l = nets[i]->getLayer(j); distributeWeights(l, base); @@ -348,9 +374,9 @@ void *gpuCUDA::syncLayer_thread(void *ptr){ return 0; } -pthread_t gpuCUDA::syncLayersMT(basicCortex **nets, int n, int j){ - pthread_t thread; - memset(&thread, 0, sizeof(pthread_t)); +THREAD_HANDLE gpuCUDA::syncLayersMT(basicCortex **nets, uint32_t n, uint32_t j){ + THREAD_HANDLE thread; + memset(&thread, 0, sizeof(THREAD_HANDLE)); sync_args *ptr = (sync_args *)malloc(sizeof(sync_args)); if (ptr != NULL){ ptr->mGPU = this; @@ -364,46 +390,41 @@ pthread_t gpuCUDA::syncLayersMT(basicCortex **nets, int n, int j){ return thread; }; -void gpuCUDA::syncNets(basicCortex **nets, int n, int interval){ - int j; - int layers = nets[0]->getLayersCount();// n; = LayerCounts - pthread_t *pThreads = (pthread_t *) calloc(layers, sizeof(pthread_t)); +void gpuCUDA::syncNets(basicCortex **nets, uint32_t n, uint32_t interval){ + uint32_t layers = nets[0]->getLayersCount(); + THREAD_HANDLE *pThreads = (THREAD_HANDLE *)calloc(layers, sizeof(THREAD_HANDLE)); nets[0]->setSeen(nets[0]->getSeen() + ( interval * (n - 1) * nets[0]->getBatch() * nets[0]->getSubdivisions()) ); - for (j = 0; j < n; ++j) nets[j]->setSeen( nets[0]->getSeen() ); - - for (j = 0; j < layers; ++j) pThreads[j] = syncLayersMT(nets, n, j); - - for (j = 0; j < layers; ++j) pthread_join(pThreads[j], 0); - + for (uint32_t j = 0; j < n; ++j) nets[j]->setSeen(nets[0]->getSeen()); + for (uint32_t j = 0; j < layers; ++j) pThreads[j] = syncLayersMT(nets, n, j); + for (uint32_t j = 0; j < layers; ++j) pthread_join(pThreads[j], 0); free(pThreads); }; -float gpuCUDA::trainNetworks(basicCortex **nets, int n, cortexDATA d, int interval){ - int i; +float gpuCUDA::trainNetworks(basicCortex **nets, uint32_t n, cortexDATA d, uint32_t interval){ int batch = nets[0]->getBatch(); int subdivisions = nets[0]->getSubdivisions(); assert(batch * subdivisions * n == d.X.rows); - pthread_t *pThreads = (pthread_t *) calloc(n, sizeof(pthread_t)); + THREAD_HANDLE *pThreads = (THREAD_HANDLE *)calloc(n, sizeof(THREAD_HANDLE)); float *errors = (float *) calloc(n, sizeof(float)); float sum = 0; - for(i = 0; i < n; ++i){ + for(uint32_t i = 0; i < n; ++i){ cortexDATA *p = get_data_part( &d, i, n); pThreads[i] = trainNetworkMT( nets[i], *p, errors + i ); }; - for(i = 0; i < n; ++i){ + for (uint32_t i = 0; i < n; ++i){ pthread_join(pThreads[i], 0); //printf("%f\n", errors[i]); sum += errors[i]; }; //cudaDeviceSynchronize(); if( nets[0]->getCurrentBatch() % interval == 0) { - printf("Syncing... "); - fflush(stdout); + //printf("Syncing... "); + //fflush(stdout); syncNets(nets, n, interval); - printf("Done!\n"); + //printf("Done!\n"); }; //cudaDeviceSynchronize(); free(pThreads); @@ -411,7 +432,7 @@ float gpuCUDA::trainNetworks(basicCortex **nets, int n, cortexDATA d, int interv return (float)sum/(n); } -float *gpuCUDA::getLayerOutput(basicCortex *net, int i){ +float *gpuCUDA::getLayerOutput(basicCortex *net, uint32_t i){ cortexLayer *l = net->getLayer(i); if( REGION != l->m_eType ) pullFloatArray( l->m_pGpuOutput, l->m_pOutput, l->m_nOutput * l->m_nBatch ); return l->m_pOutput; @@ -419,7 +440,7 @@ float *gpuCUDA::getLayerOutput(basicCortex *net, int i){ float *gpuCUDA::getNetworkOutput(basicCortex *net){ int i; - for (i = net->getLayersCount() - 1; i > 0; --i) if (COST != net->getLayer(i)->getType() ) break; // net.n == LayerCount + for (i = net->getLayersCount() - 1; i > 0; --i) if (COST != net->getLayer(i)->m_eType ) break; // net.n == LayerCount return getLayerOutput( net, i ); }; diff --git a/lib/data/cortex/layers/batchnormLayer.cpp b/lib/data/cortex/layers/batchnormLayer.cpp index ff3a7e3f..5aa87c27 100644 --- a/lib/data/cortex/layers/batchnormLayer.cpp +++ b/lib/data/cortex/layers/batchnormLayer.cpp @@ -4,54 +4,9 @@ #define LOG_ERROR( X ) m_pLog->Log( "BNormL", this, _LOG_ERROR, X ) batchnormLayer::batchnormLayer(bool useGPU) :cortexLayer(BATCHNORM, useGPU){ - m_nScale = 0; - m_pScale = NULL; - m_pScaleUpdate = NULL; - m_pMean = NULL; - m_pMeanDelta = NULL; - m_pVariance = NULL; - m_pVarianceDelta = NULL; - m_pRollingMean = NULL; - m_pRollingVariance = NULL; - m_pX = NULL; - m_pNormX = NULL; -#ifdef GPU - m_pGpuScale = NULL; - m_pGpuScaleUpdate = NULL; - m_pGpuMean = NULL; - m_pGpuVariance = NULL; - m_pGpuRollingMean = NULL; - m_pGpuRollingVariance = NULL; - m_pGpuMeanDelta = NULL; - m_pGpuVarianceDelta = NULL; - m_pGpuX = NULL; - m_pGpuNormX = NULL; -#endif }; batchnormLayer::~batchnormLayer(){ - FREE_HOST(m_pScale); - FREE_HOST(m_pScaleUpdate); - FREE_HOST(m_pMean); - FREE_HOST(m_pMeanDelta); - FREE_HOST(m_pVariance); - FREE_HOST(m_pVarianceDelta); - FREE_HOST(m_pRollingMean); - FREE_HOST(m_pRollingVariance); - FREE_HOST(m_pX); - FREE_HOST(m_pNormX); - if (m_pPU != NULL){ - FREE_PU(m_pGpuScale); - FREE_PU(m_pGpuScaleUpdate); - FREE_PU(m_pGpuMean); - FREE_PU(m_pGpuVariance); - FREE_PU(m_pGpuRollingMean); - FREE_PU(m_pGpuRollingVariance); - FREE_PU(m_pGpuMeanDelta); - FREE_PU(m_pGpuVarianceDelta); - FREE_PU(m_pGpuX); - FREE_PU(m_pGpuNormX); - }; }; bool batchnormLayer::create(uint32_t batch, uint32_t w, uint32_t h, uint32_t c){ @@ -314,8 +269,8 @@ bool batchnormLayer::create(uint32_t batch, uint32_t w, uint32_t h, uint32_t c){ m_pPU->freeMem(m_pGpuVarianceDelta); m_pGpuVarianceDelta = NULL; return false; }; - m_pGpuNormX = m_pPU->makeFloatArray(m_nOutputVol); - if (m_pGpuNormX == NULL){ + m_pGpuXNorm = m_pPU->makeFloatArray(m_nOutputVol); + if (m_pGpuXNorm == NULL){ free(m_pOutput); m_pOutput = NULL; free(m_pDelta); m_pDelta = NULL; free(m_pScale); m_pScale = NULL; @@ -361,7 +316,7 @@ void batchnormLayer::forward(cortexSTATE state){ m_pPU->calcAxpy(m_nOut_Channels, .01f, m_pGpuVariance, 1, m_pGpuRollingVariance, 1); m_pPU->makeCopy(m_nOutputVol, m_pGpuOutput, 1, m_pGpuX, 1); m_pPU->makeNormalized(m_pGpuOutput, m_pGpuMean, m_pGpuVariance, m_nBatch, m_nOut_Channels, Area); - m_pPU->makeCopy(m_nOutputVol, m_pGpuOutput, 1, m_pGpuNormX, 1); + m_pPU->makeCopy(m_nOutputVol, m_pGpuOutput, 1, m_pGpuXNorm, 1); } else { m_pPU->makeNormalized(m_pGpuOutput, m_pGpuRollingMean, m_pGpuRollingVariance, m_nBatch, m_nOut_Channels, Area); }; @@ -378,7 +333,7 @@ void batchnormLayer::forward(cortexSTATE state){ m_pPU->calcAxpy(m_nOut_Channels, .01f, m_pVariance, 1, m_pRollingVariance, 1); m_pPU->makeCopy(m_nOutputVol, m_pOutput, 1, m_pX, 1); m_pPU->makeNormalized(m_pOutput, m_pMean, m_pVariance, m_nBatch, m_nOut_Channels, Area); - m_pPU->makeCopy(m_nOutputVol, m_pOutput, 1, m_pNormX, 1); + m_pPU->makeCopy(m_nOutputVol, m_pOutput, 1, m_pXNorm, 1); } else { m_pPU->makeNormalized(m_pOutput, m_pRollingMean, m_pRollingVariance, m_nBatch, m_nOut_Channels, Area); }; @@ -392,7 +347,7 @@ void batchnormLayer::backward(cortexSTATE state){ uint32_t Area = m_nOut_Height*m_nOut_Width; #ifdef GPU if (m_bUseGPU){ - m_pPU->makeBackwardScale( m_pGpuNormX, m_pGpuDelta, m_nBatch, m_nOut_Channels, Area, m_pGpuScaleUpdate); + m_pPU->makeBackwardScale( m_pGpuXNorm, m_pGpuDelta, m_nBatch, m_nOut_Channels, Area, m_pGpuScaleUpdate); m_pPU->calcScaleBias( m_pGpuDelta, m_pGpuScale, m_nBatch, m_nOut_Channels, Area); m_pPU->makeMeanDelta( m_pGpuDelta, m_pGpuVariance, m_nBatch, m_nOut_Channels, Area, m_pGpuMeanDelta); m_pPU->makeVarianceDelta( m_pGpuX, m_pGpuDelta, m_pGpuMean, m_pGpuVariance, m_nBatch, m_nOut_Channels, Area, m_pGpuVarianceDelta); @@ -400,7 +355,7 @@ void batchnormLayer::backward(cortexSTATE state){ m_pPU->makeCopy( m_nOutputVol, m_pGpuDelta, 1, state.delta, 1); } else { #endif - m_pPU->makeBackwardScale( m_pNormX, m_pDelta, m_nBatch, m_nOut_Channels, Area, m_pScaleUpdate); + m_pPU->makeBackwardScale( m_pXNorm, m_pDelta, m_nBatch, m_nOut_Channels, Area, m_pScaleUpdate); m_pPU->calcScaleBias( m_pDelta, m_pScale, m_nBatch, m_nOut_Channels, Area); m_pPU->makeMeanDelta( m_pDelta, m_pVariance, m_nBatch, m_nOut_Channels, Area, m_pMeanDelta); m_pPU->makeVarianceDelta( m_pX, m_pDelta, m_pMean, m_pVariance, m_nBatch, m_nOut_Channels, Area, m_pVarianceDelta); @@ -411,6 +366,13 @@ void batchnormLayer::backward(cortexSTATE state){ #endif }; +void batchnormLayer::loadWeights(FILE *fp, bool transpose){ + fread(m_pScale, sizeof(float), m_nScale, fp); + fread(m_pRollingMean, sizeof(float), m_nOutput, fp); + fread(m_pRollingVariance, sizeof(float), m_nOutput, fp); + push(); +}; + // Pushes HOST Memory to GPU memory void batchnormLayer::push(void){ #ifdef GPU diff --git a/lib/data/cortex/layers/batchnormLayer.h b/lib/data/cortex/layers/batchnormLayer.h index 80b5e598..b35d08c0 100644 --- a/lib/data/cortex/layers/batchnormLayer.h +++ b/lib/data/cortex/layers/batchnormLayer.h @@ -10,27 +10,27 @@ class cpuHOST; class batchnormLayer : public cortexLayer{ private: - uint32_t m_nScale; - float * m_pScale; - float * m_pScaleUpdate; - float * m_pMean; - float * m_pMeanDelta; - float * m_pVariance; - float * m_pVarianceDelta; - float * m_pRollingMean; - float * m_pRollingVariance; - float * m_pGpuScale; - float * m_pGpuScaleUpdate; - float * m_pGpuMean; - float * m_pGpuVariance; - float * m_pGpuRollingMean; - float * m_pGpuRollingVariance; - float * m_pGpuMeanDelta; - float * m_pGpuVarianceDelta; - float * m_pX; - float * m_pNormX; - float * m_pGpuX; - float * m_pGpuNormX; + //uint32_t m_nScale; + //float * m_pScale; + //float * m_pScaleUpdate; + //float * m_pMean; + //float * m_pMeanDelta; + //float * m_pVariance; + //float * m_pVarianceDelta; + //float * m_pRollingMean; + //float * m_pRollingVariance; + //float * m_pGpuScale; + //float * m_pGpuScaleUpdate; + //float * m_pGpuMean; + //float * m_pGpuVariance; + //float * m_pGpuRollingMean; + //float * m_pGpuRollingVariance; + //float * m_pGpuMeanDelta; + //float * m_pGpuVarianceDelta; + //float * m_pX; + //float * m_pNormX; + //float * m_pGpuX; + //float * m_pGpuNormX; public: explicit batchnormLayer(bool useGPU); virtual ~batchnormLayer(); @@ -38,6 +38,7 @@ class batchnormLayer : public cortexLayer{ /* Virtual Methods */ virtual void forward(cortexSTATE state); virtual void backward(cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); //virtual void update(int batch, float learning_rate, float momentum, float decay); virtual bool resize(uint32_t w, uint32_t h); virtual void push(void); diff --git a/lib/data/cortex/layers/connectedLayer.cpp b/lib/data/cortex/layers/connectedLayer.cpp index ad0319a6..9fb3fb80 100644 --- a/lib/data/cortex/layers/connectedLayer.cpp +++ b/lib/data/cortex/layers/connectedLayer.cpp @@ -240,6 +240,25 @@ void connectedLayer::backward(cortexSTATE state){ #endif }; +void connectedLayer::loadWeights(FILE *fp, bool transpose){ + fread(m_pBias, sizeof(float), m_nBias, fp); + fread(m_pWeight, sizeof(float), m_nWeight, fp); + if (transpose){ + m_pPU->transposeMatrix(m_pWeight, m_nInput, m_nOutput); + }; + //printf("Biases: %f mean %f variance\n", mean_array(l.biases, l.outputs), variance_array(l.biases, l.outputs)); + //printf("Weights: %f mean %f variance\n", mean_array(l.weights, l.outputs*l.inputs), variance_array(l.weights, l.outputs*l.inputs)); + if (m_bBatchNormalize && (!m_bDontLoadScales)){ + fread(m_pScale, sizeof(float), m_nScale, fp); + fread(m_pRollingMean, sizeof(float), m_nOutput, fp); + fread(m_pRollingVariance, sizeof(float), m_nOutput, fp); + //printf("Scales: %f mean %f variance\n", mean_array(l.scales, l.outputs), variance_array(l.scales, l.outputs)); + //printf("rolling_mean: %f mean %f variance\n", mean_array(l.rolling_mean, l.outputs), variance_array(l.rolling_mean, l.outputs)); + //printf("rolling_variance: %f mean %f variance\n", mean_array(l.rolling_variance, l.outputs), variance_array(l.rolling_variance, l.outputs)); + }; + push(); +}; + void connectedLayer::update(int batch, float learning_rate, float momentum, float decay){ #ifdef GPU if (m_bUseGPU){ diff --git a/lib/data/cortex/layers/connectedLayer.h b/lib/data/cortex/layers/connectedLayer.h index 3097a465..547e0021 100644 --- a/lib/data/cortex/layers/connectedLayer.h +++ b/lib/data/cortex/layers/connectedLayer.h @@ -17,6 +17,7 @@ class connectedLayer: public cortexLayer{ virtual void forward(cortexSTATE state); virtual void backward(cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); virtual void update( int batch, float learning_rate, float momentum, float decay); virtual void pull(void); virtual void push(void); diff --git a/lib/data/cortex/layers/convolutionalLayer.cpp b/lib/data/cortex/layers/convolutionalLayer.cpp index d15cf5aa..1279f288 100644 --- a/lib/data/cortex/layers/convolutionalLayer.cpp +++ b/lib/data/cortex/layers/convolutionalLayer.cpp @@ -166,7 +166,8 @@ bool convolutionalLayer::create(uint32_t batch, uint32_t h, uint32_t w, uint32_t if ( m_pBinaryWeight == NULL )return false; m_pCharWeight = (char*)calloc(m_nWeight, sizeof(char)); if ( m_pCharWeight == NULL ) return false; - m_pScale = (float*)calloc(m_nOut_Channels, sizeof(float)); + m_nScale = m_nOut_Channels; + m_pScale = (float*)calloc(m_nScale, sizeof(float)); if ( m_pScale == NULL ) return false; m_pGpuBinaryWeight = m_pPU->makeFloatArray(m_nWeight, m_pWeight); if (m_pGpuBinaryWeight == NULL) return false; @@ -191,21 +192,22 @@ bool convolutionalLayer::create(uint32_t batch, uint32_t h, uint32_t w, uint32_t }; if (m_bBatchNormalize){ if (!m_pScale){ - m_pScale = (float*)calloc(m_nOut_Channels, sizeof(float)); + m_nScale = m_nOut_Channels; + m_pScale = (float*)calloc(m_nScale, sizeof(float)); if (!m_pScale)return false; }; - m_pScaleUpdate = (float*)calloc(m_nOut_Channels, sizeof(float)); + m_pScaleUpdate = (float*)calloc(m_nScale, sizeof(float)); if (!m_pScaleUpdate)return false; - for (i = 0; i < m_nOut_Channels; ++i) m_pScale[i] = 1.f; + for (i = 0; i < m_nScale; ++i) m_pScale[i] = 1.f; + + m_pMean = (float*)calloc(m_nScale, sizeof(float)); + m_pVariance = (float*)calloc(m_nScale, sizeof(float)); - m_pMean = (float*)calloc(m_nOut_Channels, sizeof(float)); - m_pVariance = (float*)calloc(m_nOut_Channels, sizeof(float)); + m_pMeanDelta = (float*)calloc(m_nScale, sizeof(float)); + m_pVarianceDelta = (float*)calloc(m_nScale, sizeof(float)); - m_pMeanDelta = (float*)calloc(m_nOut_Channels, sizeof(float)); - m_pVarianceDelta = (float*)calloc(m_nOut_Channels, sizeof(float)); - - m_pRollingMean = (float*)calloc(m_nOut_Channels, sizeof(float)); - m_pRollingVariance = (float*)calloc(m_nOut_Channels, sizeof(float)); + m_pRollingMean = (float*)calloc(m_nScale, sizeof(float)); + m_pRollingVariance = (float*)calloc(m_nScale, sizeof(float)); m_pX = (float*)calloc(m_nOutputVol, sizeof(float)); m_pXNorm = (float*)calloc(m_nOutputVol, sizeof(float)); #ifdef GPU @@ -381,6 +383,71 @@ void convolutionalLayer::backward( cortexSTATE state ){ m_pPU->backward_layer( this, state ); }; +void convolutionalLayer::loadWeights(FILE *fp, bool trans){ + if (m_bBinary){ + fread(m_pBias, sizeof(float), m_nN, fp); + if (m_bBatchNormalize && (!m_bDontLoadScales)){ + fread(m_pScale, sizeof(float), m_nN, fp); + fread(m_pRollingMean, sizeof(float), m_nN, fp); + fread(m_pRollingVariance, sizeof(float), m_nN, fp); + }; + int size = m_nIn_Channels*m_nSize*m_nSize;// l.c*l.size*l.size; + int i, j, k; + for (i = 0; i < m_nN; ++i){ + float mean = 0; + fread(&mean, sizeof(float), 1, fp); + for (j = 0; j < (size >> 3); ++j){ + int index = i*size + (j << 3); + unsigned char c = 0; + fread(&c, sizeof(char), 1, fp); + for (k = 0; k < 8; ++k){ + if (j * 8 + k >= size) break; + m_pWeight[index + k] = (c & 1 << k) ? mean : -mean; + }; + }; + }; +#ifdef GPU + m_pPU->push_layer(this); +#endif + } else { + int num = m_nN*m_nIn_Channels*m_nSize*m_nSize;//l.n*l.c*l.size*l.size; + fread(m_pBias, sizeof(float), m_nN, fp); + if (m_bBatchNormalize && (!m_bDontLoadScales)){ + fread(m_pScale, sizeof(float), m_nN, fp); + fread(m_pRollingMean, sizeof(float), m_nN, fp); + fread(m_pRollingVariance, sizeof(float), m_nN, fp); + if (0){ + int i; + for (i = 0; i < m_nN; ++i){ + printf("%g, ", m_pRollingMean[i]); + }; + printf("\n"); + for (i = 0; i < m_nN; ++i){ + printf("%g, ", m_pRollingVariance[i]); + }; + printf("\n"); + }; + if (0){ + m_pPU->makeFill(m_nN, 0, m_pRollingMean, 1); + m_pPU->makeFill(m_nN, 0, m_pRollingVariance, 1); + }; + }; + fread(m_pWeight, sizeof(float), num, fp); + if (m_bAdam){ + fread(m_pHostM, sizeof(float), num, fp); + fread(m_pHostV, sizeof(float), num, fp); + }; + //if(l.c == 3) scal_cpu(num, 1./256, l.weights, 1); + if (m_bFlipped) { + m_pPU->transposeMatrix(m_pWeight, m_nIn_Channels*m_nSize*m_nSize, m_nN); + }; + //if (l.binary) binarize_weights(l.weights, l.n, l.c*l.size*l.size, l.weights); +#ifdef GPU + m_pPU->push_layer(this); +#endif + }; +}; + void convolutionalLayer::update(uint32_t batch, float learning_rate, float momentum, float decay){ //uint32_t size = m_nSize * m_nSize * m_nIn_Channels * m_nOut_Channels; m_pPU->calcAxpy(m_nBias, learning_rate / batch, m_pBiasUpdate, 1, m_pBias, 1); diff --git a/lib/data/cortex/layers/convolutionalLayer.h b/lib/data/cortex/layers/convolutionalLayer.h index 2225d9a1..59a5ce91 100644 --- a/lib/data/cortex/layers/convolutionalLayer.h +++ b/lib/data/cortex/layers/convolutionalLayer.h @@ -30,6 +30,7 @@ class convolutionalLayer: public cortexLayer{ virtual void test(void); virtual void forward( cortexSTATE state); virtual void backward( cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); virtual void update( uint32_t batch, float learning_rate, float momentum, float decay); virtual bool resize( uint32_t w, uint32_t h); diff --git a/lib/data/cortex/layers/crnnLayer.cpp b/lib/data/cortex/layers/crnnLayer.cpp index 979b91a4..269a0c7c 100644 --- a/lib/data/cortex/layers/crnnLayer.cpp +++ b/lib/data/cortex/layers/crnnLayer.cpp @@ -80,6 +80,12 @@ void crnnLayer::backward(cortexSTATE state){ m_pPU->backward_layer(this, state); }; +void crnnLayer::loadWeights(FILE *fp, bool trans){ + m_pInputLayer->loadWeights(fp, trans); + m_pSelfLayer->loadWeights(fp, trans); + m_pOutputLayer->loadWeights(fp, trans); +}; + void crnnLayer::update(uint32_t batch, float learning_rate, float momentum, float decay){ m_pPU->update_layer(this, batch, learning_rate, momentum, decay); }; diff --git a/lib/data/cortex/layers/crnnLayer.h b/lib/data/cortex/layers/crnnLayer.h index dec0097f..baaa5118 100644 --- a/lib/data/cortex/layers/crnnLayer.h +++ b/lib/data/cortex/layers/crnnLayer.h @@ -21,6 +21,7 @@ public: bool create( uint32_t batch, uint32_t h, uint32_t w, uint32_t c, uint32_t hidden_filters, uint32_t output_filters, uint32_t steps, ACTIVATION activation, bool batch_normalize); virtual void forward( cortexSTATE state); virtual void backward( cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); virtual void update( uint32_t batch, float learning_rate, float momentum, float decay); friend class gpuCUDA; diff --git a/lib/data/cortex/layers/detectionLayer.cpp b/lib/data/cortex/layers/detectionLayer.cpp index fd698535..1311fb97 100644 --- a/lib/data/cortex/layers/detectionLayer.cpp +++ b/lib/data/cortex/layers/detectionLayer.cpp @@ -266,7 +266,14 @@ void detectionLayer::getDetectionBoxes(uint32_t w, uint32_t h, float thresh, flo }; }; +uint32_t detectionLayer::getBoxesCount(void){ + if (m_nIn_Height == m_nIn_Width) m_nSide = m_nIn_Height; + return (m_nIn_Width*m_nIn_Height*m_nN); +}; +uint32_t detectionLayer::getClassesCount(void){ + return m_nClasses; +}; #undef LOG diff --git a/lib/data/cortex/layers/detectionLayer.h b/lib/data/cortex/layers/detectionLayer.h index f17450dc..75804fa6 100644 --- a/lib/data/cortex/layers/detectionLayer.h +++ b/lib/data/cortex/layers/detectionLayer.h @@ -29,7 +29,8 @@ class detectionLayer: public cortexLayer{ //virtual void update(int batch, float learning_rate, float momentum, float decay); //virtual void resize(uint32_t w, uint32_t h); void getDetectionBoxes(uint32_t w, uint32_t h, float thresh, float **probs, cortexBOXLABEL *boxes, bool only_objectness); - + uint32_t getBoxesCount(void); + uint32_t getClassesCount(void); friend class gpuCUDA; friend class cpuHOST; friend class cortexLayersFactory; diff --git a/lib/data/cortex/layers/gruLayer.cpp b/lib/data/cortex/layers/gruLayer.cpp index 92a37284..318964b3 100644 --- a/lib/data/cortex/layers/gruLayer.cpp +++ b/lib/data/cortex/layers/gruLayer.cpp @@ -422,12 +422,11 @@ void gruLayer::backward(cortexSTATE state){ #endif }; -#ifdef GPU - -void pull_layer(gruLayer *l){ -}; - -void push_layer(gruLayer *l){ +void gruLayer::loadWeights(FILE *fp, bool trans){ + inputZLayer->loadWeights(fp, trans); + inputRLayer->loadWeights(fp, trans); + inputHLayer->loadWeights(fp, trans); + stateZLayer->loadWeights(fp, trans); + stateRLayer->loadWeights(fp, trans); + stateHLayer->loadWeights(fp, trans); }; - -#endif diff --git a/lib/data/cortex/layers/gruLayer.h b/lib/data/cortex/layers/gruLayer.h index 79c64198..6d7e9c68 100644 --- a/lib/data/cortex/layers/gruLayer.h +++ b/lib/data/cortex/layers/gruLayer.h @@ -40,6 +40,7 @@ class gruLayer : public cortexLayer{ bool create( uint32_t batch, uint32_t inputs, uint32_t outputs, uint32_t steps, bool batch_normalize); virtual void forward( cortexSTATE state); virtual void backward( cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); virtual void update( uint32_t batch, float learning_rate, float momentum, float decay); friend class gpuCUDA; diff --git a/lib/data/cortex/layers/layersFactory.cpp b/lib/data/cortex/layers/layersFactory.cpp index f113f2c4..c38c5cb3 100644 --- a/lib/data/cortex/layers/layersFactory.cpp +++ b/lib/data/cortex/layers/layersFactory.cpp @@ -45,6 +45,7 @@ cortexLayersFactory* cortexLayersFactory::getInstance() { cortexLayersFactory::cortexLayersFactory(){ m_bUseGPU = true; m_bPushPullModel = false; + m_bLoadingStatus = 0; m_pLog = basicLogCollection::getInstance(); m_pGPU = gpuCUDA::getInstance(); m_pCPU = cpuHOST::getInstance(); @@ -711,7 +712,11 @@ bool cortexLayersFactory::parse_net_options(cortexRList *opt, basicCortex *net){ }; basicCortex *cortexLayersFactory::parseConfigCustom(CSTR filename, uint32_t batch){ - cortexRList *sections = readDataÑfg(filename); + m_bLoadingStatus = 0; + m_bLoadedSection = 0; + m_bTottalSection = 0; + cortexRList *sections = readDataÑfg(filename, &m_bTottalSection ); + m_bTottalSection = sections->size; if (sections == NULL) return NULL; listNode *n = sections->front; if (n == NULL){ @@ -759,8 +764,9 @@ basicCortex *cortexLayersFactory::parseConfigCustom(CSTR filename, uint32_t batc n = n->next; int count = 0; freeSection(s); - LOG("\t\tfilters\tsize\tinput\toutput"); + LOG("\tfilters\tsize\t\tinput\t\t\toutput"); while (n){ + m_bLoadedSection++; params.index = count; s = (paramSection *)n->val; opt = s->opts; @@ -960,6 +966,8 @@ basicCortex *cortexLayersFactory::parseConfigCustom(CSTR filename, uint32_t batc }; }; freeList(sections); + m_bLoadingStatus = 100; + m_bLoadedSection = m_bTottalSection; RetVal->m_nOutput = RetVal->getOutputSize();// get_network_output_size(net); RetVal->m_pOutput = RetVal->getOutput();// get_network_output(net); if (workspace_size){ @@ -979,10 +987,24 @@ basicCortex *cortexLayersFactory::parseConfigCustom(CSTR filename, uint32_t batc RetVal->m_pWorkspace = (float *)calloc(1, workspace_size); #endif }; + m_bLoadingStatus = 255; return RetVal; }; - +uint8_t cortexLayersFactory::getStatus(CSTR msg){ + if (msg != NULL){ + if (m_bTottalSection == 0) return 0; + if (m_bLoadingStatus < 100 ){ + m_bLoadingStatus = (m_bLoadedSection * 100) / m_bTottalSection; + sprintf(msg, "Loadimg %d of %d", m_bLoadedSection, m_bTottalSection); + } else if (m_bLoadingStatus == 100){ + sprintf(msg, "Allocating Memory"); + } else if (m_bLoadingStatus > 120 ){ + sprintf(msg, "Loading Done"); + }; + }; + return m_bLoadingStatus; +}; #undef LOG #undef LOG_ERROR diff --git a/lib/data/cortex/layers/layersFactory.h b/lib/data/cortex/layers/layersFactory.h index e7a13649..b1f7fd94 100644 --- a/lib/data/cortex/layers/layersFactory.h +++ b/lib/data/cortex/layers/layersFactory.h @@ -5,6 +5,7 @@ #include "../base/basicCortex.h" #include "../base/basicLayer.h" #include "../base/basicProcessingUnit.h" +#include "../../../components/base/basicStatusProvider.h" /* Data Structures */ @@ -23,11 +24,14 @@ typedef std::vector vectorCortexLayers; /* Singletone Oject */ -class cortexLayersFactory{ +class cortexLayersFactory : public basicStatusProvider{ private: vectorCortexLayers m_vLayers; bool m_bUseGPU; bool m_bPushPullModel; + uint8_t m_bLoadingStatus; + uint8_t m_bLoadedSection; + uint8_t m_bTottalSection; basicLogCollection * m_pLog; cortexProcessingUnit * m_pGPU; cortexProcessingUnit * m_pCPU; @@ -63,6 +67,7 @@ class cortexLayersFactory{ basicCortex * parseConfigCustom(CSTR filename, uint32_t batch); void setPushPullMode(bool aa); void setGpuUsageMode(bool aa); + virtual uint8_t getStatus(CSTR msg = NULL); protected: // Constructor - protected so users cannot call it. cortexLayersFactory(); diff --git a/lib/data/cortex/layers/localLayer.cpp b/lib/data/cortex/layers/localLayer.cpp index f0ea5a24..0288196e 100644 --- a/lib/data/cortex/layers/localLayer.cpp +++ b/lib/data/cortex/layers/localLayer.cpp @@ -82,6 +82,18 @@ void localLayer::backward(cortexSTATE state){ m_pPU->backward_layer(this, state); }; +void localLayer::loadWeights(FILE *fp, bool trans){ + //int locations = m_nOut_Width*m_nOut_Height; + //int size = m_nSize*m_nSize*m_nIn_Channels*m_nN*locations; + //fread(m_pBias, sizeof(float), m_nOutput, fp); + //fread(m_pWeight, sizeof(float), size, fp); + fread(m_pBias, sizeof(float), m_nBias, fp); + fread(m_pWeight, sizeof(float), m_nWeight, fp); +#ifdef GPU + m_pPU->push_layer(this); +#endif +}; + void localLayer::update(uint32_t batch, float learning_rate, float momentum, float decay){ m_pPU->update_layer(this, batch, learning_rate, momentum, decay); }; diff --git a/lib/data/cortex/layers/localLayer.h b/lib/data/cortex/layers/localLayer.h index ba0d954b..3f2d8312 100644 --- a/lib/data/cortex/layers/localLayer.h +++ b/lib/data/cortex/layers/localLayer.h @@ -22,6 +22,7 @@ class localLayer : public cortexLayer{ /* Virtual Methods */ virtual void forward( cortexSTATE state); virtual void backward( cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); virtual void update( uint32_t batch, float learning_rate, float momentum, float decay); //virtual bool resize( uint32_t w, uint32_t h); diff --git a/lib/data/cortex/layers/maxpoolLayer.cpp b/lib/data/cortex/layers/maxpoolLayer.cpp index d957f0ca..117c7ca9 100644 --- a/lib/data/cortex/layers/maxpoolLayer.cpp +++ b/lib/data/cortex/layers/maxpoolLayer.cpp @@ -30,7 +30,7 @@ bool maxpoolLayer::create(uint32_t batch, uint32_t h, uint32_t w, uint32_t c, ui m_pGpuDelta = m_pPU->makeFloatArray(m_nOutputVol); #endif char tBuff[256]; - sprintf(tBuff, "\t\t\t%dx%d/%d\t%4dx%4dx%4d -> %4dx%4dx%4d", size, size, stride, w, h, c, m_nOut_Width, m_nOut_Height, m_nOut_Channels); + sprintf(tBuff, "\t\t%2dx%2d\t%2d\t%4dx%4dx%4d -> %4dx%4dx%4d", size, size, stride, w, h, c, m_nOut_Width, m_nOut_Height, m_nOut_Channels); LOG(tBuff); return true; }; @@ -76,5 +76,6 @@ cortexImage *maxpoolLayer::getDeltaImage(void){ }; + #undef LOG #undef LOG_ERROR diff --git a/lib/data/cortex/layers/regionLayer.cpp b/lib/data/cortex/layers/regionLayer.cpp index 7d8bb4c1..5358724e 100644 --- a/lib/data/cortex/layers/regionLayer.cpp +++ b/lib/data/cortex/layers/regionLayer.cpp @@ -375,6 +375,15 @@ void regionLayer::get_region_boxes(uint32_t w, uint32_t h, float thresh, float * }; }; +uint32_t regionLayer::getBoxesCount(void){ + if (m_nIn_Height == m_nIn_Width) m_nSide = m_nIn_Height; + return (m_nIn_Width*m_nIn_Height*m_nN); +}; + +uint32_t regionLayer::getClassesCount(void){ + return m_nClasses; +}; + #undef LOG #undef LOG_ERROR diff --git a/lib/data/cortex/layers/regionLayer.h b/lib/data/cortex/layers/regionLayer.h index 9a75265b..a5706c41 100644 --- a/lib/data/cortex/layers/regionLayer.h +++ b/lib/data/cortex/layers/regionLayer.h @@ -15,6 +15,8 @@ class regionLayer: public cortexLayer{ virtual void backward(cortexSTATE state); virtual bool resize(uint32_t w, uint32_t h); void get_region_boxes(uint32_t w, uint32_t h, float thresh, float **probs, cortexBOXLABEL *boxes, bool only_objectness, uint32_t *map); + uint32_t getBoxesCount(void); + uint32_t getClassesCount(void); friend class gpuCUDA; friend class cpuHOST; diff --git a/lib/data/cortex/layers/rnnLayer.cpp b/lib/data/cortex/layers/rnnLayer.cpp index 317e8901..c393dab0 100644 --- a/lib/data/cortex/layers/rnnLayer.cpp +++ b/lib/data/cortex/layers/rnnLayer.cpp @@ -153,6 +153,12 @@ void rnnLayer::backward(cortexSTATE state){ }; }; +void rnnLayer::loadWeights(FILE *fp, bool trans){ + inputLayer->loadWeights(fp, trans); + selfLayer->loadWeights(fp, trans); + outputLayer->loadWeights(fp, trans); +}; + #ifdef GPU #include "../cuda/cuda.h" diff --git a/lib/data/cortex/layers/rnnLayer.h b/lib/data/cortex/layers/rnnLayer.h index 755abe1b..1b749a52 100644 --- a/lib/data/cortex/layers/rnnLayer.h +++ b/lib/data/cortex/layers/rnnLayer.h @@ -25,6 +25,7 @@ class rnnLayer : public cortexLayer{ bool create( uint32_t batch, uint32_t inputs, uint32_t hidden, uint32_t outputs, uint32_t steps, ACTIVATION activation, bool batch_normalize, int logic); virtual void forward( cortexSTATE state); virtual void backward( cortexSTATE state); + virtual void loadWeights(FILE * Ptr, bool trans = false); virtual void update( uint32_t batch, float learning_rate, float momentum, float decay); friend class gpuCUDA; diff --git a/lib/sdl/core/coreLabel.cpp b/lib/sdl/core/coreLabel.cpp new file mode 100644 index 00000000..cc0a1cd9 --- /dev/null +++ b/lib/sdl/core/coreLabel.cpp @@ -0,0 +1,105 @@ +#include "coreLabel.h" +sdlLabel::sdlLabel(int x, int y, int w, int h, sdlCoreWidget *wPtr, int fsize, CSTR fontName) :sdlCoreWidget(x,y,w,h,wPtr){ + m_sColorStyle = DEFAULT_COLOR_STYLE; + m_pFontTexture = NULL; + m_pFont = NULL; + m_sRect.x = x; + m_sRect.y = y; + m_sRect.w = w; + m_sRect.h = h; + setDecoraion(false); + m_bTextAlign = ALIGN_CENTER; + memset( m_pText, 0, SDL_DEFAULT_TEXT_SIZE ); + if (fontName != NULL){ + m_pFont = TTF_OpenFont(fontName, fsize); + } else { + m_pFont = TTF_OpenFont("C:\\FruchtSystems\\cortex_test\\cortex_test\\Fonts\\Ubuntu-L.ttf", fsize); + }; + m_bRedraw = true; +}; + +sdlLabel::~sdlLabel(){ + if (m_pFont != NULL){ + TTF_CloseFont(m_pFont); + m_pFont = NULL; + }; + if (m_pFontTexture != NULL){ + SDL_DestroyTexture(m_pFontTexture); + m_pFontTexture = NULL; + }; +}; + +void sdlLabel::draw(SDL_Renderer *pRenderer){ + if (m_bRedraw){ + if (m_pFont == NULL) return; + SDL_Surface *pSurface; + pSurface = TTF_RenderText_Solid(m_pFont, m_pText, m_sColor); + if (pSurface != NULL){ + m_nLabelWidth = pSurface->w; + m_nLabelHeight = pSurface->h; + m_pFontTexture = SDL_CreateTextureFromSurface(pRenderer, pSurface); + if (m_pFontTexture != NULL) m_bRedraw = false; + }; + }; + if( m_pFontTexture != NULL ){ + SDL_Rect tRect; + switch (m_bTextAlign){ + case ALIGN_LEFT: tRect.x = 0; break; + case ALIGN_CENTER: tRect.x = (m_sRect.w - m_nLabelWidth) / 2; break; + case ALIGN_RIGHT: tRect.x = m_sRect.w - m_nLabelWidth; break; + }; + tRect.y = m_sRect.y + (m_sRect.h - m_nLabelHeight) / 2; + //tRect.y = (m_sRect.h - m_pSurface->h) / 2; + tRect.w = m_nLabelWidth; + tRect.h = m_nLabelHeight; + //SDL_RenderCopyEx(pRenderer, m_pTexture, clip, &m_sRect, angle, center, flip); + SDL_RenderCopyEx(pRenderer, m_pFontTexture, NULL, &tRect, 0, 0, SDL_FLIP_NONE); + }; +}; + +void sdlLabel::setText(CSTR pStr){ + if (pStr != NULL){ + sprintf(m_pText, "%s", pStr); + } else { + memset(m_pText, 0, SDL_DEFAULT_TEXT_SIZE ); + }; + m_bRedraw = true; +}; + +void sdlLabel::setFont(TTF_Font *tPtr){ + if (m_pFont != NULL){ + TTF_CloseFont(m_pFont); + m_pFont = NULL; + }; + m_pFont = tPtr; + m_bRedraw = true; +}; + +void sdlLabel::setColor(SDL_Color *tC){ + if (tC == NULL){ + m_sColor = m_sColorStyle.font; + } else { + memcpy(&m_sColor, tC, sizeof(SDL_Color)); + }; + m_bRedraw = true; +}; +void sdlLabel::setColor(Uint8 red, Uint8 green, Uint8 blue){ + //Modulate texture rgb + if (m_pFontTexture != NULL){ + SDL_SetTextureColorMod(m_pFontTexture, red, green, blue); + }; +}; + +void sdlLabel::setBlendMode(SDL_BlendMode blending){ + //Set blending function + if (m_pFontTexture != NULL){ + SDL_SetTextureBlendMode(m_pFontTexture, blending); + }; +}; + +void sdlLabel::setAlpha(Uint8 alpha){ + //Modulate texture alpha + if (m_pFontTexture != NULL){ + SDL_SetTextureAlphaMod(m_pFontTexture, alpha); + }; +}; diff --git a/lib/sdl/core/coreLabel.h b/lib/sdl/core/coreLabel.h new file mode 100644 index 00000000..0697bd28 --- /dev/null +++ b/lib/sdl/core/coreLabel.h @@ -0,0 +1,43 @@ +#ifndef __SDL_CORE_LABEL_HEADERS__ +#define __SDL_CORE_LABEL_HEADERS__ + +#include "../../components/base/basicMutex.h" +#include "../gui_sdl.h" +#include "coreWidget.h" + +#define SDL_DEFAULT_TEXT_SIZE 1024 +#define SDL_DEFAULT_FONT_SIZE 12 +typedef enum E_TEXT_ALIGN{ + ALIGN_LEFT = 0, + ALIGN_CENTER = 1, + ALIGN_RIGHT +} TEXT_ALIGN; + +class sdlLabel :public sdlCoreWidget{ + private: + char m_pText[SDL_DEFAULT_TEXT_SIZE]; + TTF_Font * m_pFont; + SDL_Texture * m_pFontTexture; + SDL_Color m_sColor; + SDL_Rect m_sRect; + int m_nLabelWidth; + int m_nLabelHeight; + sdlColorStyle m_sColorStyle; + TEXT_ALIGN m_bTextAlign; + protected: + virtual void draw(SDL_Renderer *pRenderer); + public: + explicit sdlLabel(int x, int y, int w, int h, sdlCoreWidget *wPtr=NULL, int fsize = SDL_DEFAULT_FONT_SIZE, CSTR fontName = NULL); + virtual ~sdlLabel(); + void setText( CSTR pStr ); + void setFont( TTF_Font *tPtr ); + void setColor( SDL_Color *tC ); + void setColor( Uint8 red, Uint8 green, Uint8 blue ); + void setBlendMode(SDL_BlendMode blending ); + void setAlpha( Uint8 alpha ); + void setAlign(TEXT_ALIGN tA){ m_bTextAlign = tA; }; + CSTR getText(void){ return m_pText; }; +}; + + +#endif \ No newline at end of file diff --git a/lib/sdl/core/coreStyleTemplate.h b/lib/sdl/core/coreStyleTemplate.h new file mode 100644 index 00000000..635534a7 --- /dev/null +++ b/lib/sdl/core/coreStyleTemplate.h @@ -0,0 +1,32 @@ +#ifndef __SDL_CORE_STYLE_TEMPLATE_HEADER__ +#define __SDL_CORE_STYLE_TEMPLATE_HEADER__ +#include + +typedef struct S_sdlColorStyle{ + SDL_Color panelBG; + SDL_Color borderTOP; + SDL_Color borderBOTTOM; + SDL_Color borderLEFT; + SDL_Color borderRIGHT; + SDL_Color borderBODY; + SDL_Color body; + SDL_Color font; + SDL_Color disabledFont; + SDL_Color activeSelector; + SDL_Color passiveSelector; +} sdlColorStyle; + +#define DEFAULT_COLOR_STYLE { \ + {0x20, 0x20, 0x20, 0xFF}, \ + {0xF0, 0xF0, 0xF0, 0xFF}, \ + {0xF0, 0xF0, 0xF0, 0xFF}, \ + {0xF0, 0xF0, 0xF0, 0xFF}, \ + {0xF0, 0xF0, 0xF0, 0xFF}, \ + {0xF0, 0xF0, 0xF0, 0xFF}, \ + {0x70, 0x70, 0x70, 0xFF}, \ + {0x0, 0x0, 0x0, 0xFF}, \ + {0x10, 0x10, 0x10, 0xFF}, \ + {0x10, 0x10, 0xF0, 0xFF}, \ + {0x0, 0x0, 0x20, 0xFF} \ +} +#endif \ No newline at end of file diff --git a/lib/sdl/core/coreWidget.cpp b/lib/sdl/core/coreWidget.cpp new file mode 100644 index 00000000..bbb3f8da --- /dev/null +++ b/lib/sdl/core/coreWidget.cpp @@ -0,0 +1,53 @@ +#include "coreWidget.h" + +sdlCoreWidget::sdlCoreWidget(int x, int y, int width, int height, sdlCoreWidget * pParent){ + m_sRect.x = x; + m_sRect.y = y; + m_sRect.w = width; + m_sRect.h = height; + m_pParent = pParent; + m_bRedraw = true; + m_sColorStyle = DEFAULT_COLOR_STYLE; + m_pWidgetTexture = NULL; + m_bNoDecoration = false; + m_pGUI = classGUI_SDL::getInstance(); + if (m_pGUI != NULL) m_pGUI->registerWidget(this); +}; + +sdlCoreWidget::~sdlCoreWidget(){ + if (m_pGUI != NULL) m_pGUI->removeWidget(this); + if (m_pWidgetTexture != NULL) SDL_DestroyTexture(m_pWidgetTexture); +}; + +void sdlCoreWidget::render(SDL_Renderer *pRenderer){ + if (pRenderer == NULL) return; + if (m_pWidgetTexture == NULL) m_pWidgetTexture = SDL_CreateTexture(pRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, m_sRect.w, m_sRect.h); + if (m_pWidgetTexture == NULL) return; + if (m_bRedraw){ + SDL_SetRenderTarget(pRenderer, m_pWidgetTexture); + SDL_SetRenderDrawColor(pRenderer, 0x00, 0x00, 0x00, 0x00); + SDL_RenderFillRect(pRenderer, &m_sRect); + if (!m_bNoDecoration){ + SDL_SetRenderDrawColor(pRenderer, m_sColorStyle.panelBG.r, m_sColorStyle.panelBG.g, m_sColorStyle.panelBG.b, m_sColorStyle.panelBG.a); + SDL_RenderClear(pRenderer); + SDL_Rect r; + r.x = 0; r.y = 0; r.w = m_sRect.w; r.h = m_sRect.h; + SDL_SetRenderDrawColor(pRenderer, m_sColorStyle.borderBODY.r, m_sColorStyle.borderBODY.g, m_sColorStyle.borderBODY.b, m_sColorStyle.borderBODY.a); + SDL_RenderDrawRect(pRenderer, &r); + }; + draw( pRenderer ); + if (m_vWidgets.size()){ + for (pWidgetVector::iterator index = m_vWidgets.begin(); index < m_vWidgets.end(); index++) (*index)->render(pRenderer); + }; + }; + if (m_pParent == NULL){ + SDL_SetRenderTarget(pRenderer, NULL); + } else { + SDL_SetRenderTarget(pRenderer, m_pParent->getWidgetTexture()); + }; + SDL_RenderCopy(pRenderer, m_pWidgetTexture, NULL, &m_sRect); +}; + +void sdlCoreWidget::setColorStyle(sdlColorStyle style){ + m_sColorStyle = style; +}; \ No newline at end of file diff --git a/lib/sdl/core/coreWidget.h b/lib/sdl/core/coreWidget.h new file mode 100644 index 00000000..44765749 --- /dev/null +++ b/lib/sdl/core/coreWidget.h @@ -0,0 +1,33 @@ +#ifndef __SDL_CORE_WIDGET_HEADER__ +#define __SDL_CORE_WIDGET_HEADER__ + +#include "../gui_sdl.h" +#include "coreStyleTemplate.h" + +class sdlCoreWidget{ + protected: + sdlCoreWidget * m_pParent; + classGUI_SDL * m_pGUI; + SDL_Rect m_sRect; + sdlColorStyle m_sColorStyle; + pWidgetVector m_vWidgets; + SDL_Texture * m_pWidgetTexture; + bool m_bNoDecoration; + bool m_bRedraw; + void requerstUpdate(void); + virtual void draw(SDL_Renderer *pRenderer){}; + SDL_Texture * getWidgetTexture(void){ return m_pWidgetTexture; }; + public: + explicit sdlCoreWidget(int x, int y, int width, int height, sdlCoreWidget * pParent = NULL); + virtual ~sdlCoreWidget(); + void render(SDL_Renderer *pRenderer); + SDL_Rect * getBoundRect(void){ return &m_sRect; }; + virtual void dispatch(SDL_Event *pEvt){}; + void setColorStyle(sdlColorStyle style); + virtual void hide(){}; + void addWidget(sdlCoreWidget *tPtr); + void setDecoraion(bool A){ m_bNoDecoration = !A; }; +}; + + +#endif \ No newline at end of file diff --git a/lib/sdl/gui_sdl.cpp b/lib/sdl/gui_sdl.cpp new file mode 100644 index 00000000..b2a416e3 --- /dev/null +++ b/lib/sdl/gui_sdl.cpp @@ -0,0 +1,193 @@ +#include "gui_sdl.h" +#include "core/coreWidget.h" + +classGUI_SDL * classGUI_SDL::m_pInstance = NULL; +classGUI_SDL * classGUI_SDL::getInstance(void){ + if (m_pInstance == NULL){ + m_pInstance = new classGUI_SDL(); + }; + return m_pInstance; +}; + +classGUI_SDL::classGUI_SDL(): basicThread(){ + m_pWindow = NULL; + m_pScreenSurface = NULL; + m_pTexture = NULL; + m_pRenderer = NULL; + m_bWindowSystemOk = false; + m_bInitOk = false; + m_pProtector = SDL_CreateMutex(); + int display_count = 0, display_index = 0, mode_index = 0; + SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 }; + if ((display_count = SDL_GetNumVideoDisplays()) < 1) { + SDL_Log("SDL_GetNumVideoDisplays returned: %i", display_count); + }; + SDL_Log("SDL_GetNumVideoDisplays returned: %i", display_count); + if (SDL_GetDisplayMode(display_index, mode_index, &mode) != 0) { + SDL_Log("SDL_GetDisplayMode failed: %s", SDL_GetError()); + }; + SDL_Log("SDL_GetDisplayMode(0, 0, &mode):\t\t%i bpp\t%i x %i", SDL_BITSPERPIXEL(mode.format), mode.w, mode.h ); + m_bInitOk = basicThread::init(); + while ( ( m_bWindowSystemOk == false ) && ( m_bThreadStatus < TH_ENDED ) ) SLEEP(1); +}; + +classGUI_SDL::~classGUI_SDL(){ + m_bWindowSystemOk = false; + m_bInitOk = false; + SDL_DestroyMutex( m_pProtector ); + if (m_pRenderer!=NULL){ + SDL_DestroyRenderer(m_pRenderer); + }; + if (m_pScreenSurface != NULL){ + //Deallocate surface + SDL_FreeSurface(m_pScreenSurface); + m_pScreenSurface = NULL; + }; + if ( m_pWindow!= NULL ){ + //Destroy window + SDL_DestroyWindow(m_pWindow); + m_pWindow = NULL; + }; + //Quit SDL subsystems + SDL_Quit(); +}; + + + +//https://www.facebook.com/missing.person.3158 +//https://www.facebook.com/guga.wereteli.90 +//https://www.facebook.com/mentul.ohmentul +//https://www.facebook.com/profile.php?id=100001772172980 +//https://www.facebook.com/egagua +/* Collect Confirmation Codes +Contact your friends and ask them for their help. +1. Call three of these friends or talk to them in person. +Raphael LlamadoChantebis SamkaroMentul OhmentulEstrada Irish PotchEvgeny Gagua +2. Ask them to visit : +https ://www.facebook.com/recover +3. Each friend will give you a code.Enter them below : +*/ +void classGUI_SDL::m_fThreadProc(void){ + if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0 ){ + m_bInitOk = false; + m_bThreadStatus = TH_ENDED; + return; + }; + if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)){ + //printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); + m_bInitOk = false; + m_bThreadStatus = TH_ENDED; + return; + }; + + //Initialize SDL_ttf + if( TTF_Init() == -1 ){ + //printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError()); + m_bInitOk = false; + m_bThreadStatus = TH_ENDED; + return; + } else { + m_bInitOk = true; + if (SDL_CreateWindowAndRenderer(SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_RESIZABLE, &m_pWindow, &m_pRenderer)){ + printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); + m_bThreadStatus = TH_ENDED; + m_bWindowSystemOk = false; + return; + } else { + //SDL_SetWindowOpacity(m_pWindow, 0.5); + //Get window surface + //m_pScreenSurface = SDL_GetWindowSurface(m_pWindow); + m_bThreadStatus = TH_WORKING; + m_bWindowSystemOk = true; + }; + }; + while( m_bThreadStatus < TH_ENDED ){ + //Event handler + SDL_Event mEvent; + //Handle events on queue + if( SDL_PollEvent(&mEvent) != 0 ){ + //m_mProtector.lock(); + SDL_LockMutex(m_pProtector); + if (m_vWidgets.size()){ + for (pWidgetVector::iterator index = m_vWidgets.begin(); index < m_vWidgets.end(); index++) (*index)->dispatch(&mEvent); + }; + //m_mProtector.unlock(); + SDL_UnlockMutex(m_pProtector); + // Global Window Event handler + if( mEvent.type == SDL_QUIT ){ + m_bThreadStatus = TH_ENDED; + } else if (mEvent.type == SDL_KEYDOWN){ //User presses a key + //Select surfaces based on key press + switch( mEvent.key.keysym.sym ){ + case SDLK_UP: + //gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_UP]; + break; + case SDLK_DOWN: + //gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_DOWN]; + break; + case SDLK_LEFT: + //gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_LEFT]; + break; + case SDLK_RIGHT: + //gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_RIGHT]; + break; + default: + //gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT]; + break; + }; + }; + }; + //m_mProtector.lock(); + SDL_LockMutex(m_pProtector); + if (m_vWidgets.size()){ + for (pWidgetVector::iterator index = m_vWidgets.begin(); index < m_vWidgets.end(); index++) (*index)->render(m_pRenderer); + SDL_RenderPresent(m_pRenderer); + }; + //m_mProtector.unlock(); + SDL_UnlockMutex(m_pProtector); + //Apply the image + //SDL_BlitSurface(gXOut, NULL, m_pScreenSurface, NULL); + //Update the surface + //SDL_UpdateWindowSurface(m_pWindow); + //SLEEP(150); + }; +}; +//FOXCONN PVB120G12H-P01 +//AVC MD413 BA13733B12H + +void classGUI_SDL::registerWidget(sdlCoreWidget * tPtr){ + while( !m_bWindowSystemOk ) SLEEP(1); + if( tPtr != NULL ){ + //m_mProtector.lock(); + SDL_LockMutex(m_pProtector); + m_vWidgets.push_back(tPtr); + //m_mProtector.unlock(); + SDL_UnlockMutex(m_pProtector); + }; +}; + +void classGUI_SDL::removeWidget(sdlCoreWidget * tPtr){ + if (tPtr != NULL){ + //m_mProtector.lock(); + SDL_LockMutex(m_pProtector); + for (pWidgetVector::iterator index = m_vWidgets.begin(); index < m_vWidgets.end(); index++){ + if ((*index) == tPtr){ + (*index)->hide(); + m_vWidgets.erase(index); + break; + }; + }; + //m_mProtector.unlock(); + SDL_UnlockMutex(m_pProtector); + }; +}; + +bool classGUI_SDL::setFullScreen( bool status ){ + if (m_pWindow == NULL) return false; + if (status){ + SDL_SetWindowFullscreen(m_pWindow, SDL_WINDOW_FULLSCREEN ); + } else { + SDL_SetWindowFullscreen(m_pWindow, SDL_WINDOW_FULLSCREEN_DESKTOP); + }; + return true; +}; \ No newline at end of file diff --git a/lib/sdl/gui_sdl.h b/lib/sdl/gui_sdl.h new file mode 100644 index 00000000..58af5a50 --- /dev/null +++ b/lib/sdl/gui_sdl.h @@ -0,0 +1,42 @@ +#ifndef __GUI_SDL_HEADER__ +#define __GUI_SDL_HEADER__ + +#include +#include +#include "../components/base/basicMutex.h" +#include "../components/base/basicThread.h" +#include +#include +#include + +#define SCREEN_WIDTH 800 +#define SCREEN_HEIGHT 600 + +class sdlCoreWidget; + +typedef std::vector pWidgetVector; + +class classGUI_SDL: public basicThread{ + private: + bool m_bInitOk; + bool m_bWindowSystemOk; + SDL_Window * m_pWindow; + SDL_Renderer * m_pRenderer; + SDL_Surface * m_pScreenSurface; + SDL_Texture * m_pTexture; + //basicMutex m_mProtector; + SDL_mutex * m_pProtector; + pWidgetVector m_vWidgets; + public: + static classGUI_SDL * getInstance(); + virtual void m_fThreadProc(void); + void registerWidget(sdlCoreWidget * tPtr); + void removeWidget( sdlCoreWidget * tPtr); + bool setFullScreen( bool status ); + protected: + classGUI_SDL(); + ~classGUI_SDL(); + static classGUI_SDL * m_pInstance; +}; + +#endif \ No newline at end of file diff --git a/lib/sdl/widgets/logWidget.cpp b/lib/sdl/widgets/logWidget.cpp new file mode 100644 index 00000000..0191e344 --- /dev/null +++ b/lib/sdl/widgets/logWidget.cpp @@ -0,0 +1,59 @@ +#include "logWidget.h" + +sdlLog::sdlLog(int x, int y, int width, int height, sdlCoreWidget * pWnd) :sdlCoreWidget(x, y, width, height, pWnd){ + m_nLines = height / SDL_DEFAULT_LOG_ROW_SIZE; + m_nCurrentLine = 0; + m_ppLines = (sdlLabel**)calloc( m_nLines, sizeof(sdlLabel*) ); + memset( m_ppLines, 0, m_nLines * sizeof(sdlLabel*) ); +}; + +sdlLog::~sdlLog(){ + if (m_ppLines != NULL){ + for (int index = 0; index < m_nLines; index++) delete(m_ppLines[index]); + free(m_ppLines); + }; +}; + +void sdlLog::logMessage(const char *Msg){ + if (m_ppLines != NULL){ + //m_mProtector.lock(); + if (m_nCurrentLine < m_nLines){ + m_ppLines[m_nCurrentLine] = new sdlLabel( + 1, + 1 + (m_nCurrentLine*SDL_DEFAULT_LOG_ROW_SIZE), + m_sRect.w - 2, + SDL_DEFAULT_LOG_ROW_SIZE, + this, + SDL_DEFAULT_LOG_FONT_SIZE + ); + if( m_ppLines[m_nCurrentLine] != NULL ){ + m_ppLines[m_nCurrentLine]->setAlign(ALIGN_LEFT); + m_nCurrentLine++; + }; + for (int index = m_nCurrentLine - 1; index > 0; index--){ + char tBuf[SDL_DEFAULT_TEXT_SIZE]; + memcpy(tBuf, m_ppLines[index - 1]->getText(), SDL_DEFAULT_TEXT_SIZE); + m_ppLines[index]->setText(tBuf); + }; + m_ppLines[0]->setText((CSTR)Msg); + } else { + for (int index = m_nLines - 1; index > 0; index-- ){ + char tBuf[SDL_DEFAULT_TEXT_SIZE]; + memcpy(tBuf, m_ppLines[index-1]->getText(), SDL_DEFAULT_TEXT_SIZE); + m_ppLines[index]->setText(tBuf); + }; + m_ppLines[0]->setText((CSTR)Msg); + }; + //m_mProtector.unlock(); + }; +}; + +void sdlLog::logMessage(CSTR Msg){ + logMessage((const char*)Msg); +}; + +void sdlLog::draw(SDL_Renderer *pRenderer){ + for (int index = 0; index < m_nLines; index++){ + if (m_ppLines[index] != NULL) m_ppLines[index]->render(pRenderer); + }; +}; \ No newline at end of file diff --git a/lib/sdl/widgets/logWidget.h b/lib/sdl/widgets/logWidget.h new file mode 100644 index 00000000..24be8068 --- /dev/null +++ b/lib/sdl/widgets/logWidget.h @@ -0,0 +1,29 @@ +#ifndef __SDL_LOG_WIDGET_HEADER__ +#define __SDL_LOG_WIDGET_HEADER__ +#include "../core/coreWidget.h" +#include "../core/coreLabel.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicLoggingService.h" + +#define SDL_DEFAULT_LOG_FONT_SIZE 10 +#define SDL_DEFAULT_LOG_ROW_SIZE 12 + +class sdlLog :public basicLoggingService, public sdlCoreWidget { + private: + sdlLabel ** m_ppLines; + int m_nLines; + int m_nCurrentLine; + basicMutex m_mProtector; + protected: + virtual void draw(SDL_Renderer *pRenderer); + public: + explicit sdlLog(int x, int y, int width, int height, sdlCoreWidget * pWnd = NULL); + virtual ~sdlLog(); + virtual void logMessage(CSTR Msg); + virtual void logMessage(const char *Msg); +}; + + + + +#endif \ No newline at end of file diff --git a/lib/sdl/widgets/progressBar.cpp b/lib/sdl/widgets/progressBar.cpp new file mode 100644 index 00000000..959682c7 --- /dev/null +++ b/lib/sdl/widgets/progressBar.cpp @@ -0,0 +1,59 @@ +#include "progressBar.h" +sdlProgressBar::sdlProgressBar(int x, int y, int width, int height, sdlCoreWidget * pWnd) :sdlCoreWidget(x, y, width, height, pWnd){ + m_pStatusProvider = NULL; + m_pLabel = NULL; +}; + +sdlProgressBar::~sdlProgressBar(){ + +}; + +void sdlProgressBar::draw(SDL_Renderer *pRenderer){ + m_mStatusProtecter.lock(); + if( m_pStatusProvider ){ + SDL_Rect r; + char tBuff[256]; + uint8_t bStatus; + bStatus = m_pStatusProvider->getStatus(tBuff); + if (tBuff[0]!=(char)0)setText(tBuff); + if (bStatus > 0){ + SDL_SetRenderDrawColor(pRenderer, m_sColorStyle.activeSelector.r, m_sColorStyle.activeSelector.g, m_sColorStyle.activeSelector.b, m_sColorStyle.activeSelector.a); + if (bStatus < 100){ + r.x = 1; r.y = 1; r.w = ( m_sRect.w * bStatus ) / 100 -2; r.h = m_sRect.h - 2; + } else { + r.x = 1; r.y = 1; r.w = m_sRect.w - 2; r.h = m_sRect.h - 2; + }; + //SDL_RenderDrawRect(pRenderer, &r); + SDL_RenderFillRect(pRenderer, &r); + + if (m_pLabel != NULL) m_pLabel->render(pRenderer); + //SDL_SetRenderDrawColor(pRenderer, m_sColorStyle.borderBODY.r, m_sColorStyle.borderBODY.g, m_sColorStyle.borderBODY.b, m_sColorStyle.borderBODY.a); + //r.x = 0; r.y = 0; r.w = m_sRect.w; r.h = m_sRect.h; + //SDL_RenderDrawRect(pRenderer, &r); + }; + }; + m_mStatusProtecter.unlock(); +}; + +void sdlProgressBar::dispatch(SDL_Event *pEvt){ + if (pEvt->type == SDL_MOUSEMOTION || pEvt->type == SDL_MOUSEBUTTONDOWN || pEvt->type == SDL_MOUSEBUTTONUP){ + //Get mouse position + int x, y; + SDL_GetMouseState(&x, &y); + }; +}; + +void sdlProgressBar::attachStatusProvider(basicStatusProvider *tPtr){ + m_mStatusProtecter.lock(); + m_pStatusProvider = tPtr; + m_mStatusProtecter.unlock(); +}; + +void sdlProgressBar::setText(CSTR tPtr){ + if (m_pLabel == NULL){ + m_pLabel = new sdlLabel( 1, 1, m_sRect.w - 2, m_sRect.h - 2, this, 12 ); + }; + if (m_pLabel != NULL){ + m_pLabel->setText(tPtr); + }; +}; \ No newline at end of file diff --git a/lib/sdl/widgets/progressBar.h b/lib/sdl/widgets/progressBar.h new file mode 100644 index 00000000..715edcf6 --- /dev/null +++ b/lib/sdl/widgets/progressBar.h @@ -0,0 +1,23 @@ +#ifndef __GUI_SDL_WIDGET_PROGRESS_BAR_HEADER__ +#define __GUI_SDL_WIDGET_PROGRESS_BAR_HEADER__ +#include "../core/coreWidget.h" +#include "../core/coreLabel.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicStatusProvider.h" + +class sdlProgressBar : public sdlCoreWidget{ + private: + basicStatusProvider * m_pStatusProvider; + sdlLabel * m_pLabel; + basicMutex m_mStatusProtecter; + protected: + virtual void draw(SDL_Renderer *pRenderer); + public: + explicit sdlProgressBar(int x, int y, int width, int height, sdlCoreWidget * pWnd = NULL); + virtual ~sdlProgressBar(); + void attachStatusProvider(basicStatusProvider *tPtr); + virtual void dispatch(SDL_Event *pEvt); + void setText( CSTR tPtr ); +}; + +#endif \ No newline at end of file diff --git a/put_to_git b/put_to_git index f63a2e78..d66eaf1e 100755 --- a/put_to_git +++ b/put_to_git @@ -1,4 +1,4 @@ #!/bin/bash #git commit -a -m '$1' -git commit -a -m 'PRU changed tp work with each Mirror and LRF separately' +git commit -a -m 'Cortex Library Updated to last MERCURY version Also added SDL preliminary basics'