You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

524 lines
16 KiB

#include "convolutionalLayer.h"
#define LOG( X ) m_pLog->Log( "CONV", this, X )
#define LOG_ERROR( X ) m_pLog->Log( "CONV", this, _LOG_ERROR, X )
convolutionalLayer::convolutionalLayer(bool useGPU) :cortexLayer(CONVOLUTIONAL, useGPU){
};
convolutionalLayer::~convolutionalLayer(){
};
void convolutionalLayer::swapBinary(void){
float *tSwap = m_pWeight;
m_pWeight = m_pBinaryWeight;
m_pBinaryWeight = tSwap;
#ifdef GPU
tSwap = m_pGpuWeight;
m_pGpuWeight = m_pGpuBinaryWeight;
m_pGpuBinaryWeight = tSwap;
#endif
};
void convolutionalLayer::binarizeWeights(float *weights, uint32_t n, uint32_t size, float *binary){
for (uint32_t f = 0; f < n; f++){
float mean = 0;
for (uint32_t i = 0; i < size; ++i){
mean += (float)(fabs(weights[f*size + i]));
};
mean = mean / size;
for (uint32_t i = 0; i < size; ++i){
binary[f*size + i] = (weights[f*size + i] > 0) ? mean : -mean;
};
};
};
void convolutionalLayer::binarize(float *input, uint32_t n, float *binary){
for (uint32_t i = 0; i < n; ++i){
binary[i] = (input[i] > 0) ? 1.f : -1.f;
};
};
void convolutionalLayer::binarizeInput(float *input, uint32_t n, uint32_t size, float *binary){
for (uint32_t s = 0; s < size; ++s){
float mean = 0;
for (uint32_t i = 0; i < n; ++i){
mean += (float)fabs(input[i*size + s]);
};
mean = mean / n;
for (uint32_t i = 0; i < n; ++i){
binary[i*size + s] = (input[i*size + s] > 0) ? mean : -mean;
};
};
};
//uint32_t convolutionalLayer::getOutputHeight(void){
// return (m_nIn_Height + 2 * m_nPad - m_nSize) / m_nStride + 1; //?
//};
//uint32_t convolutionalLayer::getOutputWidth(void){
// return (m_nIn_Width + 2 * m_nPad - m_nSize) / m_nStride + 1;
//};
cortexImage *convolutionalLayer::getOutputImage(void){
cortexImage *tImage = NULL;
tImage = new cortexImage();
if (tImage != NULL){
tImage->setData( m_nOut_Width, m_nOut_Height, m_nOut_Channels, m_pOutput);
};
return tImage;
};
cortexImage *convolutionalLayer::getDeltaImage(void){
cortexImage *tImage = NULL;
tImage = new cortexImage();
if (tImage != NULL){
tImage->setData( m_nOut_Width, m_nOut_Height, m_nOut_Channels, m_pDelta);
};
return tImage;
};
uint32_t convolutionalLayer::calcWorkspaceSize(){
#ifdef GPU
#ifdef CUDNN
if( m_bUseGPU ){
uint32_t most = 0;
uint32_t s = 0;
cudnnGetConvolutionForwardWorkspaceSize(cudnn_handle(),
l.srcTensorDesc,
l.weightDesc,
l.convDesc,
l.dstTensorDesc,
l.fw_algo,
&s);
if (s > most) most = s;
cudnnGetConvolutionBackwardFilterWorkspaceSize(cudnn_handle(),
l.srcTensorDesc,
l.ddstTensorDesc,
l.convDesc,
l.dweightDesc,
l.bf_algo,
&s);
if (s > most) most = s;
cudnnGetConvolutionBackwardDataWorkspaceSize(cudnn_handle(),
l.weightDesc,
l.ddstTensorDesc,
l.convDesc,
l.dsrcTensorDesc,
l.bd_algo,
&s);
if (s > most) most = s;
return most;
};
#endif // CUDNN
return (uint32_t)(m_nOut_Height * m_nOut_Width * m_nSize * m_nSize * m_nIn_Channels * sizeof(float));
#else // GPU
return (uint32_t)(m_nOut_Height * m_nOut_Width * m_nSize * m_nSize * m_nIn_Channels * sizeof(float));
#endif
}
bool convolutionalLayer::create(uint32_t batch, uint32_t h, uint32_t w, uint32_t c, uint32_t n, uint32_t size, uint32_t stride, uint32_t padding, ACTIVATION activation, bool batch_normalize, bool binary, bool xnor, bool adam){
uint32_t i;
m_nIn_Height = h;
m_nIn_Width = w;
m_nIn_Channels = c;
m_nN = n;
m_bBinary = binary;
m_bXNOR = xnor;
m_nBatch = batch;
m_nStride = stride;
m_nSize = size;
m_nPad = padding;
m_bBatchNormalize = batch_normalize;
m_nOut_Height = (m_nIn_Height + 2 * m_nPad - m_nSize) / m_nStride + 1;
m_nOut_Width = (m_nIn_Width + 2 * m_nPad - m_nSize) / m_nStride + 1;
m_nOut_Channels = n;
m_bAdam = adam;
m_nWeight = m_nOut_Channels * m_nIn_Channels * m_nSize * m_nSize;
m_pWeight = (float*)calloc(m_nWeight, sizeof(float));
if ( m_pWeight == NULL ) return false;
m_pWeightUpdate = (float*)calloc(m_nWeight, sizeof(float));
if ( m_pWeightUpdate == NULL ) return false;
m_nBias = m_nOut_Channels;
m_pBias = (float*)calloc(m_nBias, sizeof(float));
if ( m_pBias == NULL ) return false;
m_pBiasUpdate = (float*)calloc(m_nBias, sizeof(float));
if ( m_pBiasUpdate == NULL ) return false;
//float scale = 1./sqrt(size*size*c);
//float scale = (float)sqrt(2. / (size*size*c));
float scale = (float)sqrt( 2.f / (m_nIn_Channels * m_nSize * m_nSize));
for (i = 0; i < m_nWeight; ++i) m_pWeight[i] = scale*rand_uniform(-1, 1);
m_nDelta = m_nOutput = m_nOut_Height * m_nOut_Width * m_nOut_Channels;
m_nInput = m_nIn_Height * m_nIn_Width * m_nIn_Channels;
m_nDeltaVol = m_nOutputVol = m_nBatch * m_nOutput;
m_pOutput = (float*)calloc(m_nOutputVol, sizeof(float));
if ( m_pOutput == NULL )return false;
m_pDelta = (float*)calloc(m_nDeltaVol, sizeof(float));
if ( m_pDelta == NULL )return false;
if (m_bBinary){
m_pBinaryWeight = (float*)calloc(m_nWeight, sizeof(float));
if ( m_pBinaryWeight == NULL )return false;
m_pCharWeight = (char*)calloc(m_nWeight, sizeof(char));
if ( m_pCharWeight == NULL ) return false;
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;
};
if (m_bXNOR){
if (!m_pBinaryWeight){
m_pBinaryWeight = (float*)calloc(m_nWeight, sizeof(float));
if (m_pBinaryWeight==NULL)return false;
};
m_pBinaryInput = (float*)calloc(m_nBatch*m_nInput, sizeof(float));
if (m_pBinaryInput == NULL)return false;
#ifdef GPU
if (m_bUseGPU){
if (m_pGpuBinaryWeight == NULL){
m_pGpuBinaryWeight = m_pPU->makeFloatArray(m_nWeight, m_pWeight);
if (m_pGpuBinaryWeight == NULL)return false;
};
m_pGpuBinaryInput = m_pPU->makeFloatArray(m_nInput*m_nBatch);
if (m_pGpuBinaryInput == NULL)return false;
};
#endif
};
if (m_bBatchNormalize){
if (!m_pScale){
m_nScale = m_nOut_Channels;
m_pScale = (float*)calloc(m_nScale, sizeof(float));
if (!m_pScale)return false;
};
m_pScaleUpdate = (float*)calloc(m_nScale, sizeof(float));
if (!m_pScaleUpdate)return false;
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_pMeanDelta = (float*)calloc(m_nScale, sizeof(float));
m_pVarianceDelta = (float*)calloc(m_nScale, 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
if (m_bUseGPU){
m_pGpuMean = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pMean);
m_pGpuVariance = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pVariance);
m_pGpuRollingMean = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pRollingMean);
m_pGpuRollingVariance = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pRollingVariance);
m_pGpuMeanDelta = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pMeanDelta);
m_pGpuVarianceDelta = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pVarianceDelta);
m_pGpuX = m_pPU->makeFloatArray(m_nOutputVol);//, m_pOutput);
m_pGpuXNorm = m_pPU->makeFloatArray(m_nOutputVol);//, m_pOutput);
};
#endif
};
if (m_bAdam){
m_pHostM = (float*)calloc(m_nWeight, sizeof(float));
m_pHostV = (float*)calloc(m_nWeight, sizeof(float));
#ifdef GPU
if (m_bUseGPU){
m_pGpuM = m_pPU->makeFloatArray(m_nWeight);//, m_pHostM);
m_pGpuV = m_pPU->makeFloatArray(m_nWeight);//, m_pHostV);
};
#endif
};
#ifdef GPU
if (m_bUseGPU){
m_pGpuWeight = m_pPU->makeFloatArray(m_nWeight);//, m_pWeight);
m_pGpuWeightUpdate = m_pPU->makeFloatArray(m_nWeight);//, m_pWeightUpdate);
m_pGpuBias = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pBias);
m_pGpuBiasUpdate = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pBiasUpdate);
m_pGpuDelta = m_pPU->makeFloatArray(m_nBatch * m_nOutput);//, m_pDelta);
m_pGpuOutput = m_pPU->makeFloatArray(m_nBatch * m_nOutput);//, m_pOutput);
m_pGpuScale = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pScale);
m_pGpuScaleUpdate = m_pPU->makeFloatArray(m_nOut_Channels);//, m_pScaleUpdate);
#ifdef CUDNN
cudnnCreateTensorDescriptor(&l.srcTensorDesc);
cudnnCreateTensorDescriptor(&l.dstTensorDesc);
cudnnCreateFilterDescriptor(&l.weightDesc);
cudnnCreateTensorDescriptor(&l.dsrcTensorDesc);
cudnnCreateTensorDescriptor(&l.ddstTensorDesc);
cudnnCreateFilterDescriptor(&l.dweightDesc);
cudnnCreateConvolutionDescriptor(&l.convDesc);
cudnn_convolutional_setup(&l);
#endif // CUDNN
};
#endif // GPU
m_nWorkspace = calcWorkspaceSize();
m_eActivation = activation;
char tBuff[256];
sprintf(tBuff, "\t%5d\t%2dx%2d\t%2d\t%4dx%4dx%4d -> %4dx%4dx%4d", n, size, size, stride, w, h, c, m_nOut_Width, m_nOut_Height, m_nOut_Channels);
LOG(tBuff);
return true;
};
void convolutionalLayer::denormalize(void){
uint32_t i, j;
for (i = 0; i < m_nOut_Channels; ++i){
float scale = (float)(m_pScale[i] / sqrt(m_pRollingVariance[i] + .00001f));
for (j = 0; j < m_nIn_Channels*m_nSize*m_nSize; ++j){
m_pWeight[i*m_nIn_Channels*m_nSize*m_nSize + j] *= scale;
};
m_pBias[i] -= m_pRollingMean[i] * scale;
m_pScale[i] = 1.f;
m_pRollingMean[i] = .0f;
m_pRollingVariance[i] = 1.f;
};
};
void convolutionalLayer::test(void){
create(1, 5, 5, 3, 2, 5, 2, 1, LEAKY, true, false, false, false);
float data[] = {
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
2, 2, 2, 2, 2,
2, 2, 2, 2, 2,
2, 2, 2, 2, 2,
2, 2, 2, 2, 2,
3, 3, 3, 3, 3,
3, 3, 3, 3, 3,
3, 3, 3, 3, 3,
3, 3, 3, 3, 3,
3, 3, 3, 3, 3 };
cortexSTATE state = { 0 };
state.input = data;
forward(state);
};
bool convolutionalLayer::resize(uint32_t w, uint32_t h){
m_nIn_Width = w;
m_nIn_Height = h;
m_nOut_Width = (m_nIn_Width + 2 * m_nPad - m_nSize) / m_nStride + 1;
m_nOut_Height = (m_nIn_Height + 2 * m_nPad - m_nSize) / m_nStride + 1;
m_nOutput = m_nOut_Height * m_nOut_Width * m_nOut_Channels;
m_nInput = m_nIn_Width * m_nIn_Height * m_nIn_Channels;
m_pOutput = (float*)realloc(m_pOutput, m_nBatch*m_nOutput*sizeof(float));
m_pDelta = (float*)realloc(m_pDelta, m_nBatch*m_nOutput*sizeof(float));
if (m_bBatchNormalize){
m_pX = (float*)realloc(m_pX, m_nBatch*m_nOutput*sizeof(float));
m_pXNorm = (float*)realloc(m_pXNorm, m_nBatch*m_nOutput*sizeof(float));
};
#ifdef GPU
m_pPU->freeMem( m_pGpuDelta );
m_pPU->freeMem( m_pGpuOutput );
m_pGpuDelta = m_pPU->makeFloatArray(m_nBatch*m_nOutput, m_pDelta);
m_pGpuOutput = m_pPU->makeFloatArray(m_nBatch*m_nOutput, m_pOutput);
if (m_bBatchNormalize){
m_pPU->freeMem( m_pGpuX );
m_pPU->freeMem( m_pGpuXNorm );
m_pGpuX = m_pPU->makeFloatArray(m_nBatch*m_nOutput, m_pOutput);
m_pGpuXNorm = m_pPU->makeFloatArray(m_nBatch*m_nOutput, m_pOutput);
};
#ifdef CUDNN
cudnn_setup();
#endif
#endif
m_nWorkspace = calcWorkspaceSize();
return true;
};
#ifdef GPU
#ifdef CUDNN
void convolutionalLayer::cudnn_setup(void){
cudnnSetTensor4dDescriptor(l->dsrcTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, l->batch, l->c, l->h, l->w);
cudnnSetTensor4dDescriptor(l->ddstTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, l->batch, l->out_c, l->out_h, l->out_w);
cudnnSetFilter4dDescriptor(l->dweightDesc, CUDNN_DATA_FLOAT, CUDNN_TENSOR_NCHW, l->n, l->c, l->size, l->size);
cudnnSetTensor4dDescriptor(l->srcTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, l->batch, l->c, l->h, l->w);
cudnnSetTensor4dDescriptor(l->dstTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, l->batch, l->out_c, l->out_h, l->out_w);
cudnnSetFilter4dDescriptor(l->weightDesc, CUDNN_DATA_FLOAT, CUDNN_TENSOR_NCHW, l->n, l->c, l->size, l->size);
#if(CUDNN_MAJOR >= 6)
cudnnSetConvolution2dDescriptor(l->convDesc, l->pad, l->pad, l->stride, l->stride, 1, 1, CUDNN_CROSS_CORRELATION, CUDNN_DATA_FLOAT); // cudnn 6.0
#else
cudnnSetConvolution2dDescriptor(l->convDesc, l->pad, l->pad, l->stride, l->stride, 1, 1, CUDNN_CROSS_CORRELATION); // cudnn 5.1
#endif
cudnnGetConvolutionForwardAlgorithm(cudnn_handle(),
l->srcTensorDesc,
l->weightDesc,
l->convDesc,
l->dstTensorDesc,
CUDNN_CONVOLUTION_FWD_PREFER_FASTEST,
0,
&l->fw_algo);
cudnnGetConvolutionBackwardDataAlgorithm(cudnn_handle(),
l->weightDesc,
l->ddstTensorDesc,
l->convDesc,
l->dsrcTensorDesc,
CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST,
0,
&l->bd_algo);
cudnnGetConvolutionBackwardFilterAlgorithm(cudnn_handle(),
l->srcTensorDesc,
l->ddstTensorDesc,
l->convDesc,
l->dweightDesc,
CUDNN_CONVOLUTION_BWD_FILTER_PREFER_FASTEST,
0,
&l->bf_algo);
};
#endif
#endif
void convolutionalLayer::forward(cortexSTATE state){
m_pPU->forward_layer( this, state );
};
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);
m_pPU->calcScal(m_nBias, momentum, m_pBiasUpdate, 1);
if(m_pScale){
m_pPU->calcAxpy(m_nScale, learning_rate / batch, m_pScaleUpdate, 1, m_pScale, 1);
m_pPU->calcScal(m_nScale, momentum, m_pScaleUpdate, 1);
};
m_pPU->calcAxpy(m_nWeight, -decay*batch, m_pWeight, 1, m_pWeightUpdate, 1);
m_pPU->calcAxpy(m_nWeight, learning_rate / batch, m_pWeightUpdate, 1, m_pWeight, 1);
m_pPU->calcScal(m_nWeight, momentum, m_pWeightUpdate, 1);
};
/*
image get_convolutional_weight(convolutional_layer l, int i)
{
int h = l.size;
int w = l.size;
int c = l.c;
return float_to_image(w, h, c, l.weights + i*h*w*c);
}
void rgbgr_weights(){
int i;
for (i = 0; i < l.n; ++i){
image im = get_convolutional_weight(l, i);
if (im.c == 3) {
rgbgr_image(im);
}
}
}
void rescale_weights(convolutional_layer l, float scale, float trans)
{
int i;
for (i = 0; i < l.n; ++i){
image im = get_convolutional_weight(l, i);
if (im.c == 3) {
scale_image(im, scale);
float sum = sum_array(im.data, im.w*im.h*im.c);
l.biases[i] += sum*trans;
}
}
}
image *get_weights(convolutional_layer l)
{
image *weights = (image*)calloc(l.n, sizeof(image));
int i;
for (i = 0; i < l.n; ++i){
weights[i] = copy_image(get_convolutional_weight(l, i));
//normalize_image(weights[i]);
}
return weights;
}
image *visualize(convolutional_layer l, char *window, image *prev_weights)
{
image *single_weights = get_weights(l);
show_images(single_weights, l.n, window);
image delta = get_convolutional_image(l);
image dc = collapse_image_layers(delta, 1);
char buff[256];
sprintf(buff, "%s: Output", window);
//show_image(dc, buff);
//save_image(dc, buff);
free_image(dc);
return single_weights;
}
*/
#undef LOG
#undef LOG_ERROR