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.
 
 
 
 
 
 

540 lines
14 KiB

int gpu_index = 0;
#ifdef GPU
#include "cuda.h"
#include "../base/basicUtils.h"
#include "../base/basicCortex.h"
#include "../base/basicLayer.h"
#include "../cpu/blas.h"
#define LOG( X ) m_pLog->Log( "CUDA", this, X )
#define LOG_ERROR( X ) m_pLog->Log( "CUDA", this, _LOG_ERROR, X )
gpuCUDA* gpuCUDA::_instance = NULL;
bool gpuCUDA::m_aCublasHandleBusy[CUDA_KERNEL_NODES] = { false };
cublasHandle_t gpuCUDA::m_aCublasHandle[CUDA_KERNEL_NODES] = { NULL };
bool gpuCUDA::m_aCuRandHandleBusy[CUDA_KERNEL_NODES] = { false };
curandGenerator_t gpuCUDA::m_aCuRandHandle[CUDA_KERNEL_NODES] = { NULL };
/**
* Returns the single instance of the object.
*/
gpuCUDA *gpuCUDA::getInstance(void) {
// check if the instance has been created yet
if( NULL == _instance ){
// if not, then create it
_instance = new gpuCUDA();
}
// return the single instance
return _instance;
};
gpuCUDA::gpuCUDA(){
m_pLog = basicLogCollection::getInstance();
m_nDeviceIndex = 0;
m_sStatus = cudaGetDeviceCount(&m_nDeviceCount);
if( m_sStatus == cudaSuccess ){
cudaDeviceProp prop;// = NULL;
cudaError_t ret = cudaGetDeviceProperties( &prop, 0 );
if( ret == cudaSuccess ){
char tBuff[1256];
float mSize;
mSize = ((float)prop.totalGlobalMem) / 1073741824.f;
sprintf(tBuff, "%s [%0.1fGb] C:%dT:%dK:%d", prop.name, mSize, prop.multiProcessorCount, prop.maxThreadsPerMultiProcessor,prop.concurrentKernels );
LOG(tBuff);
};
#ifdef _DEBUG
char tBuff[256];
sprintf( tBuff, "Detected %d CUDA GPU Core(s)", m_nDeviceCount );
LOG( tBuff );
#endif
} else
//if( m_sStatus != cudaSuccess )
{
m_nDeviceCount = -1;
LOG_ERROR( "GPU Device Not FOUND!" );
};
};
gpuCUDA::~gpuCUDA(){
};
bool gpuCUDA::setDevice(uint32_t n){
#ifdef _DEBUG
char buffer[256];
snprintf(buffer, 256, "Set CUDA device[%d] ... ", n);
LOG(buffer);
#endif
m_nDeviceIndex = n;
m_sStatus = cudaSetDevice(m_nDeviceIndex);
#ifdef _DEBUG
if (m_sStatus == cudaSuccess){
snprintf(buffer, 256, "OK");
LOG(buffer);
};
#endif
return checkError();
};
int gpuCUDA::getDevice(void){
int n = 0;
LOG("Get CUDA device ... ");
m_sStatus = cudaGetDevice(&n);
if( m_sStatus == cudaSuccess ){
char tBuff[128];
sprintf( tBuff,"Device[%d] - OK", n);
LOG(tBuff);
};
if( checkError() ) return n;
return -1;
};
bool gpuCUDA::checkError(void){
cudaDeviceSynchronize();
cudaError_t tStatus = cudaGetLastError();
if (m_sStatus != cudaSuccess){
#ifdef _DEBUG
const char *s = cudaGetErrorString(m_sStatus);
char buffer[256];
snprintf(buffer, 256, "CUDA Error: %s", s);
LOG_ERROR(buffer);
//assert(0);
#endif
return false;
};
if (tStatus != cudaSuccess){
#ifdef _DEBUG
const char *s = cudaGetErrorString(m_sStatus);
char buffer[256];
snprintf(buffer, 256, "CUDA Error Prev: %s", s);
LOG_ERROR(buffer);
//assert(0);
#endif
return false;
};
return true;
};
dim3 gpuCUDA::gridSize( unsigned int n ){
unsigned int k = (n - 1) / BLOCK + 1;
unsigned int x = k;
unsigned int y = 1;
if (x > 65535){
x = (unsigned int)ceil(sqrt((double)k));
y = (unsigned int)(n - 1) / (x*BLOCK) + 1;
}
dim3 d;// = { x, y, 1 };
d.x = x; d.y = y, d.z = 1;
printf("%ld %ld %ld %ld\n", n, x, y, x*y*BLOCK);
return d;
};
#ifdef CUDNN
cudnnHandle_t gpuCUDA::cudnn_handle(){
static int init[16] = { 0 };
static cudnnHandle_t handle[16];
int i = cuda_get_device();
if (!init[i]) {
cudnnCreate(&handle[i]);
init[i] = 1;
}
return handle[i];
};
#endif
cublasHandle_t gpuCUDA::getBlasHandle(void){
int i = getDevice();
if( i < 0 ) return NULL;
#ifdef _DEBUG
char buffer[256];
snprintf(buffer, 256, "CUDA device ID: %d", i);
LOG(buffer);
#endif
if( !m_aCublasHandleBusy[i] ){
#ifdef _DEBUG
LOG("Create new BLAS handle ... ");
#endif
cublasCreate(&m_aCublasHandle[i]);
if( m_aCublasHandle[i] ){
m_aCublasHandleBusy[i] = true;
#ifdef _DEBUG
snprintf(buffer, 256, "blas[%p] - OK", m_aCublasHandle[i]);
LOG(buffer);
#endif
} else {
LOG_ERROR("Create new BLAS handle FAIL!");
return NULL;
};
};
return m_aCublasHandle[i];
};
float *gpuCUDA::makeFloatArray(uint32_t n, float *hostMem ){
float *x_gpu = NULL;
uint32_t size = sizeof(float) * n;
m_sStatus = cudaMalloc((void **)&x_gpu, size);
if( !checkError() || x_gpu == NULL ){
LOG_ERROR("cudaMalloc FAILED!");
return NULL;
};
if (hostMem){
m_sStatus = cudaMemcpy(x_gpu, hostMem, size, cudaMemcpyHostToDevice);
if( !checkError() ){
LOG_ERROR("cudaMemcpy FAILED!");
cudaFree( x_gpu );
return NULL;
};
};
return x_gpu;
};
bool gpuCUDA::makeRandom(float *gpuMem, uint32_t n){
if (gpuMem == NULL) return false;
int i = getDevice();
if (i < 0) return false;
if (!m_aCuRandHandleBusy[i]){
curandCreateGenerator(&m_aCuRandHandle[i], CURAND_RNG_PSEUDO_DEFAULT);
curandSetPseudoRandomGeneratorSeed(m_aCuRandHandle[i], time(0));
m_aCuRandHandleBusy[i] = true;
}
curandGenerateUniform(m_aCuRandHandle[i], gpuMem, n );
m_sStatus = cudaPeekAtLastError();
return checkError();
};
float gpuCUDA::compare(float *gpuMem, float *x, uint32_t n, char *s){
float *tmp = (float*)calloc(n, sizeof(float));
pullFloatArray( gpuMem, tmp, n );
uint32_t i;
for( i = 0; i < n; ++i ) printf("%f %f\n", tmp[i], x[i]);
axpy_cpu((int)n, -1, x, 1, tmp, 1);
float err = dot_cpu((int)n, tmp, 1, tmp, 1);
printf("Error %s: %f\n", s, sqrt(err / n));
free(tmp);
return err;
};
uint32_t *gpuCUDA::makeIntArray(uint32_t n, uint32_t *hostMem){
uint32_t *x_gpu = NULL;
size_t size = sizeof(int)* n;
m_sStatus = cudaMalloc((void **)&x_gpu, size);
if (!checkError() || x_gpu == NULL){
LOG_ERROR("cudaMalloc FAILED!");
return NULL;
};
if (hostMem){
m_sStatus = cudaMemcpy(x_gpu, hostMem, size, cudaMemcpyHostToDevice);
if (!checkError()){
LOG_ERROR("cudaMemcpy FAILED!");
cudaFree(x_gpu);
return NULL;
};
};
return x_gpu;
};
bool gpuCUDA::freeMem(void *gpuMem){
m_sStatus = cudaFree(gpuMem);
return checkError();
};
bool gpuCUDA::pushFloatArray(float *gpuMem, float *hostMem, uint32_t n){
uint32_t size = (uint32_t)sizeof(float)*n;
m_sStatus = cudaMemcpy(gpuMem, hostMem, size, cudaMemcpyHostToDevice);
return checkError();
};
bool gpuCUDA::pullFloatArray(float *gpuMem, float *hostMem, uint32_t n){
uint32_t size = (uint32_t) sizeof(float)*n;
m_sStatus = cudaMemcpy(hostMem, gpuMem, size, cudaMemcpyDeviceToHost);
return checkError();
};
bool gpuCUDA::pushIntArray(uint32_t *gpuMem, uint32_t *hostMem, uint32_t n){
uint32_t size = (uint32_t)sizeof(int)*n;
m_sStatus = cudaMemcpy(gpuMem, hostMem, size, cudaMemcpyHostToDevice);
return checkError();
};
bool gpuCUDA::pullIntArray(uint32_t *gpuMem, uint32_t *hostMem, uint32_t n){
uint32_t size = (uint32_t) sizeof(int)*n;
m_sStatus = cudaMemcpy(hostMem, gpuMem, size, cudaMemcpyDeviceToHost);
return checkError();
};
bool gpuCUDA::gemm_ongpu(uint32_t TA, uint32_t TB, uint32_t M, uint32_t N, uint32_t K, float ALPHA,
float *A_gpu, uint32_t lda,
float *B_gpu, uint32_t ldb,
float BETA,
float *C_gpu, uint32_t ldc){
cublasHandle_t handle = getBlasHandle();// blas_handle();
if( handle != NULL ){
char tBuffer[128];
sprintf( tBuffer, "GEMM on BLAS [%p]", handle );
LOG(tBuffer);
cublasStatus_t bla_st;
bla_st = cublasSgemm( handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N), (TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb, A_gpu, lda, &BETA, C_gpu, ldc);
return checkError();
} else {
LOG_ERROR("Blas handle error");
};
return false;
};
void gpuCUDA::gemm(uint32_t TA, uint32_t TB, uint32_t M, uint32_t N, uint32_t K, float ALPHA,
float *A, uint32_t lda,
float *B, uint32_t ldb,
float BETA,
float *C, uint32_t ldc){
float *A_gpu = makeFloatArray((TA ? lda*K : lda*M), A);
float *B_gpu = makeFloatArray((TB ? ldb*N : ldb*K), B);
float *C_gpu = makeFloatArray(ldc*M, C);
gemm_ongpu(TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc);
pullFloatArray(C_gpu, C, ldc*M);
freeMem(A_gpu);
freeMem(B_gpu);
freeMem(C_gpu);
};
bool gpuCUDA::makeTestAccuracy(uint32_t TA, uint32_t TB, uint32_t m, uint32_t k, uint32_t n){
return false;
};
bool gpuCUDA::makeTestBlas(void){
return false;
};
bool gpuCUDA::calcScaleBias(float *output, float *biases, uint32_t batch, uint32_t n, uint32_t size){
return false;
};
bool gpuCUDA::calcTimeRandomMatrix(uint32_t TA, uint32_t TB, uint32_t m, uint32_t k, uint32_t n){
return false;
};
bool gpuCUDA::calcTime(uint32_t TA, uint32_t TB, uint32_t m, uint32_t k, uint32_t n){
return false;
};
/*
Defined in CU source
float gpuCUDA::trainNetworkDatum(basicCortex *net, float *X, float *Y){
cortexSTATE tState;
memset(&tState, 0, sizeof(cortexSTATE));
{
uint64_t tVal = net->getSeen();
tVal += net->getBatch();
net->setSeen(tVal);
}
tState.index = 0;
tState.net = net;
uint16_t x_size = net->getInputSize()*net->getBatch();
uint16_t y_size;
if( net->getOutputLayer()->getTruthSize() > 0 ){ //ToDo: Check if the Output Layer is the Last one in the Network
y_size = net->getOutputLayer()->getTruthSize() * net->getBatch();
} else {
y_size = net->getOtputSize()*net->getBatch();
};
float *tPtr;
tPtr = net->getGpuInput();
if ( tPtr == NULL ){
net->setGpuInput(makeFloatArray(x_size, X));//cuda_make_array(X, x_size);
net->setGpuTruth(makeFloatArray(y_size, Y));//cuda_make_array( Y, y_size);
} else {
pushFloatArray(net->getGpuInput(), X, x_size);//cuda_push_array(*net.input_gpu, X, x_size);
pushFloatArray(net->getGpuTruth(), Y, y_size);//cuda_push_array(*net.truth_gpu, Y, y_size);
};
tState.input = net->getGpuInput();
tState.delta = NULL;
tState.truth = net->getGpuTruth();
tState.train = true;
forwardNetwork( net, tState);
backwardNetwork( net, tState);
float error = net->getCost();
if (((net->getSeen()/net->getBatch()) % net->getSubdivisions()) == 0) updateNetwork(net);
return error;
}; */
/********************************
Original DN module
*******************************/
/*
void cuda_set_device(int n){
gpu_index = n;
printf("Set CUDA device[%d] ... ", n);
cudaError_t status = cudaSetDevice(n);
if (status == 0) printf("OK\n");
check_error(status);
}
int cuda_get_device(){
int n = 0;
printf("Ged CUDA device ... ");
cudaError_t status = cudaGetDevice(&n);
if (status == 0)printf("device[%d] - OK\n", n );
check_error(status);
return n;
}
void check_error(cudaError_t status){
cudaDeviceSynchronize();
cudaError_t status2 = cudaGetLastError();
if (status != cudaSuccess)
{
const char *s = cudaGetErrorString(status);
char buffer[256];
printf("CUDA Error: %s\n", s);
assert(0);
snprintf(buffer, 256, "CUDA Error: %s", s);
error(buffer);
}
if (status2 != cudaSuccess)
{
const char *s = cudaGetErrorString(status);
char buffer[256];
printf("CUDA Error Prev: %s\n", s);
assert(0);
snprintf(buffer, 256, "CUDA Error Prev: %s", s);
error(buffer);
}
}
dim3 cuda_gridsize(unsigned int n){
unsigned int k = (n-1) / BLOCK + 1;
unsigned int x = k;
unsigned int y = 1;
if(x > 65535){
x = (unsigned int)ceil(sqrt((double)k));
y = (unsigned int)(n - 1) / (x*BLOCK) + 1;
}
dim3 d = {x, y, 1};
printf("%ld %ld %ld %ld\n", n, x, y, x*y*BLOCK);
return d;
}
#ifdef CUDNN
cudnnHandle_t cudnn_handle()
{
static int init[16] = {0};
static cudnnHandle_t handle[16];
int i = cuda_get_device();
if(!init[i]) {
cudnnCreate(&handle[i]);
init[i] = 1;
}
return handle[i];
}
#endif
cublasHandle_t blas_handle()
{
static int init[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static cublasHandle_t handle[16] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
int i = cuda_get_device();
printf("CUDA device ID: %d\n",i );
if(!init[i]) {
printf("Create new BLAS handle ... ");
cublasCreate(&handle[i]);
if(handle[i]){
init[i] = 1;
printf("blas[%p] - OK\n", handle[i] );
} else {
printf("FAIL\n");
};
};
return handle[i];
};
float *cuda_make_array(float *x, unsigned int n)
{
float *x_gpu;
unsigned int size = (unsigned int)sizeof(float)*n;
cudaError_t status = cudaMalloc((void **)&x_gpu, size);
check_error(status);
if(x){
status = cudaMemcpy(x_gpu, x, size, cudaMemcpyHostToDevice);
check_error(status);
}
if(!x_gpu) error("Cuda malloc failed\n");
return x_gpu;
}
void cuda_random(float *x_gpu, unsigned int n)
{
static curandGenerator_t gen[16];
static int init[16] = {0};
int i = cuda_get_device();
if(!init[i]){
curandCreateGenerator(&gen[i], CURAND_RNG_PSEUDO_DEFAULT);
curandSetPseudoRandomGeneratorSeed(gen[i], time(0));
init[i] = 1;
}
curandGenerateUniform(gen[i], x_gpu, n);
check_error(cudaPeekAtLastError());
}
float cuda_compare(float *x_gpu, float *x, unsigned int n, char *s)
{
float *tmp = (float*) calloc(n, sizeof(float));
cuda_pull_array(x_gpu, tmp, n);
unsigned int i;
for(i = 0; i < n; ++i) printf("%f %f\n", tmp[i], x[i]);
axpy_cpu(n, -1, x, 1, tmp, 1);
float err = dot_cpu(n, tmp, 1, tmp, 1);
printf("Error %s: %f\n", s, sqrt(err/n));
free(tmp);
return err;
}
int *cuda_make_int_array( unsigned int n)
{
int *x_gpu;
size_t size = sizeof(int)*n;
cudaError_t status = cudaMalloc((void **)&x_gpu, size);
check_error(status);
return x_gpu;
}
void cuda_free(float *x_gpu)
{
cudaError_t status = cudaFree(x_gpu);
check_error(status);
}
void cuda_push_array(float *x_gpu, float *x, unsigned int n)
{
unsigned int size = (unsigned int)sizeof(float)*n;
cudaError_t status = cudaMemcpy(x_gpu, x, size, cudaMemcpyHostToDevice);
check_error(status);
}
void cuda_pull_array(float *x_gpu, float *x, unsigned int n)
{
unsigned int size = (unsigned int) sizeof(float)*n;
cudaError_t status = cudaMemcpy(x, x_gpu, size, cudaMemcpyDeviceToHost);
check_error(status);
}
*/
#undef LOG
#undef LOG_ERROR
#endif