serial_no
int64
1
24.2k
cuda_source
stringlengths
11
9.01M
5,701
#include <cstdio> int main(void) { int count; cudaGetDeviceCount(&count); printf("%d devices found supporting CUDA\n", count); char split[] = "----------------------------------\n"; cudaDeviceProp p; for(int d = 0; d < count; d++){ cudaGetDeviceProperties(&p, d); printf("%s", split); printf("Device %s\n", p.name); printf("%s", split); printf(" Device memory: \t%zu\n", p.totalGlobalMem); printf(" Memory per-block: \t%lu\n", p.sharedMemPerBlock); printf(" Register per-block: \t%d\n", p.regsPerBlock); printf(" Warp size: \t\t%d\n", p.warpSize); printf(" Memory pitch: \t\t%lu\n", p.memPitch); printf(" Constant Memory: \t%lu\n", p.totalConstMem); printf(" Max thread per-block: \t%d\n", p.maxThreadsPerBlock); printf(" Max thread dim: \t%d / %d / %d\n", p.maxThreadsDim[0], p.maxThreadsDim[1], p.maxThreadsDim[2]); printf(" Max grid size: \t%d / %d / %d\n", p.maxGridSize[0], p.maxGridSize[1], p.maxGridSize[2]); printf(" Ver: \t\t\t%d.%d\n", p.major, p.minor); printf(" Clock: \t\t%d\n", p.clockRate); printf(" Texture Alignment: \t%lu\n", p.textureAlignment); } return 0; }
5,702
#include <stdio.h> #include <stdlib.h> #include <time.h> __global__ void blur_kernel(float *image,float *filter,float *blurred,int r,int c,float filter_sum) { int row=blockIdx.x*blockDim.x + threadIdx.x; int col=blockIdx.y*blockDim.y + threadIdx.y; int above=row-1; int below=row+1; int left=col-1; int right=col+1; int total_sum=0; // Checking conditions for each pixel value if(0<=above&&above<r){ if(0<=left&&left<c) total_sum+=(image[above*c+left]*filter[0*3+0]); if(0<=col&&col<c) total_sum+=(image[above*c+col]*filter[0*3+1]); if(0<=right&&right<c) total_sum+=(image[above*c+right]*filter[0*3+2]); } if(0<=row&&row<r){ if(0<=left&&left<c) total_sum+=(image[row*c+left]*filter[1*3+0]); if(0<=col&&col<c) total_sum+=(image[row*c+col]*filter[1*3+1]); if(0<=right&&right<c) total_sum+=(image[row*c+right]*filter[1*3+2]); } if(0<=below&&below<r){ if(0<=left&&left<c) total_sum+=(image[below*c+left]*filter[2*3+0]); if(0<=col&&col<c) total_sum+=(image[below*c+col]*filter[2*3+1]); if(0<=right&&right<c) total_sum+=(image[below*c+right]*filter[2*3+2]); } if((0<=row&&row<r)&&(0<=col&&col<c)) blurred[row*c+col]=total_sum/filter_sum; } int main() { srand(time(NULL)); // Image of size 1000*768 int dimx=1000; int dimy=768; // Device variables and memory allocation float *image,*filter,*blurred; image=(float*)malloc(sizeof(float)*dimx*dimy); filter=(float*)malloc(sizeof(float)*3*3); blurred=(float*)malloc(sizeof(float)*dimx*dimy); // Assigning fixed values to the filter matrix filter[0*3+0]=1; filter[0*3+1]=2; filter[0*3+2]=1; filter[1*3+0]=2; filter[1*3+1]=3; filter[1*3+2]=2; filter[2*3+0]=1; filter[2*3+1]=2; filter[2*3+2]=1; // Assigning random values between 0 and 255 to the image matrix for(int i=0;i<dimx;i++) { for(int j=0;j<dimy;j++) { image[i*dimy+j]=rand()%256; } } // Device variables and memory allocation float *d_image,*d_filter,*d_blurred; cudaMalloc((void**)&d_image,sizeof(float)*dimx*dimy); cudaMalloc((void**)&d_filter,sizeof(float)*3*3); cudaMalloc((void**)&d_blurred,sizeof(float)*dimx*dimy); // Copying the image and filter matrix to device memory cudaMemcpy(d_image,image,sizeof(float)*dimx*dimy,cudaMemcpyHostToDevice); cudaMemcpy(d_filter,filter,sizeof(float)*3*3,cudaMemcpyHostToDevice); // Grid and block dimensions dim3 gridDim(63,48); dim3 blockDim(16,16,1); // Calling the kernel blur_kernel<<<gridDim,blockDim>>>(d_image,d_filter,d_blurred,dimx,dimy,15.0); // Copying the blurred image from device to host cudaMemcpy(blurred,d_blurred,sizeof(float)*dimx*dimy,cudaMemcpyDeviceToHost); // Printing original image printf("Original Image\n"); for(int i=0;i<dimx;i++) { for(int j=0;j<dimy;j++) { printf("%f ",image[i*dimy+j]); } printf("\n"); } // Printing blurred image printf("\n\nBlurred Image\n"); for(int i=0;i<dimx;i++) { for(int j=0;j<dimy;j++) { printf("%f ",blurred[i*dimy+j]); } printf("\n"); } // Freeing up memory free(image); free(filter); free(blurred); cudaFree(d_image); cudaFree(d_filter); cudaFree(d_blurred); return 0; }
5,703
#include <stdio.h> #include <sys/time.h> #include <cuda_runtime.h> #include <math.h> extern "C" void initialData(float *ip, int size) { for (int i=0; i < size; i++) { ip[i] = (float)rand()/(float)(RAND_MAX/10.0); } } extern "C" void printHello(void) { printf("HELLO from C\n"); } extern "C" void print_matrix(float *c, const int nx, const int ny) { float *ic = c; for (int iy=0; iy<ny; iy++) { for (int ix=0; ix<nx; ix++) { printf("%6.2f", ic[ix]); } ic += nx; printf("\n"); } printf("\n"); } __global__ void print_thread_index(float* a, const int nx, const int ny) { int ix = threadIdx.x + blockIdx.x * blockDim.x; int iy = threadIdx.y + blockIdx.y * blockDim.y; unsigned int idx = iy*nx + ix; printf("thread_id (%d, %d) block_id (%d, %d) coordinate (%d, %d)" "global index %2d ival %2d\n", threadIdx.x, threadIdx.y, blockIdx.x, blockIdx.y, ix, iy, idx, a[idx]); } extern "C" void test() { int dev = 0; cudaSetDevice(dev); int nx = 4; int ny = 4; int nxy = nx*ny; int nbytes = nxy * sizeof(float); float *h_A; h_A = (float *) malloc(nbytes); initialData(h_A, nx*ny); print_matrix(h_A, nx, ny); float *d_A; cudaMalloc((void **) &d_A, nbytes); cudaMemcpy(d_A, h_A, nbytes, cudaMemcpyHostToDevice); dim3 block(4, 2); dim3 grid ((nx+block.x-1)/block.x, (ny+block.y-1)/block.y); print_thread_index <<< grid, block >>>(d_A, nx, ny); cudaDeviceSynchronize(); cudaFree(d_A); free(h_A); cudaDeviceReset(); }
5,704
#include <stdio.h> #include <math.h> __global__ void checkPositions(double2* rnew,int N, double L){ int tid = threadIdx.x + blockIdx.x*blockDim.x; if (tid < N){ if (fabs(rnew[tid].x) > L/2.0) printf("Thread %d: r.x = %lf\n",tid,rnew[tid].x); if (fabs(rnew[tid].y) > L/2.0) printf("Thread %d: r.y = %lf\n",tid,rnew[tid].y); } }
5,705
#include "includes.h" __global__ void global_reduction_kernel(float *data_out, float *data_in, int stride, int size) { int idx_x = blockIdx.x * blockDim.x + threadIdx.x; if (idx_x + stride < size) { data_out[idx_x] += data_in[idx_x + stride]; } }
5,706
#include "portfolio.cuh" #include <math.h> #include <numeric> #include <algorithm> #include <stdexcept> #include <iostream> #include <iomanip> #include <stdio.h> namespace fin { CUDA_CALLABLE_MEMBER Portfolio::Portfolio() { int size = 20; this->size = size; this->assets = new Asset* [size]; this->weights = new float [size]; } CUDA_CALLABLE_MEMBER Portfolio::Portfolio(int size) { this->size = size; this->assets = new Asset* [size]; this->weights = new float [size]; } CUDA_CALLABLE_MEMBER Portfolio::Portfolio(const Portfolio& portfolio) { this->size = portfolio.size; this->assets = new Asset* [this->size]; this->weights = new float [this->size]; // deep copy assets and weights for (int i = 0; i < this->size; ++i) { this->assets[i] = portfolio.assets[i]; this->weights[i] = portfolio.weights[i]; } } CUDA_CALLABLE_MEMBER Portfolio::~Portfolio() { delete[] this->assets; delete[] this->weights; } CUDA_CALLABLE_MEMBER Portfolio Portfolio::operator=(const Portfolio& portfolio) { this->size = portfolio.size; this->assets = new Asset* [this->size]; this->weights = new float [this->size]; // deep copy assets and weights for (int i = 0; i < this->size; ++i) { this->assets[i] = portfolio.assets[i]; this->weights[i] = portfolio.weights[i]; } return *this; } CUDA_CALLABLE_MEMBER int Portfolio::get_size() const { return this->size; } CUDA_CALLABLE_MEMBER Asset** Portfolio::get_assets() const { return this->assets; } CUDA_CALLABLE_MEMBER float* Portfolio::get_weights() const { return this->weights; } CUDA_CALLABLE_MEMBER void Portfolio::set_assets(Asset** assets) { for (int i = 0; i < this->size; ++i) this->assets[i] = assets[i]; } CUDA_CALLABLE_MEMBER void Portfolio::set_weights(float* weights) { // check if weights sum to 1 float sum = 0; for (int i = 0; i < this->size; ++i) sum += weights[i]; float eps = 0.01; if (sum >= 1 - eps && sum <= 1 + eps) for (int i = 0; i < this->size; ++i) this->weights[i] = weights[i]; // set weights else printf("Weights must sum to 1\n"); } CUDA_CALLABLE_MEMBER float* Portfolio::get_returns(hlp::Date start_date, hlp::Date end_date) const { // returns a list of return for each asset // allocate memory for daily returns float* returns = new float[this->size]; // set daily returns for (int i = 0; i < this->size; ++i) returns[i] = this->assets[i]->get_return(start_date, end_date); return returns; } CUDA_CALLABLE_MEMBER float Portfolio::get_return(hlp::Date start_date, hlp::Date end_date) const { float ret = 0.0; for (int i = 0; i < this->size; ++i) { float r = this->assets[i]->get_return(start_date, end_date); float w = this->weights[i]; ret += w * r; } return ret; } CUDA_CALLABLE_MEMBER float* Portfolio::get_covariance(hlp::Date start_date, hlp::Date end_date) const { float* covariance = new float[this->size * this->size]; for (int i = 0; i < this->size; ++i) { for (int j = 0; j < this->size; ++j) { if (j < i) // covariance is symetric, just copy the other half covariance[i * this->size + j] = covariance[j * this->size + i]; else { // get daily returns of assets i and j int n; float* ri = this->assets[i]->get_returns(start_date, end_date, &n); float* rj = this->assets[j]->get_returns(start_date, end_date, &n); // get average return of assets i and j float ri_avg = 0; float rj_avg = 0; for (int k = 0; k < n; ++k) { ri_avg += ri[k]; rj_avg += rj[k]; } ri_avg /= n; rj_avg /= n; // compute covariance between the assets i and j covariance[i * this->size + j] = 0; for (int k = 0; k < n; ++k) covariance[i * this->size + j] += (ri[k] - ri_avg) * (rj[k] - rj_avg); covariance[i * this->size + j] /= n; // freeing ri and rj delete[] ri; delete[] rj; } } } return covariance; } CUDA_CALLABLE_MEMBER float Portfolio::get_volatility(hlp::Date start_date, hlp::Date end_date) const { float vol = 0; float* cov = this->get_covariance(start_date, end_date); for (int i = 0; i < this->size; ++i) { for (int j = 0; j < this->size; ++j) { float wi = this->weights[i]; float wj = this->weights[j]; vol += wi * wj * cov[i * this->size + j]; } } //free covariance delete[] cov; return sqrtf(vol); } CUDA_CALLABLE_MEMBER float Portfolio::get_sharp(hlp::Date start_date, hlp::Date end_date) const { float ret = this->get_return(start_date, end_date); float vol = this->get_volatility(start_date, end_date); return ret / vol; } void Portfolio::print_weights() const { for (int i = 0; i < this->size; ++i) { float w = this->weights[i]; std::cout << std::fixed << std::setprecision(2) << w << "|"; } std::cout << std::endl; } }
5,707
/* * Parakeet * * (c) 2009-2012 Eric Hielscher, Alex Rubinsteyn * * GPU Probe * * Utility for detecting main GPU characteristics of the given * computer for use in Parakeet's code optimization. * * Outputs an XML file with the gathered information for use by the Parakeet * runtime. */ #include <cuda_runtime_api.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> // Data structures to hold the machine characteristics typedef struct { int id; cudaDeviceProp deviceProp; int *accessiblePeers; int numAccessiblePeers; int globalMemspace; float globalPeakBw; } gpu_t; typedef struct { int id; uint64_t bytes; } memspace_t; typedef struct { int srcId; int *dstIds; int numDsts; float bw; } mem_xfer_bw_t; // Helper functions to add and free the memory transfer b/w structs void add_xfer_bw(mem_xfer_bw_t **bws, int numBws, int numDsts) { mem_xfer_bw_t *tmp = (mem_xfer_bw_t*)malloc((numBws + 1) * sizeof(mem_xfer_bw_t)); if (*bws) { memcpy(tmp, *bws, numBws * sizeof(mem_xfer_bw_t)); free(*bws); } *bws = tmp; (*bws)[numBws].dstIds = (int*)malloc(numDsts * sizeof(int)); (*bws)[numBws].numDsts = numDsts; } void free_xfer_bws(mem_xfer_bw_t *bws, int numBws) { if (!bws) return; int i; for (i = 0; i < numBws; ++i) { free(bws[i].dstIds); } free(bws); } void chkError(int rslt, char *msg) { if (rslt != 0) { printf("%s: %d\n", msg, rslt); exit(1); } } // Timer helper functions double diff_timers(struct timeval *start, struct timeval *end) { double ret; if (end->tv_usec < start->tv_usec) { int nsec = (start->tv_usec - end->tv_usec) / 1000000 + 1; start->tv_usec -= 1000000 * nsec; start->tv_sec += nsec; } if (end->tv_usec - start->tv_usec > 1000000) { int nsec = (end->tv_usec - start->tv_usec) / 1000000; start->tv_usec += 1000000 * nsec; start->tv_sec -= nsec; } ret = (end->tv_sec - start->tv_sec) + (end->tv_usec - start->tv_usec) / 1000000.0; free(start); free(end); return ret; } struct timeval *gettime(void) { struct timeval *ret = (struct timeval*)(malloc(sizeof(struct timeval))); gettimeofday(ret, NULL); return ret; } // Global state const int RAMID = 0; const int PINNEDID = 1; const int GPUOFFSET = 2; mem_xfer_bw_t *bws = NULL; int numBws = 0; gpu_t *gpus = NULL; int numDevices = 0; int *ram_data; int *pinned_data; int **dev_datas; FILE *outfile; struct timeval *start, *end; int debug; // Test the memory transfer bandwidth between the src and all the destination // devices in the bitmask devs void test_mem_xfer_bw(int *src_data, int data_size, int srcId, int devs, char *src_name) { int curNumDevs = __builtin_popcount(devs); add_xfer_bw(&bws, numBws, curNumDevs); bws[numBws].srcId = srcId; int curDev = 0; int i; for (i = 0; i < numDevices; ++i) { chkError(cudaSetDevice(i), "Couldn't set device"); cudaStreamSynchronize(0); } start = gettime(); for (i = 0; i < numDevices; ++i) { if ((1 << i) & devs) { chkError(cudaSetDevice(i), "Couldn't set device"); chkError(cudaMemcpy(dev_datas[i], src_data, data_size, cudaMemcpyHostToDevice), "Couldn't copy data from RAM to GPU"); bws[numBws].dstIds[curDev++] = i + GPUOFFSET; } } for (i = 0; i < numDevices; ++i) { chkError(cudaSetDevice(i), "Couldn't set device"); cudaStreamSynchronize(0); } end = gettime(); bws[numBws].bw = data_size * curNumDevs / diff_timers(start, end) / (1 << 30); numBws++; if (debug) { if (curNumDevs == 1) { printf("%s to GPU %d B/W: %f\n", src_name, bws[numBws - 1].dstIds[0], bws[numBws - 1].bw); } else { printf("%s to %d GPUs B/W: %f\n", src_name, curNumDevs, bws[numBws - 1].bw); } } } int main(int argc, char **argv) { int i, j; // Set up program parameters // TODO: We assume here that any GPU we're going to use has at least 128MB of // global memory. This may not actually be the case. We probably want // to parameterize this so as to scale to any memory size. int data_size = (16 << 20) * sizeof(int); char *outFilename = "parakeetgpuconf.xml"; debug = 1; // Process command line args // Open output file outfile = fopen(outFilename, "w"); if (!outfile) { printf("Couldn't open output file.\n"); exit(1); } // Get number of GPU devices chkError(cudaGetDeviceCount(&numDevices), "Couldn't get number of devices"); if (numDevices > sizeof(int) * 8 - 1) { printf("Can't support more than %d devices\n", sizeof(int) * 8 - 1); exit(1); } // Create a gpu_t struct for each device gpus = (gpu_t*)malloc(numDevices * sizeof(gpu_t)); // Create memspace structs for RAM, pinned RAM and for each device memspace_t *memspaces = (memspace_t*)malloc((numDevices + GPUOFFSET) * sizeof(memspace_t)); for (i = 0; i < numDevices + GPUOFFSET; ++i) { memspaces[i].id = i; } // Set up special RAM memspace // TODO: This probably is Ubuntu-specific; need to make it general. char *cmd = "awk '{if(NR==1){print $2}}' /proc/meminfo"; FILE *cmdfile = popen(cmd, "r"); if (!cmdfile) { printf("Unable to get RAM info.\n"); exit(1); } char buffer[128]; memset(buffer, 0, 128); if (!fgets(buffer, 128, cmdfile)) { printf("Unable to read RAM info from /proc/meminfo.\n"); exit(1); } memspaces[RAMID].bytes = (uint64_t)atol(buffer) * 1024; if (!memspaces[RAMID].bytes) { printf("Unable to convert RAM info to uint64_t.\n"); exit(1); } memspaces[PINNEDID].bytes = memspaces[RAMID].bytes; pclose(cmdfile); // Allocate some memory for doing RAM <-> GPU transfers. ram_data = (int*)malloc(data_size); chkError(cudaMallocHost(&pinned_data, data_size), "Couldn't malloc pinned host mem"); dev_datas = (int**)malloc(numDevices * sizeof(int*)); // For each device, get the properties we're interested in for (i = 0; i < numDevices; ++i) { // Get device properties // TODO: Do we need to store this? Could just re-query every time. chkError(cudaGetDeviceProperties(&gpus[i].deviceProp, i), "Couldn't get properties for device"); // Take into account that RAM = 0 and PinnedRam = 1 gpus[i].globalMemspace = i + GPUOFFSET; memspaces[i+GPUOFFSET].bytes = gpus[i].deviceProp.totalGlobalMem; // Store the calculated peak global memory b/w // TODO: Assumes that all GPUs use DDR, and so uses a x2 multiplier. // If this ever changes, this won't be accurate. gpus[i].globalPeakBw = gpus[i].deviceProp.memoryClockRate * 2.0f / 1000000.0f * gpus[i].deviceProp.memoryBusWidth / 8.0f; if (debug) printf("GPU %d Theoretical Peak Global B/W: %f\n", i, gpus[i].globalPeakBw); // Allocate some device memory space chkError(cudaSetDevice(i), "Couldn't switch GPU devices"); chkError(cudaMalloc(&dev_datas[i], data_size), "Couldn't allocate GPU data"); // Get peer access info gpus[i].numAccessiblePeers = 0; int canAccessPeer; for (j = 0; j < numDevices; ++j) { if (i != j) { chkError(cudaDeviceCanAccessPeer(&canAccessPeer, i, j), "Couldn't get peer access info"); if (canAccessPeer) { gpus[i].numAccessiblePeers++; chkError(cudaDeviceEnablePeerAccess(j, 0), "Couldn't enable peer access"); } } } gpus[i].accessiblePeers = (int*)malloc(gpus[i].numAccessiblePeers * sizeof(int)); int cur = 0; for (j = 0; j < numDevices; ++j) { if (i != j) { chkError(cudaDeviceCanAccessPeer(&canAccessPeer, i, j), "Couldn't get peer access info"); if (canAccessPeer) { gpus[i].accessiblePeers[cur++] = j; // Test P2P memory bandwidth and record chkError(cudaSetDevice(j), "Coudln't switch GPU devices"); int *src_data; chkError(cudaMalloc(&src_data, data_size), "Couldn't allocate peer GPU data"); chkError(cudaSetDevice(i), "Couldn't switch GPU devices"); float peer_bw = 0.0f; cudaStreamSynchronize(0); start = gettime(); chkError(cudaMemcpyPeer(dev_datas[i], i, src_data, j, data_size), "Couldn't copy data between peer devices"); cudaStreamSynchronize(0); end = gettime(); peer_bw = data_size / diff_timers(start, end) / (1 << 30); add_xfer_bw(&bws, numBws, 1); bws[numBws].srcId = gpus[i].globalMemspace; bws[numBws].dstIds[0] = j + GPUOFFSET; bws[numBws].bw = peer_bw; numBws++; if (debug) printf("P2P transfer from %d to %d: %f\n", j, i, peer_bw); chkError(cudaSetDevice(j), "Couldn't switch GPU devices"); chkError(cudaFree(src_data), "Couldn't free peer GPU data"); chkError(cudaSetDevice(i), "Couldn't switch GPU devices"); } } } } // Test RAM <-> devices B/W for every combination of devices int numSets = 1 << numDevices; int devs; for (devs = 1; devs < numSets; ++devs) { // Test RAM <-> GPUs bw test_mem_xfer_bw(ram_data, data_size, RAMID, devs, "RAM"); // Test Pinned RAM <-> GPU bw test_mem_xfer_bw(pinned_data, data_size, PINNEDID, devs, "Pinned RAM"); } // Output XML file with the collected data int outLevel = 0; fprintf(outfile, "<Machine>\n"); outLevel++; for (i = 0; i < numDevices; ++i) { fprintf(outfile, "%*s<GPU>\n", outLevel++, ""); // Print out the contents of the CUDA device properties struct cudaDeviceProp curProp = gpus[i].deviceProp; fprintf(outfile, "%*s<Id>%d</Id>\n", outLevel, "", i); fprintf(outfile, "%*s<DeviceName>%s</DeviceName>\n", outLevel, "", curProp.name); fprintf(outfile, "%*s<TotalGlobalMemory>%ld</TotalGlobalMemory>\n", outLevel, "", curProp.totalGlobalMem); fprintf(outfile, "%*s<SharedMemPerSM>%ld</SharedMemPerSM>\n", outLevel, "", curProp.sharedMemPerBlock); fprintf(outfile, "%*s<RegsPerBlock>%d</RegsPerBlock>\n", outLevel, "", curProp.regsPerBlock); fprintf(outfile, "%*s<WarpSize>%d</WarpSize>\n", outLevel, "", curProp.warpSize); fprintf(outfile, "%*s<MemPitch>%d</MemPitch>\n", outLevel, "", curProp.memPitch); fprintf(outfile, "%*s<MaxThreadsPerBlock>%d</MaxThreadsPerBlock>\n", outLevel, "", curProp.maxThreadsPerBlock); fprintf(outfile, "%*s<MaxThreadsPerDim>\n", outLevel++, ""); fprintf(outfile, "%*s<X>%d</X>\n", outLevel, "", curProp.maxThreadsDim[0]); fprintf(outfile, "%*s<Y>%d</Y>\n", outLevel, "", curProp.maxThreadsDim[1]); fprintf(outfile, "%*s<Z>%d</Z>\n", outLevel, "", curProp.maxThreadsDim[2]); fprintf(outfile, "%*s</MaxThreadsPerDim>\n", --outLevel, ""); fprintf(outfile, "%*s<MaxGridSize>\n", outLevel++, ""); fprintf(outfile, "%*s<X>%d</X>\n", outLevel, "", curProp.maxGridSize[0]); fprintf(outfile, "%*s<Y>%d</Y>\n", outLevel, "", curProp.maxGridSize[1]); fprintf(outfile, "%*s<Z>%d</Z>\n", outLevel, "", curProp.maxGridSize[2]); fprintf(outfile, "%*s</MaxGridSize>\n", --outLevel, ""); fprintf(outfile, "%*s<ClockRate>%f</ClockRate>\n", outLevel, "", curProp.clockRate / 1024.0f / 1024.0f); fprintf(outfile, "%*s<TotalConstMem>%d</TotalConstMem>\n", outLevel, "", curProp.totalConstMem); // Print out the other data if (gpus[i].numAccessiblePeers > 0) { fprintf(outfile, "%*s<AccessiblePeers>\n", outLevel++, ""); for (j = 0; j < gpus[i].numAccessiblePeers; ++j) { fprintf(outfile, "%*s<AccessiblePeer>%d</AccessiblePeer>\n", outLevel, "", gpus[i].accessiblePeers[j]); } fprintf(outfile, "%*s</AccessiblePeers>\n", --outLevel, ""); } fprintf(outfile, "%*s<GlobalMemspace>%d</GlobalMemspace>\n", outLevel, "", gpus[i].globalMemspace); fprintf(outfile, "%*s<TheoreticalPeakGlobalBW>%f</TheoreticalPeakGlobalBW>\n", outLevel, "", gpus[i].globalPeakBw); fprintf(outfile, "%*s</GPU>\n", --outLevel, ""); } // Print out Memspace info for (i = 0; i < numDevices + GPUOFFSET; ++i) { fprintf(outfile, "%*s<MemSpace>\n", outLevel++, ""); fprintf(outfile, "%*s<Id>%d</Id>\n", outLevel, "", memspaces[i].id); fprintf(outfile, "%*s<Bytes>%ld</Bytes>\n", outLevel, "", memspaces[i].bytes); fprintf(outfile, "%*s</MemSpace>\n", --outLevel, ""); } // Print out Memory Transfer B/W info for (i = 0; i < numBws; ++i) { fprintf(outfile, "%*s<MemXferBW>\n", outLevel++, ""); fprintf(outfile, "%*s<SrcId>%d</SrcId>\n", outLevel, "", bws[i].srcId); fprintf(outfile, "%*s<DstIds>\n", outLevel++, ""); for (j = 0; j < bws[i].numDsts; ++j) { fprintf(outfile, "%*s<DstId>%d</DstId>\n", outLevel, "", bws[i].dstIds[j]); } fprintf(outfile, "%*s</DstIds>\n", --outLevel, ""); fprintf(outfile, "%*s<BW>%f</BW>\n", outLevel, "", bws[i].bw); fprintf(outfile, "%*s</MemXferBW>\n", --outLevel, ""); } fprintf(outfile, "</Machine>\n"); fclose(outfile); // Free memory and return free(ram_data); cudaFree(pinned_data); for (i = 0; i < numDevices; ++i) { free(gpus[i].accessiblePeers); cudaFree(dev_datas[i]); } free(gpus); free_xfer_bws(bws, numBws); return 0; }
5,708
#include "includes.h" // ERROR CHECKING MACROS ////////////////////////////////////////////////////// __global__ void roadCrossingsKernel(int rows, int segs, int* adjacency, int* cross) { int idx = blockIdx.x*blockDim.x + threadIdx.x; if (idx < rows) { cross[idx] = 0; for (int ii = 0; ii < segs; ii++) { cross[idx] += adjacency[idx*segs + ii]; } } }
5,709
/* * * Accessing out of bound memory from GPU * Vector addition * */ #include <stdio.h> #include <stdlib.h> #include "cuda_runtime.h" #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) { if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } __global__ void vector_addition(double n, int *e_x, int *e_y, int *e_z, int *e_z_copy, int *e_k_copy) { int id = blockIdx.x * blockDim.x + threadIdx.x; if (id < n) { //for (id = 0; id <= n; id++) { e_z[id] = (2*(e_x[id] + e_y[id])); e_k_copy[id] = 1; //if (id == 1000) // e_k_copy[id] = 0; e_z_copy[id] = e_z[id]; if (id == n-1) e_z_copy[id+1000] = e_z[id]; } } int check_results(int *result, int n) { int i = 0; for (i = 0; i < n; i++) { if (result[i] != (2 * (i + i + 2))) { printf("result fails at index %d\n", i); return 0; } } printf("result is correct\n"); return 1; } int check_results2(int *result, int n) { int i = 0; for (i = 0; i < n; i++) { if (result[i] != 1) { printf("result fails at index %d !!\n", i); return 0; } } printf("result is correct !!\n"); return 1; } int main() { int no_el = 268435456; int block_size = 1024; int grid_size = (no_el/block_size) + 1; //ceil doesn't give correct grid size int *h_x, *d_x, *h_y, *d_y, *h_z, *d_z; int *h_z_copy, *d_z_copy; int *h_k_copy, *d_k_copy; h_x = (int*)malloc(no_el*sizeof(int)); h_y = (int*)malloc(no_el*sizeof(int)); h_z = (int*)malloc(no_el*sizeof(int)); h_z_copy = (int*)malloc((no_el-1000)*sizeof(int)); h_k_copy = (int*)malloc(no_el*sizeof(int)); int i = 0; for (i = 0; i < no_el; i++) { h_x[i] = i; h_y[i] = i + 2; h_z[i] = 0; } // printf("allocated x, y, z\n"); for (i = 0; i < (no_el - 1000); i++) { h_z_copy[i] = 0; } for (i = 0; i < no_el; i++) { h_k_copy[i] = 0; } // printf("filled up h_z_copy array\n"); cudaMalloc(&d_x, no_el*sizeof(int)); cudaMalloc(&d_y, no_el*sizeof(int)); cudaMalloc(&d_z, no_el*sizeof(int)); cudaMalloc(&d_z_copy, (no_el-1000)*sizeof(int)); cudaMalloc(&d_k_copy, no_el*sizeof(int)); // printf("cuda malloc succeeded\n"); cudaMemcpy(d_x, h_x, no_el*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_y, h_y, no_el*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_z, h_z, no_el*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_z_copy, h_z_copy, (no_el-1000)*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_k_copy, h_k_copy, no_el*sizeof(int), cudaMemcpyHostToDevice); // printf("cuda memcpy succeeded\n"); while(1) { dim3 block(block_size); dim3 grid(grid_size); vector_addition<<<grid, block>>>(no_el, d_x, d_y, d_z, d_z_copy, d_k_copy); printf("kernel launch succeeded\n"); gpuErrchk(cudaMemcpy(h_z, d_z, no_el*sizeof(int), cudaMemcpyDeviceToHost)); gpuErrchk(cudaMemcpy(h_k_copy, d_k_copy, no_el*sizeof(int), cudaMemcpyDeviceToHost)); printf("copied result from gpu to cpu successfully\n"); int valid = check_results(h_z, no_el); if (valid == 0) { printf("wrong computation result\n"); //break; } int valid2 = check_results2(h_k_copy, no_el); if (valid2 == 0) { printf("wrong computation result !!\n"); //break; } } cudaFree(d_x); cudaFree(d_y); cudaFree(d_z); cudaFree(d_z_copy); free(h_x); free(h_y); free(h_z); free(h_z_copy); }
5,710
#include "includes.h" __global__ void add(int a, int b, int *c) { //Add 2 numbers together and store in location pointed by *c *c = a + b; }
5,711
#include "includes.h" extern "C" // don't forget to compile with "nvcc -ptx cudaKernel.cu -o cudaKernel.ptx // And to move the ptx file in the resources ! __global__ void add(int n, float* a, float* b, float* sum) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n; i += stride) sum[i] = a[i] + b[i]; }
5,712
#include <stdio.h> #include <iostream> #define CUDA_SAFE_CALL(call) \ do { \ cudaError_t err = call; \ if (cudaSuccess != err) { \ fprintf (stderr, "Cuda error in file '%s' in line %i : %s.", \ __FILE__, __LINE__, cudaGetErrorString(err) ); \ exit(EXIT_FAILURE); }} while (0) typedef float data_t; //typedef double data_t; using namespace std; struct cell_t { data_t vr = 0, vz = 0, P = 0, rho = 0, T = 0; bool is_wall = false; __host__ __device__ cell_t operator+(const cell_t& c) const { cell_t d; d.vr=vr+c.vr; d.vz=vz+c.vz; d.P=P+c.P; d.rho=rho+c.rho; d.T=T+c.T; d.is_wall=is_wall; return d; } __host__ __device__ cell_t operator-(const cell_t& c) const { cell_t d; d.vr=vr+c.vr; d.vz=vz+c.vz; d.P=P+c.P; d.rho=rho+c.rho; d.T=T+c.T; d.is_wall=is_wall; return d; } __host__ __device__ cell_t operator*(const data_t& f) const { cell_t d; d.vr=vr*f; d.vz=vz*f; d.P=P*f; d.rho=rho*f; d.T=T*f; d.is_wall=is_wall; return d; } __host__ __device__ cell_t operator/(const data_t& f) const { cell_t d; d.vr=vr/f; d.vz=vz/f; d.P=P/f; d.rho=rho/f; d.T=T/f; d.is_wall=is_wall; return d; } }; __host__ ostream& operator<<(ostream& os, const cell_t& c) { os << "(" << c.vr << ", " << c.vz << ", " << c.rho << ", " << c.T << ", " << c.P << ")"; return os; } __global__ void cuda_operator_plus(cell_t* C, cell_t* A, cell_t* B, int size_i, int size_j) { int i = blockIdx.x*blockDim.x+threadIdx.x; int j = blockIdx.y*blockDim.y+threadIdx.y; if (i>=size_i || j>=size_j) return; C[j*size_i+i] = A[j*size_i+i] + B[j*size_i+i]; } __global__ void cuda_operator_minus(cell_t* C, cell_t* A, cell_t* B, int size_i, int size_j) { int i = blockIdx.x*blockDim.x+threadIdx.x; int j = blockIdx.y*blockDim.y+threadIdx.y; if (i>=size_i || j>=size_j) return; C[j*size_i+i] = A[j*size_i+i] - B[j*size_i+i]; } __global__ void cuda_operator_times(cell_t* B, cell_t* A, data_t f, int size_i, int size_j) { int i = blockIdx.x*blockDim.x+threadIdx.x; int j = blockIdx.y*blockDim.y+threadIdx.y; if (i>=size_i || j>=size_j) return; B[j*size_i+i] = A[j*size_i+i] * f; } __global__ void cuda_operator_divided(cell_t* B, cell_t* A, data_t f, int size_i, int size_j) { int i = blockIdx.x*blockDim.x+threadIdx.x; int j = blockIdx.y*blockDim.y+threadIdx.y; if (i>=size_i || j>=size_j) return; B[j*size_i+i] = A[j*size_i+i] / f; } struct dev_meshgrid_t { int size_i, size_j; cell_t* d_data = NULL; //int zone {IN=0, LEFT=1, BELOW=2, RIGHT=3, ABOVE=4} // ~dev_meshgrid_t() {} __device__ inline cell_t& dat(int i, int j) { int zone = (i<0) + 2*(j<0) + 3*(i>size_i-1) + 4*(j>size_j-1); switch (zone) { case 0: return d_data[j*size_i+i]; case 1: return d_data[j*size_i]; case 2: return d_data[i]; case 3: return d_data[j*size_i+size_i-1]; case 4: return d_data[(size_j-1)*size_i+i]; default: printf("completely outside : %d %d\n", i, j); return d_data[0]; } } __device__ inline const cell_t& cdat(int i, int j) const { int zone = (i<0) + 2*(j<0) + 3*(i>size_i-1) + 4*(j>size_j-1); switch (zone) { case 0: return d_data[j*size_i+i]; case 1: return d_data[j*size_i]; case 2: return d_data[i]; case 3: return d_data[j*size_i+size_i-1]; case 4: return d_data[(size_j-1)*size_i+i]; default: printf("completely outside : %d %d\n", i, j); return d_data[0]; } } }; struct meshgrid_t { int size_i = 0, size_j = 0; dim3 gridsize, blocksize; cell_t *h_data = NULL, *d_data = NULL; dev_meshgrid_t *d_m = NULL; bool free_mem = true; __host__ meshgrid_t() {} __host__ meshgrid_t(const meshgrid_t& m); __host__ meshgrid_t(int _size_i, int _size_j, dim3 _gridsize, dim3 _blocksize); __host__ ~meshgrid_t(); __host__ void cpy_prop_new_data(const meshgrid_t& m); __host__ void reserve_host_data(); __host__ meshgrid_t operator+(const meshgrid_t& m) const; __host__ meshgrid_t operator-(const meshgrid_t& m) const; __host__ meshgrid_t operator*(const data_t& f) const; __host__ meshgrid_t operator/(const data_t& f) const; // __host__ // meshgrid_t& operator=(meshgrid_t&& m) noexcept; __host__ meshgrid_t& operator=(const meshgrid_t& m); __host__ data_t compare(const meshgrid_t& m) const; __host__ bool equivalent(const meshgrid_t& m) const; __host__ void data_to_host() ; __host__ const cell_t& cat(int i, int j) const; __host__ cell_t& at(int i, int j) ; }; __host__ ostream& operator<<(ostream& os, const meshgrid_t& m) { for (int j=0; j<m.size_j; j++) { for (int i=0; i<m.size_i; i++) cout << m.cat(i, j) << " "; cout << endl; } return os; } __host__ meshgrid_t::meshgrid_t(const meshgrid_t& m) { *this = m; } __host__ meshgrid_t::meshgrid_t(int _size_i, int _size_j, dim3 _gridsize, dim3 _blocksize) : size_i(_size_i), size_j(_size_j), gridsize(_gridsize), blocksize(_blocksize) { CUDA_SAFE_CALL(cudaMalloc(&d_data, sizeof(cell_t)*size_i*size_j)); if (!d_data) printf("could not allocate device memory (init, data)\n"); dev_meshgrid_t tmp; tmp.size_i = size_i; tmp.size_j = size_j; tmp.d_data = d_data; CUDA_SAFE_CALL(cudaMalloc(&d_m, sizeof(dev_meshgrid_t))); if (!d_m) printf("could not allocate device memory (init, dm)\n"); CUDA_SAFE_CALL(cudaMemcpy(d_m, &tmp, sizeof(dev_meshgrid_t), cudaMemcpyHostToDevice)); } __host__ meshgrid_t::~meshgrid_t() { if (free_mem) { // printf("d_data free (this)%p (device)%p (host)%p\n", this, d_data, h_data); if (d_data) CUDA_SAFE_CALL(cudaFree(d_data)); if (d_m) CUDA_SAFE_CALL(cudaFree(d_m)); if (h_data) free(h_data); } } __host__ void meshgrid_t::cpy_prop_new_data(const meshgrid_t& m) { gridsize = m.gridsize; blocksize = m.blocksize; if(size_i != m.size_i || size_j != m.size_j) { size_i = m.size_i; size_j = m.size_j; if (d_data) CUDA_SAFE_CALL(cudaFree(d_data)); CUDA_SAFE_CALL(cudaMalloc(&d_data, sizeof(cell_t)*size_i*size_j)); if (!d_data) printf("could not allocate device memory (cpy, data)\n"); if (h_data) h_data = (cell_t*) realloc(h_data, sizeof(size_i*size_j)); dev_meshgrid_t tmp; tmp.size_i = size_i; tmp.size_j = size_j; tmp.d_data = d_data; if (!d_m) CUDA_SAFE_CALL(cudaMalloc(&d_m, sizeof(dev_meshgrid_t))); if (!d_m) printf("could not allocate device memory (cpy, dm)\n"); CUDA_SAFE_CALL(cudaMemcpy(d_m, &tmp, sizeof(dev_meshgrid_t), cudaMemcpyHostToDevice)); } } __host__ void meshgrid_t::reserve_host_data() { if (!h_data) h_data = (cell_t*) malloc(sizeof(cell_t)*size_i*size_j); } __host__ meshgrid_t meshgrid_t::operator+(const meshgrid_t& m) const { if (!equivalent(m)) printf("meshgrids not equivalent\n"); meshgrid_t res(size_i, size_j, gridsize, blocksize); cuda_operator_plus<<<gridsize, blocksize>>>(res.d_data, d_data, m.d_data, size_i, size_j); return res; } __host__ meshgrid_t meshgrid_t::operator-(const meshgrid_t& m) const { if (!equivalent(m)) printf("meshgrids not equivalent\n"); meshgrid_t res(size_i, size_j, gridsize, blocksize); cuda_operator_minus<<<gridsize, blocksize>>>(res.d_data, d_data, m.d_data, size_i, size_j); return res; } __host__ meshgrid_t meshgrid_t::operator*(const data_t& f) const { meshgrid_t res(size_i, size_j, gridsize, blocksize); cuda_operator_times<<<gridsize, blocksize>>>(res.d_data, d_data, f, size_i, size_j); return res; } __host__ meshgrid_t meshgrid_t::operator/(const data_t& f) const { meshgrid_t res(size_i, size_j, gridsize, blocksize); cuda_operator_divided<<<gridsize, blocksize>>>(res.d_data, d_data, f, size_i, size_j); return res; } //__host__ //meshgrid_t& meshgrid_t::operator=(meshgrid_t&& m) noexcept //{ // printf("moving %p to %p\n", &m, this); // if (this == &m) return *this; // std::copy(&m, &m+sizeof(meshgrid_t), this); // m.d_data = NULL; // m.d_m = NULL; // m.h_data = NULL; // return *this; //} __host__ meshgrid_t& meshgrid_t::operator=(const meshgrid_t& m) { // printf("copying %p to %p\n", &m, this); if (this == &m) return *this; cpy_prop_new_data(m); CUDA_SAFE_CALL(cudaMemcpy(d_data, m.d_data, sizeof(cell_t)*size_i*size_j, cudaMemcpyDeviceToDevice)); return *this; } __host__ data_t meshgrid_t::compare(const meshgrid_t& m) const { return 0; } __host__ bool meshgrid_t::equivalent(const meshgrid_t& m) const { return (size_i==m.size_i && size_j==m.size_j && gridsize.x==m.gridsize.x && blocksize.x==m.blocksize.x && gridsize.y==m.gridsize.y && blocksize.y==m.blocksize.y); } __host__ void meshgrid_t::data_to_host() { CUDA_SAFE_CALL(cudaMemcpy((void*) h_data, (const void*) d_data, (size_t) sizeof(cell_t)*size_i*size_j, cudaMemcpyDeviceToHost)); } __host__ const cell_t& meshgrid_t::cat(int i, int j) const { if (i<size_i && j<size_j) return h_data[j*size_i+i]; else { printf("out of range : %d %d\n", i, j); return h_data[0]; } } __host__ cell_t& meshgrid_t::at(int i, int j) { if (i<size_i && j<size_j) return h_data[j*size_i+i]; else { printf("out of range : %d %d\n", i, j); return h_data[0]; } }
5,713
// Josh Morris // Lab 6 // Dr Pettey // 4330 Parallel Processing /* A cuda program to add two 16X32 matrices supplied by the user The host will print the result generated by the kernel */ #include <stdio.h> #include <stdlib.h> const int NUM_ROW = 16; const int NUM_COL = 32; __global__ void addMatrices(int arraySize, int* a, int* b) { // calculate position int i = blockIdx.x * blockDim.x + threadIdx.x; // if in array, add if (i < arraySize) { a[i] += b[i]; } } int main(){ const int arraySize = NUM_ROW * NUM_COL; //total number of elements in each array int i, j; //counters int* a; // Host A int* b; // Host B int* d_a; // device A int* d_b; // device B // allocate matrix A a = (int*)malloc(sizeof(int) * arraySize); // allocate matrix B b = (int*)malloc(sizeof(int) * arraySize); //allocate A and B in the GPU cudaMalloc(&d_a, arraySize * sizeof(int)); cudaMalloc(&d_b, arraySize * sizeof(int)); // get matrix A printf("Please input matrix A:\n"); for (i = 0; i < arraySize; ++i) { scanf("%i", &a[i]); } //get matrix B printf("Please input matrix B:\n"); for (i = 0; i < arraySize; ++i) { scanf("%d", &b[i]); } //copy data to the GPU cudaMemcpy(d_a, a, sizeof(int) * arraySize, cudaMemcpyHostToDevice); cudaMemcpy(d_b, b, sizeof(int) * arraySize, cudaMemcpyHostToDevice); //issue command to GPU addMatrices<<<(arraySize+511)/512, 512>>>(arraySize, d_a, d_b); //copy data from device a to host a cudaMemcpy(a, d_a, sizeof(int) * arraySize, cudaMemcpyDeviceToHost); //print the results for (i = 0; i < NUM_ROW; ++i){ for(j = 0; j < NUM_COL; ++j) { printf("%d ", a[(i*NUM_COL) + j]); } printf("\n"); } //clean up free(a); free(b); cudaFree(d_a); cudaFree(d_b); }
5,714
#include <stdlib.h> #include <stdio.h> #include <string> #include <time.h> #include <fstream> #include <iostream> using namespace std; __global__ void KMP(char* pattern, char* text, int prefixTable[], int result[], int pattern_length, int text_length) { int index = blockIdx.x * blockDim.x + threadIdx.x; int i = pattern_length * index; int j = pattern_length * (index + 2) - 1; if(i > text_length) { return; } if(j > text_length) { j = text_length; } int k = 0; while (i < j) { if (k == -1) { i++; k = 0; } else if (text[i] == pattern[k]) { i++; k++; if (k == pattern_length) { result[i - pattern_length] = i - pattern_length; i = i - k + 1; } } else { k = prefixTable[k]; } } return; } void loadInputFile(string fName, char* inputArray) { ifstream inputFile; inputFile.open(fName.c_str()); if (inputFile.is_open()) { int cnt = 0; while (!inputFile.eof()) { string temp; getline(inputFile, temp, '\n'); inputArray[cnt++] = atof(temp.c_str()); } inputFile.close(); } } void preKMP(char* pattern, int prefixTable[]) { int m = strlen(pattern); int k; prefixTable[0] = -1; for (int i = 1; i < m; i++) { k = prefixTable[i - 1]; while (k >= 0) { if (pattern[k] == pattern[i - 1]) { break; } else { k = prefixTable[k]; } } prefixTable[i] = k + 1; } } int main(int argc, char* argv[]) { int textlen = 200000; int patternlen = 10; char* text = (char*)malloc(textlen * sizeof(char)); char* pattern = (char*)malloc(patternlen * sizeof(char)); std::ifstream file; file.open("KMP_Input_200000.txt"); file.getline(text, textlen); file.close(); file.open("pat.txt"); file.getline(pattern, 10); int text_length = strlen(text); int pattern_length = strlen(pattern); char *d_text; char *d_pattern; int *prefixTable,*d_prefixTable; int *result,*d_result; prefixTable = new int[text_length]; result = new int[text_length]; for(int i = 0; i < text_length; i++) { result[i] = -1; } preKMP(pattern, prefixTable); cudaEvent_t start, stop; float elapsedTime; cudaEventCreate( &start ); cudaEventCreate( &stop ); cudaEventRecord( start, 0 ); cudaMalloc((void **)&d_text, text_length * sizeof(char)); cudaMalloc((void **)&d_pattern, pattern_length * sizeof(char)); cudaMalloc((void **)&d_prefixTable, text_length * sizeof(int)); cudaMalloc((void **)&d_result, text_length * sizeof(int)); cudaMemcpy(d_text, text, text_length * sizeof(char), cudaMemcpyHostToDevice); cudaMemcpy(d_pattern, pattern, pattern_length * sizeof(char), cudaMemcpyHostToDevice); cudaMemcpy(d_prefixTable, prefixTable, text_length * sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(d_result, result, text_length * sizeof(int), cudaMemcpyHostToDevice); KMP<<<(text_length / pattern_length + 4)/4, 4>>>(d_pattern, d_text ,d_prefixTable, d_result, pattern_length, text_length); cudaMemcpy(result, d_result, text_length * sizeof(int), cudaMemcpyDeviceToHost); cudaEventRecord( stop, 0 ); cudaEventSynchronize( stop ); cudaEventElapsedTime( &elapsedTime, start, stop ); cudaEventDestroy(start); cudaEventDestroy(stop); int matches=0; for(int i = 0; i < text_length; i++) { if (result[i] != -1) { matches++; } } cout << "Length of text " << textlen << endl; cout << "Length of pattern " << strlen(pattern) << endl; cout<<"Number of matches of \""<<pattern<<"\" is "<<matches<<endl<<"Time taken: "<< elapsedTime; cudaFree(d_text); cudaFree(d_pattern); cudaFree(d_prefixTable); cudaFree(d_result); free(text); free(pattern); return 0; }
5,715
#include "includes.h" __global__ void bfsCheck( bool *d_graph_mask, bool *d_updating_graph_mask, bool *d_graph_visited, int no_of_nodes, bool *stop ) { *stop = false; int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid < no_of_nodes){ if (d_updating_graph_mask[tid] == true){ d_graph_mask[tid] = true; d_graph_visited[tid] = true; *stop = true; d_updating_graph_mask[tid] = false; } } }
5,716
#include <stdio.h> #include <cuda_runtime.h> int main() { cudaDeviceProp* cdp = (cudaDeviceProp*) malloc(sizeof(cudaDeviceProp)); int deviceCount = 0, i; cudaGetDeviceCount(&deviceCount); printf("Number of devices : %d\n", deviceCount); for ( i = 0 ; i < deviceCount ; i++ ) { cudaGetDeviceProperties(cdp, i); printf("Device n°%d (%s)\n", i, cdp->name); printf("frequency : %d KHz\n", cdp->clockRate); printf("Global memory size : %zd bytes\n", cdp->totalGlobalMem); printf("WarpSize : %d threads\n", cdp->warpSize); } free(cdp); return 0; }
5,717
#include "includes.h" __global__ void binarize_weights_mean_kernel(float *weights, int n, int size, float *binary, float *mean_arr_gpu) { int i = blockIdx.x * blockDim.x + threadIdx.x; int f = i / size; if (f >= n) return; float mean = mean_arr_gpu[f]; binary[i] = (weights[i] > 0) ? mean : -mean; }
5,718
#include "includes.h" __global__ void convolution1d_notile_noconstant_kernel(int *In, int *Out){ unsigned int index = blockIdx.x * blockDim.x + threadIdx.x; // Index 1d iterator. int Value = 0; int N_start_point = index - (Mask_size/2); for ( int j = 0; j < Mask_size; j ++) { if (N_start_point + j >= 0 && N_start_point + j < N_elements) { Value += In[N_start_point + j] * Global_Mask[j]; } } Out[index] = Value; }
5,719
#include "includes.h" __global__ void InterpolateFromMemBlock(float* input1, float* input2, float* output, float* weightMemBlock, int inputSize) { int threadId = blockDim.x*blockIdx.y*gridDim.x //rows preceeding current row in grid + blockDim.x*blockIdx.x //blocks preceeding current block + threadIdx.x; if(threadId < inputSize) { if (weightMemBlock[0] <= 0) { output[threadId] = input1[threadId]; } else if (weightMemBlock[0] >= 1) { output[threadId] = input2[threadId]; } else { output[threadId] = (1 - weightMemBlock[0]) * input1[threadId] + weightMemBlock[0] * input2[threadId]; } } }
5,720
#include <stdio.h> __global__ void make_hello(char *str, int *transform_mtx) { str[threadIdx.x] += transform_mtx[threadIdx.x]; } int main(int argc, char **argv) { printf("Hello from main!\n"); for (int ii = 0; ii < argc; ii++) { printf("argv[%d] = %s\n", ii, argv[ii]); } char str[16] = "Hello \0\0\0\0\0\0"; int transform_mtx[16] = {15, 10, 6, 0, -11, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; printf("From CUDA: %s", str); char *ad; int *bd; cudaMalloc((void**)&ad, sizeof(str)); cudaMalloc((void**)&bd, sizeof(transform_mtx)); cudaMemcpy(ad, str, sizeof(str), cudaMemcpyHostToDevice); cudaMemcpy(bd, transform_mtx, sizeof(transform_mtx), cudaMemcpyHostToDevice); dim3 dimBlock(16, 1); dim3 dimGrid(1, 1); make_hello<<<dimGrid, dimBlock>>>(ad, bd); cudaMemcpy(str, ad, sizeof(str), cudaMemcpyDeviceToHost); cudaFree(ad); cudaFree(bd); printf("%s\n", str); return 0; }
5,721
#include <iostream> #include <stdio.h> #include <time.h> using namespace std; #define BLOCK_SIZE 16 __global__ void tranposition(float *A, float *B, int N) { // Matrix multiplication for NxN matrices C=A*B // Each thread computes a single element of C int row = blockIdx.y*blockDim.y + threadIdx.y; int col = blockIdx.x*blockDim.x + threadIdx.x; B[row*N+col] = A[col*N+row]; } int main(int argc, char *argv[]) { // Initialize clock variables clock_t cpuClock; clock_t gpuClock; // Perform matrix multiplication C = A*B // where A, B and C are NxN matrices // Restricted to matrices where N = K*BLOCK_SIZE; int N,K; K = 500; N = K*BLOCK_SIZE; cout << "Matrix size: " << N << "x" << N << endl << endl; // Allocate memory on the host float *hA,*hB; hA = new float[N*N]; hB = new float[N*N]; // Initialize matrices on the host for (int j=0; j<N; j++){ for (int i=0; i<N; i++){ hA[j*N+i] = 2.f*(j+i); hA[j*N+i] = 1.f*(j+i); } } // Allocate memory on the device int size = N*N*sizeof(float); // Size of the memory in bytes float *dA,*dB; cudaMalloc(&dA,size); cudaMalloc(&dB,size); dim3 threadBlock(BLOCK_SIZE,BLOCK_SIZE); dim3 grid(K,K); // Copy matrices from the host to device cudaMemcpy(dA,hA,size,cudaMemcpyHostToDevice); // Do the matrix multiplication on the GPU gpuClock = clock(); tranposition<<<grid,threadBlock>>>(dA,dB,N); gpuClock = clock() - gpuClock; // Now do the matrix tranposition on the CPU cpuClock = clock(); for (int row=0; row<N; row++){ for (int col=0; col<N; col++){ hB[row*N+col] = hA[col*N+row]; } } cpuClock = clock() - cpuClock; // Allocate memory to store the GPU answer on the host float *B; B = new float[N*N]; // Now copy the GPU result back to CPU cudaMemcpy(B,dB,size,cudaMemcpyDeviceToHost); // Check the result and make sure it is correct for (int row=0; row<N; row++){ for (int col=0; col<N; col++){ if( B[row*N+col] != hB[row*N+col] ){ cout << "Wrong answer!" << endl; row = col = N; } } } printf("The CPU took %f seconds to perform matrix transposition. \n", ((float)cpuClock)/CLOCKS_PER_SEC); printf("The GPU took %f seconds to perform matrix transposition. \n", ((float)gpuClock)/CLOCKS_PER_SEC); }
5,722
#include <stdio.h> const int N = 7; const int blocksize = 7; /* Adds the an integer from the [b] array to a character in the same position * in the [a] array and stores the result back in [a]. Uses a multithreaded * pattern to add the two (each thread modifies a different index in parallel). * * Requires: |a| = |b|. */ __global__ void hello(char* a, int* b) { a[threadIdx.x] += b[threadIdx.x]; } /* Initializes the arrays and prints out the actual hello-world program. * * Requires: Computer supports CUDA hardware for multithreaded code to run. */ int main(int argc, char* argv[]) { char a[N] = "Hello "; int b[N] = {47, 10, 6, 0, -11, 1, 0}; // Diffs between "Hello " and "world!" char* ad; int* bd; const int csize = N * sizeof(char); const int isize = N * sizeof(int); printf("%s", a); // Print out "Hello " cudaMalloc((void**) &ad, csize); cudaMalloc((void**) &bd, isize); cudaMemcpy(ad, a, csize, cudaMemcpyHostToDevice); cudaMemcpy(bd, b, isize, cudaMemcpyHostToDevice); dim3 dimBlock(blocksize, 1); dim3 dimGrid(1, 1); // Set up blocks to copy. hello<<<dimGrid, dimBlock>>>(ad, bd); // Works in theory, but requires CUDA. cudaMemcpy(a, ad, csize, cudaMemcpyDeviceToHost); cudaFree(ad); cudaFree(bd); printf("%s\n", a); // Print out "world!" return EXIT_SUCCESS; }
5,723
#include <iostream> using namespace std; static void HandleError(cudaError_t err, const char *file, int line) { if (err != cudaSuccess) { cout << cudaGetErrorString(err) << " in file '" << file << "' at line " << line << endl; exit(EXIT_FAILURE); } } #define HANDLE_ERROR(err) (HandleError(err, __FILE__, __LINE__)) #define N 10 __global__ void add(int *a, int *b, int *c) { int tid = blockIdx.x; if(tid < N) { c[tid] = a[tid] + b[tid]; } } int main(void) { int a[N], b[N], c[N]; int *dev_a, *dev_b, *dev_c; HANDLE_ERROR(cudaMalloc((void**)&dev_a, N * sizeof(int))); HANDLE_ERROR(cudaMalloc((void**)&dev_b, N * sizeof(int))); HANDLE_ERROR(cudaMalloc((void**)&dev_c, N * sizeof(int))); //Вот тут ошибка for (int i = 0; i < N; i++) { a[i] = -i; b[i] = i * i; } HANDLE_ERROR(cudaMemcpy(dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice)); HANDLE_ERROR(cudaMemcpy(dev_b, b, N * sizeof(int), cudaMemcpyHostToDevice)); add<<<N, 1>>>(dev_a, dev_b, dev_c); HANDLE_ERROR(cudaMemcpy(c, dev_c, N * sizeof(int), cudaMemcpyDeviceToHost)); for (int i = 0; i < N; i++) { cout << a[i] << " + " << b[i] << " = " << c[i] << endl; } HANDLE_ERROR(cudaFree( dev_a )); HANDLE_ERROR(cudaFree( dev_b )); HANDLE_ERROR(cudaFree( dev_c )); return 0; }
5,724
#include <cuda.h> #include <stdio.h> #include <dlfcn.h> #include <stdlib.h> CUresult cuDeviceTotalMem(size_t* bytes, CUdevice dev) { void *handle; handle = dlopen("/usr/lib/x86_64-linux-gnu/libcuda.so.1", RTLD_LAZY); printf("%s\n", "cuDeviceTotalMem is hijacked based on env MYMEM!"); const char* mymem = getenv("MYMEM"); int env_set_mem_i = 0; sscanf(mymem, "%d", &env_set_mem_i); size_t env_set_mem = env_set_mem_i < 0 ? 0 : env_set_mem_i; CUresult (*ori_cu_device_total_mem)(size_t*, CUdevice); ori_cu_device_total_mem = (CUresult (*)(size_t *, CUdevice))dlsym(handle, "cuDeviceTotalMem_v2"); size_t total_mem = 0; CUresult res = ori_cu_device_total_mem(&total_mem, dev); *bytes = env_set_mem < total_mem ? env_set_mem : total_mem; dlclose(handle); return res; }
5,725
/* * Device code */ __global__ void ParallelGaussElim( int const nDim_image, int const nDim_matrix, double* d_A, double* d_b, double* d_x) { // Assign image pixels to blocks and threads int i_image = blockDim.x*blockIdx.x + threadIdx.x; if (i_image > nDim_image*nDim_image) return; //int i_image = blockDim.y*blockIdx.y + threadIdx.y; //printf("blockDim.x = %i \n",blockDim.x); //printf("blockIdx.x = %i \n",blockIdx.x); //printf("threadIdx.x = %i \n",threadIdx.x); //printf("i_image = %i \n", i_image); //int offset = (j_image + i_image*nDim_image)*nDim_matrix*nDim_matrix; int offset_2d = i_image*nDim_matrix*nDim_matrix; int offset_1d = i_image*nDim_matrix; //printf("offset = %i \n", offset); // Gauss elimination //int nDim_local = 8; //double local_A[nDim_local*nDim_local] = 0; for (int k=0; k<nDim_matrix-1; k++) { for (int i=k+1; i<nDim_matrix; i++) { double pivot = d_A[offset_2d+i+k*nDim_matrix]/d_A[offset_2d+k+k*nDim_matrix]; for (int j=k; j<nDim_matrix; j++) { d_A[offset_2d+i+j*nDim_matrix] -= pivot*d_A[offset_2d+k+j*nDim_matrix]; } d_b[offset_1d+i] -= pivot*d_b[offset_1d+k]; } } // Backward substitution for (int i=nDim_matrix-1; i>=0; i--) { d_x[offset_1d+i] = d_b[offset_1d+i]; for (int j=nDim_matrix-1; j>i; j--) { d_x[offset_1d+i] -= d_A[offset_2d+i+j*nDim_matrix]*d_x[offset_1d+j]; } d_x[offset_1d+i] = d_x[offset_1d+i]/d_A[offset_2d+i+i*nDim_matrix]; //if (d_x[offset_1d+i] /= 1) printf ("blkdim,id,tdid = %i,%i,%i \n",blockDim.x,blockIdx.x,threadIdx.x); } }
5,726
#include "float3math.cuh"
5,727
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <cuda.h> #include <iostream> using namespace std; void initArray(float* vec, int n) { int i; for(i=0; i<n; i++) vec[i] = rand() % 9 + 1; } void initMat(float* mat, int n) { int i, j; for(i=0; i<n; i++) for(j=0; j<n; j++) mat[i*n+j] = rand() % 9 + 1; } void printVec(float* vector, int size) { for(int i=0; i<size; i++) cout << vector[i] << " "; cout<<endl; } void printMat(float *a, int n) { for(int i=0; i<n; i++){ for (int j=0; j<n; j++) cout<< a[i*n+j] << " "; cout<<endl; } } __global__ void mulKernel(float *vec, float *mat, float* c, int n) { int i = threadIdx.x + blockDim.x * blockIdx.x ; float sum=0; if(i < n){ for(int j=0; j<n; j++) sum += vec[j]*mat[(j*n) + i]; c[i]=sum; } } void mulVecMat(float* vec, float* mat, int n){ float* c; float* dev_a, * dev_b, * dev_c; cout<<"is oke"<<endl; vec = (float*)malloc(sizeof(float)*n); mat = (float*)malloc(sizeof(float)*n*n); c = (float*)malloc(sizeof(float)*n); cout<<"is oke"<<endl; initArray(vec, n); cout<<"array is okey"<<endl; initMat(mat, n*n); cout<<"init ,at is okey"<<endl; initMat(c, n); cout<<"init mat 2 is okey"<<endl; // printVec(vec, n); // printMat(mat, n*n); // printVec(c, n); cudaMalloc((void**)&dev_a, sizeof(float)*n); cudaMemcpy(dev_a, vec, sizeof(float)*n, cudaMemcpyHostToDevice); cudaMalloc((void**)&dev_b, sizeof(float)*n*n); cudaMemcpy(dev_b, mat, sizeof(float)*n*n, cudaMemcpyHostToDevice); cudaMalloc((void**)&dev_c, sizeof(float)*n); mulKernel<<<ceil(n/256.0), 256>>>(dev_a, dev_b, dev_c, n); cudaMemcpy(c, dev_c, sizeof(float)*n, cudaMemcpyDeviceToHost); cudaFree(dev_a); cudaFree(dev_b); cudaFree(dev_c); // printMat(c, n); } int main() { // Size of vectors int n = 100; // Host input vectors float* h_a = 0; float* h_ma = 0; mulVecMat(h_a, h_ma, n); return 0; }
5,728
#include <iostream> using namespace std; #include <thrust/reduce.h> #include <thrust/sequence.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> void task1(void) { const int N = 50000; int sum = 0, sumA = 0, i = 0; thrust::device_vector<int>a(N); thrust::sequence(a.begin(), a.end(), 0); sumA = thrust::reduce(a.begin(), a.end(), 0); for (; i < N; i ++) { sum += i; } std::cout << sum << std::endl; std::cout << sumA << std::endl; } __global__ void fillKernel(int *a, int n) { int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid < n) { a[tid] = tid; } } void fill(int* d_a, int n) { int block = 512; int nblock = n / block + (( n % block) ? 1 : 0); fillKernel <<< nblock, block >>> (d_a, n); } void task2(void) { const int N = 50000; int sum = 0, sumA = 0, i = 0; thrust::device_vector<int>a(N); fill(thrust::raw_pointer_cast(&a[0]), N); sumA = thrust::reduce(a.begin(), a.end(), 0); for (; i < N; i ++) { sum += i; } std::cout << sum << std::endl; std::cout << sumA << std::endl; } void task3(void) { const int N = 50000; int sum = 0, sumA = 0, i = 0; thrust::device_vector<int>a(N); thrust::sequence(a.begin(), a.end(), 0); #pragma omp parallel for reduction(+ : sum) for (i = 0; i < N; i ++) sum += i; sumA = thrust::reduce(a.begin(), a.end(), 0); std::cout << sum << std::endl; std::cout << sumA << std::endl; } int main(void) { task1(); task2(); task3(); }
5,729
/* * GPU based implementation of the elastic mesh deriviatives computations. */ //#define FLOAT_INFINITY __int_as_float(0x7f800000) #define FLOAT_INFINITY __int_as_float(-1) #define SMALL_VALUE 0.0001 /* Huber Loss Functions */ inline __device__ float huber( const float value, const float target, const float sigma, const float d_value_dx, const float d_value_dy, float* d_huber_dx, float* d_huber_dy ) { float diff, a, b; diff = value - target; if (abs(diff) <= sigma) { a = (diff * diff) / 2; *d_huber_dx = diff * d_value_dx; *d_huber_dy = diff * d_value_dy; return a; } else { b = sigma * (abs(diff) - sigma / 2); *d_huber_dx = sigma * d_value_dx; *d_huber_dy = sigma * d_value_dy; return b; } } /* Regularized length function */ inline __device__ float reglen( const float vx, const float vy, const float d_vx_dx, const float v_vy_dy, float* d_reglen_dx, float* d_reglen_dy ) { float sq_len, sqrt_len; sq_len = vx * vx + vy * vy + SMALL_VALUE; sqrt_len = sqrt(sq_len); *d_reglen_dx = vx / sqrt_len; *d_reglen_dy = vy / sqrt_len; return sqrt_len; } /* Mesh cross-link derivs */ __global__ void crosslink_mesh_derivs( const float2* mesh1, const float2* mesh2, float2* d_cost_d_mesh1, float2* d_cost_d_mesh2, const uint3* indices1, const uint3* indices2, const int indices_num, const float3* barys1, const float3* barys2, const float all_weight, const float sigma, float* crosslink_costs ) { float px, py, qx, qy; int pidx0, pidx1, pidx2; int qidx0, qidx1, qidx2; float pb0, pb1, pb2; float qb0, qb1, qb2; float r, h; float dr_dx, dr_dy, dh_dx, dh_dy; float cost = 0; const int idx = blockDim.x * blockIdx.x + threadIdx.x; // Check that the given index is valid if (idx >= indices_num) return; pidx0 = indices1[idx].x; pidx1 = indices1[idx].y; pidx2 = indices1[idx].z; pb0 = barys1[idx].x; pb1 = barys1[idx].y; pb2 = barys1[idx].z; qidx0 = indices2[idx].x; qidx1 = indices2[idx].y; qidx2 = indices2[idx].z; qb0 = barys2[idx].x; qb1 = barys2[idx].y; qb2 = barys2[idx].z; px = (mesh1[pidx0].x * pb0 + mesh1[pidx1].x * pb1 + mesh1[pidx2].x * pb2); py = (mesh1[pidx0].y * pb0 + mesh1[pidx1].y * pb1 + mesh1[pidx2].y * pb2); qx = (mesh2[qidx0].x * qb0 + mesh2[qidx1].x * qb1 + mesh2[qidx2].x * qb2); qy = (mesh2[qidx0].y * qb0 + mesh2[qidx1].y * qb1 + mesh2[qidx2].y * qb2); r = reglen(px - qx, py - qy, 1, 1, &(dr_dx), &(dr_dy)); h = huber(r, 0, sigma, dr_dx, dr_dy, &(dh_dx), &(dh_dy)); cost = h * all_weight; dh_dx *= all_weight; dh_dy *= all_weight; // update derivs atomicAdd(&d_cost_d_mesh1[pidx0].x, pb0 * dh_dx); atomicAdd(&d_cost_d_mesh1[pidx1].x, pb1 * dh_dx); atomicAdd(&d_cost_d_mesh1[pidx2].x, pb2 * dh_dx); atomicAdd(&d_cost_d_mesh1[pidx0].y, pb0 * dh_dy); atomicAdd(&d_cost_d_mesh1[pidx1].y, pb1 * dh_dy); atomicAdd(&d_cost_d_mesh1[pidx2].y, pb2 * dh_dy); // opposite direction for other end of spring, and distributed according to weight atomicAdd(&d_cost_d_mesh2[qidx0].x, -qb0 * dh_dx); atomicAdd(&d_cost_d_mesh2[qidx1].x, -qb1 * dh_dx); atomicAdd(&d_cost_d_mesh2[qidx2].x, -qb2 * dh_dx); atomicAdd(&d_cost_d_mesh2[qidx0].y, -qb0 * dh_dy); atomicAdd(&d_cost_d_mesh2[qidx1].y, -qb1 * dh_dy); atomicAdd(&d_cost_d_mesh2[qidx2].y, -qb2 * dh_dy); crosslink_costs[idx] = cost; } /* Mesh internal-links derivs */ __global__ void internal_mesh_derivs( const float2* mesh, float2* d_cost_d_mesh, const uint2* edge_indices, const int edge_indices_num, const float* rest_lengths, const float all_weight, const float sigma, float* edge_costs ) { int idx1, idx2; float px, py, qx, qy; float r, h; float dr_dx, dr_dy, dh_dx, dh_dy; float cost = 0; const int edge_idx = blockDim.x * blockIdx.x + threadIdx.x; // Check that the given edge index is valid if (edge_idx >= edge_indices_num) return; idx1 = edge_indices[edge_idx].x; idx2 = edge_indices[edge_idx].y; px = mesh[idx1].x; py = mesh[idx1].y; qx = mesh[idx2].x; qy = mesh[idx2].y; r = reglen(px - qx, py - qy, 1.0, 1.0, &(dr_dx), &(dr_dy)); h = huber(r, rest_lengths[edge_idx], sigma, dr_dx, dr_dy, &(dh_dx), &(dh_dy)); cost = h * all_weight; dh_dx *= all_weight; dh_dy *= all_weight; // update derivs atomicAdd(&d_cost_d_mesh[idx1].x, dh_dx); atomicAdd(&d_cost_d_mesh[idx1].y, dh_dy); atomicAdd(&d_cost_d_mesh[idx2].x, -dh_dx); atomicAdd(&d_cost_d_mesh[idx2].y, -dh_dy); edge_costs[edge_idx] = cost; } /* Mesh area derivs (triangle area) */ __global__ void area_mesh_derivs( const float2* mesh, float2* d_cost_d_mesh, const uint3* triangle_indices, const int triangle_indices_num, const float* rest_areas, const float all_weight, float* triangle_costs ) { int idx0, idx1, idx2; float v01x, v01y, v02x, v02y, area, r_area; float cost, dc_da; float a1; const int triangle_idx = blockDim.x * blockIdx.x + threadIdx.x; // Check that the given edge index is valid if (triangle_idx >= triangle_indices_num) return; idx0 = triangle_indices[triangle_idx].x; idx1 = triangle_indices[triangle_idx].y; idx2 = triangle_indices[triangle_idx].z; v01x = mesh[idx1].x - mesh[idx0].x; v01y = mesh[idx1].y - mesh[idx0].y; v02x = mesh[idx2].x - mesh[idx0].x; v02y = mesh[idx2].y - mesh[idx0].y; area = 0.5 * (v02x * v01y - v01x * v02y); r_area = rest_areas[triangle_idx]; if (area * r_area <= 0) { cost = FLOAT_INFINITY; dc_da = 0; } else { /* # cost is ((A - A_rest) / A) ^ 2 * A_rest (last term is for area normalization) # # / A - A \ 2 # | rest | | | # | ----------- | * | A | # \ A / | rest | */ a1 = ((area - r_area) / area); cost = all_weight * (a1 * a1); dc_da = 2 * all_weight * r_area * (area - r_area) / (area * area * area); } // update derivs atomicAdd(&d_cost_d_mesh[idx1].x, dc_da * 0.5 * (-v02y)); atomicAdd(&d_cost_d_mesh[idx1].y, dc_da * 0.5 * (v02x)); atomicAdd(&d_cost_d_mesh[idx2].x, dc_da * 0.5 * (v01y)); atomicAdd(&d_cost_d_mesh[idx2].y, dc_da * 0.5 * (-v01x)); // sum of negative of above atomicAdd(&d_cost_d_mesh[idx0].x, dc_da * 0.5 * (v02y - v01y)); atomicAdd(&d_cost_d_mesh[idx0].y, dc_da * 0.5 * (v01x - v02x)); triangle_costs[triangle_idx] = cost; } /* Mesh area derivs (triangle area) */ __global__ void update_mesh_and_momentum_grads( float2* mesh, const int pts_num, const float2* grads, float2* momentum_grads, const float momentum, const float stepsize ) { const int pt_idx = blockDim.x * blockIdx.x + threadIdx.x; // Check that the given point index is valid if (pt_idx >= pts_num) return; // Update the gradients with momentum // gradients_with_momentum[sec_idx] = gradients[sec_idx] + momentum * gradients_with_momentum[sec_idx] momentum_grads[pt_idx].x = grads[pt_idx].x + momentum * momentum_grads[pt_idx].x; momentum_grads[pt_idx].y = grads[pt_idx].y + momentum * momentum_grads[pt_idx].y; // Update the mesh points // meshes[sec_idx].pts -= stepsize * gradients_with_momentum[sec_idx] mesh[pt_idx].x -= stepsize * momentum_grads[pt_idx].x; mesh[pt_idx].y -= stepsize * momentum_grads[pt_idx].y; }
5,730
#include "includes.h" /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /********************************** When updating a kernel or adding a new one, please compile the ptx file and commit it: nvcc -ptx -arch=sm_30 SystemML.cu ***********************************/ /** * Performs a slice operation where the input matrix is sparse and the output matrix is dense. * This function avoids unnecessary sparse to dense conversion of the input matrix. * Parallelization: rows of output matrix. * * @params inVal input val pointer * @params inRowPtr input row pointer * @params colInd input col index pointer * @params ret dense output pointer * @param rl row lower * @param ru row upper * @param cl column lower * @param cu column upper * @param retClen number of columns of output matrix */ extern "C" /** * Performs a slice operation where the input matrix is sparse and the output matrix is dense. * This function avoids unnecessary sparse to dense conversion of the input matrix. * Parallelization: subset of number of non-zeroes of input matrix. * * @params inVal input val pointer * @params inRowPtr input row pointer * @params colInd input col index pointer * @params ret dense output pointer * @param rl row lower * @param ru row upper * @param cl column lower * @param cu column upper * @param retClen number of columns of output matrix */ extern "C" /** * Performs a slice operation where the input matrix is dense and the output matrix is dense. * * @params in dense input pointer * @params ret dense output pointer * @param rl row lower * @param ru row upper * @param cl column lower * @param cu column upper * @param inClen number of columns of input matrix * @param retRlen number of rows of output matrix * @param retClen number of columns of output matrix */ extern "C" /** * Does a copy of upper to lower triangle of the given matrix * @param ret the input and output array allocated on the GPU * @param dim the number of rows of the square matrix ret * @param N total number of elements of the matrix */ extern "C" extern "C" __global__ void matrix_abs(double *A, double *C, unsigned int size) { int index = blockIdx.x * blockDim.x + threadIdx.x; if (index < size){ C[index] = (double)fabs(A[index]); } }
5,731
#include "includes.h" __device__ int locate(int val, int *data, int n) { int i_left = 0; int i_right = n-1; int i = (i_left+i_right)/2; while(i_right-i_left>1) { if (data[i] > val) i_right = i; else if (data[i]<val) i_left = i; else break; i=(i_left+i_right)/2; } return i; } __global__ void prescan_arbitrary_unoptimized(int *output, int *input, int n, int powerOfTwo) { extern __shared__ int temp[];// allocated on invocation int threadID = threadIdx.x; if (threadID < n) { temp[2 * threadID] = input[2 * threadID]; // load input into shared memory temp[2 * threadID + 1] = input[2 * threadID + 1]; } else { temp[2 * threadID] = 0; temp[2 * threadID + 1] = 0; } int offset = 1; for (int d = powerOfTwo >> 1; d > 0; d >>= 1) // build sum in place up the tree { __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; temp[bi] += temp[ai]; } offset *= 2; } if (threadID == 0) { temp[powerOfTwo - 1] = 0; } // clear the last element for (int d = 1; d < powerOfTwo; d *= 2) // traverse down tree & build scan { offset >>= 1; __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; int t = temp[ai]; temp[ai] = temp[bi]; temp[bi] += t; } } __syncthreads(); if (threadID < n) { output[2 * threadID] = temp[2 * threadID]; // write results to device memory output[2 * threadID + 1] = temp[2 * threadID + 1]; } }
5,732
#include "includes.h" // GPU Libraries // Macro to handle errors occured in CUDA api __device__ void recursiveReduce(int *g_inData, int *g_outData, int inSize, int outSize) { extern __shared__ int sData[]; // Identification unsigned int tId = threadIdx.x; unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; // Initialize sData[tId] = 0; __syncthreads(); // Fill up the shared memory if (tId < blockDim.x) { sData[tId] = g_inData[i]; } __syncthreads(); // Tree based reduction for (unsigned int d = 1; d < blockDim.x; d *= 2) { if (tId % (2 * d) == 0) if (tId + d < blockDim.x) sData[tId] += sData[tId + d]; __syncthreads(); } // Write the result for this block to global memory if (tId == 0) { g_outData[blockIdx.x] = sData[0]; } __syncthreads(); // Recursive call if (outSize > 1 && i == 0) { // Kernel Launch recursiveReduce(g_outData, g_outData, outSize, (outSize - 1) / blockDim.x + 1); } else return; } __global__ void reduceKernel(int *g_inData, int *g_outData, int inSize, int outSize) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i == 0) { recursiveReduce(g_inData, g_outData, inSize, outSize); } }
5,733
#include <stdio.h> #include <sys/time.h> #include <cuda.h> long long getCurrentTime() { struct timeval te; gettimeofday(&te, NULL); // get current time long long microseconds = te.tv_sec*1000000LL + te.tv_usec; return microseconds; } #define CUDA_ERROR_CHECK #define CudaSafeCall( err ) __cudaSafeCall( err, __FILE__, __LINE__ ) inline void __cudaSafeCall( cudaError err, const char *file, const int line ) { #ifdef CUDA_ERROR_CHECK if ( cudaSuccess != err ) { fprintf( stderr, "cudaSafeCall() failed at %s:%i : %s\n", file, line, cudaGetErrorString( err ) ); exit( -1 ); } #endif return; } int main() { for (int N = 1024; N < 256 * 1024* 1024; N = N * 2) { int *pageA, *pageB, *pinnedA, *pinnedB; int *dA; // Allocate pageable memory on the host pageA = (int*)malloc(sizeof(int) * N); pageB = (int*)malloc(sizeof(int) * N); // Allocate pinned memory on the CudaSafeCall(cudaMallocHost((void**)&pinnedA, sizeof(int) * N)); CudaSafeCall(cudaMallocHost((void**)&pinnedB, sizeof(int) * N)); // Allocate memory on the device CudaSafeCall(cudaMalloc(&dA, sizeof(int) * N)); // Initilize data for (int i = 0; i < N; i++) { pageA[i] = i; pinnedA[i] = i; } int error = 0; cudaEvent_t startH2DPage, endH2DPage; cudaEvent_t startD2HPage, endD2HPage; cudaEvent_t startH2DPinned, endH2DPinned; cudaEvent_t startD2HPinned, endD2HPinned; // Measuring H2D/D2H performance (Pageable Memory) { CudaSafeCall(cudaEventCreate(&startH2DPage)); CudaSafeCall(cudaEventCreate(&endH2DPage)); CudaSafeCall(cudaEventCreate(&startD2HPage)); CudaSafeCall(cudaEventCreate(&endD2HPage)); // H2D CudaSafeCall(cudaEventRecord(startH2DPage)); CudaSafeCall(cudaMemcpy(dA, pageA, sizeof(int) * N, cudaMemcpyHostToDevice)); CudaSafeCall(cudaEventRecord(endH2DPage)); CudaSafeCall(cudaEventSynchronize(endH2DPage)); // D2H CudaSafeCall(cudaEventRecord(startD2HPage)); CudaSafeCall(cudaMemcpy(pageB, dA, sizeof(int) * N, cudaMemcpyDeviceToHost)); CudaSafeCall(cudaEventRecord(endD2HPage)); CudaSafeCall(cudaEventSynchronize(endD2HPage)); error = 0; for (int i = 0; i < N; i++) { if (pageA[i] != pageB[i]) { error++; } } } // Measuring H2D/D2H performance (Pinned Memory) { CudaSafeCall(cudaEventCreate(&startH2DPinned)); CudaSafeCall(cudaEventCreate(&endH2DPinned)); CudaSafeCall(cudaEventCreate(&startD2HPinned)); CudaSafeCall(cudaEventCreate(&endD2HPinned)); // H2D CudaSafeCall(cudaEventRecord(startH2DPinned)); CudaSafeCall(cudaMemcpy(dA, pinnedA, sizeof(int) * N, cudaMemcpyHostToDevice)); CudaSafeCall(cudaEventRecord(endH2DPinned)); CudaSafeCall(cudaEventSynchronize(endH2DPinned)); // D2H CudaSafeCall(cudaEventRecord(startD2HPinned)); CudaSafeCall(cudaMemcpy(pinnedB, dA, sizeof(int) * N, cudaMemcpyDeviceToHost)); CudaSafeCall(cudaEventRecord(endD2HPinned)); CudaSafeCall(cudaEventSynchronize(endD2HPinned)); for (int i = 0; i < N; i++) { if (pinnedA[i] != pinnedB[i]) { error++; } } } if (!error) { float h2dpage, d2hpage, h2dpinned, d2hpinned; CudaSafeCall(cudaEventElapsedTime(&h2dpage, startH2DPage, endH2DPage)); CudaSafeCall(cudaEventElapsedTime(&d2hpage, startD2HPage, endD2HPage)); CudaSafeCall(cudaEventElapsedTime(&h2dpinned, startH2DPinned, endH2DPinned)); CudaSafeCall(cudaEventElapsedTime(&d2hpinned, startD2HPinned, endD2HPinned)); printf("Size: %lu bytes, H2D Page: %lf msec, D2H Page: %lf msec, H2D Pinned: %lf msec, D2H Pinned: %lf msec\n", N * sizeof(int), h2dpage, d2hpage, h2dpinned, d2hpinned); } } return 0; }
5,734
#include "includes.h" __global__ void laplacianFilter(unsigned char *srcImage, unsigned char *dstImage, unsigned int width, unsigned int height) { int x = blockIdx.x*blockDim.x + threadIdx.x; int y = blockIdx.y*blockDim.y + threadIdx.y; float ker[3][3] = {{0, -1, 0}, {-1, 4, -1}, {0, -1, 0}}; //float kernel[3][3] = {-1, -1, -1, -1, 8, -1, -1, -1, -1}; // only threads inside image will write results if((x>=FILTER_WIDTH/2) && (x<(width-FILTER_WIDTH/2)) && (y>=FILTER_HEIGHT/2) && (y<(height-FILTER_HEIGHT/2))) { // Sum of pixel values float sum = 0; // Loop inside the filter to average pixel values for(int ky=-FILTER_HEIGHT/2; ky<=FILTER_HEIGHT/2; ky++) { for(int kx=-FILTER_WIDTH/2; kx<=FILTER_WIDTH/2; kx++) { float fl = srcImage[((y+ky)*width + (x+kx))]; sum += fl*ker[ky+FILTER_HEIGHT/2][kx+FILTER_WIDTH/2]; } } dstImage[(y*width+x)] = sum; } }
5,735
#include <stdio.h> #include <cuda_runtime.h> void initialize(int *H, int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) H[N*i+j] = 0; for (int i = 0; i < N; i++) { H[N*i] = H[N*i+N-1] = H[N*(N-1)+i] = 20; H[i] = i >= ((N*30)/100) && i < ((N*70)/100) ? 100 : 20; } } void serial_heat_distribution(int *H, int *G, int N, int limit) { for (int iteration = 0; iteration < limit; iteration++) { for (int i = 1; i < N-1; i++) for (int j = 1; j < N-1; j++) G[N*i+j] = 0.25*(H[N*i+j-N] + H[N*i+j-1] + H[N*i+j+1] + H[N*i+j+N]); for (int i = 1; i < N-1; i++) for (int j = 1; j < N-1; j++) H[N*i+j] = G[N*i+j]; } } __global__ void heat_distribution(int *H, int *G, int N, int limit) { for (int iteration = 0; iteration < limit; iteration++) { if (blockIdx.x > 0 && threadIdx.x > 0 && blockIdx.x < N-1 && threadIdx.x < N-1) { int index = N*blockIdx.x + threadIdx.x; G[index] = 0.25*(H[index-N] + H[index-1] + H[index+1] + H[index+N]); __syncthreads(); H[index] = G[index]; __syncthreads(); } } } int main(void) { int N = 1000, limit = 1000; int *H, *d_H, *G, *d_G; cudaMalloc((void **)&d_H, sizeof(int)*N*N); cudaMalloc((void **)&d_G, sizeof(int)*N*N); H = (int *)malloc(sizeof(int)*N*N); G = (int *)malloc(sizeof(int)*N*N); initialize(H, N); cudaMemcpy(d_H, H, sizeof(int)*N*N, cudaMemcpyHostToDevice); heat_distribution<<<N, N>>>(d_H, d_G, N, limit); cudaMemcpy(H, d_H, sizeof(int)*N*N, cudaMemcpyDeviceToHost); // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) // printf("%d ", H[N*i+j]); // printf("\n"); // } free(H); free(G); cudaFree(d_H); cudaFree(d_G); return 0; }
5,736
//****************************************************************************** // // File: ModCubeRoot.cu // // This CUDA C file is the kernel function for the GPU to try and break the cipher // key // //****************************************************************************** // Number of threads per block. #define NT 1024 // Overall counter variable in global memory. __device__ unsigned int incrementNumber; /** * This kernel is used to break the RSA * @param N is a large integer, e.g. a 2048-bit integer. * @param C cipher key. * @param possibleValues array of possible answers. * * @author Nikhil Keswaney * @version 11-15-2018 */ extern "C" __global__ void DoBruteForce (unsigned long long int N, unsigned long long int C, unsigned long long int* possibleValues) { unsigned long long int thr, size, rank; unsigned long long int m; // Determine number of threads and this thread's rank. thr = threadIdx.x; size = gridDim.x*NT; rank = blockIdx.x*NT + thr; for (unsigned long long int i = rank; i < N; i += size) { m = (((i * i) % N) * i) % N; if(m == C){ possibleValues[atomicAdd(&incrementNumber, 1)] = i; } } }
5,737
//transform length #define TLEN 128 #define TILE_DIM 16 #define HEIGHT 8 //1, 2, 4, 8 #define NEG_2PI_BY_TLEN -0.04908738521f //-2*PI/128 #define STRIDE_STAGE_1 0x00000040 //64 #define STRIDE_STAGE_2 0x00000020 //32 #define STRIDE_STAGE_3 0x00000010 //16 #define STRIDE_STAGE_4 0x00000008 //08 #define STRIDE_STAGE_5 0x00000004 //04 #define STRIDE_STAGE_6 0x00000002 //02 #define STRIDE_STAGE_7 0x00000001 //01 #define M12 0x60 #define M34 0x18 #define M35 0x14 #define M46 0x0a #define M246 0x2a #define M135 0x54 #define M357 0x15 #define M56 0x06 #define M5 0x04 __device__ int bitreverse(int tid) { int revtid = tid; revtid = ((0xf0f0f0f0 & revtid) >> 4) | ((0x0f0f0f0f & revtid) << 4); revtid = ((0xcccccccc & revtid) >> 2) | ((0x33333333 & revtid) << 2); revtid = ((0xaaaaaaaa & revtid) >> 2) | ((0x55555555 & revtid)); return revtid; } __global__ void FFT1D(float *real, float *img) { float rVal[HEIGHT], iVal[HEIGHT]; //assuming that thread block size is 128 __shared__ float shReal[HEIGHT][TLEN]; __shared__ float shImg[HEIGHT][TLEN]; #pragma unroll for(int I = 0; I < HEIGHT; I++) { rVal[I] = real[((blockIdx.x*HEIGHT) + I)*blockDim.x + threadIdx.x]; iVal[I] = img[((blockIdx.x*HEIGHT) + I)*blockDim.x + threadIdx.x]; } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); if((threadIdx.x & STRIDE_STAGE_1) == STRIDE_STAGE_1) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_1] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_1] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_1] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_1] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_1] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_1] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_1] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_1] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_1] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_1] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_1] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_1] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_1] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_1] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_1] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_1] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_1] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_1] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_1] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_1] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_1] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_1] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_1] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_1] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_1] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_1] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_1] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_1] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_1] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_1] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_1] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_1] + iVal[7]; #endif } if((threadIdx.x & STRIDE_STAGE_2) == STRIDE_STAGE_2) { //calculate Q twiddle factor float Q = (float)((threadIdx.x & STRIDE_STAGE_1)>>1); Q = Q*NEG_2PI_BY_TLEN; float c, s, T; __sincosf(Q, &s, &c); #pragma unroll for(int I = 0; I < HEIGHT; I++) { T = rVal[I]; rVal[I] = rVal[I]*c - iVal[I]*s; iVal[I] = T*s + iVal[I]*c; } } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); //stage 2 if((threadIdx.x & STRIDE_STAGE_2) == STRIDE_STAGE_2) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_2] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_2] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_2] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_2] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_2] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_2] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_2] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_2] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_2] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_2] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_2] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_2] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_2] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_2] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_2] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_2] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_2] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_2] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_2] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_2] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_2] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_2] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_2] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_2] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_2] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_2] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_2] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_2] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_2] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_2] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_2] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_2] + iVal[7]; #endif } //end of stage 2 //multiply with twiddle for beginning of stage 3 //STRIDE_STAGE_3 16 if((threadIdx.x & STRIDE_STAGE_3) == STRIDE_STAGE_3) { //calculate Q twiddle factor float Q = (float)((threadIdx.x & STRIDE_STAGE_2) | ((threadIdx.x & STRIDE_STAGE_1)>>2)); Q = Q*NEG_2PI_BY_TLEN; float c, s, T; __sincosf(Q, &s, &c); #pragma unroll for(int I = 0; I < HEIGHT; I++) { T = rVal[I]; rVal[I] = rVal[I]*c - iVal[I]*s; iVal[I] = T*s + iVal[I]*c; } } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); //stage3 if((threadIdx.x & STRIDE_STAGE_3) == STRIDE_STAGE_3) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_3] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_3] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_3] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_3] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_3] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_3] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_3] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_3] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_3] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_3] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_3] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_3] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_3] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_3] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_3] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_3] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_3] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_3] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_3] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_3] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_3] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_3] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_3] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_3] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_3] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_3] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_3] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_3] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_3] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_3] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_3] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_3] + iVal[7]; #endif } //end of stage 3 //multiply with twiddle for beginning of stage 4 //STRIDE_STAGE_4 8 if((threadIdx.x & STRIDE_STAGE_4) == STRIDE_STAGE_4) { //calculate Q twiddle factor float Q = (float)(((threadIdx.x & STRIDE_STAGE_1)>>3) | ((threadIdx.x & STRIDE_STAGE_2)>>1) | ((threadIdx.x & STRIDE_STAGE_3)<<1)); Q = Q*NEG_2PI_BY_TLEN; float c, s, T; __sincosf(Q, &s, &c); #pragma unroll for(int I = 0; I < HEIGHT; I++) { T = rVal[I]; rVal[I] = rVal[I]*c - iVal[I]*s; iVal[I] = T*s + iVal[I]*c; } } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); //stage 4 if((threadIdx.x & STRIDE_STAGE_4) == STRIDE_STAGE_4) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_4] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_4] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_4] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_4] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_4] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_4] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_4] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_4] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_4] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_4] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_4] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_4] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_4] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_4] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_4] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_4] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_4] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_4] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_4] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_4] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_4] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_4] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_4] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_4] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_4] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_4] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_4] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_4] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_4] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_4] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_4] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_4] + iVal[7]; #endif } //end of stage 4 //multiply with twiddle for beginning of stage 5 //STRIDE_STAGE_5 4 if((threadIdx.x & STRIDE_STAGE_5) == STRIDE_STAGE_5) { //calculate Q twiddle factor int q = ((threadIdx.x & M12)>>4) | (threadIdx.x & M34); q = (q & M35) | ((q & M46)<<2); float Q = q*NEG_2PI_BY_TLEN; float c, s, T; __sincosf(Q, &s, &c); #pragma unroll for(int I = 0; I < HEIGHT; I++) { T = rVal[I]; rVal[I] = rVal[I]*c - iVal[I]*s; iVal[I] = T*s + iVal[I]*c; } } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); //stage 5 if((threadIdx.x & STRIDE_STAGE_5) == STRIDE_STAGE_5) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_5] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_5] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_5] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_5] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_5] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_5] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_5] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_5] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_5] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_5] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_5] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_5] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_5] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_5] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_5] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_5] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_5] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_5] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_5] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_5] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_5] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_5] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_5] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_5] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_5] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_5] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_5] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_5] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_5] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_5] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_5] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_5] + iVal[7]; #endif } //end of stage 5 //multiply with twiddle for beginning of stage 6 //STRIDE_STAGE_6 2 if((threadIdx.x & STRIDE_STAGE_6) == STRIDE_STAGE_6) { //calculate Q twiddle factor int q = ((threadIdx.x & M12)>>5) | ((threadIdx.x & M34)>>1) | ((threadIdx.x & M5)<<3); q = (q & M246) | ((q & M357)<<2); float Q = q*NEG_2PI_BY_TLEN; float c, s, T; __sincosf(Q, &s, &c); #pragma unroll for(int I = 0; I < HEIGHT; I++) { T = rVal[I]; rVal[I] = rVal[I]*c - iVal[I]*s; iVal[I] = T*s + iVal[I]*c; } } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); //stage 6 if((threadIdx.x & STRIDE_STAGE_6) == STRIDE_STAGE_6) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_6] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_6] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_6] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_6] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_6] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_6] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_6] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_6] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_6] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_6] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_6] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_6] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_6] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_6] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_6] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_6] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_6] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_6] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_6] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_6] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_6] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_6] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_6] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_6] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_6] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_6] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_6] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_6] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_6] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_6] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_6] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_6] + iVal[7]; #endif } //end of stage 6 //multiply with twiddle for beginning of stage 7 //STRIDE_STAGE_7 1 if((threadIdx.x & STRIDE_STAGE_7) == STRIDE_STAGE_7) { //calculate Q twiddle factor int q = ((threadIdx.x & M12)>>4) | (threadIdx.x & M34) | ((threadIdx.x & M56)<<4); q = ((q & M135)>>2) | (q & M246); float Q = q*NEG_2PI_BY_TLEN; float c, s, T; __sincosf(Q, &s, &c); #pragma unroll for(int I = 0; I < HEIGHT; I++) { T = rVal[I]; rVal[I] = rVal[I]*c - iVal[I]*s; iVal[I] = T*s + iVal[I]*c; } } #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][threadIdx.x] = rVal[I]; shImg[I][threadIdx.x] = iVal[I]; } __syncthreads(); //stage 7 if((threadIdx.x & STRIDE_STAGE_7) == STRIDE_STAGE_7) { rVal[0] = shReal[0][threadIdx.x - STRIDE_STAGE_7] - rVal[0]; iVal[0] = shImg[0][threadIdx.x - STRIDE_STAGE_7] - iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x - STRIDE_STAGE_7] - rVal[1]; iVal[1] = shImg[1][threadIdx.x - STRIDE_STAGE_7] - iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x - STRIDE_STAGE_7] - rVal[2]; iVal[2] = shImg[2][threadIdx.x - STRIDE_STAGE_7] - iVal[2]; rVal[3] = shReal[3][threadIdx.x - STRIDE_STAGE_7] - rVal[3]; iVal[3] = shImg[3][threadIdx.x - STRIDE_STAGE_7] - iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x - STRIDE_STAGE_7] - rVal[4]; iVal[4] = shImg[4][threadIdx.x - STRIDE_STAGE_7] - iVal[4]; rVal[5] = shReal[5][threadIdx.x - STRIDE_STAGE_7] - rVal[5]; iVal[5] = shImg[5][threadIdx.x - STRIDE_STAGE_7] - iVal[5]; rVal[6] = shReal[6][threadIdx.x - STRIDE_STAGE_7] - rVal[6]; iVal[6] = shImg[6][threadIdx.x - STRIDE_STAGE_7] - iVal[6]; rVal[7] = shReal[7][threadIdx.x - STRIDE_STAGE_7] - rVal[7]; iVal[7] = shImg[7][threadIdx.x - STRIDE_STAGE_7] - iVal[7]; #endif } else { rVal[0] = shReal[0][threadIdx.x + STRIDE_STAGE_7] + rVal[0]; iVal[0] = shImg[0][threadIdx.x + STRIDE_STAGE_7] + iVal[0]; #if HEIGHT > 1 rVal[1] = shReal[1][threadIdx.x + STRIDE_STAGE_7] + rVal[1]; iVal[1] = shImg[1][threadIdx.x + STRIDE_STAGE_7] + iVal[1]; #endif #if HEIGHT > 2 rVal[2] = shReal[2][threadIdx.x + STRIDE_STAGE_7] + rVal[2]; iVal[2] = shImg[2][threadIdx.x + STRIDE_STAGE_7] + iVal[2]; rVal[3] = shReal[3][threadIdx.x + STRIDE_STAGE_7] + rVal[3]; iVal[3] = shImg[3][threadIdx.x + STRIDE_STAGE_7] + iVal[3]; #endif #if HEIGHT > 4 rVal[4] = shReal[4][threadIdx.x + STRIDE_STAGE_7] + rVal[4]; iVal[4] = shImg[4][threadIdx.x + STRIDE_STAGE_7] + iVal[4]; rVal[5] = shReal[5][threadIdx.x + STRIDE_STAGE_7] + rVal[5]; iVal[5] = shImg[5][threadIdx.x + STRIDE_STAGE_7] + iVal[5]; rVal[6] = shReal[6][threadIdx.x + STRIDE_STAGE_7] + rVal[6]; iVal[6] = shImg[6][threadIdx.x + STRIDE_STAGE_7] + iVal[6]; rVal[7] = shReal[7][threadIdx.x + STRIDE_STAGE_7] + rVal[7]; iVal[7] = shImg[7][threadIdx.x + STRIDE_STAGE_7] + iVal[7]; #endif } int revtid = bitreverse(threadIdx.x); /* #pragma unroll for(int I = 0; I < HEIGHT; I++) { shReal[I][revtid] = rVal[I]; shImg[I][revtid] = iVal[I]; } */ shReal[0][revtid] = rVal[0]; shImg[0][revtid] = iVal[0]; #if HEIGHT > 1 shReal[1][revtid] = rVal[1]; shImg[1][revtid] = iVal[1]; #endif #if HEIGHT > 2 shReal[2][revtid] = rVal[2]; shImg[2][revtid] = iVal[2]; shReal[3][revtid] = rVal[3]; shImg[3][revtid] = iVal[3]; #endif #if HEIGHT > 4 shReal[4][revtid] = rVal[4]; shImg[4][revtid] = iVal[4]; shReal[5][revtid] = rVal[5]; shImg[5][revtid] = iVal[5]; shReal[6][revtid] = rVal[6]; shImg[6][revtid] = iVal[6]; shReal[7][revtid] = rVal[7]; shImg[7][revtid] = iVal[7]; #endif __syncthreads(); #pragma unroll for(int I = 0; I < HEIGHT; I++) { real[((blockIdx.x*HEIGHT) + I)*blockDim.x + threadIdx.x] = shReal[I][threadIdx.x]; img[((blockIdx.x*HEIGHT) + I)*blockDim.x + threadIdx.x] = shImg[I][threadIdx.x]; } } __global__ void transposeDiagonal_xy(float *odatar, float *odatai, float *idatar, float *idatai, int width) { __shared__ float tile[TILE_DIM][TILE_DIM+1]; int blockIdx_x, blockIdx_y; // do diagonal reordering blockIdx_y = blockIdx.x; blockIdx_x = (blockIdx.x+blockIdx.y)%gridDim.x; // from here on the code is same as previous kernel except blockIdx_x replaces blockIdx.x // and similarly for y int xIndex = blockIdx_x * TILE_DIM + threadIdx.x; int yIndex = blockIdx_y * TILE_DIM + threadIdx.y; int index_in = xIndex + (yIndex + blockIdx.z*width)*width; xIndex = blockIdx_y * TILE_DIM + threadIdx.x; yIndex = blockIdx_x * TILE_DIM + threadIdx.y; int index_out = xIndex + (yIndex + blockIdx.z*width)*width; tile[threadIdx.y][threadIdx.x] = idatar[index_in]; __syncthreads(); odatar[index_out] = tile[threadIdx.x][threadIdx.y]; __syncthreads(); tile[threadIdx.y][threadIdx.x] = idatai[index_in]; __syncthreads(); odatai[index_out] = tile[threadIdx.x][threadIdx.y]; } __global__ void transposeDiagonal_xz(float *odatar, float *odatai, float *idatar, float *idatai, int width) { __shared__ float tile[TILE_DIM][TILE_DIM+1]; int blockIdx_x, blockIdx_z; // do diagonal reordering blockIdx_z = blockIdx.x; blockIdx_x = (blockIdx.x+blockIdx.z)%gridDim.x; // from here on the code is same as previous kernel except blockIdx_x replaces blockIdx.x // and similarly for y int xIndex = blockIdx_x * TILE_DIM + threadIdx.x; int zIndex = blockIdx_z * TILE_DIM + threadIdx.z; int index_in = xIndex + (blockIdx.y + zIndex*width)*width; xIndex = blockIdx_z * TILE_DIM + threadIdx.x; zIndex = blockIdx_x * TILE_DIM + threadIdx.z; int index_out = xIndex + (blockIdx.y + zIndex*width)*width; tile[threadIdx.z][threadIdx.x] = idatar[index_in]; __syncthreads(); odatar[index_out] = tile[threadIdx.x][threadIdx.z]; __syncthreads(); tile[threadIdx.z][threadIdx.x] = idatai[index_in]; __syncthreads(); odatai[index_out] = tile[threadIdx.x][threadIdx.z]; } __global__ void transposeDiagonal_xy(float *odata, float *idata, int width) { __shared__ float tile[TILE_DIM][TILE_DIM+1]; int blockIdx_x, blockIdx_y; // do diagonal reordering blockIdx_y = blockIdx.x; blockIdx_x = (blockIdx.x+blockIdx.y)%gridDim.x; // from here on the code is same as previous kernel except blockIdx_x replaces blockIdx.x // and similarly for y int xIndex = blockIdx_x * TILE_DIM + threadIdx.x; int yIndex = blockIdx_y * TILE_DIM + threadIdx.y; int index_in = xIndex + (yIndex + blockIdx.z*width)*width; xIndex = blockIdx_y * TILE_DIM + threadIdx.x; yIndex = blockIdx_x * TILE_DIM + threadIdx.y; int index_out = xIndex + (yIndex + blockIdx.z*width)*width; tile[threadIdx.y][threadIdx.x] = idata[index_in]; __syncthreads(); odata[index_out] = tile[threadIdx.x][threadIdx.y]; } __global__ void transposeDiagonal_xz(float *odata, float *idata, int width) { __shared__ float tile[TILE_DIM][TILE_DIM+1]; int blockIdx_x, blockIdx_z; // do diagonal reordering blockIdx_z = blockIdx.x; blockIdx_x = (blockIdx.x+blockIdx.z)%gridDim.x; // from here on the code is same as previous kernel except blockIdx_x replaces blockIdx.x // and similarly for y int xIndex = blockIdx_x * TILE_DIM + threadIdx.x; int zIndex = blockIdx_z * TILE_DIM + threadIdx.z; int index_in = xIndex + (blockIdx.y + zIndex*width)*width; xIndex = blockIdx_z * TILE_DIM + threadIdx.x; zIndex = blockIdx_x * TILE_DIM + threadIdx.z; int index_out = xIndex + (blockIdx.y + zIndex*width)*width; tile[threadIdx.z][threadIdx.x] = idata[index_in]; __syncthreads(); odata[index_out] = tile[threadIdx.x][threadIdx.z]; }
5,738
#include <cuda.h> #include <stdio.h> __global__ void matAddKernel(float* A, float* B, float* C, int width, int height){ int col = blockDim.x*blockIdx.x + threadIdx.x; int row = blockDim.y*blockIdx.y + threadIdx.y; int i = col + row*width; if(i < width*height){ C[i] = A[i] + B[i]; } } void matAdd(float* A, float* B, float* C, int width, int height) { int size = width * height * sizeof(float); static float *d_A, *d_B, *d_C; cudaMalloc((void **) &d_A, size); cudaMemcpy(d_A, A, size, cudaMemcpyHostToDevice); cudaMalloc((void **) &d_B, size); cudaMemcpy(d_B, B, size, cudaMemcpyHostToDevice); cudaMalloc((void **) &d_C, size); dim3 dimGrid(5, 4, 1); dim3 dimBlock(16, 16, 1); matAddKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C, width, height); cudaMemcpy(C, d_C, size, cudaMemcpyDeviceToHost); printf("\nA: \n"); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++){ printf("%2.0f ", A[i + j*width]); } printf("\n"); } printf("\nB: \n"); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++){ printf("%2.0f ", B[i + j*width]); } printf("\n"); } printf("\n-------------------------------------"); printf("\nC: \n"); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++){ printf("%2.0f ", C[i + j*width]); } printf("\n"); } printf("\n-------------------------------------\n"); cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); } int main() { int width = 76; int height = 62; static float h_A[76*62]; static float h_B[76*62]; static float h_C[76*62]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { h_A[i + j*width] = (i+j)%2; h_B[i + j*width] = (i+j)%3; } } matAdd(h_A, h_B, h_C, width, height); }
5,739
#include <math.h> #include <stdio.h> // Array access macros #define INPUT(i,j) imgBef[(i)*n + j] #define OUTPUT(i,j) imgAfter[(i)*n + j] #define fNi(i,j) fNi[(i)*patchSize + j] #define fNj(i,j) fNj[(i)*patchSize + j] #define fN(i,j) fN[(i)*patchSize + j] #define H(i,j) H[(i)*patchSize + j] #define PATCH(i,j) patch[(i)*blockDim.y + j] #define OTHER_PATCH(i,j) other_patch[(i)*blockDim.y + j] /* If out of block -> get fNi from global memory Else get from patch (shared) Out of block happens when: k or l <= padSize OR if k > blockDim.x + padSize or if l > blockDim.y + padSize */ __device__ int isInBlock(int k, int l, int padSize, int a, int b){ if (k<0 || l<0 || k>a || l>b){ return 0; } else { return 1; } } /* Calculates the norm between two vectors based on the gaussian matrix H for a predetermined patch size. */ __device__ float calcNorm(float *fNi, float *fNj, float *H, int patchSize){ float sum =0; for (int k=0; k< patchSize; k++){ for (int l=0; l<patchSize; l++){ sum+=(fNi(k,l)-fNj(k,l))*(fNi(k,l)-fNj(k,l))*H(k,l); } } return sum; } /* Checks if targetted pixel at the edges of the final blocks is outside of the image. */ __device__ int pixelOutofImg(int x, int y, int m, int n){ if (x > m || y > n){ return 1; } else{ return 0; } } __device__ void computeFN(float * fN, int i, int j, int n, float * patch, float const * imgBef, int padSize, int patchSize, int currentBlock_X, int currentBlock_Y, int blockDimX, int blockDimY ){ int a,b,k,l,e=0,f=0; for (k=i-padSize; k<=i+padSize; k++){ for (l = j-padSize; l<=j+padSize; j++){ a = k - currentBlock_X * blockDimX; // a e [0,patchSize) b = l - currentBlock_Y * blockDimY; // b e [0,patchSize) if (isInBlock(a, b, padSize, blockDimX, blockDimY)){ fN(e,f) = PATCH(a,b); } else{ fN(e,f) = INPUT(k,l); } f++; if (f==patchSize){ f=0; e++; } } } } __global__ void cudaNonLocalMeans(float const *imgBef, float *imgAfter, float *H, float filtSigma, int m, int n, int padSize) { // Get pixel (x,y) in input __shared__ extern float patch[]; float *other_patch = patch + blockDim.x*blockDim.y; int currentBlock_X = blockIdx.x; // [0,numBlocksX) int currentBlock_Y = blockIdx.y; // [0,numBlocksY) int patchSize = 2*padSize+1; int notInPaddedArea=1; //float *other_patch = patch + int i = currentBlock_X * blockDim.x + threadIdx.x; int j = currentBlock_Y * blockDim.y + threadIdx.y; // nBlocks_X,Y is the number of blocks per axis int nBlocks_X = gridDim.x; int nBlocks_Y = gridDim.y; float Z=0; float exponent=0; float pixel=0; float *fNi, *fNj; // if i or j less than 2 or greater than 65 they are outside of the image. if (i < padSize || j < padSize || i > m-padSize-1 || j > n-padSize-1) notInPaddedArea=0; if (i < m && j < n){ // INSIDE IMAGE if (notInPaddedArea){ PATCH(threadIdx.x, threadIdx.y) = INPUT(i,j); // fNi calculation computeFN(fNi, i, j, n, patch,imgBef,padSize,patchSize,currentBlock_X, currentBlock_Y, blockDim.x, blockDim.y); // fNj calculation for CURRENT block only. for (int row = currentBlock_X*blockDim.x ; row<(currentBlock_X+1)*blockDim.x; row++){ for (int col = currentBlock_Y*blockDim.y ; col<(currentBlock_Y+1)*blockDim.y; col++){ //if (row > m-padSize || col > n-padSize || row < padSize || col < padSize )continue; computeFN(fNj, row, col, n, patch,imgBef,padSize,patchSize,currentBlock_X, currentBlock_Y, blockDim.x, blockDim.y); exponent = calcNorm(fNi, fNj, H, patchSize); exponent/=filtSigma; Z+=exp(-exponent); pixel += exp(-exponent)*INPUT(row,col); } } } } __syncthreads(); /* So far the pixel has been affected only by the values of its own block. The following code implements the effect of the rest of the blocks on the pixel. */ int blockNoX, blockNoY; // For each block other than the current for (blockNoX = 0; blockNoX < nBlocks_X ; blockNoX++){ for (blockNoY = 0; blockNoY < nBlocks_Y ; blockNoY++){ if (blockNoX!=currentBlock_X && blockNoY!=currentBlock_Y){ // Save block to shared // For each pixel of the block copy to shared (other_patch) if (!(pixelOutofImg(blockNoX * blockDim.x + threadIdx.x, blockNoY * blockDim.y + threadIdx.y, m, n))){ OTHER_PATCH(threadIdx.x,threadIdx.y)=INPUT(blockNoX * blockDim.x + threadIdx.x , blockNoY * blockDim.y + threadIdx.y); } __syncthreads(); // If the pixel is inside the current block compute from shared, otherwise from global. if (notInPaddedArea){ for (int row = blockNoX*blockDim.x ; row<(blockNoX+1)*blockDim.x; row++){ for (int col = blockNoY*blockDim.y ; col<(blockNoY+1)*blockDim.y; col++){ if (row > m-padSize || col > n-padSize) continue; computeFN(fNj, row, col, n, other_patch,imgBef,padSize,patchSize,blockNoX,blockNoY, blockDim.x, blockDim.y); exponent = calcNorm(fNi, fNj, H, patchSize); exponent/=filtSigma; Z+=exp(-exponent); pixel += exp(-exponent)*INPUT(row,col); } } } } } } /* Finally since the total effect of the other pixels on the current pixel has been calculated, pixel is divided by the finalized Z matrix ending up with its final denoised version. */ if (notInPaddedArea){ OUTPUT(i,j) = pixel/Z; }else{ OUTPUT(i,j) = 1; } }
5,740
#include <stdio.h> #include <stdlib.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_runtime_api.h> #include <curand.h> #define CUDA_CALL(x) do { if((x)!=cudaSuccess) {\ printf("Error at %s:%d\n", __FILE__,__LINE__);\ return EXIT_FAILURE;}} while(0) #define CURAND_CALL(x) do { if((x)!=CURAND_STATUS_SUCCESS) { \ printf("Error");\ return EXIT_FAILURE;}} while(0) int main(void) { size_t n = 100; size_t i; curandGenerator_t gen; float *d_data, *h_data; float mean, stddev; //Set mean and standard deviation mean = 0.0; stddev = 1.0; // Allocate n floats on host h_data = (float *)malloc(n*sizeof(h_data)); // Allocate n floats on device CUDA_CALL(cudaMalloc((void **)&d_data, n*sizeof(d_data))); //Create random number generator CURAND_CALL(curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT)); //Set seed CURAND_CALL(curandSetPseudoRandomGeneratorSeed(gen, 1234ULL)); //Generate n normally distributed values CURAND_CALL(curandGenerateNormal(gen, d_data, n, mean, stddev)); //Copy generated numbers to host CUDA_CALL(cudaMemcpy(h_data, d_data,n * sizeof(float), cudaMemcpyDeviceToHost)); //Print results for (i = 0; i < n; i++) { printf("%1.4f ", h_data[i]); printf("\n"); } //Cleanup CURAND_CALL(curandDestroyGenerator(gen)); CUDA_CALL(cudaFree(d_data)); free(h_data); return EXIT_SUCCESS; }
5,741
// NAME: Jose Torres #include <stdio.h> #include <iostream> #include <assert.h> __global__ void matrixMulCUDA(float *A, float *B, float *C, int size){ // Code from HW slide __shared__ float smem_c[64][64]; __shared__ float smem_a[64][8]; __shared__ float smem_b[8][64]; int c = blockIdx.x * 64; int r = blockIdx.y * 64; for(int kk = 0; kk < size; kk += 8){ for(int i = threadIdx.x + blockDim.x * threadIdx.y; i < 64 * 8; i += blockDim.x * blockDim.y){ // load into shared memory int k = kk + i / 64; int rt = r + i % 64; int ct = c + i % 64; smem_a[i%64][i/64] = A[rt*size+k]; smem_b[i/64][i%64] = B[k*size+ct]; } __syncthreads(); for(int i=0; i < 2; ++i){ for(int j=0; j < 2; ++j){ int rowIdx = threadIdx.y * 2 + j; int colIdx = threadIdx.x * 2 + i; for(int k=0; k < 8; ++k){ // Store / Compute results in shared C smem_c[rowIdx][colIdx] += smem_a[rowIdx][k] * smem_b[k][colIdx]; } // Store back into global memory C[(r+rowIdx) * size + (c+colIdx)] = smem_c[rowIdx][colIdx]; } } } } int main() { const int N = 8192; // Declare host memory for Matrices A and B float *hostA, *hostB, *hostC, *hostSumTemp; // Declare device memory float *deviceA, *deviceB, *deviceC; // Allocate host memory for all Matrices size_t memSize = sizeof(float) * N * N; hostA = (float*) malloc(memSize); hostB = (float*) malloc(memSize); hostC = (float*) malloc(memSize); hostSumTemp = (float*) malloc(memSize); // init host memory // A = 2, 2, 2, 2 . . . // B = 3, 3, 3, 3 . . . // C = 0, 0, 0, 0 . . . // hostSumTemp = 6, 6, 6, 6, ... // hostSumTemp is just temp variable to compare to // values are chosen to be really easy for(int i=0; i < N; ++i){ for(int j=0; j < N; ++j){ hostA[i*N+j] = 2; hostB[i*N+j] = 3; hostC[i*N+j] = 0; hostSumTemp[i*N+j] = 6; } } // Allocate device memory cudaMalloc((void**) &deviceA, memSize); cudaMalloc((void**) &deviceB, memSize); cudaMalloc((void**) &deviceC, memSize); // Copy Matrix A and B from host to device cudaMemcpy(deviceA, hostA, memSize, cudaMemcpyHostToDevice); cudaMemcpy(deviceB, hostB, memSize, cudaMemcpyHostToDevice); // Invoke Kernel dim3 nblocks(N / 64, N / 64); dim3 nthreads(32, 32); // Init Kernel matrixMulCUDA<<<nblocks, nthreads>>> (deviceA, deviceB, deviceC, N); // Transfer from result matrix from device to host cudaMemcpy(hostC, deviceC, memSize, cudaMemcpyDeviceToHost); // Check results bool isSame = true; int row, col; for(row=0; row < N; ++row){ for(col=0; col < N; ++col){ if(hostC[row*N+col] != hostSumTemp[row*N+col]){ isSame = false; break; } } } // Print comparasion if(!isSame){ std::cout << "Did not match at \n\trow = " << row << "\n\tcol = " << col << std::endl; } else { std::cout << "Results matched.\n"; } // free memory free(hostA); free(hostB); free(hostC); free(hostSumTemp); cudaFree(deviceA); cudaFree(deviceB); cudaFree(deviceC); return 0; }
5,742
//#include "stdafx.h" //#include "voxel.cuh" //#include "cuda_definitions.h" //// From http://www.jcgt.org/published/0006/02/01/ //__device__ bool intersect_aabb_branchless2(const glm::vec3& origin, const glm::vec3& direction, float& tmin) { // constexpr glm::vec3 box_min = { 0, 0, 0 }; // constexpr glm::vec3 box_max = { grid_size, grid_size, grid_height }; // // const glm::vec3 t1 = (box_min - origin) / direction; // const glm::vec3 t2 = (box_max - origin) / direction; // const glm::vec3 tMin = glm::min(t1, t2); // const glm::vec3 tMax = glm::max(t1, t2); // // tmin = glm::max(glm::max(tMin.x, 0.f), glm::max(tMin.y, tMin.z)); // return glm::min(tMax.x, glm::min(tMax.y, tMax.z)) > tmin; //} // //__device__ bool intersect_byte(glm::vec3 origin, glm::vec3 direction, glm::vec3& normal, float& distance, uint8_t byte) { // glm::ivec3 pos = origin; // // glm::ivec3 out; // glm::ivec3 step; // glm::vec3 cb, tmax, tdelta; // // cb.x = direction.x > 0 ? pos.x + 1 : pos.x; // cb.y = direction.y > 0 ? pos.y + 1 : pos.y; // cb.z = direction.z > 0 ? pos.z + 1 : pos.z; // out.x = direction.x > 0 ? 2 : -1; // out.y = direction.y > 0 ? 2 : -1; // out.z = direction.z > 0 ? 2 : -1; // step.x = direction.x > 0 ? 1 : -1; // step.y = direction.y > 0 ? 1 : -1; // step.z = direction.z > 0 ? 1 : -1; // // float rxr, ryr, rzr; // if (direction.x != 0) { // rxr = 1.0f / direction.x; // tmax.x = (cb.x - origin.x) * rxr; // tdelta.x = step.x * rxr; // } else // tmax.x = 1000000.f; // if (direction.y != 0) { // ryr = 1.0f / direction.y; // tmax.y = (cb.y - origin.y) * ryr; // tdelta.y = step.y * ryr; // } else // tmax.y = 1000000.f; // if (direction.z != 0) { // rzr = 1.0f / direction.z; // tmax.z = (cb.z - origin.z) * rzr; // tdelta.z = step.z * rzr; // } else // tmax.z = 1000000.f; // // pos = pos % 2; // // distance = 0.f; // int smallest_component = -1; // // Stepping through grid // while (1) { // if (byte & (1 << (pos.x + pos.y * 2 + pos.z * 4))) { // if (smallest_component > -1) { // normal = glm::vec3(0, 0, 0); // normal[smallest_component] = -step[smallest_component]; // } // return true; // } // // smallest_component = (tmax.x < tmax.y) ? ((tmax.x < tmax.z) ? 0 : 2) : ((tmax.y < tmax.z) ? 1 : 2); // // distance = glm::min(tmax.x, glm::min(tmax.y, tmax.z)); // // if (tmax.x < tmax.y) { // if (tmax.x < tmax.z) { // pos.x += step.x; // if (pos.x == out.x) // return false; // tmax.x += tdelta.x; // } else { // pos.z += step.z; // if (pos.z == out.z) // return false; // tmax.z += tdelta.z; // } // } else { // if (tmax.y < tmax.z) { // pos.y += step.y; // if (pos.y == out.y) // return false; // tmax.y += tdelta.y; // } else { // pos.z += step.z; // if (pos.z == out.z) // return false; // tmax.z += tdelta.z; // } // } // } // return false; //} // //__device__ bool intersect_brick(glm::vec3 origin, glm::vec3 direction, glm::vec3& normal, float& distance, Brick* brick) { // glm::ivec3 pos = origin; // // glm::ivec3 out; // glm::ivec3 step; // glm::vec3 cb, tmax, tdelta; // // cb.x = direction.x > 0 ? pos.x + 1 : pos.x; // cb.y = direction.y > 0 ? pos.y + 1 : pos.y; // cb.z = direction.z > 0 ? pos.z + 1 : pos.z; // out.x = direction.x > 0 ? brick_size : -1; // out.y = direction.y > 0 ? brick_size : -1; // out.z = direction.z > 0 ? brick_size : -1; // step.x = direction.x > 0 ? 1 : -1; // step.y = direction.y > 0 ? 1 : -1; // step.z = direction.z > 0 ? 1 : -1; // // float rxr, ryr, rzr; // if (direction.x != 0) { // rxr = 1.0f / direction.x; // tmax.x = (cb.x - origin.x) * rxr; // tdelta.x = step.x * rxr; // } else // tmax.x = 1000000.f; // if (direction.y != 0) { // ryr = 1.0f / direction.y; // tmax.y = (cb.y - origin.y) * ryr; // tdelta.y = step.y * ryr; // } else // tmax.y = 1000000.f; // if (direction.z != 0) { // rzr = 1.0f / direction.z; // tmax.z = (cb.z - origin.z) * rzr; // tdelta.z = step.z * rzr; // } else // tmax.z = 1000000.f; // // pos = pos % 8; // // distance = 0.f; // int smallest_component = -1; // // Stepping through grid // while (1) { // int sub_data = (pos.x + pos.y * brick_size + pos.z * brick_size * brick_size) / 32; // int bit = (pos.x + pos.y * brick_size + pos.z * brick_size * brick_size) % 32; // // if (brick->data[sub_data] & (1 << bit)) { // if (smallest_component > -1) { // normal = glm::vec3(0, 0, 0); // normal[smallest_component] = -step[smallest_component]; // } // return true; // } // smallest_component = (tmax.x < tmax.y) ? ((tmax.x < tmax.z) ? 0 : 2) : ((tmax.y < tmax.z) ? 1 : 2); // // distance = glm::min(tmax.x, glm::min(tmax.y, tmax.z)); // // if (tmax.x < tmax.y) { // if (tmax.x < tmax.z) { // pos.x += step.x; // if (pos.x == out.x) // return false; // tmax.x += tdelta.x; // } else { // pos.z += step.z; // if (pos.z == out.z) // return false; // tmax.z += tdelta.z; // } // } else { // if (tmax.y < tmax.z) { // pos.y += step.y; // if (pos.y == out.y) // return false; // tmax.y += tdelta.y; // } else { // pos.z += step.z; // if (pos.z == out.z) // return false; // tmax.z += tdelta.z; // } // } // } // return false; //} // //__device__ bool intersect_voxel(glm::vec3 origin, glm::vec3 direction, glm::vec3& normal, float& distance, Scene::GPUScene scene, glm::ivec3 camera_position) { // float tminn; // if (!intersect_aabb_branchless2(origin, direction, tminn)) { // return false; // } // // // Move ray to hitpoint // if (tminn > 0) { // origin += direction * tminn; // // constexpr glm::vec3 scale = (glm::vec3(1.f / (grid_size / static_cast<float>(grid_height)), 1.f / (grid_size / static_cast<float>(grid_height)), 1.f / (grid_height / static_cast<float>(grid_height)))); // constexpr glm::vec3 grid_center = glm::vec3(grid_size / 2.f, grid_size / 2.f, grid_height / 2.f); // // glm::vec3 to_center = glm::abs(grid_center - origin) * scale; // glm::vec3 signs = glm::sign(origin - grid_center); // to_center /= glm::max(to_center.x, glm::max(to_center.y, to_center.z)); // normal = signs * glm::trunc(to_center + 0.000001f); // // origin -= normal * epsilon; // } // origin /= 8.f; // glm::ivec3 pos = origin; // glm::ivec3 out; // glm::ivec3 step; // glm::vec3 cb, tmax, tdelta; // // // Needed because sometimes the AABB intersect returns true while the ray is actually outside slightly. Only happens for faces that touch the AABB sides // if (pos.x < 0 || pos.x >= cells || pos.y < 0 || pos.y >= cells || pos.z < 0 || pos.z >= cells_height) { // return false; // } // // cb.x = direction.x > 0 ? pos.x + 1 : pos.x; // cb.y = direction.y > 0 ? pos.y + 1 : pos.y; // cb.z = direction.z > 0 ? pos.z + 1 : pos.z; // out.x = direction.x > 0 ? cells : -1; // out.y = direction.y > 0 ? cells : -1; // out.z = direction.z > 0 ? cells_height : -1; // step.x = direction.x > 0 ? 1 : -1; // step.y = direction.y > 0 ? 1 : -1; // step.z = direction.z > 0 ? 1 : -1; // // float rxr, ryr, rzr; // if (direction.x != 0) { // rxr = 1.0f / direction.x; // tmax.x = (cb.x - origin.x) * rxr; // tdelta.x = step.x * rxr; // } else // tmax.x = 1000000; // if (direction.y != 0) { // ryr = 1.0f / direction.y; // tmax.y = (cb.y - origin.y) * ryr; // tdelta.y = step.y * ryr; // } else // tmax.y = 1000000; // if (direction.z != 0) { // rzr = 1.0f / direction.z; // tmax.z = (cb.z - origin.z) * rzr; // tdelta.z = step.z * rzr; // } else // tmax.z = 1000000; // // float new_distance = 0.f; // // int smallest_component = -1; // while (1) { // int supercell_index = pos.x / supergrid_cell_size + (pos.y / supergrid_cell_size) * supergrid_xy + (pos.z / supergrid_cell_size) * supergrid_xy * supergrid_xy; // //uint32_t& index = scene.brick_grid[morton(pos.x) + (morton(pos.y) << 1) + (morton(pos.z) << 2)]; // uint32_t& index = scene.indices[supercell_index][(pos.x % supergrid_cell_size) + (pos.y % supergrid_cell_size) * supergrid_cell_size + (pos.z % supergrid_cell_size) * supergrid_cell_size * supergrid_cell_size]; // // if (index) { // if (smallest_component > -1) { // normal = glm::vec3(0, 0, 0); // normal[smallest_component] = -step[smallest_component]; // } // // glm::ivec3 difference = camera_position - pos; // int lod_distance_squared = difference.x * difference.x + difference.y * difference.y + difference.z * difference.z; // float sub_distance = 0.f; // // if (lod_distance_squared > lod_distance_8x8x8) { // distance = new_distance * 8.f + tminn; // return true; // } else if (lod_distance_squared > lod_distance_2x2x2) { // // For some reason the normal displacement has to be made even smaller // if (intersect_byte((origin + direction * new_distance) * 2.f - normal * 0.2f * epsilon, direction, normal, sub_distance, (index & brick_lod_bits) >> 12)) { // distance = new_distance * 8.f + sub_distance * 4.f + tminn; // return true; // } // } else { // if (index & brick_loaded_bit) { // Brick* p = scene.bricks[supercell_index]; // if (intersect_brick((origin + direction * new_distance) * 8.f - normal * epsilon, direction, normal, sub_distance, &p[index & brick_index_bits])) { // distance = new_distance * 8.f + sub_distance + tminn; // return true; // } // } else if (index & brick_unloaded_bit) { // uint32_t old = atomicOr(&index, brick_requested_bit); // // if (!(old & brick_requested_bit)) { // // request chunk to be loaded // // const unsigned int load_index = atomicAdd(scene.brick_load_queue_count, 1); // if (load_index < brick_load_queue_size) { // scene.brick_load_queue[load_index] = pos; // } else { // atomicAnd(&index, ~brick_requested_bit); // // ToDo happens a lot. Fix? // } // } // // distance = new_distance * 8.f + tminn; // return true; // } // } // } // // smallest_component = (tmax.x < tmax.y) ? ((tmax.x < tmax.z) ? 0 : 2) : ((tmax.y < tmax.z) ? 1 : 2); // // if (tmax.x < tmax.y) { // if (tmax.x < tmax.z) { // pos.x += step.x; // if (pos.x == out.x) // return false; // new_distance = tmax.x; // tmax.x += tdelta.x; // } else { // pos.z += step.z; // if (pos.z == out.z) // return false; // new_distance = tmax.z; // tmax.z += tdelta.z; // } // } else { // if (tmax.y < tmax.z) { // pos.y += step.y; // if (pos.y == out.y) // return false; // new_distance = tmax.y; // tmax.y += tdelta.y; // } else { // pos.z += step.z; // if (pos.z == out.z) // return false; // new_distance = tmax.z; // tmax.z += tdelta.z; // } // } // } // return false; //}
5,743
#include "includes.h" __device__ float_t d_randu(int * seed, int index) { int M = INT_MAX; int A = 1103515245; int C = 12345; int num = A * seed[index] + C; seed[index] = num % M; return fabsf(seed[index] / ((float_t) M)); } __device__ void cdfCalc(float_t * CDF, float_t * weights, int Nparticles) { int x; CDF[0] = weights[0]; for (x = 1; x < Nparticles; x++) { CDF[x] = weights[x] + CDF[x - 1]; } } __global__ void normalize_weights_kernel(float_t * weights, int Nparticles, float_t* partial_sums, float_t * CDF, float_t * u, int * seed) { int block_id = blockIdx.x; int i = blockDim.x * block_id + threadIdx.x; __shared__ float_t u1, sumWeights; if (0 == threadIdx.x) sumWeights = partial_sums[0]; __syncthreads(); if (i < Nparticles) { weights[i] = weights[i] / sumWeights; } __syncthreads(); if (i == 0) { cdfCalc(CDF, weights, Nparticles); u[0] = (1 / ((float_t) (Nparticles))) * d_randu(seed, i); // do this to allow all threads in all blocks to use the same u1 } __syncthreads(); if (0 == threadIdx.x) u1 = u[0]; __syncthreads(); if (i < Nparticles) { u[i] = u1 + i / ((float_t) (Nparticles)); } }
5,744
#include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/copy.h> #include <thrust/sort.h> #include <thrust/functional.h> #include <iostream> #include <iterator> int main() { thrust::host_vector<int> host_input{5, 1, 9, 3, 7}; thrust::device_vector<int> device_vec(5); thrust::copy(host_input.begin(), host_input.end(), device_vec.begin()); // 昇順でソートする thrust::sort(device_vec.begin(), device_vec.end()); thrust::copy(device_vec.begin(), device_vec.end(), std::ostream_iterator<int>(std::cout, ", ")); // 1, 3, 5, 7, 9 // 降順でソートする thrust::sort(device_vec.begin(), device_vec.end(), thrust::greater<int>()); thrust::copy(device_vec.begin(), device_vec.end(), std::ostream_iterator<int>(std::cout, ", ")); // 9, 7, 5, 3, 1 return 0; }
5,745
#include "includes.h" __global__ void childKernel(unsigned int parentThreadIndex, float* data) { data[threadIdx.x] = parentThreadIndex + 0.1f * threadIdx.x; }
5,746
extern "C" //must be same as threads!!! //Block_Size = blockDim.x #define Block_Size 64 #define m 0.001/2000 #define PI 3.14159265359f __global__ void ker_rho(float *out, const float *x, const int *ind, const float h) { //int IND = gridDim.z * gridDim.y * blockIdx.x + gridDim.z * blockIdx.y + blockIdx.z int istart = ind[2 * gridDim.z * gridDim.y * blockIdx.x + 2 * gridDim.z * blockIdx.y + 2 * blockIdx.z + 0]; int iend = ind[2 * gridDim.z * gridDim.y * blockIdx.x + 2 * gridDim.z * blockIdx.y + 2 * blockIdx.z + 1]; for (int i = istart; i < iend; i += Block_Size) { int id = i + threadIdx.x; float xi[3]; if (id < iend) { xi[0] = x[3 * id + 0]; xi[1] = x[3 * id + 1]; xi[2] = x[3 * id + 2]; } float dx[3]; float r2; float r; float W; float rho = 0; __shared__ float xj[Block_Size * 3]; for (int a = -1; a < 2; a++) { for (int b = -1; b < 2; b++) { if ((int)blockIdx.x + a < 0 || (int)blockIdx.x + a >= (int)gridDim.x || (int)blockIdx.y + b < 0 || (int)blockIdx.y + b >= (int)gridDim.y) { continue; } int Zstart = max((int)blockIdx.z - 1, 0); int Zend = min((int)blockIdx.z + 1, (int)gridDim.z - 1); int jstart = ind[2 * gridDim.z * gridDim.y * (blockIdx.x+a) + 2 * gridDim.z * (blockIdx.y+b) + 2 * Zstart + 0]; int jend = ind[2 * gridDim.z * gridDim.y * (blockIdx.x+a) + 2 * gridDim.z * (blockIdx.y+b) + 2 * Zend + 1]; for (int j = jstart; j < jend; j += Block_Size) { int jd = j + threadIdx.x; if (jd < jend) { xj[3 * threadIdx.x + 0] = x[3 * jd + 0]; xj[3 * threadIdx.x + 1] = x[3 * jd + 1]; xj[3 * threadIdx.x + 2] = x[3 * jd + 2]; } __syncthreads(); if (id < iend) { for (int k = 0; k < Block_Size; k++) { if (j + k < jend) { dx[0] = xj[3 * k + 0] - xi[0]; dx[1] = xj[3 * k + 1] - xi[1]; dx[2] = xj[3 * k + 2] - xi[2]; r2 = (dx[0] * dx[0] + dx[1] * dx[1] + dx[2] * dx[2]) / (h * h); if (r2 < 1.0) { r = sqrtf(r2+0.001*h*h); W = (1.0-r); W*=W; W*=W;//(1-r)^4 W*=(1+4.0*r)*21.0/(2.0*PI*h*h*h); //Wendland //dW = (1.0 - r); //dW *= dW*dW; //(1-r)^3 //dW *= -5*r; //dW *= 21.0 / (16.0 * PI * h * h * h * h); rho += m*W; } } } } __syncthreads(); } //ivol = 2 * gridDim.z * gridDim.y * blockIdx.x + 2 * gridDim.z * blockIdx.y + 2 * Zend; } } if (id < iend) { out[id] = rho; } } }
5,747
#include "includes.h" #define SEED #define BLOCK_SIZE 32 typedef struct _data { char * values; char * next_values; int width; int height; } data; __global__ void operate(char * source, char * goal, int sizex, int sizey) { __shared__ char local[BLOCK_SIZE + MASK_WIDTH - 1][BLOCK_SIZE + MASK_WIDTH - 1]; int i = blockIdx.y * blockDim.y + threadIdx.y; int j = blockIdx.x * blockDim.x + threadIdx.x; int index = i * sizex + j; int prim_x = j - MASK_RADIUS; int first_x = prim_x; for(; first_x - prim_x + threadIdx.x < MASK_WIDTH + BLOCK_SIZE - 1; first_x += BLOCK_SIZE) { int prim_y = i - MASK_RADIUS; int first_y = prim_y; for(; first_y - prim_y + threadIdx.y < MASK_WIDTH + BLOCK_SIZE - 1; first_y += BLOCK_SIZE) { if(first_y >= 0 && first_y < sizey && first_x >= 0 && first_x < sizex) { local[first_y - prim_y + threadIdx.y][first_x - prim_x + threadIdx.x] = source[first_y * sizex + first_x]; } else { local[first_y - prim_y + threadIdx.y][first_x - prim_x + threadIdx.x] = '0'; } } } __syncthreads(); if(i < sizey && j < sizex) { int l_j, l_i; int amount = 0; for(l_i = 0; l_i < MASK_WIDTH; l_i++) { if( ( (int) threadIdx.y + l_i >= 0 ) && ( (int) threadIdx.y + l_i < BLOCK_SIZE + MASK_WIDTH - 1) ) { for(l_j = 0; l_j < MASK_WIDTH; l_j++){ if( ( (int) threadIdx.x + l_j >= 0 ) && ( (int) threadIdx.x + l_j < BLOCK_SIZE + MASK_WIDTH - 1) ) { if(local[threadIdx.y + l_i][threadIdx.x + l_j] == '1') amount++; } } } } if(source[index] == '1') amount--; if(source[index] == '1') { if(amount < 2 || amount > 3) goal[index] = '0'; else goal[index] = '1'; } else { if(amount == 3) goal[index] = '1'; else goal[index] = '0'; } } }
5,748
#include <stdio.h> #include <stdlib.h> __global__ void add(int a, int b, int *c) { *c = a + b; } int main(int argc, char *argv[]) { int c; int *dev_c; cudaError_t error = cudaMalloc((void **)&dev_c, sizeof(int)); if(error != cudaSuccess) { printf("Memory could not be allocated on device\n"); exit(EXIT_FAILURE); } add<<<1,1>>>(2, 7, dev_c); error = cudaMemcpy(&c, dev_c, sizeof(int), cudaMemcpyDeviceToHost); if(error != cudaSuccess) { printf("Could not copy from device to host\n"); exit(EXIT_FAILURE); } printf("%d = 2 + 7\n", c); cudaFree(dev_c); return 0; }
5,749
#include "includes.h" #define BLOCKSIZE 4 #define CELLS_PER_THREAD 4 // Stride length __global__ void ShortestPath1(float *Arr1,float *Arr2,int N){ //Arr1 input array,Holds of (u,v) //Arr2 output array int k; int col=blockIdx.x * blockDim.x + threadIdx.x; int row=blockIdx.y * blockDim.y + threadIdx.y; int index=row*N+col; if((row<N)&&(col<N)){ Arr2[index]=Arr1[index]; for(k=0;k<N;k++){ if(Arr1[index]>(Arr1[row*N+k]+Arr1[N*k+col])){ Arr2[index]=Arr1[row*N+k]+Arr1[N*k+col]; // printf("ENTERED %f \n",Arr2[index]); } } } }
5,750
#include <stdio.h> __global__ void print_kernel() { // this time print the thread index // for simplicity print only for thread index equals 1 if (threadIdx.x == 1 ){ printf("Hello from block %d, thread %d\n", blockIdx.x, threadIdx.x); } // note use of threadIdx.x and blockIdx.x to get // thread and block index respectively } int main() { // specify the number of threads print_kernel<<<10, 10>>>(); // synchronize execution between host and device cudaDeviceSynchronize(); return 0; }
5,751
// cudaDCA.cu // //This file contains the recursive DCA function, and the function that is used to invoke DCA and //interperate the results. //Included Files #include <iostream> //Function Prototypes // Functions found in this file void RecDCA(double Zs[], int n, int i, double AF[], int cut_off,double Xs[]); // Functions found in Init_setup.cu void CudaInitialize(double m[], double l[], double I[], double x[], int n, double Zs[]); // Functions found in Assemble_setup.cu void cudaAssemble(double Zs[],double Xs[], int num, double nZs[], double nXs[], int odd, int newlen); // Functions found in Disassemble_setup.cu void cudaDisassemble(double OldAF[], double Zs[], double Xs[],double nZs[], double nXs[], int odd, int morelen, int lesslen, double AF[]); // Functions found in Assemble.cu // Functions found in SolveBCs.cu void solve_BCs(double Zs[], double Xs[], double AF[]); void printa(double A[], int n); void printm(double A[6][6]); void update(double Mass[], double Inertia[], double Init_Zetas[], double Zetas[], int n, double Body_Vectors[], double ang_vels[], double DCMs[],double Ps[], double PdotUs[],double Ds[],bool active_DOF[], double speeds[],int dof_index[]); void kinematics(bool Active_DOF[], double Coords[], double DCMs[], double speeds[], double omegas[], int dof_index[],int n); void getGenAccel(double Y[], double AF[],double omegas[], bool Active_DOF[], int n,double PdotUs[], double Ps[]); void multPinv(double Ps[], double tempy[], int b, int n); void RecDCA(double Zs[], int n, int i, double AF[], int cut_off,double Xs[], double DCMs[], double omegas[], int dof_index[], bool Active_DOF[], double Speeds[],double PdotUs[], double Ds[], int Pindex[],int numbods); void Assemble(double Zs[], double Xs[],double nZs[], double nXs[], int len, int odd, int n, double PdotUs[], double Ds[], int Pindex[],int numbods, bool active_DOF[]); void Disassemble(double lessZs[], double lessXs[],double moreZs[], double moreXs[], double oldAs[] ,double newAs[], int num, int odd,double Ds[], int Pindex[],int numbods, double PdotUs[]); void multPinv(double Ps[], double tempy[], int b, int n); void Mat61Mult2(double A[6][6], double B[6], double C[6]); void printzz(double A[], int n, int b, int zeta); //DCAhelp: // Function that prepares the list of bodies for DCA and finds the final state vector // state is the state of the system at that timestep // bs is a list of bodies used for initialization // js is a list of joints // n is the number of bodies // Y is the array where the final velocities and accelerations are stored void DCAhelp(int n,bool Active_DOF[],double Coords[], double Speeds[], int dof_index[], double initZetas[],double Mass[], double Inertia[],int DOF, double Y[], int cut_off, double Body_Vectors[]) { double *Zetas = new double[n*26*6]; double *Xs = new double[n*5*5]; double *DCMs = new double[n*3*3]; double *omegas= new double[n*3]; double *AF = new double[n*4*6]; double *Ps = new double[n*6*6]; double *PdotUs = new double[n*6]; double *Ds = new double[n*6*6]; int *Pindex = new int[n]; for(int i =0; i<n; i++) { Pindex[i]=i; } kinematics(Active_DOF, Coords, DCMs, Speeds, omegas, dof_index, n); update(Mass, Inertia, initZetas, Zetas, n, Body_Vectors, omegas, DCMs,Ps,PdotUs,Ds,Active_DOF,Speeds,dof_index); RecDCA(Zetas, n, 0, AF, cut_off,Xs,DCMs,omegas,dof_index,Active_DOF,Speeds,PdotUs,Ds,Pindex,n); getGenAccel(Y,AF,omegas,Active_DOF,n,PdotUs,Ps); //Free memory delete[] Zetas; delete[] Xs; delete[] DCMs; delete[] omegas; delete[] AF; delete[] Ps; delete[] PdotUs; delete[] Ds; delete[] Pindex; } void printzz(double A[], int n, int b, int zeta) { std::cout<<std::endl; for(int r = 0; r<6; r++) { for(int c =0; c<6; c++) { std::cout<<A[c+zeta+n*26*r+b*26]<<"\t"; } std::cout<<std::endl; } } void getGenAccel(double Y[], double AF[],double omegas[], bool Active_DOF[], int n, double PdotUs[], double Ps[]) { int c =0; int l =0; //double A1[6]; //double A2[6]; double tempy[6]; for(int i =0; i<6; i++) { tempy[i]=AF[i*4*n]-PdotUs[i]; } multPinv(Ps,tempy,0,n); for(int i =0; i<6; i++) { if(Active_DOF[i]) { Y[c]=tempy[c]; c++; } } for(int i =1; i<n; i++) { l =0; for(int k =0; k<6; k++) { tempy[k]=AF[i*4+k*4*n-2]-AF[i*4+k*4*n]-PdotUs[i*6+k]; } multPinv(Ps,tempy,i,n); for(int j=0; j<6; j++) { if(Active_DOF[6*i+j]) { Y[c]=tempy[l]; c++; l++; } } } } void multPinv(double Ps[], double tempy[], int b, int n) { double Pinv[6][6]; for( int r =0; r<6; r++) { for(int c =0; c<6; c++) { Pinv[c][r]=Ps[c+b*6+r*6*n]; } } Mat61Mult2(Pinv,tempy,tempy); } //RecDCA: // Function used to solve for the velocty and acceleration of the list of bodies at // the current timestep. This is a recursive function that continues to call itself // until there is a single body left. Once at this point the accelerations and forces // are found using the boundary conditions of a pendulum. These values are then returned // to the previous level of recursion which then finds the new accelerations and forces // for the disassembled bodies. This continues until all bodies are disassembled, ultimately // returning the forces and accelerations at both handles of every body in the system. These // results are intererated by DCAhelp (above) to obtain the actual generalized accelerations. // bodies is the list of bodies // n is the number of bodies // i is the level of recursion // AF is the array in which the accelerations and forces at the handles of the bodies // will be stored. void RecDCA(double Zs[], int n, int i, double AF[], int cut_off,double Xs[], double DCMs[], double omegas[], int dof_index[], bool Active_DOF[], double Speeds[],double PdotUs[], double Ds[], int Pindex[],int numbods) { if (n==1) //If there is only 1 body { solve_BCs(Zs,Xs, AF); //Solve the boundary conditions and find the acceleratins and forces } else //If there is more than 1 body { int newlen; //New number of bodies after assembly bool odd = 0; //Flag to keep track of the parity of the length of the list of if(n % 2 == 0) //If there is an even number of bodies { newlen = (int) (n/2); //The new number of bodies will be half the original number } else //If there is an odd number of bodies { newlen = (int)((n+1)/2); //The new number of bodies will be half the original number //rounded down, plus 1 odd = 1; //odd is set to 1 because there are an odd number of bodies } double *nZs=new double[newlen*26*6]; double *nXs=new double[newlen*5*5]; int *nPindex = new int[newlen]; for(int k =0; k<newlen-odd; k++) { nPindex[i]=Pindex[i*2]; } if(odd) { nPindex[newlen-1]=Pindex[n-1]; } /* if(i<cut_off) { cudaAssemble(Zs,Xs, n, nZs, nXs , odd, newlen); //Assemble the bodies, storing them in newbds } else {*/ Assemble(Zs,Xs,nZs,nXs, newlen,odd, n,PdotUs,Ds,Pindex,numbods,Active_DOF); //Assemble the bodies, storing them in newbds //} //Create a list of accelerations and forces of the new bodies. double *AFo= new double[6*newlen*4]; //Call the DCA function again to return the accelerations and forces of the new bodies RecDCA(nZs,newlen,i+1 ,AFo,cut_off,nXs,DCMs,omegas,dof_index,Active_DOF,Speeds,PdotUs,Ds,nPindex,numbods); //Knowing the accelerations and forces of the new bodies, the new bodies can be disassembled //again, finding the accelerations and forces of the old bodies. /*if(i<cut_off) { cudaDisassemble(AFo, Zs,Xs , nZs,nXs, odd, n, newlen, AF); } else {*/ Disassemble(nZs,nXs,Zs,Xs,AFo, AF, newlen,odd,Ds,Pindex,numbods,PdotUs); //} //Free memory delete[] nZs; delete[] nXs; delete[] AFo; delete[] nPindex; } }
5,752
#include <stdio.h> #include <time.h> #include <math.h> #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #include <cuda_fp16.h> #define EPS 0.0000001f #define SIZE 1024 #define BIG_VALUE 65536 #define BLOCK_SIZE 256 // generate random matrix void getMatrix(float* matrix, unsigned size) { if (matrix == NULL){ fprintf(stderr, "getMatrix doesn't get matrix\n"); exit(-1); } for (unsigned i = 0; i < size; i++) { for (unsigned j = 0; j < size; j++) { matrix[i + size * j] = (((float)rand() / RAND_MAX) - 0.5f) * 10; } } // add diagonal predominance for (unsigned i = 0; i < size; i++) { matrix[i + size * i] += 1000; } } // generate random vector void get_f(float *f, unsigned size) { if (get_f == NULL){ fprintf(stderr, "get_f doen't get vector\n"); exit(-1); } for (unsigned i = 0; i < size; i++) { f[i] = (((float)rand() / RAND_MAX) - 0.5f) * 10; } } // compute Matrix B, and return result in argument void computeBMatrix(float *A, unsigned size) { if (A == NULL){ fprintf(stderr, "computeBMatrix doesn't get matrix\n"); exit(-1); } float *inverse_D = (float *)calloc(size, sizeof(float)); if (inverse_D == NULL){ fprintf(stderr, "error on allocate memory\n"); exit(-1); } //D = diag(A) //compute D^-1 for (unsigned i = 0; i < size; i++) { inverse_D[i] = 1.0f / A[i + size * i]; } //compute D^-1 * A for (unsigned i = 0; i < size; i++) { //columns for (unsigned j = 0; j < size; j++) { //lines A[i + size * j] = inverse_D[j] * A[i + size * j]; } } //compute I - D^-1 * A for (unsigned i = 0; i < size; i++) { for (unsigned j = 0; j < size; j++) { float tmp = (i == j) ? 1 : 0; A[i + size * j] = tmp - A[i + size * j]; } } free(inverse_D); } // compute vector g and return in argument void compute_g(float *A, float* b, unsigned size) { if (A == NULL || b == NULL){ fprintf(stderr, "compute_g get invalud arguments\n"); exit(-1); } // g = diag(A) ^ -1 * b; for (unsigned i = 0; i < size; i++) { b[i] = (1.0f / A[i + size * i]) * b[i]; } } // metric is : max(|Ax_i - f_i|) float precision(float *matrix, float *f, float* x, unsigned size) { if (matrix == NULL || f == NULL || x == NULL){ fprintf(stderr, "precision get invalid parametr\n"); exit(-1); } float max = 0; for (unsigned i = 0; i < size; i++) { float cur = 0; for (unsigned j = 0; j < size; j++) { cur += matrix[j + size * i] * x[j]; } cur = fabs(f[i] - cur); max = max < cur ? cur : max; } return max; } // cuda kernel //with transpose matrix B __global__ void jacobi(float* B, float* g, float* x, unsigned size, float* x_next) { int idx = blockIdx.x * blockDim.x + threadIdx.x; float x_curr = 0; __shared__ float shared_x[SIZE]; for (int i = 0; i < SIZE / blockDim.x; i++){ int loc_idx = blockDim.x * i + threadIdx.x; shared_x[loc_idx] = x[loc_idx]; } __syncthreads(); #pragma uroll 16 for (int i = 0; i < size; i++) { // here loc_i is useless, becouse matrix B x_curr += B[idx + i * size] * shared_x[i]; } x_next[idx] = x_curr + g[idx]; } void transpose(float* matrix, unsigned size) { for (unsigned i = 0; i < size; i++){ for (unsigned j = 0; j < i; j++){ //swap value float tmp = matrix[i + j * size]; matrix[i + j * size] = matrix[j + i * size]; matrix[j + i * size] = tmp; } } } void checkGPUOperation() { cudaError_t code = cudaGetLastError(); if (code != cudaSuccess){ fprintf(stderr, "Cuda Error : %s\n", cudaGetErrorString(code)); exit(-1); } } int main() { float eps = EPS; unsigned size = SIZE; // alloc memory on CPU float *host_A = (float *)malloc(size * size * sizeof(float)); float *host_B = (float *)malloc(size * size * sizeof(float)); float *host_f = (float *)malloc(size * sizeof(float)); float *host_g = (float *)malloc(size * sizeof(float)); float *host_x = (float *)calloc(size, sizeof(float)); // start with null vector if (host_A == NULL || host_B == NULL || host_f == NULL || host_g == NULL || host_x == NULL){ fprintf(stderr, "error on allocate memory\n"); return -1; } getMatrix(host_A, size); get_f(host_f, size); memcpy(host_B, host_A, size * size * sizeof(float)); memcpy(host_g, host_f, size * sizeof(float)); compute_g(host_A, host_g, size); computeBMatrix(host_B, size); transpose(host_B, size); // transpose for optimization // alloc memory on GPU float *dev_B, *dev_g, *dev_x_prev, *dev_x_next; cudaMalloc((void **)&dev_B, size * size * sizeof(float)); checkGPUOperation(); cudaMalloc((void **)&dev_g, size * sizeof(float)); checkGPUOperation(); cudaMalloc((void **)&dev_x_prev, size * sizeof(float)); checkGPUOperation(); cudaMalloc((void **)&dev_x_next, size * sizeof(float)); checkGPUOperation(); //copy memory from CPU to GPU cudaMemcpy(dev_x_prev, host_x, size * sizeof(float), cudaMemcpyHostToDevice); checkGPUOperation(); cudaMemcpy(dev_x_next, dev_x_prev, size * sizeof(float), cudaMemcpyDeviceToDevice); checkGPUOperation(); cudaMemcpy(dev_B, host_B, size * size * sizeof(float), cudaMemcpyHostToDevice); checkGPUOperation(); cudaMemcpy(dev_g, host_g, size * sizeof(float), cudaMemcpyHostToDevice); float p = 0; //precision float prev_p = BIG_VALUE; //previos precision // when precision stop decrease stop compute do { for (int i = 0; i < 512; i++) { //swap vectors float *tmp = dev_x_next; dev_x_next = dev_x_prev; dev_x_prev = tmp; jacobi <<<dim3(size / BLOCK_SIZE), dim3(BLOCK_SIZE)>>> (dev_B, dev_g, dev_x_prev, size, dev_x_next); cudaDeviceSynchronize(); } //get result cudaMemcpy(host_x, dev_x_next, size * sizeof(float), cudaMemcpyDeviceToHost); checkGPUOperation(); prev_p = p; p = precision(host_A, host_f, host_x, size); printf("precision : %f \n", p); } while (p > eps && p < prev_p); printf("success\n"); //free memory on CPU free(host_A); free(host_B); free(host_f); free(host_g); free(host_x); //free memory on GPU cudaFree(dev_B); cudaFree(dev_g); cudaFree(dev_x_prev); cudaFree(dev_x_next); #ifdef _WIN32 // stop console // only Windows needed scanf("\n"); #endif return 0; }
5,753
#include <thrust/device_vector.h> #include <thrust/transform.h> #include <thrust/sequence.h> #include <thrust/copy.h> #include <thrust/fill.h> #include <thrust/replace.h> #include <thrust/functional.h> #include <iostream> #include <vector> template <typename T> std::vector<std::vector<T> > matrix_wise_plus(std::vector<std::vector<T> > mat, T nb) { unsigned int row_size, col_size; col_size = mat.size(); row_size = mat[0].size(); thrust::device_vector<float> d_mat(row_size * col_size); thrust::device_vector<float> d_result(row_size * col_size); for (unsigned int i = 0; i < col_size; i += 1) thrust::copy(mat[i].begin(), mat[i].end(), d_mat.begin() + (i * row_size)); thrust::fill(d_result.begin(), d_result.end(), nb); thrust::transform(d_mat.begin(), d_mat.end(), d_result.begin(), d_result.begin(), thrust::plus<float>()); for (unsigned int i = 0; i < col_size; i += 1) thrust::copy(d_result.begin() + (i * row_size), d_result.begin() + (i * row_size) + row_size, mat[i].begin()); return (mat); } int main(void) { std::vector< std::vector<float> > mat(3, std::vector< float >(3, 1.1)); for (int i = 0; i < 3; i++) { mat[1][i] = 4.4; mat[2][i] = 7.7; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) std::cout << mat[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; mat = matrix_wise_plus(mat, 1.1f); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) std::cout << mat[i][j] << " "; std::cout << std::endl; } return (0); } // int main(void) // { // // allocate three device_vectors with 10 elements // thrust::device_vector<float> X(10); // thrust::device_vector<float> Y(10); // thrust::device_vector<float> Z(10); // // initialize X to 0,1,2,3, .... // // thrust::sequence(X.begin(), X.end()); // for (float i = 0; i < 10; i++) // X[i] = i; // // // compute Y = -X // // thrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>()); // // fill Z with twos // thrust::fill(Z.begin(), Z.end(), 10); // // // compute Y = X mod 2 // thrust::transform(X.begin(), X.end(), Z.begin(), Y.begin(), thrust::plus<int>()); // // // replace all the ones in Y with tens // // thrust::replace(Y.begin(), Y.end(), 1, 10); // // print Y // // thrust::copy(Y.begin(), Y.end(), std::ostream_iterator<int>(std::cout, "\n")); // Sf a; // for (int i = 0; i < 10; i++) // { // a = Z[i]; // std::cout << a << std::endl; // } // return 0; // } // #include <thrust/device_vector.h> // #include <thrust/transform.h> // #include <thrust/sequence.h> // #include <thrust/copy.h> // #include <thrust/fill.h> // #include <thrust/replace.h> // #include <thrust/functional.h> // #include <iostream> // #include <vector> // template <typename T> // struct apx_functor // { // const T a; // apx_functor(T _a) : a(_a) {} // __host__ __device__ // T operator()(const T& x) const { // return a + x; // } // }; // template <typename T> // void apx_fast(T A, thrust::device_vector<T>& X, thrust::device_vector<T>& Y) // { // // Y <- A + X // thrust::transform(X.begin(), X.end(), Y.begin(), Y.begin(), apx_functor(A)); // thrust::copy(Y.begin(), Y.end(), std::ostream_iterator<int>(std::cout, "\n")); // } // // square<T> computes the square of a number f(x) -> x*x // template <typename T> // struct square // { // __host__ __device__ // T operator()(const T& x) const { // return x * x; // } // }; // int main(void) // { // // initialize host array // std::vector<float> x; // std::vector<float> y; // for (int i = 0; i < 4; i++) // x.push_back(float(i)); // // transfer to device // thrust::device_vector<float> d_x(x.begin(), x.end()); // thrust::device_vector<float> d_y(x.begin(), x.end()); // apx_fast(float(5.), d_x, d_y); // // setup arguments // square<float> unary_op; // thrust::plus<float> binary_op; // float init = 0; // // compute norm // float norm = std::sqrt(thrust::transform_reduce(d_x.begin(), d_x.end(), unary_op, init, binary_op)); // std::cout << norm << std::endl; // return 0; // }
5,754
#include "includes.h" __global__ void kernel( int *a, int dimx, int dimy ) { int ix = blockIdx.x*blockDim.x + threadIdx.x; int iy = blockIdx.y*blockDim.y + threadIdx.y; int idx = iy*dimx + ix; a[idx] = a[idx]+1; }
5,755
#include <stdio.h> #include "cuda.h" #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) #define ceil(a,b) ((a) % (b) == 0 ? (a) / (b) : ((a) / (b)) + 1) void check_error (const char* message) { cudaError_t error = cudaGetLastError (); if (error != cudaSuccess) { printf ("CUDA error : %s, %s\n", message, cudaGetErrorString (error)); exit(-1); } } __global__ void sw4 (double * uacc_in_0, double * uacc_in_1, double * uacc_in_2, double * __restrict__ u_in_0, double * __restrict__ u_in_1, double * __restrict__ u_in_2, double * __restrict__ mu_in, double * __restrict__ la_in, double * strx, double * stry, double * strz, int N) { //Determing the block's indices int blockdim_i= (int)(blockDim.x); int i0 = (int)(blockIdx.x)*(blockdim_i); int i = max (i0, 0) + (int)(threadIdx.x); int blockdim_j= (int)(blockDim.y); int j0 = (int)(blockIdx.y)*(blockdim_j); int j = max (j0, 0) + (int)(threadIdx.y); int blockdim_k= (int)(blockDim.z); int k0 = (int)(blockIdx.z)*(blockdim_k); int k = max (k0, 0) + (int)(threadIdx.z); // Assumptions int a1 = 1; double h = 3.7; double cof = 1e0 / ( h * h); double (*uacc_0)[304][304] = (double (*)[304][304])uacc_in_0; double (*uacc_1)[304][304] = (double (*)[304][304])uacc_in_1; double (*uacc_2)[304][304] = (double (*)[304][304])uacc_in_2; double (*u_0)[304][304] = (double (*)[304][304])u_in_0; double (*u_1)[304][304] = (double (*)[304][304])u_in_1; double (*u_2)[304][304] = (double (*)[304][304])u_in_2; double (*mu)[304][304] = (double (*)[304][304])mu_in; double (*la)[304][304] = (double (*)[304][304])la_in; double mux1, mux2, mux3, mux4, muy1, muy2, muy3, muy4, muz1, muz2, muz3, muz4; double r1, r2, r3; if (i>=2 & j>=2 & k>=2 & i<=N-3 & j<=N-3 & k<=N-3) { #pragma begin stencil1 unroll k=1,j=1,i=1 mux1 = mu[k][j][i-1] * strx[i-1] - 3e0 / 4 * mu[k][j][i] * strx[i] - 3e0 / 4 * mu[k][j][i-2] * strx[i-2]; mux2 = mu[k][j][i-2] * strx[i-2] + mu[k][j][i+1] * strx[i+1] + 3.0 * mu[k][j][i] * strx[i] + 3.0 * mu[k][j][i-1] * strx[i-1]; mux3 = mu[k][j][i-1] * strx[i-1] + mu[k][j][i+2] * strx[i+2] + 3.0 * mu[k][j][i+1] * strx[i+1] + 3.0 * mu[k][j][i] * strx[i]; mux4 = mu[k][j][i+1] * strx[i+1] - 3e0 / 4 * mu[k][j][i] * strx[i] - 3e0 / 4 * mu[k][j][i+2] * strx[i+2]; muy1 = mu[k][j-1][i] * stry[j-1] - 3e0 / 4 * mu[k][j][i] * stry[j] -3e0 / 4 * mu[k][j-2][i] * stry[j-2]; muy2 = mu[k][j-2][i] * stry[j-2] + mu[k][j+1][i] * stry[j+1] + 3.0 * mu[k][j][i] * stry[j] + 3.0 * mu[k][j-1][i] * stry[j-1]; muy3 = mu[k][j-1][i] * stry[j-1] + mu[k][j+2][i] * stry[j+2] + 3.0 * mu[k][j+1][i] * stry[j+1] + 3.0 * mu[k][j][i] * stry[j]; muy4 = mu[k][j+1][i] * stry[j+1] - 3e0 / 4 * mu[k][j][i] * stry[j] - 3e0 / 4 * mu[k][j+2][i] * stry[j+2]; muz1 = mu[k-1][j][i] * strz[k-1] - 3e0 / 4 * mu[k][j][i] * strz[k] - 3e0 / 4 * mu[k-2][j][i] * strz[k-2]; muz2 = mu[k-2][j][i] * strz[k-2] + mu[k+1][j][i] * strz[k+1] + 3.0 * mu[k][j][i] * strz[k] + 3.0 * mu[k-1][j][i] * strz[k-1]; muz3 = mu[k-1][j][i] * strz[k-1] + mu[k+2][j][i] * strz[k+2] + 3.0 * mu[k+1][j][i] * strz[k+1] + 3.0 * mu[k][j][i] * strz[k]; muz4 = mu[k+1][j][i] * strz[k+1] - 3e0 / 4 * mu[k][j][i] * strz[k] - 3e0 /4 * mu[k+2][j][i] * strz[k+2]; r1 = 1e0 / 6 * (strx[i] * ((2 * mux1 + la[k][j][i-1] * strx[i-1] - 3e0 / 4 * la[k][j][i] * strx[i] - 3e0 / 4 * la[k][j][i-2] * strx[i-2]) * (u_0[k][j][i-2] - u_0[k][j][i]) + (2 * mux2 + la[k][j][i-2] * strx[i-2] + la[k][j][i+1] * strx[i+1] + 3 * la[k][j][i] * strx[i] + 3 * la[k][j][i-1] * strx[i-1]) * (u_0[k][j][i-1] - u_0[k][j][i]) + (2 * mux3 + la[k][j][i-1] * strx[i-1] + la[k][j][i+2] * strx[i+2] + 3 * la[k][j][i+1] * strx[i+1] + 3 * la[k][j][i] * strx[i]) * (u_0[k][j][i+1] - u_0[k][j][i]) + (2 * mux4 + la[k][j][i+1] * strx[i+1] - 3e0 / 4 * la[k][j][i] * strx[i] - 3e0 / 4 * la[k][j][i+2] * strx[i+2]) * (u_0[k][j][i+2] - u_0[k][j][i])) + stry[j] * (muy1 * (u_0[k][j-2][i] - u_0[k][j][i]) + muy2 * (u_0[k][j-1][i] - u_0[k][j][i]) + muy3 * (u_0[k][j+1][i] - u_0[k][j][i]) + muy4 * (u_0[k][j+2][i] - u_0[k][j][i])) + strz[k] * (muz1 * (u_0[k-2][j][i] - u_0[k][j][i]) + muz2 * (u_0[k-1][j][i] - u_0[k][j][i]) + muz3 * (u_0[k+1][j][i] - u_0[k][j][i]) + muz4 * (u_0[k+2][j][i] - u_0[k][j][i]))); r2 = 1e0 / 6 * (strx[i] * (mux1 * (u_1[k][j][i-2] - u_1[k][j][i]) + mux2 * (u_1[k][j][i-1] - u_1[k][j][i]) + mux3 * (u_1[k][j][i+1] - u_1[k][j][i]) + mux4 * (u_1[k][j][i+2] - u_1[k][j][i])) + stry[j] * ((2 * muy1 + la[k][j-1][i] * stry[j-1] - 3e0 / 4 * la[k][j][i] * stry[j] - 3e0 / 4 * la[k][j-2][i] * stry[j-2]) * (u_1[k][j-2][i] - u_1[k][j][i]) + (2 * muy2 + la[k][j-2][i] * stry[j-2] + la[k][j+1][i] * stry[j+1] + 3 * la[k][j][i] * stry[j] + 3 * la[k][j-1][i] * stry[j-1]) * (u_1[k][j-1][i] - u_1[k][j][i]) + (2 * muy3 + la[k][j-1][i] * stry[j-1] + la[k][j+2][i] * stry[j+2] + 3 * la[k][j+1][i] * stry[j+1] + 3 * la[k][j][i] * stry[j]) * (u_1[k][j+1][i] - u_1[k][j][i]) + (2 * muy4 + la[k][j+1][i] * stry[j+1] - 3e0 / 4 * la[k][j][i] * stry[j] - 3e0 / 4 * la[k][j+2][i] * stry[j+2]) * (u_1[k][j+2][i] - u_1[k][j][i])) + strz[k] * (muz1 * (u_1[k-2][j][i] - u_1[k][j][i]) + muz2 * (u_1[k-1][j][i] - u_1[k][j][i]) + muz3 * (u_1[k+1][j][i] - u_1[k][j][i]) + muz4 * (u_1[k+2][j][i] - u_1[k][j][i]))); r3 = 1e0 / 6 * (strx[i] * (mux1 * (u_2[k][j][i-2] - u_2[k][j][i]) + mux2 * (u_2[k][j][i-1] - u_2[k][j][i]) + mux3 * (u_2[k][j][i+1] - u_2[k][j][i]) + mux4 * (u_2[k][j][i+2] - u_2[k][j][i])) + stry[j] * (muy1 * (u_2[k][j-2][i] - u_2[k][j][i]) + muy2 * (u_2[k][j-1][i] - u_2[k][j][i]) + muy3 * (u_2[k][j+1][i] - u_2[k][j][i]) + muy4 * (u_2[k][j+2][i] - u_2[k][j][i])) + strz[k] * ((2 * muz1 + la[k-1][j][i] * strz[k-1] - 3e0 / 4 * la[k][j][i] * strz[k] - 3e0 / 4 * la[k-2][j][i] * strz[k-2]) * (u_2[k-2][j][i] - u_2[k][j][i]) + (2 * muz2 + la[k-2][j][i] * strz[k-2] + la[k+1][j][i] * strz[k+1] + 3 * la[k][j][i] * strz[k] + 3 * la[k-1][j][i] * strz[k-1]) * (u_2[k-1][j][i] - u_2[k][j][i]) + (2 * muz3 + la[k-1][j][i] * strz[k-1] + la[k+2][j][i] * strz[k+2] + 3 * la[k+1][j][i] * strz[k+1] + 3 * la[k][j][i] * strz[k]) * (u_2[k+1][j][i] - u_2[k][j][i]) + (2 * muz4 + la[k+1][j][i] * strz[k+1] - 3e0 / 4 * la[k][j][i] * strz[k] - 3e0 / 4 * la[k+2][j][i] * strz[k+2]) * (u_2[k+2][j][i] - u_2[k][j][i]))); r3 += strx[i] * strz[k] * (1e0 / 144) * (mu[k][j][i-2] * (u_0[k-2][j][i-2] - u_0[k+2][j][i-2] + 8 * (-u_0[k-1][j][i-2] + u_0[k+1][j][i-2])) - 8 * (mu[k][j][i-1] * (u_0[k-2][j][i-1] - u_0[k+2][j][i-1] + 8 * (-u_0[k-1][j][i-1] + u_0[k+1][j][i-1]))) + 8 * (mu[k][j][i+1] * (u_0[k-2][j][i+1] - u_0[k+2][j][i+1] + 8 * (-u_0[k-1][j][i+1] + u_0[k+1][j][i+1]))) - (mu[k][j][i+2] * (u_0[k-2][j][i+2] - u_0[k+2][j][i+2] + 8 * (-u_0[k-1][j][i+2] + u_0[k+1][j][i+2])))) + stry[j] * strz[k] * (1e0 / 144) * (mu[k][j-2][i] * (u_1[k-2][j-2][i] - u_1[k+2][j-2][i] + 8 * (-u_1[k-1][j-2][i] + u_1[k+1][j-2][i])) - 8 * (mu[k][j-1][i] * (u_1[k-2][j-1][i] - u_1[k+2][j-1][i] + 8 * (-u_1[k-1][j-1][i] + u_1[k+1][j-1][i]))) + 8 * (mu[k][j+1][i] * (u_1[k-2][j+1][i] - u_1[k+2][j+1][i] + 8 * (-u_1[k-1][j+1][i] + u_1[k+1][j+1][i]))) - (mu[k][j+2][i] * (u_1[k-2][j+2][i] - u_1[k+2][j+2][i] + 8 * (-u_1[k-1][j+2][i] + u_1[k+1][j+2][i])))) + strx[i] * strz[k] * (1e0 / 144) * (la[k-2][j][i] * (u_0[k-2][j][i-2] - u_0[k-2][j][i+2] + 8 * (-u_0[k-2][j][i-1] + u_0[k-2][j][i+1])) - 8 * (la[k-1][j][i] * (u_0[k-1][j][i-2] - u_0[k-1][j][i+2] + 8 * (-u_0[k-1][j][i-1] + u_0[k-1][j][i+1]))) + 8 * (la[k+1][j][i] * (u_0[k+1][j][i-2] - u_0[k+1][j][i+2] + 8 * (-u_0[k+1][j][i-1] + u_0[k+1][j][i+1]))) - (la[k+2][j][i] * (u_0[k+2][j][i-2] - u_0[k+2][j][i+2] + 8 * (-u_0[k+2][j][i-1] + u_0[k+2][j][i+1])))) + stry[j] * strz[k] * (1e0 / 144) * (la[k-2][j][i] * (u_1[k-2][j-2][i] - u_1[k-2][j+2][i] + 8 * (-u_1[k-2][j-1][i] + u_1[k-2][j+1][i])) - 8 * (la[k-1][j][i] * (u_1[k-1][j-2][i] - u_1[k-1][j+2][i] + 8 * (-u_1[k-1][j-1][i] + u_1[k-1][j+1][i]))) + 8 * (la[k+1][j][i] * (u_1[k+1][j-2][i] - u_1[k+1][j+2][i] + 8 * (-u_1[k+1][j-1][i] + u_1[k+1][j+1][i]))) - (la[k+2][j][i] * (u_1[k+2][j-2][i] - u_1[k+2][j+2][i] + 8 * (-u_1[k+2][j-1][i] + u_1[k+2][j+1][i])))); r1 += strx[i] * stry[j] * (1e0 / 144) * (la[k][j][i-2] * (u_1[k][j-2][i-2] - u_1[k][j+2][i-2] + 8 * (-u_1[k][j-1][i-2] + u_1[k][j+1][i-2])) - 8 * (la[k][j][i-1] * (u_1[k][j-2][i-1] - u_1[k][j+2][i-1] + 8 * (-u_1[k][j-1][i-1] + u_1[k][j+1][i-1]))) + 8 * (la[k][j][i+1] * (u_1[k][j-2][i+1] - u_1[k][j+2][i+1] + 8 * (-u_1[k][j-1][i+1] + u_1[k][j+1][i+1]))) - (la[k][j][i+2] * (u_1[k][j-2][i+2] - u_1[k][j+2][i+2] + 8 * (-u_1[k][j-1][i+2] + u_1[k][j+1][i+2])))) + strx[i] * strz[k] * (1e0 / 144) * (la[k][j][i-2] * (u_2[k-2][j][i-2] - u_2[k+2][j][i-2] + 8 * (-u_2[k-1][j][i-2] + u_2[k+1][j][i-2])) - 8 * (la[k][j][i-1] * (u_2[k-2][j][i-1] - u_2[k+2][j][i-1] + 8 * (-u_2[k-1][j][i-1] + u_2[k+1][j][i-1]))) + 8 * (la[k][j][i+1] * (u_2[k-2][j][i+1] - u_2[k+2][j][i+1] + 8 * (-u_2[k-1][j][i+1] + u_2[k+1][j][i+1]))) - (la[k][j][i+2] * (u_2[k-2][j][i+2] - u_2[k+2][j][i+2] + 8 * (-u_2[k-1][j][i+2] + u_2[k+1][j][i+2])))) + strx[i] * stry[j] * (1e0 / 144) * (mu[k][j-2][i] * (u_1[k][j-2][i-2] - u_1[k][j-2][i+2] + 8 * (-u_1[k][j-2][i-1] + u_1[k][j-2][i+1])) - 8 * (mu[k][j-1][i] * (u_1[k][j-1][i-2] - u_1[k][j-1][i+2] + 8 * (-u_1[k][j-1][i-1] + u_1[k][j-1][i+1]))) + 8 * (mu[k][j+1][i] * (u_1[k][j+1][i-2] - u_1[k][j+1][i+2] + 8 * (-u_1[k][j+1][i-1] + u_1[k][j+1][i+1]))) - (mu[k][j+2][i] * (u_1[k][j+2][i-2] - u_1[k][j+2][i+2] + 8 * (-u_1[k][j+2][i-1] + u_1[k][j+2][i+1])))) + strx[i] * strz[k] * (1e0 / 144) * (mu[k-2][j][i] * (u_2[k-2][j][i-2] - u_2[k-2][j][i+2] + 8 * (-u_2[k-2][j][i-1] + u_2[k-2][j][i+1])) - 8 * (mu[k-1][j][i] * (u_2[k-1][j][i-2] - u_2[k-1][j][i+2] + 8 * (-u_2[k-1][j][i-1] + u_2[k-1][j][i+1]))) + 8 * (mu[k+1][j][i] * (u_2[k+1][j][i-2] - u_2[k+1][j][i+2] + 8 * (-u_2[k+1][j][i-1] + u_2[k+1][j][i+1]))) - (mu[k+2][j][i] * (u_2[k+2][j][i-2] - u_2[k+2][j][i+2] + 8 * (-u_2[k+2][j][i-1] + u_2[k+2][j][i+1])))); r2 += strx[i] * stry[j] * (1e0 / 144) * (mu[k][j][i-2] * (u_0[k][j-2][i-2] - u_0[k][j+2][i-2] + 8 * (-u_0[k][j-1][i-2] + u_0[k][j+1][i-2])) - 8 * (mu[k][j][i-1] * (u_0[k][j-2][i-1] - u_0[k][j+2][i-1] + 8 * (-u_0[k][j-1][i-1] + u_0[k][j+1][i-1]))) + 8 * (mu[k][j][i+1] * (u_0[k][j-2][i+1] - u_0[k][j+2][i+1] + 8 * (-u_0[k][j-1][i+1] + u_0[k][j+1][i+1]))) - (mu[k][j][i+2] * (u_0[k][j-2][i+2] - u_0[k][j+2][i+2] + 8 * (-u_0[k][j-1][i+2] + u_0[k][j+1][i+2])))) + strx[i] * stry[j] * (1e0 / 144) * (la[k][j-2][i] * (u_0[k][j-2][i-2] - u_0[k][j-2][i+2] + 8 * (-u_0[k][j-2][i-1] + u_0[k][j-2][i+1])) - 8 * (la[k][j-1][i] * (u_0[k][j-1][i-2] - u_0[k][j-1][i+2] + 8 * (-u_0[k][j-1][i-1] + u_0[k][j-1][i+1]))) + 8 * (la[k][j+1][i] * (u_0[k][j+1][i-2] - u_0[k][j+1][i+2] + 8 * (-u_0[k][j+1][i-1] + u_0[k][j+1][i+1]))) - (la[k][j+2][i] * (u_0[k][j+2][i-2] - u_0[k][j+2][i+2] + 8 * (-u_0[k][j+2][i-1] + u_0[k][j+2][i+1])))) + stry[j] * strz[k] * (1e0 / 144) * (la[k][j-2][i] * (u_2[k-2][j-2][i] - u_2[k+2][j-2][i] + 8 * (-u_2[k-1][j-2][i] + u_2[k+1][j-2][i])) - 8 * (la[k][j-1][i] * (u_2[k-2][j-1][i] - u_2[k+2][j-1][i] + 8 * (-u_2[k-1][j-1][i] + u_2[k+1][j-1][i]))) + 8 * (la[k][j+1][i] * (u_2[k-2][j+1][i] - u_2[k+2][j+1][i] + 8 * (-u_2[k-1][j+1][i] + u_2[k+1][j+1][i]))) - (la[k][j+2][i] * (u_2[k-2][j+2][i] - u_2[k+2][j+2][i] + 8 * (-u_2[k-1][j+2][i] + u_2[k+1][j+2][i])))) + stry[j] * strz[k] * (1e0 / 144) * (mu[k-2][j][i] * (u_2[k-2][j-2][i] - u_2[k-2][j+2][i] + 8 * (-u_2[k-2][j-1][i] + u_2[k-2][j+1][i])) - 8 * (mu[k-1][j][i] * (u_2[k-1][j-2][i] - u_2[k-1][j+2][i] + 8 * (-u_2[k-1][j-1][i] + u_2[k-1][j+1][i]))) + 8 * (mu[k+1][j][i] * (u_2[k+1][j-2][i] - u_2[k+1][j+2][i] + 8 * (-u_2[k+1][j-1][i] + u_2[k+1][j+1][i]))) - (mu[k+2][j][i] * (u_2[k+2][j-2][i] - u_2[k+2][j+2][i] + 8 * (-u_2[k+2][j-1][i] + u_2[k+2][j+1][i])))); uacc_0[k][j][i] = a1 * uacc_0[k][j][i] + cof * r1; uacc_1[k][j][i] = a1 * uacc_1[k][j][i] + cof * r2; uacc_2[k][j][i] = a1 * uacc_2[k][j][i] + cof * r3; #pragma end stencil1 } } extern "C" void host_code (double *h_uacc_0, double *h_uacc_1, double *h_uacc_2, double *h_u_0, double *h_u_1, double *h_u_2, double *h_mu, double *h_la, double *h_strx, double *h_stry, double *h_strz, int N) { double *uacc_0; cudaMalloc (&uacc_0, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for uacc_0\n"); cudaMemcpy (uacc_0, h_uacc_0, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *uacc_1; cudaMalloc (&uacc_1, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for uacc_1\n"); cudaMemcpy (uacc_1, h_uacc_1, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *uacc_2; cudaMalloc (&uacc_2, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for uacc_2\n"); cudaMemcpy (uacc_2, h_uacc_2, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *u_0; cudaMalloc (&u_0, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for u_0\n"); cudaMemcpy (u_0, h_u_0, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *u_1; cudaMalloc (&u_1, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for u_1\n"); cudaMemcpy (u_1, h_u_1, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *u_2; cudaMalloc (&u_2, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for u_2\n"); cudaMemcpy (u_2, h_u_2, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *mu; cudaMalloc (&mu, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for mu\n"); cudaMemcpy (mu, h_mu, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *la; cudaMalloc (&la, sizeof(double)*N*N*N); check_error ("Failed to allocate device memory for la\n"); cudaMemcpy (la, h_la, sizeof(double)*N*N*N, cudaMemcpyHostToDevice); double *strx; cudaMalloc (&strx, sizeof(double)*N); check_error ("Failed to allocate device memory for strx\n"); cudaMemcpy (strx, h_strx, sizeof(double)*N, cudaMemcpyHostToDevice); double *stry; cudaMalloc (&stry, sizeof(double)*N); check_error ("Failed to allocate device memory for stry\n"); cudaMemcpy (stry, h_stry, sizeof(double)*N, cudaMemcpyHostToDevice); double *strz; cudaMalloc (&strz, sizeof(double)*N); check_error ("Failed to allocate device memory for strz\n"); cudaMemcpy (strz, h_strz, sizeof(double)*N, cudaMemcpyHostToDevice); dim3 blockconfig (16, 2, 2); dim3 gridconfig (ceil(N, blockconfig.x), ceil(N, blockconfig.y), ceil(N, blockconfig.z)); sw4 <<<gridconfig, blockconfig>>> (uacc_0, uacc_1, uacc_2, u_0, u_1, u_2, mu, la, strx, stry, strz, N); cudaMemcpy (h_uacc_0, uacc_0, sizeof(double)*N*N*N, cudaMemcpyDeviceToHost); cudaMemcpy (h_uacc_1, uacc_1, sizeof(double)*N*N*N, cudaMemcpyDeviceToHost); cudaMemcpy (h_uacc_2, uacc_2, sizeof(double)*N*N*N, cudaMemcpyDeviceToHost); cudaFree (uacc_0); cudaFree (uacc_1); cudaFree (uacc_2); cudaFree (u_0); cudaFree (u_1); cudaFree (u_2); cudaFree (mu); cudaFree (la); cudaFree (strx); cudaFree (stry); cudaFree (strz); }
5,756
#include "includes.h" __global__ void totalWithThreadSyncAndSharedMemInterleaved(float *input, float *output, int len) { //@@ Compute reduction for a segment of the input vector __shared__ float sdata[BLOCK_SIZE]; int tid = threadIdx.x, i = blockIdx.x * blockDim.x + threadIdx.x; if(i < len) sdata[tid] = input[i]; else sdata[tid] = 0.0; for(unsigned int j = 1; j < blockDim.x; j *= 2) { if (tid % (2 * j) == 0) sdata[tid] += sdata[tid+j]; __syncthreads(); } if(tid == 0) { output[blockIdx.x] = sdata[0]; } }
5,757
#include <chrono> #include <stdio.h> #include <stdlib.h> #include "cuda_runtime.h" #include "device_launch_parameters.h" using namespace std; using namespace chrono; #define GRIDSIZE 1 #define BLOCKSIZE 1024 #define TOTALSIZE (GRIDSIZE*BLOCKSIZE) void genData(unsigned* ptr, unsigned int size) { while (size--) { *ptr++ = (float)(rand() % 1000) / 1000.0F; } } void kernel(unsigned* pData, unsigned* pAnswer, unsigned size) { while (size--) { unsigned value = *pData++; *pAnswer = *pAnswer + value; } } int main(void) { unsigned* pData = NULL; unsigned answer = 0; //malloc memories on the host-side pData = (unsigned*)malloc(2 * BLOCKSIZE * sizeof(unsigned)); //generate source data genData(pData, 2 * BLOCKSIZE); //HOST: start the timer system_clock::time_point h_start = system_clock::now(); kernel(pData, &answer, 2 * BLOCKSIZE); //end the timer system_clock::time_point h_end = system_clock::now(); nanoseconds h_du = h_end - h_start; printf("%lld nano-secodns\n", h_du); printf("answer= %lld \n", answer); }
5,758
#include "includes.h" __global__ void vecAdd(int *xd, float *Ag, float *Bg, float *Cg) { // this is a kernel, which state the computations the gpu shall do //int j = threadIdx.x; int j = blockIdx.x*blockDim.x + threadIdx.x; *(Cg+j) = *(Ag+j) + *(Bg+j) + (*xd); }
5,759
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include<iostream> #include "config.cuh" #include<map> #include <sstream> #include <vector> #include <algorithm> #include <cassert> #define maxWordSize 1024 using namespace std; vector < string > v1; /* * Mapping function to be run for each input. The input must be read from memory * and the the key/value output must be stored in memory at pairs. Multiple * pairs may be stored at the next postiion in pairs, but the maximum number of * key/value pairs stored must not exceed NUM_KEYS. */ __device__ void mapper(input_type *input, KeyValuePair *pairs) { pairs->key =0; for(int i=0;input->inputName[i]!='\0';i++) { pairs->value[i] =input->inputName[i]; } } /* * Reducing function to be run for each set of key/value pairs that share the * same key. len key/value pairs may be read from memory, and the output * generated from these pairs must be stored at output in memory. */ __device__ void reducer(KeyValuePair *pairs, int len,output_type *output) { for(int k=0;k<(len-1);k++) { int wordCount=0; int stringCount=1; int size=0; int duplicatWordCount=0; int duplicateCount=1; for(int w=0;((pairs+k)->value[w])!='\0';w++) { size++; } for(int l=k+1;l<len;l++) { wordCount=0; for(int m=0;m<size;m++) { if((((pairs+k)->value[m])==((pairs+l)->value[m]))) { if(((pairs+l)->value[size])!='\0') { break; } else { wordCount++; } } if(size==wordCount) { stringCount++; } } } for(int v=k-1;v>=0;v--) { duplicatWordCount=0; for(int m=0;m<size;m++) { if((((pairs+k)->value[m])==((pairs+v)->value[m]))) { if(((pairs+v)->value[size])!='\0') { } else { duplicatWordCount++; } } if(size==duplicatWordCount) { duplicateCount++; } } } if(duplicateCount==1) { (output+k)->x = stringCount; for(int i=0;((pairs+k)->value[i])!='\0';i++) { (output+k)->y[i] = (pairs+k)->value[i] ; } } else { (output+k)->x = 0; for(int i=0;((pairs+k)->value[i])!='\0';i++) { (output+k)->y[i] ='\0'; } } } } void StringWithoutSigns(char *sign) { int len=strlen(sign); if(sign[len-1]>0 && sign[len-1]>32 && sign[len-1]<65) { sign[len-1]=0; StringWithoutSigns(sign); } } void read_words (FILE *f, map<string, int> &m) { char x[maxWordSize]; cout<<"Input Data"<<endl; cout<<"*************************"<<endl; while (fscanf(f, " %1023s", x) == 1) { StringWithoutSigns(x); m[x]++; string s = std::string(x); v1.push_back( s ); cout<<s<<endl; } cout<<"*************************"<<endl; } /* * Main function that runs a map reduce job. */ int main(int argc, char const *argv[]) { // Allocate host memory size_t input_size = NUM_INPUT * sizeof(input_type); size_t output_size = NUM_OUTPUT * sizeof(output_type); input_type *input = (input_type *) malloc(input_size); output_type *output = (output_type *) malloc(output_size); map<string, int> m; FILE *inputFile; cudaEvent_t start, stop; float milliseconds = 0.0f; cudaEventCreate(&start); cudaEventCreate(&stop); inputFile = fopen("/home/pavankum.sama/fileInput.txt","r"); read_words(inputFile, m); // printf("Generating %d Test Points\n", NUM_INPUT); for (size_t i = 0; i < NUM_INPUT; i++) { string s =v1[i]; int n = s.length(); // declaring character array char char_array[n + 1]; // copying the contents of the // string to char array strcpy(char_array, s.c_str()); for (int j = 0; j < n; j++) { input[i].inputName[j]=char_array[j]; } } cudaEventRecord(start); // Run the Map Reduce Job runMapReduce(input, output); cudaEventRecord(stop); // Iterate through the output array cout<<"Map Reduce wordCount"<<endl; cout<<"*************************"<<endl; for (size_t i = 0; i <NUM_OUTPUT; i++) { if(output[i].x!=0) cout<<"("<<output[i].y<<","<<output[i].x<<")"<<endl; } cout<<"*************************"<<endl; cudaEventElapsedTime(&milliseconds, start, stop); cout<<"Kernel Exceuction completed"<<endl; cout<<"GPU Exceution Time is: "<<milliseconds<<" ms"<<endl; // Free host memory free(input); free(output); return 0; }
5,760
#include "includes.h" __global__ void kArgMaxColumnwise(float* mat, float* target, unsigned int width, unsigned int height) { __shared__ float max_vals[32]; __shared__ unsigned int max_args[32]; float cur_max = -2e38; unsigned int cur_arg = 0; float val = 0; for (unsigned int i = threadIdx.x; i < height; i += 32) { val = mat[i * width + blockIdx.x]; if (val > cur_max) { cur_max = val; cur_arg = i; } } max_vals[threadIdx.x] = cur_max; max_args[threadIdx.x] = cur_arg; __syncthreads(); if (threadIdx.x == 0) { cur_max = -2e38; cur_arg = 0; for (unsigned int i = 0; i < 32; i++) if (max_vals[i] > cur_max) { cur_max = max_vals[i]; cur_arg = max_args[i]; } target[blockIdx.x] = cur_arg; } }
5,761
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <device_functions.h> #include "kernels.cuh" #define SHARED_MEMORY_BANKS 32 #define LOG_MEM_BANKS 5 #define CONFLICT_FREE_OFFSET(n) ((n) >> LOG_MEM_BANKS) __global__ void prescan_arbitrary(int *output, int *input, int n, int powerOfTwo) { extern __shared__ int temp[];// allocated on invocation int threadID = threadIdx.x; int ai = threadID; int bi = threadID + (n / 2); int bankOffsetA = CONFLICT_FREE_OFFSET(ai); int bankOffsetB = CONFLICT_FREE_OFFSET(bi); if (threadID < n) { temp[ai + bankOffsetA] = input[ai]; temp[bi + bankOffsetB] = input[bi]; } else { temp[ai + bankOffsetA] = 0; temp[bi + bankOffsetB] = 0; } int offset = 1; for (int d = powerOfTwo >> 1; d > 0; d >>= 1) // build sum in place up the tree { __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; ai += CONFLICT_FREE_OFFSET(ai); bi += CONFLICT_FREE_OFFSET(bi); temp[bi] += temp[ai]; } offset *= 2; } if (threadID == 0) { temp[powerOfTwo - 1 + CONFLICT_FREE_OFFSET(powerOfTwo - 1)] = 0; // clear the last element } for (int d = 1; d < powerOfTwo; d *= 2) // traverse down tree & build scan { offset >>= 1; __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; ai += CONFLICT_FREE_OFFSET(ai); bi += CONFLICT_FREE_OFFSET(bi); int t = temp[ai]; temp[ai] = temp[bi]; temp[bi] += t; } } __syncthreads(); if (threadID < n) { output[ai] = temp[ai + bankOffsetA]; output[bi] = temp[bi + bankOffsetB]; } } __global__ void prescan_arbitrary_unoptimized(int *output, int *input, int n, int powerOfTwo) { extern __shared__ int temp[];// allocated on invocation int threadID = threadIdx.x; if (threadID < n) { temp[2 * threadID] = input[2 * threadID]; // load input into shared memory temp[2 * threadID + 1] = input[2 * threadID + 1]; } else { temp[2 * threadID] = 0; temp[2 * threadID + 1] = 0; } int offset = 1; for (int d = powerOfTwo >> 1; d > 0; d >>= 1) // build sum in place up the tree { __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; temp[bi] += temp[ai]; } offset *= 2; } if (threadID == 0) { temp[powerOfTwo - 1] = 0; } // clear the last element for (int d = 1; d < powerOfTwo; d *= 2) // traverse down tree & build scan { offset >>= 1; __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; int t = temp[ai]; temp[ai] = temp[bi]; temp[bi] += t; } } __syncthreads(); if (threadID < n) { output[2 * threadID] = temp[2 * threadID]; // write results to device memory output[2 * threadID + 1] = temp[2 * threadID + 1]; } } __global__ void prescan_large(int *output, int *input, int n, int *sums) { extern __shared__ int temp[]; int blockID = blockIdx.x; int threadID = threadIdx.x; int blockOffset = blockID * n; int ai = threadID; int bi = threadID + (n / 2); int bankOffsetA = CONFLICT_FREE_OFFSET(ai); int bankOffsetB = CONFLICT_FREE_OFFSET(bi); temp[ai + bankOffsetA] = input[blockOffset + ai]; temp[bi + bankOffsetB] = input[blockOffset + bi]; int offset = 1; for (int d = n >> 1; d > 0; d >>= 1) // build sum in place up the tree { __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; ai += CONFLICT_FREE_OFFSET(ai); bi += CONFLICT_FREE_OFFSET(bi); temp[bi] += temp[ai]; } offset *= 2; } __syncthreads(); if (threadID == 0) { sums[blockID] = temp[n - 1 + CONFLICT_FREE_OFFSET(n - 1)]; temp[n - 1 + CONFLICT_FREE_OFFSET(n - 1)] = 0; } for (int d = 1; d < n; d *= 2) // traverse down tree & build scan { offset >>= 1; __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; ai += CONFLICT_FREE_OFFSET(ai); bi += CONFLICT_FREE_OFFSET(bi); int t = temp[ai]; temp[ai] = temp[bi]; temp[bi] += t; } } __syncthreads(); output[blockOffset + ai] = temp[ai + bankOffsetA]; output[blockOffset + bi] = temp[bi + bankOffsetB]; } __global__ void prescan_large_unoptimized(int *output, int *input, int n, int *sums) { int blockID = blockIdx.x; int threadID = threadIdx.x; int blockOffset = blockID * n; extern __shared__ int temp[]; temp[2 * threadID] = input[blockOffset + (2 * threadID)]; temp[2 * threadID + 1] = input[blockOffset + (2 * threadID) + 1]; int offset = 1; for (int d = n >> 1; d > 0; d >>= 1) // build sum in place up the tree { __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; temp[bi] += temp[ai]; } offset *= 2; } __syncthreads(); if (threadID == 0) { sums[blockID] = temp[n - 1]; temp[n - 1] = 0; } for (int d = 1; d < n; d *= 2) // traverse down tree & build scan { offset >>= 1; __syncthreads(); if (threadID < d) { int ai = offset * (2 * threadID + 1) - 1; int bi = offset * (2 * threadID + 2) - 1; int t = temp[ai]; temp[ai] = temp[bi]; temp[bi] += t; } } __syncthreads(); output[blockOffset + (2 * threadID)] = temp[2 * threadID]; output[blockOffset + (2 * threadID) + 1] = temp[2 * threadID + 1]; } __global__ void add(int *output, int length, int *n) { int blockID = blockIdx.x; int threadID = threadIdx.x; int blockOffset = blockID * length; output[blockOffset + threadID] += n[blockID]; } __global__ void add(int *output, int length, int *n1, int *n2) { int blockID = blockIdx.x; int threadID = threadIdx.x; int blockOffset = blockID * length; output[blockOffset + threadID] += n1[blockID] + n2[blockID]; }
5,762
#include "includes.h" /** * C file for parallel QR factorization program usign CUDA * See header for more infos. * * 2016 Marco Tieghi - marco01.tieghi@student.unife.it * */ #define THREADS_PER_BLOCK 512 //I'll use 512 threads for each block (as required in the assignment) __global__ void xTA (double *y, int k, double*A, int m, int lda, double *x, int ldx) { int idx = blockIdx.x * blockDim.x + threadIdx.x; double s; //It memorizes the sum if (idx < k) { for (int ii = 0; ii < m; ii++) { //Moving through rows s += x[ii * ldx] * A[idx + ii*lda]; } y[idx] = s; //Adding the sum to result vector } }
5,763
#include <iostream> #include <algorithm> using namespace std; class Net { private: int rows, cols; int** inputTensor; int** outputTensor; public: Net(int, int); int relulayer(); void poolingFunction(int, int, bool); void filterConvolve(int); void printArray(); }; Net::Net(int r, int c) { rows = r; cols = c; cout << "\n\nInitialization of " << rows << " x " << cols << " 2D array with random values between -9 and 9\n\n"; //input tensor initialization inputTensor = new int*[rows]; for (int k = 0; k < rows; k++) inputTensor[k] = new int[cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { inputTensor[i][j] = rand() % 19 + (-9); } } //output tensor initialization to zero outputTensor = new int*[rows]; for (int k = 0; k < rows; k++) outputTensor[k] = new int[cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { outputTensor[i][j] = 0; } } } int Net::relulayer() { /* * A `ReLULayer` is the identity function for * non-negative inputs, and gives zero for negative inputs. */ cout << "\n\nReluLayer Identity Function converts negative inputs to zero\n\n"; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (inputTensor[i][j] < 0) outputTensor[i][j] = 0; else outputTensor[i][j] = inputTensor[i][j]; } } return 0; } void Net::printArray() { cout << "\n\nINPUT TENSOR\n\n"; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << inputTensor[i][j] << '\t'; } cout << "\n"; } cout << "\n\nOUTPUT TENSOR\n\n"; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << outputTensor[i][j] << '\t'; } cout << "\n"; } } void Net::poolingFunction(int stride, int windowSize, bool minMax) { //output matrix calculation //bool minMax=true implied min else max operation cout << "\n\nPooling function -- find on min/max operations\n\n"; if (minMax == true) cout << "Pools using min operation, stride is " << stride << " and window size is " << windowSize << endl; else cout << "Pools using max operation, stride is " << stride << " and window size is " << windowSize << endl; int kernelSize = windowSize / 2; int minimum=999,maximum=-999; for (int y = 1; y < rows - 1; y++) { for (int x = 1; x < cols - 1; x++) { for (int k = -kernelSize; k <= kernelSize; k++) { for (int j = -kernelSize; j <= kernelSize; j++) { if (minMax == true) minimum = min(inputTensor[j + 1][k + 1], inputTensor[y - j][x - k]); else maximum = max(inputTensor[j + 1][k + 1], inputTensor[y - j][x - k]); } } if (minMax == true) outputTensor[y][x] = minimum; else outputTensor[y][x] = maximum; } } } void Net::filterConvolve(int windowSize) { cout << "\n\nConvolution function \n\n"; int sum; int kernelSize = windowSize / 2; for (int y = 1; y < rows - 1; y++) { for (int x = 1; x < cols - 1; x++) { sum = 0; for (int k = -kernelSize; k <= kernelSize; k++) { for (int j = -kernelSize; j <= kernelSize; j++) { sum = sum + inputTensor[j + 1][k + 1] * inputTensor[y - j][x - k]; } } outputTensor[y][x] = sum; } } } int main() { Net net(3, 6); net.printArray(); net.relulayer(); net.printArray(); net.poolingFunction(3, 3, false); net.printArray(); net.filterConvolve(3); net.printArray(); return 0; }
5,764
#include "includes.h" __global__ void cuSearchDoublet( const int* nSpM, const float* spMmat, const int* nSpB, const float* spBmat, const int* nSpT, const float* spTmat, const float* deltaRMin, const float* deltaRMax, const float* cotThetaMax, const float* collisionRegionMin, const float* collisionRegionMax, int* nSpMcomp, int* nSpBcompPerSpM_Max, int* nSpTcompPerSpM_Max, int* nSpBcompPerSpM, int* nSpTcompPerSpM, int* McompIndex, int* BcompIndex, int* tmpBcompIndex, int* TcompIndex, int* tmpTcompIndex) { extern __shared__ float sharedMem[]; int* mPos = (int*)sharedMem; int* isMcompat = (int*)&mPos[1]; if (threadIdx.x == 0) { *isMcompat = false; } __syncthreads(); float rM = spMmat[blockIdx.x + (*nSpM) * 3]; float zM = spMmat[blockIdx.x + (*nSpM) * 2]; bool isBcompat(true); bool isTcompat(true); int offset(0); while (offset < max(*nSpB, *nSpT)) { isBcompat = true; // Doublet search for bottom hits if (threadIdx.x + offset < *nSpB) { float rB = spBmat[threadIdx.x + offset + (*nSpB) * 3]; float zB = spBmat[threadIdx.x + offset + (*nSpB) * 2]; float deltaR = rM - rB; if (deltaR > *deltaRMax) { isBcompat = false; } if (deltaR < *deltaRMin) { isBcompat = false; } float cotTheta = (zM - zB) / deltaR; if (fabsf(cotTheta) > *cotThetaMax) { isBcompat = false; } float zOrigin = zM - rM * cotTheta; if (zOrigin < *collisionRegionMin || zOrigin > *collisionRegionMax) { isBcompat = false; } if (isBcompat == true) { int bPos = atomicAdd(&nSpBcompPerSpM[blockIdx.x], 1); tmpBcompIndex[bPos + (*nSpB) * blockIdx.x] = threadIdx.x + offset; } } isTcompat = true; // Doublet search for top hits if (threadIdx.x + offset < *nSpT) { float rT = spTmat[threadIdx.x + offset + (*nSpT) * 3]; float zT = spTmat[threadIdx.x + offset + (*nSpT) * 2]; float deltaR = rT - rM; if (deltaR < *deltaRMin) { isTcompat = false; } if (deltaR > *deltaRMax) { isTcompat = false; } if (isTcompat == true) { float cotTheta = (zT - zM) / deltaR; if (fabsf(cotTheta) > *cotThetaMax) { isTcompat = false; } float zOrigin = zM - rM * cotTheta; if (zOrigin < *collisionRegionMin || zOrigin > *collisionRegionMax) { isTcompat = false; } } if (isTcompat == true) { int tPos = atomicAdd(&nSpTcompPerSpM[blockIdx.x], 1); tmpTcompIndex[tPos + (*nSpT) * blockIdx.x] = threadIdx.x + offset; } } offset += blockDim.x; } __syncthreads(); if (threadIdx.x == 0) { if (nSpBcompPerSpM[blockIdx.x] > 0 && nSpTcompPerSpM[blockIdx.x] > 0) { *mPos = atomicAdd(nSpMcomp, 1); *isMcompat = true; McompIndex[*mPos] = blockIdx.x; int bMax = atomicMax(nSpBcompPerSpM_Max, nSpBcompPerSpM[blockIdx.x]); int tMax = atomicMax(nSpTcompPerSpM_Max, nSpTcompPerSpM[blockIdx.x]); } } __syncthreads(); if (*isMcompat == true) { offset = 0; while (offset < max(nSpBcompPerSpM[blockIdx.x], nSpTcompPerSpM[blockIdx.x])) { if (threadIdx.x + offset < nSpBcompPerSpM[blockIdx.x]) { BcompIndex[threadIdx.x + offset + (*nSpB) * (*mPos)] = tmpBcompIndex[threadIdx.x + offset + (*nSpB) * blockIdx.x]; } if (threadIdx.x + offset < nSpTcompPerSpM[blockIdx.x]) { TcompIndex[threadIdx.x + offset + (*nSpT) * (*mPos)] = tmpTcompIndex[threadIdx.x + offset + (*nSpT) * blockIdx.x]; } offset += blockDim.x; } } }
5,765
#include "cuda_runtime.h" #include "cuda.h" #include "device_launch_parameters.h" #include "iostream" #include "stdlib.h" #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds #include "time.h" #include <ctime> #include "fstream" using namespace std; int getPos(int m, int n, const int width) { return m* width + n; } void printCells(int* cells, int const height, int const width) { for (int i = 0; i < height + 2; i++) { for (int j = 0; j < width + 2; j++) { if (cells[getPos(i, j, width)] == 1) { cout << "O" << " "; } else { cout << "-" << " "; } } cout << endl; } cout << endl; std::this_thread::sleep_for(std::chrono::milliseconds(100)); system("cls"); } void populateArray(int* cellArray, int arraySize) { for (int i = 0; i < arraySize; i++) { cellArray[i] = rand() % 2; } } __device__ int getX(int i, int width) { return i % width; } __device__ int getY(int i, int width) { return i / width; } __device__ int getI(int m, int n, int width) { return m * width + n; } //Gets the neigbour cells via von Neuman Neigbourhood __device__ int getNeigbours(int m, int n, int* cells, int width, int height) { int neigbours = 0; for (int i = m - 1; i <= m + 1; i++) { for (int j = n - 1; j <= n + 1; j++) { if (i >= 0 && i < height && j >= 0 && j < width) { neigbours += cells[getI(i, j, width)]; } else { neigbours += cells[getI((i + height) % height, (j + width) % width, width)]; } } } return neigbours; } // rules that determines the state of the cell __device__ int rules(int neigbours, int state) { int n = neigbours - state; if (state == 1) { if (n > 1 && n < 4) { return 1; } else { return 0; } } else { if (n == 3){ return 1; } return 0; } } // creates the new state of the world __global__ void evolve(int* cells, const int height, const int width, const int arraySize, const int cellsPerThread) { extern __shared__ int sharedCells[]; int i = threadIdx.x + blockIdx.x * blockDim.x; for (int k = i * cellsPerThread; k < ((i + 1) * cellsPerThread); k++) { sharedCells[k] = cells[k]; int x, y, neigbours; x = getX(k, width); y = getY(k, width); neigbours = getNeigbours(y, x, sharedCells, width, height); cells[k] = rules(neigbours, sharedCells[getI(y, x, width)]); __syncthreads(); } } // Runs the simulation int main() { srand(1); const int height = 100, width = 100, arraySize = 10000, timeSteps = 10000, cellsPerThread = 10, gridSize = 10; char b; int* cells; // CPU int* cellsDev; // GPU cells = (int*)malloc(sizeof(int)*arraySize); // creating arrays populateArray(cells, arraySize); cudaMalloc((void**)&cellsDev, sizeof(float)*arraySize); // creating space on gpu cudaMemcpy(cellsDev, cells, sizeof(int)*arraySize, cudaMemcpyHostToDevice); // copying arrays to gpu clock_t begin = clock(); for (int i = 1; i < timeSteps; i++) { evolve <<<gridSize, arraySize / cellsPerThread / gridSize >>>(cellsDev, height, width, arraySize, cellsPerThread); // running evolution iteration } clock_t end = clock(); cudaMemcpy(cells, cellsDev, sizeof(int)*arraySize, cudaMemcpyDeviceToHost); // copying cells back from gpu to cpu cudaFree(cellsDev); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << elapsed_secs; ofstream myfile; myfile.open("para4.txt"); for (int i = 0; i < arraySize; i++) { myfile << cells[i] << endl; } free(cells); myfile.close(); cin >> b; return 0; }
5,766
/****************************************************************************\ * --- Practical Course: GPU Programming in Computer Vision --- * * time: winter term 2012/13 / March 11-18, 2013 * * project: diffusion * file: diffusion.cu * * \******* PLEASE ENTER YOUR CORRECT STUDENT LOGIN, NAME AND ID BELOW *********/ const char* studentLogin = "p116"; const char* studentName = "Arash Bakhtiari"; const int studentID = 03625141; /****************************************************************************\ * * In this file the following methods have to be edited or completed: * * diffuse_linear_isotrop_shared(const float *d_input, ... ) * diffuse_linear_isotrop_shared(const float3 *d_input, ... ) * diffuse_nonlinear_isotrop_shared(const float *d_input, ... ) * diffuse_nonlinear_isotrop_shared(const float3 *d_input, ... ) * compute_tv_diffusivity_shared * compute_tv_diffusivity_joined_shared * compute_tv_diffusivity_separate_shared * jacobi_shared(float *d_output, ... ) * jacobi_shared(float3 *d_output, ... ) * sor_shared(float *d_output, ... ) * sor_shared(float3 *d_output, ... ) * \****************************************************************************/ #define DIFF_BW 16 #define DIFF_BH 16 #define TV_EPSILON 0.1f #include "diffusion.cuh" const char* getStudentLogin() { return studentLogin; }; const char* getStudentName() { return studentName; }; int getStudentID() { return studentID; }; bool checkStudentData() { return strcmp(studentLogin, "p010") != 0 && strcmp(studentName, "John Doe") != 0 && studentID != 1234567; }; bool checkStudentNameAndID() { return strcmp(studentName, "John Doe") != 0 && studentID != 1234567; }; //---------------------------------------------------------------------------- // Linear Diffusion //---------------------------------------------------------------------------- // mode 0 gray: linear diffusion __global__ void diffuse_linear_isotrop_shared( const float *d_input, float *d_output, float timeStep, int nx, int ny, size_t pitch) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const int idx = y*pitch + x; //d_output[idx] = 0; __shared__ float u[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = d_input[idx]; if (x == 0) u[0][ty] = u[tx][ty]; else if (threadIdx.x == 0) u[0][ty] = d_input[idx-1]; if (x == nx-1) u[tx+1][ty] = u[tx][ty]; else if (threadIdx.x == blockDim.x-1) u[tx+1][ty] = d_input[idx+1]; if (y == 0) u[tx][0] = u[tx][ty]; else if (threadIdx.y == 0) u[tx][0] = d_input[idx-pitch]; if (y == ny-1) u[tx][ty+1] = u[tx][ty]; else if (threadIdx.y == blockDim.y-1) u[tx][ty+1] = d_input[idx+pitch]; } __syncthreads(); // ### implement me ### if (x < nx && y < ny) { d_output[idx] = u[tx][ty] + timeStep * ( u[tx + 1][ty] + u[tx - 1][ty] + u[tx][ty + 1] + u[tx][ty - 1] - 4 * u[tx][ty]); } } // mode 0 interleaved: linear diffusion __global__ void diffuse_linear_isotrop_shared ( const float3 *d_input, float3 *d_output, float timeStep, int nx, int ny, size_t pitchBytes ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const char* imgP = (char*)d_input + y*pitchBytes + x*sizeof(float3); __shared__ float3 u[DIFF_BW+2][DIFF_BH+2]; float3 imgValue; // load data into shared memory if (x < nx && y < ny) { imgValue = *( (float3*)imgP ); u[tx][ty] = imgValue; if (x == 0) u[0][ty] = imgValue; else if (threadIdx.x == 0) u[0][ty] = *( ((float3*)imgP)-1 ); if (x == nx-1) u[tx+1][ty] = imgValue; else if (threadIdx.x == blockDim.x-1) u[tx+1][ty] = *( ((float3*)imgP)+1 ); if (y == 0) u[tx][0] = imgValue; else if (threadIdx.y == 0) u[tx][0] = *( (float3*)(imgP-pitchBytes) ); if (y == ny-1) u[tx][ty+1] = imgValue; else if (threadIdx.y == blockDim.y-1) u[tx][ty+1] = *( (float3*)(imgP+pitchBytes) ); } __syncthreads(); float3 tmpValue; tmpValue.x = u[tx][ty].x + timeStep * (u[tx + 1][ty].x + u[tx - 1][ty].x + u[tx][ty + 1].x + u[tx][ty - 1].x - 4 * u[tx][ty].x); tmpValue.y = u[tx][ty].y + timeStep * (u[tx + 1][ty].y + u[tx - 1][ty].y + u[tx][ty + 1].y + u[tx][ty - 1].y - 4 * u[tx][ty].y); tmpValue.z = u[tx][ty].z + timeStep * (u[tx + 1][ty].z + u[tx - 1][ty].z + u[tx][ty + 1].z + u[tx][ty - 1].z - 4 * u[tx][ty].z); if (x < nx && y < ny) *((float3*)(((char*)d_output) + y*pitchBytes) + x) = tmpValue; } //---------------------------------------------------------------------------- // Non-linear Diffusion - explicit scheme //---------------------------------------------------------------------------- // mode 1 gray: nonlinear diffusion __global__ void diffuse_nonlinear_isotrop_shared ( const float *d_input, const float *d_diffusivity, float *d_output, float timeStep, int nx, int ny, size_t pitch ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const int idx = y*pitch + x; __shared__ float u[DIFF_BW+2][DIFF_BH+2]; __shared__ float g[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = d_input[idx]; g[tx][ty] = d_diffusivity[idx]; if (x == 0) { u[0][ty] = u[tx][ty]; g[0][ty] = g[tx][ty]; } else if (threadIdx.x == 0) { u[0][ty] = d_input[idx-1]; g[0][ty] = d_diffusivity[idx-1]; } if (x == nx-1) { u[tx+1][ty] = u[tx][ty]; g[tx+1][ty] = g[tx][ty]; } else if (threadIdx.x == blockDim.x-1) { u[tx+1][ty] = d_input[idx+1]; g[tx+1][ty] = d_diffusivity[idx+1]; } if (y == 0) { u[tx][0] = u[tx][ty]; g[tx][0] = g[tx][ty]; } else if (threadIdx.y == 0) { u[tx][0] = d_input[idx-pitch]; g[tx][0] = d_diffusivity[idx-pitch]; } if (y == ny-1) { u[tx][ty+1] = u[tx][ty]; g[tx][ty+1] = g[tx][ty]; } else if (threadIdx.y == blockDim.y-1) { u[tx][ty+1] = d_input[idx+pitch]; g[tx][ty+1] = d_diffusivity[idx+pitch]; } } __syncthreads(); float phiR = 0.5 * (g[tx+1][ty] + g[tx][ty]); float phiL = 0.5 * (g[tx-1][ty] + g[tx][ty]); float phiU = 0.5 * (g[tx][ty+1] + g[tx][ty]); float phiD = 0.5 * (g[tx][ty-1] + g[tx][ty]); // ### implement me ### if (x < nx && y < ny) { d_output[idx] = u[tx][ty] + timeStep * ( u[tx + 1][ty]*phiR + u[tx - 1][ty]*phiL + u[tx][ty + 1]*phiU + u[tx][ty - 1]*phiD - u[tx][ty]*(phiR+phiL+phiU+phiD) ); } } // mode 1 interleaved: nonlinear diffusion __global__ void diffuse_nonlinear_isotrop_shared ( const float3 *d_input, const float3 *d_diffusivity, float3 *d_output, float timeStep, int nx, int ny, size_t pitchBytes ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const char* imgP = (char*)d_input + y*pitchBytes + x*sizeof(float3); const char* diffP = (char*)d_diffusivity + y*pitchBytes + x*sizeof(float3); __shared__ float3 u[DIFF_BW+2][DIFF_BH+2]; __shared__ float3 g[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = *( (float3*)imgP ); g[tx][ty] = *( (float3*)diffP ); if (x == 0) { u[0][ty] = u[tx][ty]; g[0][ty] = g[tx][ty]; } else if (threadIdx.x == 0) { u[0][ty] = *( ((float3*)imgP)-1 ); g[0][ty] = *( ((float3*)diffP)-1 ); } if (x == nx-1) { u[tx+1][ty] = u[tx][ty]; g[tx+1][ty] = g[tx][ty]; } else if (threadIdx.x == blockDim.x-1) { u[tx+1][ty] = *( ((float3*)imgP)+1 ); g[tx+1][ty] = *( ((float3*)diffP)+1 ); } if (y == 0) { u[tx][0] = u[tx][ty]; g[tx][0] = g[tx][ty]; } else if (threadIdx.y == 0) { u[tx][0] = *( (float3*)(imgP-pitchBytes) ); g[tx][0] = *( (float3*)(diffP-pitchBytes) ); } if (y == ny-1) { u[tx][ty+1] = u[tx][ty]; g[tx][ty+1] = g[tx][ty]; } else if (threadIdx.y == blockDim.y-1) { u[tx][ty+1] = *( (float3*)(imgP+pitchBytes) ); g[tx][ty+1] = *( (float3*)(diffP+pitchBytes) ); } } __syncthreads(); float3 phiR,phiL,phiU, phiD; phiR.x = 0.5 * (g[tx+1][ty].x+ g[tx][ty].x); phiL.x = 0.5 * (g[tx-1][ty].x+ g[tx][ty].x); phiU.x = 0.5 * (g[tx][ty+1].x+ g[tx][ty].x); phiD.x = 0.5 * (g[tx][ty-1].x+ g[tx][ty].x); phiR.y= 0.5 * (g[tx+1][ty].y+ g[tx][ty].y); phiL.y= 0.5 * (g[tx-1][ty].y+ g[tx][ty].y); phiU.y= 0.5 * (g[tx][ty+1].y+ g[tx][ty].y); phiD.y= 0.5 * (g[tx][ty-1].y+ g[tx][ty].y); phiR.z= 0.5 * (g[tx+1][ty].z+ g[tx][ty].z); phiL.z= 0.5 * (g[tx-1][ty].z+ g[tx][ty].z); phiU.z= 0.5 * (g[tx][ty+1].z+ g[tx][ty].z); phiD.z= 0.5 * (g[tx][ty-1].z+ g[tx][ty].z); // ### implement me ### float3 res; if (x < nx && y < ny) { res.x = u[tx][ty].x + timeStep * ( u[tx + 1][ty].x*phiR.x + u[tx - 1][ty].x*phiL.x + u[tx][ty + 1].x*phiU.x + u[tx][ty - 1].x*phiD.x - u[tx][ty].x*(phiR.x+phiL.x+phiU.x+phiD.x) ); res.y = u[tx][ty].y + timeStep * ( u[tx + 1][ty].y*phiR.y + u[tx - 1][ty].y*phiL.y + u[tx][ty + 1].y*phiU.y + u[tx][ty - 1].y*phiD.y - u[tx][ty].y*(phiR.y+phiL.y+phiU.y+phiD.y) ); res.z = u[tx][ty].z + timeStep * ( u[tx + 1][ty].z*phiR.z + u[tx - 1][ty].z*phiL.z + u[tx][ty + 1].z*phiU.z + u[tx][ty - 1].z*phiD.z - u[tx][ty].z*(phiR.z+phiL.z+phiU.z+phiD.z) ); *((float3*)(((char*)d_output) + y*pitchBytes) + x) = res; } } // diffusivity computation for modes 1-3 gray __global__ void compute_tv_diffusivity_shared ( const float *d_input, float *d_output, int nx, int ny, size_t pitch ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const int idx = y*pitch + x; __shared__ float u[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = d_input[idx]; if (x == 0) u[0][ty] = u[tx][ty]; else if (threadIdx.x == 0) u[0][ty] = d_input[idx-1]; if (x == nx-1) u[tx+1][ty] = u[tx][ty]; else if (threadIdx.x == blockDim.x-1) u[tx+1][ty] = d_input[idx+1]; if (y == 0) u[tx][0] = u[tx][ty]; else if (threadIdx.y == 0) u[tx][0] = d_input[idx-pitch]; if (y == ny-1) u[tx][ty+1] = u[tx][ty]; else if (threadIdx.y == blockDim.y-1) u[tx][ty+1] = d_input[idx+pitch]; } __syncthreads(); // make use of the constant TV_EPSILON float tempDerX; float tempDerY; float tmpGrad; if (x < nx && y < ny) { tempDerX = 0.5f*(u[threadIdx.x + 2][threadIdx.y+1]-u[threadIdx.x][threadIdx.y+1]); tempDerY = 0.5f*(u[threadIdx.x+1][threadIdx.y + 2] - u[threadIdx.x+1][threadIdx.y]); tmpGrad = sqrt( tempDerX*tempDerX + tempDerY*tempDerY ); d_output[idx] = 1.0 / sqrt(tmpGrad*tmpGrad + TV_EPSILON); } } /*! Computes a joined diffusivity for an RGB Image: * (g_R,g_G,g_B)(R,G,B) := * (g((R+G+B)/3),g((R+G+B)/3),g((R+G+B)/3)) * */ __global__ void compute_tv_diffusivity_joined_shared ( const float3 *d_input, float3 *d_output, int nx, int ny, size_t pitchBytes ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const char* imgP = (char*)d_input + y*pitchBytes + x*sizeof(float3); __shared__ float3 u[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = *( (float3*)imgP ); if (x == 0) u[0][ty] = u[tx][ty]; else if (threadIdx.x == 0) u[0][ty] = *( ((float3*)imgP)-1 ); if (x == nx-1) u[tx+1][ty] = u[tx][ty]; else if (threadIdx.x == blockDim.x-1) u[tx+1][ty] = *( ((float3*)imgP)+1 ); if (y == 0) u[tx][0] = u[tx][ty]; else if (threadIdx.y == 0) u[tx][0] = *( (float3*)(imgP-pitchBytes) ); if (y == ny-1) u[tx][ty+1] = u[tx][ty]; else if (threadIdx.y == blockDim.y-1) u[tx][ty+1] = *( (float3*)(imgP+pitchBytes) ); } __syncthreads(); // make use of the constant TV_EPSILON float3 tmpGrad; float3 xValue; float3 yValue; if (x < nx && y < ny) { float avgr = ( u[threadIdx.x + 2][threadIdx.y+1].x + u[threadIdx.x + 2][threadIdx.y+1].y + u[threadIdx.x + 2][threadIdx.y+1].z ) / 3.0; float avgu = ( u[threadIdx.x+1][threadIdx.y + 2].x + u[threadIdx.x+1][threadIdx.y + 2].y + u[threadIdx.x+1][threadIdx.y + 2].z ) / 3.0; float avgl = ( u[threadIdx.x][threadIdx.y+1].x + u[threadIdx.x][threadIdx.y+1].y + u[threadIdx.x][threadIdx.y+1].z) / 3.0; float avgd = ( u[threadIdx.x+1][threadIdx.y].x + u[threadIdx.x+1][threadIdx.y].y + u[threadIdx.x+1][threadIdx.y].z) / 3.0; // x derivatives xValue.x = 0.5f * (avgr - avgl); xValue.y = xValue.x; xValue.z = xValue.x; // y derivatives yValue.x = 0.5f * (avgu - avgd); yValue.y = yValue.x; yValue.z = yValue.x; tmpGrad.x = 1.0 / sqrt(xValue.x*xValue.x + yValue.x*yValue.x + TV_EPSILON); tmpGrad.y = 1.0 / sqrt(xValue.x*xValue.x + yValue.x*yValue.x + TV_EPSILON); tmpGrad.z = 1.0 / sqrt(xValue.x*xValue.x + yValue.x*yValue.x + TV_EPSILON); *((float3*)(((char*)d_output) + y*pitchBytes) + x) = tmpGrad; } } /*! Computes a separate diffusivity for an RGB Image: * (g_R,g_G,g_B)(R,G,B) := * (g(R),g(G),g(B)) * */ __global__ void compute_tv_diffusivity_separate_shared ( const float3 *d_input, float3 *d_output, int nx, int ny, size_t pitchBytes ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; const char* imgP = (char*)d_input + y*pitchBytes + x*sizeof(float3); __shared__ float3 u[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = *( (float3*)imgP ); if (x == 0) u[threadIdx.x][ty] = u[tx][ty]; else if (threadIdx.x == 0) u[0][ty] = *( ((float3*)imgP)-1 ); if (x == nx-1) u[tx+1][ty] = u[tx][ty]; else if (threadIdx.x == blockDim.x-1) u[tx+1][ty] = *( ((float3*)imgP)+1 ); if (y == 0) u[tx][0] = u[tx][ty]; else if (threadIdx.y == 0) u[tx][0] = *( (float3*)(imgP-pitchBytes) ); if (y == ny-1) u[tx][ty+1] = u[tx][ty]; else if (threadIdx.y == blockDim.y-1) u[tx][ty+1] = *( (float3*)(imgP+pitchBytes) ); } __syncthreads(); // make use of the constant TV_EPSILON float3 tmpGrad; float3 xValue; float3 yValue; if (x < nx && y < ny) { // x derivatives xValue.x = 0.5f * (u[threadIdx.x + 2][threadIdx.y+1].x - u[threadIdx.x][threadIdx.y+1].x); xValue.y = 0.5f * (u[threadIdx.x + 2][threadIdx.y+1].y - u[threadIdx.x][threadIdx.y+1].y); xValue.z = 0.5f * (u[threadIdx.x + 2][threadIdx.y+1].z - u[threadIdx.x][threadIdx.y+1].z); // y derivatives yValue.x = 0.5f * (u[threadIdx.x+1][threadIdx.y + 2].x - u[threadIdx.x+1][threadIdx.y].x); yValue.y = 0.5f * (u[threadIdx.x+1][threadIdx.y + 2].y - u[threadIdx.x+1][threadIdx.y].y); yValue.z = 0.5f * (u[threadIdx.x+1][threadIdx.y + 2].z - u[threadIdx.x+1][threadIdx.y].z); tmpGrad.x = 1.0 / sqrt(xValue.x*xValue.x + yValue.x*yValue.x + TV_EPSILON); tmpGrad.y = 1.0 / sqrt(xValue.x*xValue.x + yValue.x*yValue.x + TV_EPSILON); tmpGrad.z = 1.0 / sqrt(xValue.x*xValue.x + yValue.x*yValue.x + TV_EPSILON); *((float3*)(((char*)d_output) + y*pitchBytes) + x) = tmpGrad; } } //---------------------------------------------------------------------------- // Non-linear Diffusion - Jacobi scheme //---------------------------------------------------------------------------- // mode 2 gray: Jacobi solver __global__ void jacobi_shared ( float *d_output, const float *d_input, const float *d_original, const float *d_diffusivity, float weight, int nx, int ny, size_t pitch ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int idx = y*pitch + x; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; __shared__ float u[DIFF_BW+2][DIFF_BH+2]; __shared__ float g[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = d_input[idx]; g[tx][ty] = d_diffusivity[idx]; if (x == 0) { u[0][ty] = u[tx][ty]; g[0][ty] = g[tx][ty]; } else if (threadIdx.x == 0) { u[0][ty] = d_input[idx-1]; g[0][ty] = d_diffusivity[idx-1]; } if (x == nx-1) { u[tx+1][ty] = u[tx][ty]; g[tx+1][ty] = g[tx][ty]; } else if (threadIdx.x == blockDim.x-1) { u[tx+1][ty] = d_input[idx+1]; g[tx+1][ty] = d_diffusivity[idx+1]; } if (y == 0) { u[tx][0] = u[tx][ty]; g[tx][0] = g[tx][ty]; } else if (threadIdx.y == 0) { u[tx][0] = d_input[idx-pitch]; g[tx][0] = d_diffusivity[idx-pitch]; } if (y == ny-1) { u[tx][ty+1] = u[tx][ty]; g[tx][ty+1] = g[tx][ty]; } else if (threadIdx.y == blockDim.y-1) { u[tx][ty+1] = d_input[idx+pitch]; g[tx][ty+1] = d_diffusivity[idx+pitch]; } } __syncthreads(); // ### implement me ### float phiR = 0.5 * (g[tx+1][ty] + g[tx][ty]); float phiL = 0.5 * (g[tx-1][ty] + g[tx][ty]); float phiU = 0.5 * (g[tx][ty+1] + g[tx][ty]); float phiD = 0.5 * (g[tx][ty-1] + g[tx][ty]); if (x == 0) phiL = 0; else if (x == nx - 1) phiR = 0; if (y == 0) phiD = 0; else if (y == ny - 1) phiU = 0; // ### implement me ### if (x < nx && y < ny) { d_output[idx] = (1 / ( 1 + weight * (phiR+phiL+phiU+phiD ) ) )* ( d_original[idx] + weight*( u[tx + 1][ty]*phiR + u[tx - 1][ty]*phiL + u[tx][ty + 1]*phiU + u[tx][ty - 1]*phiD ) ); } } // mode 2 interleaved: Jacobi solver __global__ void jacobi_shared ( float3 *d_output, const float3 *d_input, const float3 *d_original, const float3 *d_diffusivity, float weight, int nx, int ny, size_t pitchBytes ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const char* imgP = (char*)d_input + y*pitchBytes + x*sizeof(float3); const char* diffP = (char*)d_diffusivity + y*pitchBytes + x*sizeof(float3); const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; __shared__ float3 u[DIFF_BW+2][DIFF_BH+2]; __shared__ float3 g[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = *( (float3*)imgP ); g[tx][ty] = *( (float3*)diffP ); if (x == 0) { u[0][ty] = u[tx][ty]; g[0][ty] = g[tx][ty]; } else if (threadIdx.x == 0) { u[0][ty] = *( ((float3*)imgP)-1 ); g[0][ty] = *( ((float3*)diffP)-1 ); } if (x == nx-1) { u[tx+1][ty] = u[tx][ty]; g[tx+1][ty] = g[tx][ty]; } else if (threadIdx.x == blockDim.x-1) { u[tx+1][ty] = *( ((float3*)imgP)+1 ); g[tx+1][ty] = *( ((float3*)diffP)+1 ); } if (y == 0) { u[tx][0] = u[tx][ty]; g[tx][0] = g[tx][ty]; } else if (threadIdx.y == 0) { u[tx][0] = *( (float3*)(imgP-pitchBytes) ); g[tx][0] = *( (float3*)(diffP-pitchBytes) ); } if (y == ny-1) { u[tx][ty+1] = u[tx][ty]; g[tx][ty+1] = g[tx][ty]; } else if (threadIdx.y == blockDim.y-1) { u[tx][ty+1] = *( (float3*)(imgP+pitchBytes) ); g[tx][ty+1] = *( (float3*)(diffP+pitchBytes) ); } } __syncthreads(); float3 phiR,phiL,phiU, phiD; phiR.x = 0.5 * (g[tx+1][ty].x+ g[tx][ty].x); phiL.x = 0.5 * (g[tx-1][ty].x+ g[tx][ty].x); phiU.x = 0.5 * (g[tx][ty+1].x+ g[tx][ty].x); phiD.x = 0.5 * (g[tx][ty-1].x+ g[tx][ty].x); phiR.y= 0.5 * (g[tx+1][ty].y+ g[tx][ty].y); phiL.y= 0.5 * (g[tx-1][ty].y+ g[tx][ty].y); phiU.y= 0.5 * (g[tx][ty+1].y+ g[tx][ty].y); phiD.y= 0.5 * (g[tx][ty-1].y+ g[tx][ty].y); phiR.z= 0.5 * (g[tx+1][ty].z+ g[tx][ty].z); phiL.z= 0.5 * (g[tx-1][ty].z+ g[tx][ty].z); phiU.z= 0.5 * (g[tx][ty+1].z+ g[tx][ty].z); phiD.z= 0.5 * (g[tx][ty-1].z+ g[tx][ty].z); if (x == 0) { phiL.x = 0; phiL.y = 0; phiL.z = 0; } else if (x == nx - 1) { phiR.x = 0; phiR.y = 0; phiR.z = 0; } if (y == 0) { phiD.x = 0; phiD.y = 0; phiD.z = 0; } else if (y == ny - 1) { phiU.x = 0; phiU.y = 0; phiU.z = 0; } // ### implement me ### float3 res; const char* original = (char*)d_original + y*pitchBytes + x*sizeof(float3); const float3 origVal = *((float3*)original); if (x < nx && y < ny) { res.x = (1 / ( 1 + weight * (phiR.x+phiL.x+phiU.x+phiD.x ) ) )* ( origVal.x + weight*( u[tx + 1][ty].x*phiR.x + u[tx - 1][ty].x*phiL.x + u[tx][ty + 1].x*phiU.x + u[tx][ty - 1].x*phiD.x ) ); res.y = (1 / ( 1 + weight * (phiR.y+phiL.y+phiU.y+phiD.y ) ) )* ( origVal.y + weight*( u[tx + 1][ty].y*phiR.y + u[tx - 1][ty].y*phiL.y + u[tx][ty + 1].y*phiU.y + u[tx][ty - 1].y*phiD.y ) ); res.z = (1 / ( 1 + weight * (phiR.z+phiL.z+phiU.z+phiD.z ) ) )* ( origVal.z + weight*( u[tx + 1][ty].z*phiR.z + u[tx - 1][ty].z*phiL.z + u[tx][ty + 1].z*phiU.z + u[tx][ty - 1].z*phiD.z ) ); *((float3*)(((char*)d_output) + y*pitchBytes) + x) = res; } } //---------------------------------------------------------------------------- // Non-linear Diffusion - Successive Over-Relaxation (SOR) //---------------------------------------------------------------------------- // mode 3 gray: SOR solver __global__ void sor_shared ( float *d_output, const float *d_input, const float *d_original, const float *d_diffusivity, float weight, float overrelaxation, int nx, int ny, size_t pitch, int red ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const int idx = y*pitch + x; const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; __shared__ float u[DIFF_BW+2][DIFF_BH+2]; __shared__ float g[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = d_input[idx]; g[tx][ty] = d_diffusivity[idx]; if (x == 0) { u[0][ty] = u[tx][ty]; g[0][ty] = g[tx][ty]; } else if (threadIdx.x == 0) { u[0][ty] = d_input[idx-1]; g[0][ty] = d_diffusivity[idx-1]; } if (x == nx-1) { u[tx+1][ty] = u[tx][ty]; g[tx+1][ty] = g[tx][ty]; } else if (threadIdx.x == blockDim.x-1) { u[tx+1][ty] = d_input[idx+1]; g[tx+1][ty] = d_diffusivity[idx+1]; } if (y == 0) { u[tx][0] = u[tx][ty]; g[tx][0] = g[tx][ty]; } else if (threadIdx.y == 0) { u[tx][0] = d_input[idx-pitch]; g[tx][0] = d_diffusivity[idx-pitch]; } if (y == ny-1) { u[tx][ty+1] = u[tx][ty]; g[tx][ty+1] = g[tx][ty]; } else if (threadIdx.y == blockDim.y-1) { u[tx][ty+1] = d_input[idx+pitch]; g[tx][ty+1] = d_diffusivity[idx+pitch]; } } __syncthreads(); float phiR = 0.5 * (g[tx+1][ty] + g[tx][ty]); float phiL = 0.5 * (g[tx-1][ty] + g[tx][ty]); float phiU = 0.5 * (g[tx][ty+1] + g[tx][ty]); float phiD = 0.5 * (g[tx][ty-1] + g[tx][ty]); if (x == 0) phiL = 0; else if (x == nx - 1) phiR = 0; if (y == 0) phiD = 0; else if (y == ny - 1) phiU = 0; if ((x < nx && y < ny && red && (x+y)%2==0) || (x < nx && y < ny && !red && (x+y)%2!=0)) { d_output[idx] = overrelaxation*(1 / ( 1 + weight * (phiR+phiL+phiU+phiD ) ) )* ( d_original[idx] + weight*( u[tx + 1][ty]*phiR + u[tx - 1][ty]*phiL + u[tx][ty + 1]*phiU + u[tx][ty - 1]*phiD ) ) + (1 - overrelaxation)*u[tx][ty]; } } // mode 3 interleaved: SOR solver __global__ void sor_shared ( float3 *d_output, const float3 *d_input, const float3 *d_original, const float3 *d_diffusivity, float weight, float overrelaxation, int nx, int ny, size_t pitchBytes, int red ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; const char* imgP = (char*)d_input + y*pitchBytes + x*sizeof(float3); const char* diffP = (char*)d_diffusivity + y*pitchBytes + x*sizeof(float3); const int tx = threadIdx.x+1; const int ty = threadIdx.y+1; __shared__ float3 u[DIFF_BW+2][DIFF_BH+2]; __shared__ float3 g[DIFF_BW+2][DIFF_BH+2]; // load data into shared memory if (x < nx && y < ny) { u[tx][ty] = *( (float3*)imgP ); g[tx][ty] = *( (float3*)diffP ); if (x == 0) { u[0][ty] = u[tx][ty]; g[0][ty] = g[tx][ty]; } else if (threadIdx.x == 0) { u[0][ty] = *( ((float3*)imgP)-1 ); g[0][ty] = *( ((float3*)diffP)-1 ); } if (x == nx-1) { u[tx+1][ty] = u[tx][ty]; g[tx+1][ty] = g[tx][ty]; } else if (threadIdx.x == blockDim.x-1) { u[tx+1][ty] = *( ((float3*)imgP)+1 ); g[tx+1][ty] = *( ((float3*)diffP)+1 ); } if (y == 0) { u[tx][0] = u[tx][ty]; g[tx][0] = g[tx][ty]; } else if (threadIdx.y == 0) { u[tx][0] = *( (float3*)(imgP-pitchBytes) ); g[tx][0] = *( (float3*)(diffP-pitchBytes) ); } if (y == ny-1) { u[tx][ty+1] = u[tx][ty]; g[tx][ty+1] = g[tx][ty]; } else if (threadIdx.y == blockDim.y-1) { u[tx][ty+1] = *( (float3*)(imgP+pitchBytes) ); g[tx][ty+1] = *( (float3*)(diffP+pitchBytes) ); } } __syncthreads(); float3 phiR,phiL,phiU, phiD; phiR.x = 0.5 * (g[tx+1][ty].x+ g[tx][ty].x); phiL.x = 0.5 * (g[tx-1][ty].x+ g[tx][ty].x); phiU.x = 0.5 * (g[tx][ty+1].x+ g[tx][ty].x); phiD.x = 0.5 * (g[tx][ty-1].x+ g[tx][ty].x); phiR.y= 0.5 * (g[tx+1][ty].y+ g[tx][ty].y); phiL.y= 0.5 * (g[tx-1][ty].y+ g[tx][ty].y); phiU.y= 0.5 * (g[tx][ty+1].y+ g[tx][ty].y); phiD.y= 0.5 * (g[tx][ty-1].y+ g[tx][ty].y); phiR.z= 0.5 * (g[tx+1][ty].z+ g[tx][ty].z); phiL.z= 0.5 * (g[tx-1][ty].z+ g[tx][ty].z); phiU.z= 0.5 * (g[tx][ty+1].z+ g[tx][ty].z); phiD.z= 0.5 * (g[tx][ty-1].z+ g[tx][ty].z); if (x == 0) { phiL.x = 0; phiL.y = 0; phiL.z = 0; } else if (x == nx - 1) { phiR.x = 0; phiR.y = 0; phiR.z = 0; } if (y == 0) { phiD.x = 0; phiD.y = 0; phiD.z = 0; } else if (y == ny - 1) { phiU.x = 0; phiU.y = 0; phiU.z = 0; } // ### implement me ### float3 res; const char* original = (char*)d_original + y*pitchBytes + x*sizeof(float3); const float3 origVal = *((float3*)original); if ((x < nx && y < ny && red && (x+y)%2==0) || (x < nx && y < ny && !red && (x+y)%2!=0)) { res.x = overrelaxation*(1 / ( 1 + weight * (phiR.x+phiL.x+phiU.x+phiD.x ) ) )* ( origVal.x + weight*( u[tx + 1][ty].x*phiR.x + u[tx - 1][ty].x*phiL.x + u[tx][ty + 1].x*phiU.x + u[tx][ty - 1].x*phiD.x ) ) + (1 - overrelaxation)*u[tx][ty].x; res.y = (1 / ( 1 + weight * (phiR.y+phiL.y+phiU.y+phiD.y ) ) )* ( origVal.y + weight*( u[tx + 1][ty].y*phiR.y + u[tx - 1][ty].y*phiL.y + u[tx][ty + 1].y*phiU.y + u[tx][ty - 1].y*phiD.y ) ) + (1 - overrelaxation)*u[tx][ty].y; res.z = (1 / ( 1 + weight * (phiR.z+phiL.z+phiU.z+phiD.z ) ) )* ( origVal.z + weight*( u[tx + 1][ty].z*phiR.z + u[tx - 1][ty].z*phiL.z + u[tx][ty + 1].z*phiU.z + u[tx][ty - 1].z*phiD.z ) ) + (1 - overrelaxation)*u[tx][ty].z; *((float3*)(((char*)d_output) + y*pitchBytes) + x) = res; } } //---------------------------------------------------------------------------- // Host function //---------------------------------------------------------------------------- void gpu_diffusion ( const float *input, float *output, int nx, int ny, int nc, float timeStep, int iterations, float weight, int lagged_iterations, float overrelaxation, int mode, bool jointDiffusivity ) { int i,j; size_t pitchF1, pitchBytesF1, pitchBytesF3; float *d_input = 0; float *d_output = 0; float *d_diffusivity = 0; float *d_original = 0; float *temp = 0; dim3 dimGrid((int)ceil((float)nx/DIFF_BW), (int)ceil((float)ny/DIFF_BH)); dim3 dimBlock(DIFF_BW,DIFF_BH); // Allocation of GPU Memory if (nc == 1) { cutilSafeCall( cudaMallocPitch( (void**)&(d_input), &pitchBytesF1, nx*sizeof(float), ny ) ); cutilSafeCall( cudaMallocPitch( (void**)&(d_output), &pitchBytesF1, nx*sizeof(float), ny ) ); if (mode) cutilSafeCall( cudaMallocPitch( (void**)&(d_diffusivity), &pitchBytesF1, nx*sizeof(float), ny ) ); if (mode >= 2) cutilSafeCall( cudaMallocPitch( (void**)&(d_original), &pitchBytesF1, nx*sizeof(float), ny ) ); cutilSafeCall( cudaMemcpy2D(d_input, pitchBytesF1, input, nx*sizeof(float), nx*sizeof(float), ny, cudaMemcpyHostToDevice) ); if (mode >= 2) cutilSafeCall( cudaMemcpy2D(d_original, pitchBytesF1, d_input, pitchBytesF1, nx*sizeof(float), ny, cudaMemcpyDeviceToDevice) ); pitchF1 = pitchBytesF1/sizeof(float); } else if (nc == 3) { cutilSafeCall( cudaMallocPitch( (void**)&(d_input), &pitchBytesF3, nx*sizeof(float3), ny ) ); cutilSafeCall( cudaMallocPitch( (void**)&(d_output), &pitchBytesF3, nx*sizeof(float3), ny ) ); if (mode) cutilSafeCall( cudaMallocPitch( (void**)&(d_diffusivity), &pitchBytesF3, nx*sizeof(float3), ny ) ); if (mode >= 2) cutilSafeCall( cudaMallocPitch( (void**)&(d_original), &pitchBytesF3, nx*sizeof(float3), ny ) ); cutilSafeCall( cudaMemcpy2D(d_input, pitchBytesF3, input, nx*sizeof(float3), nx*sizeof(float3), ny, cudaMemcpyHostToDevice) ); if (mode >= 2) cutilSafeCall( cudaMemcpy2D(d_original, pitchBytesF3, d_input, pitchBytesF3, nx*sizeof(float3), ny, cudaMemcpyDeviceToDevice) ); } // Execution of the Diffusion Kernel if (mode == 0) { // linear isotropic diffision if (nc == 1) { for (i=0;i<iterations;i++) { diffuse_linear_isotrop_shared<<<dimGrid,dimBlock>>>(d_input, d_output, timeStep, nx, ny, pitchF1); cutilSafeCall( cudaThreadSynchronize() ); temp = d_input; d_input = d_output; d_output = temp; } } else if (nc == 3) { for (i=0;i<iterations;i++) { diffuse_linear_isotrop_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_output,timeStep,nx,ny,pitchBytesF3); cutilSafeCall( cudaThreadSynchronize() ); temp = d_input; d_input = d_output; d_output = temp; } } } else if (mode == 1) { // nonlinear isotropic diffusion if (nc == 1) { for (i=0;i<iterations;i++) { compute_tv_diffusivity_shared<<<dimGrid,dimBlock>>>(d_input,d_diffusivity,nx,ny,pitchF1); cutilSafeCall( cudaThreadSynchronize() ); diffuse_nonlinear_isotrop_shared<<<dimGrid,dimBlock>>>(d_input,d_diffusivity,d_output,timeStep,nx,ny,pitchF1); cutilSafeCall( cudaThreadSynchronize() ); temp = d_input; d_input = d_output; d_output = temp; } } else if (nc == 3) { for (i=0;i<iterations;i++) { if (jointDiffusivity) compute_tv_diffusivity_joined_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_diffusivity,nx,ny,pitchBytesF3); else compute_tv_diffusivity_separate_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_diffusivity,nx,ny,pitchBytesF3); cutilSafeCall( cudaThreadSynchronize() ); diffuse_nonlinear_isotrop_shared<<<dimGrid,dimBlock>>> ((float3*)d_input,(float3*)d_diffusivity,(float3*)d_output,timeStep,nx,ny,pitchBytesF3); cutilSafeCall( cudaThreadSynchronize() ); temp = d_input; d_input = d_output; d_output = temp; } } } else if (mode == 2) { // Jacobi-method if (nc == 1) { for (i=0;i<iterations;i++) { compute_tv_diffusivity_shared<<<dimGrid,dimBlock>>>(d_input,d_diffusivity,nx,ny,pitchF1); cutilSafeCall( cudaThreadSynchronize() ); for (j=0;j<lagged_iterations;j++) { jacobi_shared<<<dimGrid,dimBlock>>> (d_output,d_input,d_original, d_diffusivity,weight,nx,ny,pitchF1); cutilSafeCall( cudaThreadSynchronize() ); temp = d_input; d_input = d_output; d_output = temp; } } } else if (nc == 3) { for (i=0;i<iterations;i++) { if (jointDiffusivity) compute_tv_diffusivity_joined_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_diffusivity,nx,ny,pitchBytesF3); else compute_tv_diffusivity_separate_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_diffusivity,nx,ny,pitchBytesF3); cutilSafeCall( cudaThreadSynchronize() ); for (j=0;j<lagged_iterations;j++) { jacobi_shared<<<dimGrid,dimBlock>>> ((float3*)d_output,(float3*)d_input, (float3*)d_original,(float3*)d_diffusivity, weight,nx,ny,pitchBytesF3); cutilSafeCall( cudaThreadSynchronize() ); temp = d_input; d_input = d_output; d_output = temp; } } } } else if (mode == 3) { // Successive Over Relaxation (Gauss-Seidel with extrapolation) if (nc == 1) { for (i=0;i<iterations;i++) { compute_tv_diffusivity_shared<<<dimGrid,dimBlock>>>(d_input,d_diffusivity,nx,ny,pitchF1); cutilSafeCall( cudaThreadSynchronize() ); for(j=0;j<lagged_iterations;j++) { sor_shared<<<dimGrid,dimBlock>>>(d_input,d_input,d_original, d_diffusivity,weight,overrelaxation,nx,ny,pitchF1, 0); cutilSafeCall( cudaThreadSynchronize() ); sor_shared<<<dimGrid,dimBlock>>>(d_input,d_input,d_original, d_diffusivity,weight,overrelaxation,nx,ny,pitchF1, 1); cutilSafeCall( cudaThreadSynchronize() ); } } } if (nc == 3) { for (i=0;i<iterations;i++) { if (jointDiffusivity) compute_tv_diffusivity_joined_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_diffusivity,nx,ny,pitchBytesF3); else compute_tv_diffusivity_separate_shared<<<dimGrid,dimBlock>>>((float3*)d_input,(float3*)d_diffusivity,nx,ny,pitchBytesF3); cutilSafeCall( cudaThreadSynchronize() ); for (j=0;j<lagged_iterations;j++) { sor_shared<<<dimGrid,dimBlock>>> ((float3*)d_input,(float3*)d_input, (float3*)d_original,(float3*)d_diffusivity, weight,overrelaxation,nx,ny,pitchBytesF3, 0); cutilSafeCall( cudaThreadSynchronize() ); sor_shared<<<dimGrid,dimBlock>>> ((float3*)d_input,(float3*)d_input, (float3*)d_original,(float3*)d_diffusivity, weight,overrelaxation,nx,ny,pitchBytesF3, 1); cutilSafeCall( cudaThreadSynchronize() ); } } } } if (nc == 1) { if (mode == 3) cutilSafeCall( cudaMemcpy2D(output, nx*sizeof(float), d_input, pitchBytesF1, nx*sizeof(float), ny, cudaMemcpyDeviceToHost) ); else cutilSafeCall( cudaMemcpy2D(output, nx*sizeof(float), d_output, pitchBytesF1, nx*sizeof(float), ny, cudaMemcpyDeviceToHost) ); } else if (nc == 3) { if (mode == 3) cutilSafeCall( cudaMemcpy2D(output, nx*sizeof(float3), d_input, pitchBytesF3, nx*sizeof(float3), ny, cudaMemcpyDeviceToHost) ); else cutilSafeCall( cudaMemcpy2D(output, nx*sizeof(float3), d_output, pitchBytesF3, nx*sizeof(float3), ny, cudaMemcpyDeviceToHost) ); } // clean up if (d_original) cutilSafeCall( cudaFree(d_original) ); if (d_diffusivity) cutilSafeCall( cudaFree(d_diffusivity) ); if (d_output) cutilSafeCall( cudaFree(d_output) ); if (d_input) cutilSafeCall( cudaFree(d_input) ); }
5,767
#include <cuda_runtime.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fstream> #define BILLION 1E9; const int n=300; __global__ void grayscaleKernel(int *ms, int *aux, int n){ int i = threadIdx.x+blockDim.x*blockIdx.x; int k=0; int grayscale=0; if(i<n){ for(k=0; k<n-3; k+=3){ grayscale = 0.299*ms[i*n+k] + 0.5876*ms[i*n+k+1] + 0.114*ms[i*n+k+2]; aux[i*n+k] = aux[i*n+k+1] = aux[i*n+k+2] = grayscale; } } } int main(){ int m[n][n], a[n][n]; int *d_m, *d_a; struct timespec requestStart, requestEnd, reqSt, reqEd; static unsigned int color[3]; FILE *fp = fopen("picture_col.ppm", "w"); (void) fprintf(fp,"P6\n%d %d\n255\n", n, n); FILE *sp = fopen("picture_gray.ppm", "w"); (void) fprintf(sp,"P6\n%d %d\n255\n", n, n); // Inicialización y construcción de imagen a color for(int i=0; i<n; i++) for(int j=0; j<n-3; j+=3){ m[i][j] = j%256; m[i][j+1] = i%256; m[i][j+2] = i*j%256; color[0] = m[i][j]; color[1] = m[i][j+1]; color[2] = m[i][j+2]; (void) fwrite(color, sizeof(int), 3, fp); } int size = sizeof(int)*n*n; clock_gettime(CLOCK_REALTIME, &reqSt); cudaMalloc((void **) &d_m, size); cudaMalloc((void **) &d_a, size); clock_gettime(CLOCK_REALTIME, &reqEd); cudaMemcpy(d_m, m, size, cudaMemcpyHostToDevice); cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice); dim3 dimBlock(n/4, n/4); dim3 dimGrid(n/dimBlock.x, n/dimBlock.y); clock_gettime(CLOCK_REALTIME, &requestStart); grayscaleKernel<<<dimBlock, dimGrid>>>(d_m, d_a, n); clock_gettime(CLOCK_REALTIME, &requestEnd); cudaMemcpy(a, d_a, size, cudaMemcpyDeviceToHost); printf("%d %d\n", a[0][0], a[n-1][n-1]); cudaFree(d_a); cudaFree(d_m); for(int i=0; i<n; i++) for(int j=0; j<n-3; j+=3){ color[0] = a[i][j]; color[1] = a[i][j+1]; color[2] = a[i][j+2]; (void) fwrite(color, sizeof(int), 3, sp); } double accum = (double) (requestEnd.tv_sec - requestStart.tv_sec) + (requestEnd.tv_nsec - requestStart.tv_nsec)/BILLION; printf( "Tiempo de ejecución: %.15lf\n", accum ); double accum2 = (double) (reqEd.tv_sec - reqSt.tv_sec) + (reqEd.tv_nsec - reqSt.tv_nsec)/BILLION; printf( "Tiempo empleado en la reserva de memoria: %.15lf\n", accum2 ); return cudaThreadExit(); }
5,768
#include "includes.h" /* Addition of two numbers using a kernel method. * Note: Documentation will explain each thing only once. */ /* Header files */ /* This a kernel function, it has the __global__ qualifier in the definition. * addition: Perform the addition of two numbers and return their sum. * +------------+-----------------------------------+ * | Parameters | Description | * +------------+-----------------------------------+ * | int a | Takes an integer passed by value. | * | int b | Takes an integer passed by value. | * | int *c | An integer pointer that refers to | * | | the GPU memory where we store the | * | | result of the addition. | * +------------+-----------------------------------+ */ /* main method runs on the host. */ __global__ void addition ( int a, int b, int *c ) { *c = a + b; }
5,769
#include <iostream> #include <sstream> #include <stdexcept> using namespace std; // assuming same padding __global__ void Variation2DKernel(float* var, const float* img, int nx, int ny, int nc, float eps) { int ix = blockIdx.x * blockDim.x + threadIdx.x; int iy = blockIdx.y * blockDim.y + threadIdx.y; if (ix >= nx || iy >= ny) { return; } int ind = (ix * ny + iy) * nc; float x = img[ind]; float dx = 0; float dy = 0; if (ix > 0) { dx = x - img[ind - ny * nc]; } if (iy > 0) { dy = x - img[ind - nc]; } var[ind] = sqrtf(dx * dx + dy * dy + eps); } // s1, s2 are the first and second derivatives of the surrogate function __global__ void TVSQS2DKernel(float* s1, float* s2, const float* var, const float* img, int nx, int ny, int nc) { int ix = blockIdx.x * blockDim.x + threadIdx.x; int iy = blockIdx.y * blockDim.y + threadIdx.y; if (ix >= nx || iy >= ny) { return; } int ind = (ix * ny + iy) * nc; float x = img[ind]; float v = var[ind]; float dx0 = 0; float dx1 = 0; float dy0 = 0; float dy1 = 0; float varx, vary; if (ix > 0) { dx0 = x - img[ind - ny * nc]; } if (ix < nx - 1) { dx1 = x - img[ind + ny * nc]; varx = var[ind + ny * nc]; } else { varx = v; // approximate var(nx,j) with var(nx-1,j) } if (iy > 0) { dy0 = x - img[ind - nc]; } if (iy < ny - 1) { dy1 = x - img[ind + nc]; vary = var[ind + nc]; } else { vary = v; // approximate var(i, ny) with var(i, ny-1) } s1[ind] = (dx0 + dy0) / v + dx1 / varx + dy1 / vary; s2[ind] = 2 / v + 1 / varx + 1 / vary; } // get first and second order derivatives of the surrogate function // get the variation of the image void TVSQS2D_gpu(float* s1, float* s2, float* var, const float* img, int nb, int nx, int ny, int nc, float eps) { dim3 threads(32, 16, 1); dim3 blocks(ceilf(nx / (float)threads.x), ceilf(ny / (float)threads.y), 1); for (int ib = 0; ib < nb; ib++) { for (int ic = 0; ic < nc; ic++) { int offset = ib * nx * ny * nc + ic; Variation2DKernel<<<blocks, threads>>>(var + offset, img + offset, nx, ny, nc, eps); TVSQS2DKernel<<<blocks, threads>>>(s1 + offset, s2 + offset, var + offset, img + offset, nx, ny, nc); } } } extern "C" void cTVSQS2D(float* s1, float* s2, float* var, const float* img, int nb, int nx, int ny, int nc, float eps = 1e-8f) { float* pcus1 = NULL; float* pcus2 = NULL; float* pcuVar = NULL; float* pcuImg = NULL; try { int N = nb * nx * ny * nc; if (cudaSuccess != cudaMalloc(&pcus1, sizeof(float) * N)) { throw runtime_error("pcus1 allocation failed"); } if (cudaSuccess != cudaMalloc(&pcus2, sizeof(float) * N)) { throw runtime_error("pcus2 allocation failed"); } if (cudaSuccess != cudaMalloc(&pcuVar, sizeof(float) * N)) { throw runtime_error("pcuVar allocation failed"); } if (cudaSuccess != cudaMalloc(&pcuImg, sizeof(float) * N)) { throw runtime_error("pcuImg allocation failed"); } cudaMemcpy(pcuImg, img, sizeof(float) * N, cudaMemcpyHostToDevice); TVSQS2D_gpu(pcus1, pcus2, pcuVar, pcuImg, nb, nx, ny, nc, eps); cudaMemcpy(s1, pcus1, sizeof(float) * N, cudaMemcpyDeviceToHost); cudaMemcpy(s2, pcus2, sizeof(float) * N, cudaMemcpyDeviceToHost); cudaMemcpy(var, pcuVar, sizeof(float) * N, cudaMemcpyDeviceToHost); } catch (exception& e) { if (pcus1 != NULL) cudaFree(pcus1); if (pcus2 != NULL) cudaFree(pcus2); if (pcuVar != NULL) cudaFree(pcuVar); if (pcuImg != NULL) cudaFree(pcuImg); ostringstream oss; oss << "cTVSQS2D failed: " << e.what() << "(" << cudaGetErrorString(cudaGetLastError()) << ")"; cerr << oss.str() << endl; throw runtime_error(oss.str().c_str()); } cudaFree(pcus1); cudaFree(pcus2); cudaFree(pcuVar); cudaFree(pcuImg); } // assuming same padding __global__ void Variation3DKernel(float* var, const float* img, int nx, int ny, int nz, int nc, float eps) { int ix = blockIdx.x * blockDim.x + threadIdx.x; int iy = blockIdx.y * blockDim.y + threadIdx.y; int iz = blockIdx.z * blockDim.z + threadIdx.z; if (ix >= nx || iy >= ny || iz >= nz) { return; } int ind = (ix * ny * nz + iy * nz + iz) * nc; float x = img[ind]; float dx = 0; float dy = 0; float dz = 0; if (ix > 0) { dx = x - img[ind - ny * nz * nc]; } if (iy > 0) { dy = x - img[ind - nz * nc]; } if (iz > 0) { dz = x - img[ind - nc]; } var[ind] = sqrtf(dx * dx + dy * dy + dz * dz + eps); } // s1, s2 are the first and second derivatives of the surrogate function __global__ void TVSQS3DKernel(float* s1, float* s2, const float* var, const float* img, int nx, int ny, int nz, int nc) { int ix = blockIdx.x * blockDim.x + threadIdx.x; int iy = blockIdx.y * blockDim.y + threadIdx.y; int iz = blockIdx.z * blockDim.z + threadIdx.z; if (ix >= nx || iy >= ny || iz >= nz) { return; } int ind = (ix * ny * nz + iy * nz + iz) * nc; float x = img[ind]; float v = var[ind]; float dx0 = 0; float dx1 = 0; float dy0 = 0; float dy1 = 0; float dz0 = 0; float dz1 = 0; float varx, vary, varz; if (ix > 0) { dx0 = x - img[ind - ny * nz * nc]; } if (ix < nx - 1) { dx1 = x - img[ind + ny * nz * nc]; varx = var[ind + ny * nz * nc]; } else { varx = v; // approximate var(nx,j) with var(nx-1,j) } if (iy > 0) { dy0 = x - img[ind - nz * nc]; } if (iy < ny - 1) { dy1 = x - img[ind + nz * nc]; vary = var[ind + nz * nc]; } else { vary = v; // approximate var(i, ny) with var(i, ny-1) } if (iz > 0) { dz0 = x - img[ind - nc]; } if (iz < nz - 1) { dz1 = x - img[ind + nc]; varz = var[ind + nc]; } else { varz = v; } s1[ind] = (dx0 + dy0 + dz0) / v + dx1 / varx + dy1 / vary + dz1 / varz; s2[ind] = 3 / v + 1 / varx + 1 / vary + 1 / varz; } // get first and second order derivatives of the surrogate function // get the variation of the image void TVSQS3D_gpu(float* s1, float* s2, float* var, const float* img, int nb, int nx, int ny, int nz, int nc, float eps) { dim3 threads(32, 16, 1); dim3 blocks(ceilf(nx / (float)threads.x), ceilf(ny / (float)threads.y), nz); for (int ib = 0; ib < nb; ib++) { for (int ic = 0; ic < nc; ic++) { int offset = ib * nx * ny * nz * nc + ic; Variation3DKernel<<<blocks, threads>>>(var + offset, img + offset, nx, ny, nz, nc, eps); TVSQS3DKernel<<<blocks, threads>>>(s1 + offset, s2 + offset, var + offset, img + offset, nx, ny, nz, nc); } } } extern "C" void cTVSQS3D(float* s1, float* s2, float* var, const float* img, int nb, int nx, int ny, int nz, int nc, float eps = 1e-8f) { float* pcus1 = NULL; float* pcus2 = NULL; float* pcuVar = NULL; float* pcuImg = NULL; try { int N = nb * nx * ny * nz * nc; if (cudaSuccess != cudaMalloc(&pcus1, sizeof(float) * N)) { throw runtime_error("pcus1 allocation failed"); } if (cudaSuccess != cudaMalloc(&pcus2, sizeof(float) * N)) { throw runtime_error("pcus2 allocation failed"); } if (cudaSuccess != cudaMalloc(&pcuVar, sizeof(float) * N)) { throw runtime_error("pcuVar allocation failed"); } if (cudaSuccess != cudaMalloc(&pcuImg, sizeof(float) * N)) { throw runtime_error("pcuImg allocation failed"); } cudaMemcpy(pcuImg, img, sizeof(float) * N, cudaMemcpyHostToDevice); TVSQS3D_gpu(pcus1, pcus2, pcuVar, pcuImg, nb, nx, ny, nz, nc, eps); cudaMemcpy(s1, pcus1, sizeof(float) * N, cudaMemcpyDeviceToHost); cudaMemcpy(s2, pcus2, sizeof(float) * N, cudaMemcpyDeviceToHost); cudaMemcpy(var, pcuVar, sizeof(float) * N, cudaMemcpyDeviceToHost); } catch (exception& e) { if (pcus1 != NULL) cudaFree(pcus1); if (pcus2 != NULL) cudaFree(pcus2); if (pcuVar != NULL) cudaFree(pcuVar); if (pcuImg != NULL) cudaFree(pcuImg); ostringstream oss; oss << "cTVSQS3D failed: " << e.what() << "(" << cudaGetErrorString(cudaGetLastError()) << ")"; cerr << oss.str() << endl; throw runtime_error(oss.str().c_str()); } cudaFree(pcus1); cudaFree(pcus2); cudaFree(pcuVar); cudaFree(pcuImg); }
5,770
#include <stdio.h> #include <stdlib.h> #include <math.h> #define BLOCK_SIZE 512 #define _check(stmt) \ do { \ cudaError_t err = stmt; \ if (err != cudaSuccess) { \ printf("Failed to run stmt ", #stmt); \ printf("Got CUDA error ... ", cudaGetErrorString(err)); \ return -1; \ } \ } while (0) __global__ void add(float* arr, float* aux, int len) { int j = blockIdx.x-1; int i = threadIdx.x + blockIdx.x*BLOCK_SIZE; if(i < len && j >= 0) { arr[i] = arr[i] + aux[j]; } } __global__ void reduce(float *input, float *output, int len) { int id = threadIdx.x; int pos = threadIdx.x + blockIdx.x*BLOCK_SIZE; if((blockIdx.x+1)*BLOCK_SIZE > len) { if(id == (len - blockIdx.x*BLOCK_SIZE - 1)) { output[blockIdx.x] = input[pos]; } } else { output[blockIdx.x] = input[(blockIdx.x+1)*BLOCK_SIZE - 1]; } } __global__ void scan(float *input, float *output, int len) { __shared__ float ls[BLOCK_SIZE]; int stride = 0x1; int i = threadIdx.x; int ind = threadIdx.x + blockIdx.x*BLOCK_SIZE; float temp; // Load into the local_scan: if(ind < len){ ls[i] = input[ind]; } else { ls[i] = 0.0; } for(stride = 0x1; stride < BLOCK_SIZE; stride = stride << 1) { __syncthreads(); if(i >= stride) { temp = ls[i] + ls[i-stride]; } __syncthreads(); if(i >= stride) { ls[i] = temp; } } // Copy to output array: if(ind < len) { output[ind] = ls[i]; } } int main(int argc, char** argv) { if(argc != 2) { printf("Usage: ./scan <input_data_file>\n"); return -1; } float *hostInput; // The input 1D list float *hostOutput; // The output list float *deviceInput; float *deviceOutput; int numElements; // number of elements in the list FILE* infile = fopen(argv[1], "r"); fscanf(infile, "%d\n", &numElements); hostInput = (float*)malloc(numElements * sizeof(float)); hostOutput = (float *)malloc(numElements * sizeof(float)); for(int i = 0; i < numElements; i++) { int temp; fscanf(infile, "%d\n", &temp); hostInput[i] = (float)temp; printf("%d, ", (int)hostInput[i]); } printf("\n"); _check(cudaMalloc((void **)&deviceInput, numElements * sizeof(float))); _check(cudaMalloc((void **)&deviceOutput, numElements * sizeof(float))); _check(cudaMemset(deviceOutput, 0, numElements * sizeof(float))); _check(cudaMemcpy(deviceInput, hostInput, numElements * sizeof(float), cudaMemcpyHostToDevice)); int grid_size = ceil((float)numElements/BLOCK_SIZE); dim3 scan_grid(grid_size,1,1); dim3 scan_block(BLOCK_SIZE,1,1); dim3 aux_grid(ceil((float)grid_size/BLOCK_SIZE),1,1); dim3 aux_block(BLOCK_SIZE,1,1); dim3 reduce_block(BLOCK_SIZE>>1,1,1); // Allocate the auxillary reduction array: float* deviceAuxIn; float* hostAuxIn; float* deviceAuxOut; float* hostAuxOut; _check(cudaMalloc((void **)&deviceAuxIn, grid_size*sizeof(float))); _check(cudaMalloc((void **)&deviceAuxOut, grid_size*sizeof(float))); hostAuxIn = (float*)malloc(grid_size*sizeof(float)); hostAuxIn = (float*)malloc(grid_size*sizeof(float)); // 1. Scan individual blocks: scan<<<scan_grid, scan_block>>>(deviceInput, deviceOutput, numElements); // 2. Compute a Reduction on Each Block: reduce<<<scan_grid, reduce_block>>>(deviceOutput, deviceAuxIn, numElements); _check(cudaMemcpy(hostAuxIn, deviceAuxIn, grid_size * sizeof(float), cudaMemcpyDeviceToHost)); for(int i = 0; i < grid_size; i++) { printf("%d, ",(int)hostAuxIn[i]); } printf("\n"); // 3. Scan the aux array: scan<<<aux_grid, aux_block>>>(deviceAuxIn, deviceAuxOut, grid_size); _check(cudaMemcpy(hostAuxOut, deviceAuxOut, grid_size * sizeof(float), cudaMemcpyDeviceToHost)); for(int i = 0; i < grid_size; i++) { printf("%d, ",(int)hostAuxOut[i]); } printf("\n"); // 4. Add the aux to the individual scanned blocks: add<<<scan_grid, scan_block>>>(deviceOutput, deviceAuxOut, numElements); cudaDeviceSynchronize(); _check(cudaMemcpy(hostOutput, deviceOutput, numElements * sizeof(float), cudaMemcpyDeviceToHost)); for(int i = 0; i < numElements; i++) { printf("%d, ", (int)hostOutput[i]); } printf("\n"); cudaFree(deviceInput); cudaFree(deviceOutput); free(hostInput); free(hostOutput); return 0; }
5,771
#include<iostream> #include<cuda_runtime.h> int main(void) { cudaDeviceProp prop; int count; cudaGetDeviceCount(&count); for (int i = 0; i < count; i++) { cudaGetDeviceProperties(&prop, i); } return 0; }
5,772
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <time.h> #define BLOCK_SIZE 16 // CPU Implementation void cpu_matrix_mult(int *h_a, int *h_b, int *h_result, int m, int n, int k) { for (int i = 0; i < m; ++i) { for (int j = 0; j < k; ++j) { int tmp = 0.0; for (int h = 0; h < n; ++h) { tmp += h_a[i * n + h] * h_b[h * k + j]; } h_result[i * k + j] = tmp; } } } // GPU Implementation __global__ void gpu_square_matrix_mult(int *d_a, int *d_b, int *d_result, int n) { __shared__ int tile_a[BLOCK_SIZE][BLOCK_SIZE]; __shared__ int tile_b[BLOCK_SIZE][BLOCK_SIZE]; int row = blockIdx.y * BLOCK_SIZE + threadIdx.y; int col = blockIdx.x * BLOCK_SIZE + threadIdx.x; int tmp = 0; int idx; for (int sub = 0; sub < gridDim.x; ++sub) { idx = row * n + sub * BLOCK_SIZE + threadIdx.x; if(idx >= n*n) { // n may not divisible by BLOCK_SIZE tile_a[threadIdx.y][threadIdx.x] = 0; } else { tile_a[threadIdx.y][threadIdx.x] = d_a[idx]; } idx = (sub * BLOCK_SIZE + threadIdx.y) * n + col; if(idx >= n*n) { tile_b[threadIdx.y][threadIdx.x] = 0; } else { tile_b[threadIdx.y][threadIdx.x] = d_b[idx]; } __syncthreads(); for (int k = 0; k < BLOCK_SIZE; ++k) { tmp += tile_a[threadIdx.y][k] * tile_b[k][threadIdx.x]; } __syncthreads(); } if(row < n && col < n) { d_result[row * n + col] = tmp; } } // Main Function int main(int argc, char const *argv[]) { int m, n, k; // m x n matrix multiplied with n x k matrix float gpu_elapsed_time_ms, cpu_elapsed_time_ms; srand(time(NULL)); printf("Enter square matrix size (nxn): "); scanf("%d", &n); // We consider only square matrices. m = k = n; // allocate memory in host RAM, h_cc is used to store CPU result int *h_a, *h_b, *h_c, *h_cc; cudaMallocHost((void **) &h_a, sizeof(int) * m * n); cudaMallocHost((void **) &h_b, sizeof(int) * n * k); cudaMallocHost((void **) &h_c, sizeof(int) * m * k); cudaMallocHost((void **) &h_cc, sizeof(int) * m * k); printf("Filling matrices A and B with random values...\n"); // random initialize matrix A for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { h_a[i * n + j] = rand() % 1024; } } // random initialize matrix B for (int i = 0; i < n; ++i) { for (int j = 0; j < k; ++j) { h_b[i * k + j] = rand() % 1024; } } // some events to count the execution time cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); printf("Running GPU Algorithm...\n"); // start to count execution time of GPU version cudaEventRecord(start, 0); // Allocate memory space on the device int *d_a, *d_b, *d_c; cudaMalloc((void **) &d_a, sizeof(int)*m*n); cudaMalloc((void **) &d_b, sizeof(int)*n*k); cudaMalloc((void **) &d_c, sizeof(int)*m*k); // copy matrix A and B from host to device memory cudaMemcpy(d_a, h_a, sizeof(int)*m*n, cudaMemcpyHostToDevice); cudaMemcpy(d_b, h_b, sizeof(int)*n*k, cudaMemcpyHostToDevice); unsigned int grid_rows = (m + BLOCK_SIZE - 1) / BLOCK_SIZE; unsigned int grid_cols = (k + BLOCK_SIZE - 1) / BLOCK_SIZE; dim3 dimGrid(grid_cols, grid_rows); dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE); // Launch kernel gpu_square_matrix_mult<<<dimGrid, dimBlock>>>(d_a, d_b, d_c, n); // Transfer results from device to host cudaMemcpy(h_c, d_c, sizeof(int)*m*k, cudaMemcpyDeviceToHost); cudaDeviceSynchronize(); // time counting terminate cudaEventRecord(stop, 0); cudaEventSynchronize(stop); // compute time elapse on GPU computing cudaEventElapsedTime(&gpu_elapsed_time_ms, start, stop); printf("GPU Time: %f ms.\n\n", gpu_elapsed_time_ms); printf("Running CPU Algorithm...\n"); cudaEventRecord(start, 0); cpu_matrix_mult(h_a, h_b, h_cc, m, n, k); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&cpu_elapsed_time_ms, start, stop); printf("CPU Time: %f ms.\n\n", cpu_elapsed_time_ms); // validate results computed by GPU int all_ok = 1; for (int i = 0; i < m; ++i) { for (int j = 0; j < k; ++j) { if(h_cc[i*k + j] != h_c[i*k + j]) { all_ok = 0; } } } // roughly compute speedup if(all_ok) { printf("Results cross-verified as correct, speedup = %f\n", cpu_elapsed_time_ms / gpu_elapsed_time_ms); } else { printf("Incorrect results. \n"); } // free memeory cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); cudaFreeHost(h_a); cudaFreeHost(h_b); cudaFreeHost(h_c); cudaFreeHost(h_cc); printf("Exiting.\n"); return 0; }
5,773
/* Copyright 2016-2017 the devicemem_cuda authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cuda_runtime_api.h> // FIXME(20160123): commentng out for cuda 7.0. //#include <cuda_fp16.h> #include <stdint.h> __global__ void vector_set_scalar_f32_kernel( float *dst, int dim, float c) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { dst[idx] = c; } } extern "C" void devicemem_cuda_vector_set_scalar_f32( float *dst, size_t dim, float c, cudaStream_t stream) { vector_set_scalar_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim, c); } __global__ void vector_add_constant_f32_kernel( float *dst, int dim, float c) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = dst[idx] + c; dst[idx] = y; } } extern "C" void devicemem_cuda_vector_add_constant_f32( float *dst, size_t dim, float c, cudaStream_t stream) { vector_add_constant_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim, c); } __global__ void vector_add_scalar_f32_kernel( uint32_t dim, const float *c, float *y) { uint32_t idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { y[idx] += c[0]; } } extern "C" void devicemem_cuda_vector_add_scalar_f32( size_t dim, const float *c, float *y, cudaStream_t stream) { vector_add_scalar_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dim, c, y); } __global__ void vector_scale_f32_kernel( float *dst, int dim, float alpha) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = alpha * dst[idx]; dst[idx] = y; } } extern "C" void devicemem_cuda_vector_scale_f32( float *dst, size_t dim, float alpha, cudaStream_t stream) { vector_scale_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim, alpha); } __global__ void vector_div_scalar_f32_kernel( float *dst, int dim, float c) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = dst[idx] / c; dst[idx] = y; } } extern "C" void devicemem_cuda_vector_div_scalar_f32( float *dst, size_t dim, float c, cudaStream_t stream) { vector_div_scalar_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim, c); } __global__ void vector_exp_f32_kernel( float *xs, int dim) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float x = expf(xs[idx]); xs[idx] = x; } } extern "C" void devicemem_cuda_vector_exp_f32( float *xs, size_t dim, cudaStream_t stream) { vector_exp_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( xs, dim); } __global__ void vector_square_f32_kernel( float *dst, int dim) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float x = dst[idx]; dst[idx] = x * x; } } extern "C" void devicemem_cuda_vector_square_f32( float *dst, size_t dim, cudaStream_t stream) { vector_square_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim); } __global__ void vector_reciprocal_f32_kernel( float *dst, int dim) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = 1.0f / dst[idx]; dst[idx] = y; } } extern "C" void devicemem_cuda_vector_reciprocal_f32( float *dst, size_t dim, cudaStream_t stream) { vector_reciprocal_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim); } __global__ void vector_set_f32_kernel( const float *src, int dim, float alpha, float *dst) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = alpha * src[idx]; dst[idx] = y; } } extern "C" void devicemem_cuda_vector_set_f32( const float *src, size_t dim, float alpha, float *dst, cudaStream_t stream) { vector_set_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( src, dim, alpha, dst); } __global__ void vector_add_f32_kernel( const float *src, int dim, float alpha, float *dst) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = alpha * src[idx] + dst[idx]; dst[idx] = y; } } extern "C" void devicemem_cuda_vector_add_f32( const float *src, size_t dim, float alpha, float *dst, cudaStream_t stream) { vector_add_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( src, dim, alpha, dst); } __global__ void vector_average_f32_kernel( const float *src, int dim, float alpha, float *dst) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = dst[idx]; y = y + alpha * (src[idx] - y); dst[idx] = y; } } extern "C" void devicemem_cuda_vector_average_f32( const float *src, size_t dim, float alpha, float *dst, cudaStream_t stream) { vector_average_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( src, dim, alpha, dst); } __global__ void vector_elemwise_mult_f32_kernel( float *ys, int dim, const float *xs) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = xs[idx] * ys[idx]; ys[idx] = y; } } extern "C" void devicemem_cuda_vector_elemwise_mult_f32( float *dst, size_t dim, const float *xs, cudaStream_t stream) { vector_elemwise_mult_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim, xs); } __global__ void vector_elemwise_div_f32_kernel( float *ys, int dim, const float *xs) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < dim) { float y = ys[idx] / xs[idx]; ys[idx] = y; } } extern "C" void devicemem_cuda_vector_elemwise_div_f32( float *dst, size_t dim, const float *xs, cudaStream_t stream) { vector_elemwise_div_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dst, dim, xs); } __global__ void elem_div_f32_kernel( uint32_t dim, const float *divisor, float *x) { uint32_t idx = threadIdx.x + blockDim.x * blockIdx.x; if (idx < dim) { x[idx] = x[idx] / divisor[idx]; } } extern "C" void devicemem_cuda_kernel_elem_div_f32( size_t dim, const float *divisor, float *x, cudaStream_t stream) { elem_div_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dim, divisor, x); } __global__ void elem_ldiv_f32_kernel( uint32_t dim, const float *ldivisor, float *x) { uint32_t idx = threadIdx.x + blockDim.x * blockIdx.x; if (idx < dim) { x[idx] = ldivisor[idx] / x[idx]; } } extern "C" void devicemem_cuda_kernel_elem_ldiv_f32( size_t dim, const float *ldivisor, float *x, cudaStream_t stream) { elem_ldiv_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( dim, ldivisor, x); } __global__ void accumulate_scale_constant_f32_kernel( float alpha, uint32_t dim, const float *x, float *y, float beta) { uint32_t idx = threadIdx.x + blockDim.x * blockIdx.x; if (idx < dim) { y[idx] = alpha * x[idx] + beta * y[idx]; } } extern "C" void devicemem_cuda_kernel_accumulate_scale_constant_f32( float alpha, size_t dim, const float *x, float *y, float beta, cudaStream_t stream) { accumulate_scale_constant_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( alpha, dim, x, y, beta); } __global__ void accumulate_elem_mult_f32_kernel( float alpha, uint32_t dim, const float *a, const float *x, float *y, float beta) { uint32_t idx = threadIdx.x + blockDim.x * blockIdx.x; if (idx < dim) { y[idx] = alpha * a[idx] * x[idx] + beta * y[idx]; } } extern "C" void devicemem_cuda_kernel_accumulate_elem_mult_f32( float alpha, size_t dim, const float *a, const float *x, float *y, float beta, cudaStream_t stream) { accumulate_elem_mult_f32_kernel<<<(dim+1024-1)/1024, 1024, 0, stream>>>( alpha, dim, a, x, y, beta); }
5,774
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #define TILE_SIZE 14 #define KERNEL_SIZE 5 #define BLOCK_SIZE (TILE_SIZE + (KERNEL_SIZE - 1)) // global variable, outsize any function __constant__ float Mc[KERNEL_SIZE][KERNEL_SIZE]; __global__ void Convolution2D(float* d_M, float* d_N, float* d_P,int M_Width_row,int M_Width_col,int P_Width_row,int P_Width_col){ int tx = threadIdx.x; int ty = threadIdx.y; int row_o = blockIdx.y * TILE_SIZE + ty; int col_o = blockIdx.x * TILE_SIZE + tx; int row_i =row_o - ((KERNEL_SIZE - 1) / 2); // Assumes kernel size is 3 int col_i =col_o - ((KERNEL_SIZE - 1) / 2); // Assumes kernel size is 3 int i=0; int j=0; float output = 0.0f; __shared__ float Ms[TILE_SIZE+KERNEL_SIZE-1][TILE_SIZE+KERNEL_SIZE-1]; if((row_i >= 0) && (row_i < M_Width_row) && (col_i >= 0) && (col_i < M_Width_col)){ Ms[ty][tx] = d_M[row_i*M_Width_col + col_i]; } else{ Ms[ty][tx] = 0.0f; } if(ty < TILE_SIZE && tx < TILE_SIZE){ for(i = 0; i < KERNEL_SIZE; i++){ for(j = 0; j < KERNEL_SIZE; j++){ output += Mc[i][j] * Ms[i+ty][j+tx]; //printf("Mc[%d][%d]:%f Ms[%d][%d]:%f\n",i,j,Mc[i][j],i+ty,j+tx,Ms[i+ty][j+tx]); } } // some threads do not write output if(row_o < P_Width_row && col_o < P_Width_col){ d_P[row_o * P_Width_col + col_o] = output; } } } void verification(const float *N, const float *M, const float *P, int Rows, int Columns) ; int main(int argc,char **argv){ float *d_M,*d_N,*d_P; float *h_M,*h_N,*h_P; // cudaEvent_t start,end; // float time_ms=0; // cudaEventCreate(&start); // cudaEventCreate(&end); h_M=(float*)malloc(sizeof(float)*TILE_SIZE*TILE_SIZE ); h_N=(float*)malloc(sizeof(float)*KERNEL_SIZE*KERNEL_SIZE); h_P=(float*)malloc(sizeof(float)*TILE_SIZE*TILE_SIZE); memset(h_P, 0,TILE_SIZE * TILE_SIZE * sizeof(float)); for(int i=0;i<TILE_SIZE*TILE_SIZE;i++){ h_M[i]=i+1; } for(int i=0;i<KERNEL_SIZE*KERNEL_SIZE;i++){ h_N[i]=100+i; } cudaMalloc((void**)&d_M, sizeof(float) *TILE_SIZE*TILE_SIZE); cudaMalloc((void**)&d_N, sizeof(float) *KERNEL_SIZE*KERNEL_SIZE); cudaMalloc((void**)&d_P, sizeof(float) *TILE_SIZE*TILE_SIZE); cudaMemcpy(d_M,h_M,TILE_SIZE*TILE_SIZE*sizeof(float),cudaMemcpyHostToDevice); cudaMemcpy(d_P,h_P,TILE_SIZE*TILE_SIZE*sizeof(float),cudaMemcpyHostToDevice); cudaMemcpyToSymbol(Mc, h_N, sizeof(float) * KERNEL_SIZE * KERNEL_SIZE,0,cudaMemcpyHostToDevice); dim3 dimBlock(TILE_SIZE + (KERNEL_SIZE - 1), TILE_SIZE + (KERNEL_SIZE - 1)); // cudaEventRecord(start,0); Convolution2D<<< 1,dimBlock>>>(d_M,d_N,d_P,TILE_SIZE,TILE_SIZE,TILE_SIZE,TILE_SIZE); // cudaEventRecord(end,0); //printf("Execution time for Cuda Convolution2D: %.2f ms \n\n",time_ms); cudaMemcpy(h_P,d_P,TILE_SIZE*TILE_SIZE*sizeof(float),cudaMemcpyDeviceToHost); verification(h_M, h_N, h_P, TILE_SIZE, TILE_SIZE); free(h_P); free(h_M); free(h_N); cudaFree(d_P); cudaFree(d_M); cudaFree(d_N); return 0; } void verification(const float *N, const float *M, const float *P, int Rows, int Columns) { int r, c, h, w; int row_i, col_i; bool equal; float* results; results = (float*)malloc(Rows * Columns * sizeof(float)); memset(results, 0, Rows * Columns * sizeof(float)); for (r = 0; r < Rows; r++) { for (c = 0; c < Columns; c++) { for (h = 0; h < KERNEL_SIZE; h++) { for (w = 0; w < KERNEL_SIZE; w++) { row_i = r - ((KERNEL_SIZE - 1) / 2) + h; col_i = c - ((KERNEL_SIZE - 1) / 2) + w; if ((row_i >= 0) && (row_i < Rows) && (col_i >= 0) && (col_i < Columns)) { results[r*Columns + c] += (M[h*KERNEL_SIZE + w] * N[row_i*Columns + col_i]); } } } } } equal = true; for (int i = 0; i < Rows * Columns && equal; i++) { //printf("results[%d]:%f P[%d]:%f\n",i,results[i],i,P[i]); if (abs(results[i] - P[i]) >= 0.001f) { equal = false; printf("NOT EQUAL!\n"); } } if (equal) { printf("Results are equal!\n"); } else { printf("Results are NOT equal!\n"); } free(results); return; } #include <iostream> #define MASK_WIDTH 3 #define MASK_RADIUS MASK_WIDTH / 2 #define TILE_WIDTH 8 #define W (TILE_WIDTH + MASK_WIDTH - 1) /** * GPU 2D Convolution using shared memory */
5,775
/* * Université Pierre et Marie Curie * Calcul de transport de neutrons * Version séquentielle */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <cuda.h> #include <curand.h> #include <curand_kernel.h> #define OUTPUT_FILE "/tmp/absorbed.dat" #define NB_BLOCK 256 #define NB_THREAD 256 #define CUDA_CALL(x) do { if((x) != cudaSuccess) { \ printf("Error at %s:%d\n",__FILE__,__LINE__); \ return EXIT_FAILURE;}} while(0) // Déclaration dans le mémoire RAM du GPU __device__ int device_r; __device__ int device_b; __device__ int device_t; char info[] = "\ Usage:\n\ neutron-seq H Nb C_c C_s\n\ \n\ H : épaisseur de la plaque\n\ Nb : nombre d'échantillons\n\ C_c: composante absorbante\n\ C_s: componente diffusante\n\ \n\ Exemple d'execution : \n\ neutron-seq 1.0 500000000 0.5 0.5\n\ "; __global__ void setup_kernel(curandState *state){ int idx = threadIdx.x+blockDim.x*blockIdx.x; // On initialise chaque générateur avec une graine différente curand_init(idx, 0, 0, &state[idx]); /*On initialise chaque générateur avec la même graine mais avec une séquence différente Les générateur donneront pas les mêmes chiffres car chaque séquence est séparé de 2^67 nombres*/ // curand_init(666, idx, 0, &state[idx]); } /* * notre gettimeofday() */ double my_gettimeofday(){ struct timeval tmp_time; gettimeofday(&tmp_time, NULL); return tmp_time.tv_sec + (tmp_time.tv_usec * 1.0e-6L); } __global__ void neutron_gpu(curandState *state, float h, int n, float c_c, float c_s, float *result) { // nombre de neutrons refléchis, absorbés et transmis int r, b, t; r = b = t = 0; // Tableau pour l'écriture de chaque thread __shared__ int R[NB_THREAD]; __shared__ int B[NB_THREAD]; __shared__ int T[NB_THREAD]; float c; c = c_c + c_s; // distance parcourue par le neutron avant la collision float L; // direction du neutron (0 <= d <= PI) float d; // variable aléatoire uniforme float u; // position de la particule (0 <= x <= h) float x; int idx; idx = threadIdx.x + blockIdx.x * blockDim.x; // On copie le générateur sur le registre pour plus d'efficacité curandState localState = state[idx]; /* code GPU */ while(idx < n) { d = 0.0; x = 0.0; while(1) { u = curand_uniform(&localState); L = -(1 / c) * log(u); x = x + L * cos(d); if (x < 0) { r++; break; } else if (x >= h) { t++; break; } else if ((u = curand_uniform(&localState)) < c_c / c) { b++; result[idx] = x; break; } else { u = curand_uniform(&localState); d = u * M_PI; } } idx+= blockDim.x * gridDim.x; } // On stock r,b,t dans le tableau R[threadIdx.x] = r; B[threadIdx.x] = b; T[threadIdx.x] = t; // Synchronisation avant qu'un thread calcule la somme totale __syncthreads(); // Reduction des tableaux for(unsigned int s = blockDim.x/2; s > 0; s = s/2) { if(threadIdx.x < s) { R[threadIdx.x] += R[threadIdx.x + s]; B[threadIdx.x] += B[threadIdx.x + s]; T[threadIdx.x] += T[threadIdx.x + s]; } __syncthreads(); } // Seul le thread 0 d'une bloc va additionner l'ensemble des valeurs if(threadIdx.x == 0) { atomicAdd(&device_r,R[0]); atomicAdd(&device_b,B[0]); atomicAdd(&device_t,T[0]); } } /* * main() */ int main(int argc, char *argv[]) { // La distance moyenne entre les interactions neutron/atome est 1/c. // c_c et c_s sont les composantes absorbantes et diffusantes de c. float c_c, c_s; // épaisseur de la plaque float h; // nombre d'échantillons int n; // chronometrage cudaEvent_t start, finish; cudaEventCreate(&start); cudaEventCreate(&finish); if( argc == 1) fprintf( stderr, "%s\n", info); // valeurs par defaut h = 1.0; n = 500000000; c_c = 0.5; c_s = 0.5; // recuperation des parametres if (argc > 1) h = atof(argv[1]); if (argc > 2) n = atoi(argv[2]); if (argc > 3) c_c = atof(argv[3]); if (argc > 4) c_s = atof(argv[4]); // affichage des parametres pour verificatrion printf("Épaisseur de la plaque : %4.g\n", h); printf("Nombre d'échantillons : %d\n", n); printf("C_c : %g\n", c_c); printf("C_s : %g\n", c_s); //Allocation mémoire du résultat côté CPU float *host_absorbed; host_absorbed = (float *) calloc(n, sizeof(float)); int r,b,t; //Allocation mémoire du résultat côté GPU float *device_absorbed; cudaMalloc((void **)&device_absorbed, n*sizeof(float)); cudaMemset(device_absorbed,0,n*sizeof(float)); // Allocation mémoire par le CPU du tableau de générateur pseudo-aléatoire curandState *d_state; CUDA_CALL(cudaMalloc((void **)&d_state, NB_BLOCK*NB_THREAD*sizeof(curandState))); // debut du chronometrage cudaEventRecord(start, 0); // On initialise les générateurs setup_kernel<<<NB_BLOCK,NB_THREAD>>>(d_state); neutron_gpu<<<NB_BLOCK,NB_THREAD>>>(d_state, h, n, c_c, c_s, device_absorbed); cudaMemcpy(host_absorbed,device_absorbed,n*sizeof(float),cudaMemcpyDeviceToHost); cudaMemcpyFromSymbol(&r, device_r, sizeof(int),0); cudaMemcpyFromSymbol(&b, device_b, sizeof(int),0); cudaMemcpyFromSymbol(&t, device_t, sizeof(int),0); // fin du chronometrage cudaEventRecord(finish, 0); cudaEventSynchronize(finish); float elapsedTime; cudaEventElapsedTime(&elapsedTime, start, finish); printf("r=%d, b=%d, t=%d\n",r,b,t); printf("\nPourcentage des neutrons refléchis : %4.2g\n", (float) r / (float) n); printf("Pourcentage des neutrons absorbés : %4.2g\n", (float) b / (float) n); printf("Pourcentage des neutrons transmis : %4.2g\n", (float) t / (float) n); printf("\nTemps total de calcul: %.8g sec\n", elapsedTime/1000.0); printf("Millions de neutrons /s: %.2g\n", (double) n / ((elapsedTime/1000.0)*1e6)); // ouverture du fichier pour ecrire les positions des neutrons absorbés FILE *f_handle = fopen(OUTPUT_FILE, "w"); if (!f_handle) { fprintf(stderr, "Cannot open " OUTPUT_FILE "\n"); exit(EXIT_FAILURE); } for (int j = 0; j < b; j++) fprintf(f_handle, "%f\n", host_absorbed[j]); // fermeture du fichier fclose(f_handle); printf("Result written in " OUTPUT_FILE "\n"); cudaFree(d_state); cudaFree(device_absorbed); free(host_absorbed); return EXIT_SUCCESS; }
5,776
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> cudaError_t MovAvgWithCuda(float *result, const float *input, size_t size, int avgWindowSize); __global__ void MovAvgKernel(float *result, const float *input, int threadCount, int elementsCount, const int avgWindowSize) { int idx = threadIdx.x; int uniqueElementsForThread = elementsCount/ threadCount; int maxIdxForThread = (idx+1)*uniqueElementsForThread + avgWindowSize; if(idx == threadCount - 1) maxIdxForThread = elementsCount - 1; float sum = 0; //initialize first for(int i=0; i<avgWindowSize; i++) { float element = (float)input[uniqueElementsForThread*idx + i]/(float)avgWindowSize; sum += element; } int currentInd = uniqueElementsForThread*idx + avgWindowSize -1; result[currentInd] = sum; //run through while(currentInd<maxIdxForThread) { currentInd++; sum -= input[currentInd - avgWindowSize]/(float)avgWindowSize; sum += input[currentInd]/(float)avgWindowSize; result[currentInd] = sum; } } int main() { const int arraySize = 10000; const int avgWindowSize = 15; float a[arraySize] = {0}; for(int i=0; i<arraySize; i++) { a[i] = i; } float result[arraySize] = { 0 }; // Add vectors in parallel. cudaError_t cudaStatus = MovAvgWithCuda(result, a, arraySize, avgWindowSize); if (cudaStatus != cudaSuccess) { fprintf(stderr, "addWithCuda failed!"); return 1; } // cudaDeviceReset must be called before exiting in order for profiling and // tracing tools such as Nsight and Visual Profiler to show complete traces. cudaStatus = cudaDeviceReset(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaDeviceReset failed!"); return 1; } for(int i = 0; i< arraySize; i++ ) { printf("%f \n", result[i]); } getchar(); return 0; } // Helper function for using CUDA to add vectors in parallel. cudaError_t MovAvgWithCuda(float *result, const float *input, size_t size, int avgWindowSize) { const int BLOCKS = 1; const int THREADS = 256; float *dev_input = 0; float *dev_result = 0; cudaError_t cudaStatus; // Choose which GPU to run on, change this on a multi-GPU system. cudaStatus = cudaSetDevice(0); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?"); goto Error; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&dev_result, size * sizeof(float)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } cudaStatus = cudaMalloc((void**)&dev_input, size * sizeof(float)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } // Copy input vectors from host memory to GPU buffers. cudaStatus = cudaMemcpy(dev_input, input, size * sizeof(float), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } // Launch a kernel on the GPU with one thread for each element. MovAvgKernel<<<BLOCKS, THREADS>>>(dev_result, dev_input, THREADS, size, avgWindowSize); // cudaDeviceSynchronize waits for the kernel to finish, and returns // any errors encountered during the launch. cudaStatus = cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus); goto Error; } // Copy output vector from GPU buffer to host memory. cudaStatus = cudaMemcpy(result, dev_result, size * sizeof(float), cudaMemcpyDeviceToHost); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } Error: cudaFree(dev_result); cudaFree(dev_input); return cudaStatus; }
5,777
#include <stdio.h> __global__ void device_hello(){ //uncomment this line to print only one time (unless you have multiple blocks) if(threadIdx.x==0) printf("Hello world! from the device! thread:%d,%d\n",blockIdx.x,threadIdx.x); return; } int main(void){ // rather than calling fflush setbuf(stdout, NULL); // greet from the host printf("Hello world! from the host!\n"); // launch a kernel with a block of threads to greet from the device dim3 blockSize(32,1,1); dim3 gridSize(1,1,1); // run several variations by playing with the block and grid sizes // above -- if you change the y or z dimensions change the print // statement to reflect that. device_hello<<<gridSize,blockSize>>>(); // comment this line out and see what happens cudaDeviceSynchronize(); printf("Goodbye world! from the host!\n"); return 0; }
5,778
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cuda_runtime.h> // Setup for measuing time #include <sys/time.h> #include <time.h> int timeval_subtract(struct timeval* result, struct timeval* t2, struct timeval* t1) { unsigned int resolution=1000000; long int diff = (t2->tv_usec + resolution * t2->tv_sec) - (t1->tv_usec + resolution * t1->tv_sec); result->tv_sec = diff / resolution; result->tv_usec = diff % resolution; return (diff<0); } void seqFunct(float* m_out) { for (int i = 1; i <= 753411; i++) { m_out[i-1] = pow(i/(i-2.3), 3); } } __global__ void parFunct(float *d_in, float *d_out, int limit) { const unsigned int lid = threadIdx.x; //local id inside a block const unsigned int gid = blockIdx.x*blockDim.x + lid; // global id float x; if (gid <= limit) { x = d_in[gid]; d_out[gid] = pow((x/(x-2.3)),3); // Compute } } int main(int argc, char** argv) { unsigned int num_threads = 753411; unsigned int mem_size = num_threads*sizeof(float); // Initialize vars for measuring time unsigned long int par_elapsed; unsigned long int seq_elapsed; struct timeval p_start, p_end, p_diff; struct timeval s_start, s_end, s_diff; // alocate host memory float* h_in = (float*) malloc(mem_size); float* h_out = (float*) malloc(mem_size); float* m_out = (float*) malloc(mem_size); // iniitalize the memory for(unsigned int i=1; i<=num_threads; ++i) { h_in[i-1] = (float)(i); } // allocate device memory float* d_in; float* d_out; cudaMalloc((void**)&d_in, mem_size); cudaMalloc((void**)&d_out, mem_size); // copy host memory to device cudaMemcpy(d_in, h_in, mem_size, cudaMemcpyHostToDevice); // Start timer gettimeofday(&p_start, NULL); // execute the kernel parFunct<<< ceil(num_threads/1024.0), 1024>>>(d_in, d_out, num_threads); cudaThreadSynchronize(); // calc elapsed time gettimeofday(&p_end, NULL); timeval_subtract(&p_diff, &p_end, &p_start); par_elapsed = p_diff.tv_sec*1e6+p_diff.tv_usec; cudaMemcpy(h_out, d_out, mem_size, cudaMemcpyDeviceToHost); gettimeofday(&s_start, NULL); // execute the kernel seqFunct(m_out); // Print elapsed time gettimeofday(&s_end, NULL); timeval_subtract(&s_diff, &s_end, &s_start); seq_elapsed = s_diff.tv_sec*1e6+s_diff.tv_usec; //printf("Took %d microseconds (%.2fms)\n", elapsed, elapsed/1000.0); bool isValid = true; for (int i = 0; i < num_threads; i++) { if (abs(m_out[i] - h_out[i]) > 0.000001) { isValid = false; break; } } if (isValid) { printf("VALID\n"); } else { printf("INVALID\n"); } printf("CPU Time: %d microseconds (%.fms)\n", seq_elapsed, seq_elapsed/1000.0); printf("GPU Time: %d microseconds (%.fms)\n", par_elapsed, par_elapsed/1000.0); // clean-up memory free(h_in); free(h_out); free(m_out); cudaFree(d_in); cudaFree(d_out); }
5,779
/* =============================================================================== Name : simulatorutils.cu Author : Mridul & Srinidhi Version : Copyright : Copyleft Description : Parallel implementation of Rigid Body Dynamics on GPU using CUDA =============================================================================== */ #include <stdio.h> #define EPSILON 1 __device__ int checkIntersection(double x1,double x2,double y1,double y2,double z1,double z2,double a1,double a2,double b1,double b2,double c1, double c2) { if((a1 < (x2 + EPSILON) && x1 < (a2 + EPSILON)) && (b1 < (y2 + EPSILON) && y1 < (b2 + EPSILON)) && (c1 < (z2 + EPSILON) && z1 < (c2 + EPSILON))) return 1; return 0; } __global__ void checkCollision(double *d_x, double *d_y, double *d_z, int *d_mat, int n) { int row = threadIdx.y ; int col = threadIdx.x ; int idx = row*n + col; for (long int j = 0; j < n; ++j) { if(idx != j && checkIntersection(d_x[2*idx], d_x[2*idx+1], d_y[2*idx], d_y[2*idx+1], d_z[2*idx], d_z[2*idx+1], d_x[2*j], d_x[2*j+1], d_y[2*j], d_y[2*j+1], d_z[2*j], d_z[2*j+1])) d_mat[idx*n+j] = 1; else d_mat[idx*n+j] = 0; __syncthreads(); } } __host__ void collisionWrapper(double *x, double *y, double *z, int *mat, int n) { double *d_x, *d_y, *d_z; int *d_mat; cudaMalloc(&d_x, n*sizeof(double)); cudaMalloc(&d_y, n*sizeof(double)); cudaMalloc(&d_z, n*sizeof(double)); cudaMalloc(&d_mat, n*n*sizeof(int)); cudaMemcpy(d_x, x, n*sizeof(double), cudaMemcpyHostToDevice); cudaMemcpy(d_y, y, n*sizeof(double), cudaMemcpyHostToDevice); cudaMemcpy(d_z, z, n*sizeof(double), cudaMemcpyHostToDevice); dim3 dimGrid(n,1); dim3 dimBlock(n,1); checkCollision <<< dimGrid, dimBlock >>> (d_x, d_y, d_z, d_mat, n); cudaMemcpy(mat, d_mat, n*n*sizeof(int), cudaMemcpyDeviceToHost); }
5,780
#include <cuda_runtime_api.h> #include <stdint.h> #define OFFSET_BANK(idx) ({ __typeof__ (idx) _idx = idx; ((_idx) + ((_idx) / 32)); }) __global__ void softmax_lr_loss_fwd_kernel( const float *ys, uint32_t dim, uint32_t batch_sz, const uint32_t *labels, const float *targets, const float *weights, float cutoff, float *loss) { uint32_t idx = threadIdx.x + blockDim.x * blockIdx.x; uint32_t j = idx % dim; uint32_t batch_idx = idx / dim; if (j < dim && batch_idx < batch_sz) { uint32_t label = labels[batch_idx]; float ratio = ys[label + dim * batch_idx] / targets[batch_idx]; // FIXME(20170130): also check for inf, nan, negative. if (cutoff < ratio) { ratio = cutoff; } loss[batch_idx] = weights[batch_idx] * ratio; } } extern "C" void neuralops_cuda_softmax_lr_loss_fwd( const float *ys, uint32_t dim, uint32_t batch_sz, const uint32_t *labels, const float *targets, const float *weights, float cutoff, float *loss, cudaStream_t stream) { softmax_lr_loss_fwd_kernel<<<(batch_sz+1024-1)/1024, 1024, 0, stream>>>( ys, dim, batch_sz, labels, targets, weights, cutoff, loss); } __global__ void softmax_lr_loss_bwd_kernel( const float *ys, uint32_t dim, uint32_t batch_sz, const uint32_t *labels, const float *targets, const float *weights, float cutoff, float *grad) { uint32_t idx = threadIdx.x + blockDim.x * blockIdx.x; uint32_t j = idx % dim; uint32_t batch_idx = idx / dim; if (j < dim && batch_idx < batch_sz) { uint32_t label = labels[batch_idx]; float y_label = ys[label + dim * batch_idx]; float ratio = y_label / targets[batch_idx]; // FIXME(20170130): also check for inf, nan, negative. if (cutoff < ratio) { grad[idx] = 0.0f; } else { float w = weights[batch_idx]; float y_j = ys[idx]; if (label == j) { grad[idx] = w * ratio * (1.0f - y_j); } else { grad[idx] = -w * ratio * y_j; } } } } extern "C" void neuralops_cuda_softmax_lr_loss_bwd( const float *ys, uint32_t dim, uint32_t batch_sz, const uint32_t *labels, const float *targets, const float *weights, float cutoff, float *grad, cudaStream_t stream) { softmax_lr_loss_bwd_kernel<<<(batch_sz+1024-1)/1024, 1024, 0, stream>>>( ys, dim, batch_sz, labels, targets, weights, cutoff, grad); } __global__ void softmax_kl_loss_fwd_kernel( const float *ys, uint32_t dim, uint32_t batch_sz, const float *targets, float epsilon, float *loss) { __shared__ float cache[1024 + 32]; uint32_t j = threadIdx.x; uint32_t batch_idx = blockIdx.x; uint32_t idx = j + dim * batch_idx; if (j < dim && batch_idx < batch_sz) { float t = targets[idx]; float y = ys[idx]; t += epsilon * (1.0f - t); y += epsilon * (1.0f - y); float kl; if (t > 0.0f) { kl = t * (logf(t) - logf(y)); } else { kl = -t * logf(y); } cache[OFFSET_BANK(j)] = kl; } else { cache[OFFSET_BANK(j)] = 0.0f; } __syncthreads(); for (uint32_t s = 1; s < blockDim.x; s *= 2) { if (j < dim && batch_idx < batch_sz) { if (j % (2*s) == 0 && (j + s) < dim) { cache[OFFSET_BANK(j)] += cache[OFFSET_BANK(j + s)]; } } __syncthreads(); } if (j < dim && batch_idx < batch_sz) { if (j == 0) { loss[batch_idx] = cache[0]; } } } extern "C" void neuralops_cuda_softmax_kl_loss_fwd( const float *ys, uint32_t dim, uint32_t batch_sz, const float *targets, float epsilon, float *loss, cudaStream_t stream) { //assert(dim <= 1024); softmax_kl_loss_fwd_kernel<<<batch_sz, 1024, 0, stream>>>( ys, dim, batch_sz, targets, epsilon, loss); } __global__ void softmax_kl_loss_bwd_kernel( const float *ys, uint32_t dim, uint32_t batch_sz, const float *targets, float *grad) { uint32_t idx = threadIdx.x + blockIdx.x * blockDim.x; uint32_t j = idx % dim; uint32_t batch_idx = idx / dim; if (j < dim && batch_idx < batch_sz) { float t = targets[idx]; float y = ys[idx]; grad[idx] = y - t; } } extern "C" void neuralops_cuda_softmax_kl_loss_bwd( const float *ys, uint32_t dim, uint32_t batch_sz, const float *targets, float *grad, cudaStream_t stream) { uint32_t n = dim * batch_sz; softmax_kl_loss_bwd_kernel<<<(n+1024-1)/1024, 1024, 0, stream>>>( ys, dim, batch_sz, targets, grad); } __global__ void softmax_kl_loss_rfwd_kernel( const float *ys, uint32_t dim, uint32_t batch_sz, const float *r_xs, const float *r_mean, const float *targets, float *r_loss, float *r_grad) { __shared__ float cache[1024 + 32]; uint32_t j = threadIdx.x; uint32_t batch_idx = blockIdx.x; uint32_t idx = j + dim * batch_idx; if (j < dim && batch_idx < batch_sz) { float r_yp_j = r_xs[idx] - r_mean[batch_idx]; r_grad[idx] = ys[idx] * r_yp_j; cache[OFFSET_BANK(j)] = -targets[idx] * r_yp_j; } else { cache[OFFSET_BANK(j)] = 0.0f; } __syncthreads(); for (uint32_t s = 1; s < blockDim.x; s *= 2) { if (j < dim && batch_idx < batch_sz) { if (j % (2*s) == 0 && (j + s) < dim) { cache[OFFSET_BANK(j)] += cache[OFFSET_BANK(j + s)]; } } __syncthreads(); } if (j < dim && batch_idx < batch_sz) { if (j == 0) { r_loss[batch_idx] = cache[0]; } } } extern "C" void neuralops_cuda_softmax_kl_loss_rfwd( const float *ys, uint32_t dim, uint32_t batch_sz, const float *r_xs, const float *r_mean, const float *targets, float *r_loss, float *r_grad, cudaStream_t stream) { //assert(dim <= 1024); softmax_kl_loss_rfwd_kernel<<<batch_sz, 1024, 0, stream>>>( ys, dim, batch_sz, r_xs, r_mean, targets, r_loss, r_grad); } __global__ void softmax_nll_loss_fwd_kernel( const float *out_act, int dim, int batch_size, const uint32_t *label_cats, const float *weights, //const float *targets, float *out_loss) { int batch_idx = threadIdx.x + blockIdx.x * blockDim.x; if (batch_idx < batch_size) { int cat_i = label_cats[batch_idx]; int idx = cat_i + batch_idx * dim; float x = -logf(out_act[idx]) * weights[batch_idx]; out_loss[batch_idx] = x; } } extern "C" void neuralops_cuda_softmax_nll_loss_fwd( const float *out_act, size_t dim, size_t batch_size, const uint32_t *label_cats, const float *weights, float *out_loss, cudaStream_t stream) { int n = batch_size; softmax_nll_loss_fwd_kernel<<<(n+1024-1)/1024, 1024, 0, stream>>>( out_act, dim, batch_size, label_cats, weights, out_loss); } __global__ void softmax_nll_loss_bwd_kernel( const float *out_act, int dim, int batch_size, const uint32_t *label_cats, const float *weights, const float *jac_targ, float *in_delta) { int idx = threadIdx.x + blockIdx.x * blockDim.x; int i = idx % dim; int batch_idx = idx / dim; if ((i < dim) && (batch_idx < batch_size)) { int cat_i = label_cats[batch_idx]; float dx = out_act[idx]; if ((uint32_t)(i) == cat_i) { dx -= 1.0f; } dx *= weights[batch_idx] * jac_targ[batch_idx]; in_delta[idx] = dx; } } extern "C" void neuralops_cuda_softmax_nll_loss_bwd( const float *out_act, size_t dim, size_t batch_size, const uint32_t *label_cats, const float *weights, const float *jac_targ, float *in_delta, cudaStream_t stream) { int n = dim * batch_size; softmax_nll_loss_bwd_kernel<<<(n+1024-1)/1024, 1024, 0, stream>>>( out_act, dim, batch_size, label_cats, weights, jac_targ, in_delta); } __global__ void softmax_nll_loss_bwd2_kernel( const float *out_act, uint32_t dim, uint32_t batch_size, const uint32_t *label_cats, const float *weights, const float *jac_targ, float *in_delta2) { uint32_t idx = threadIdx.x + blockIdx.x * blockDim.x; uint32_t i = idx % dim; uint32_t batch_idx = idx / dim; if ((i < dim) && (batch_idx < batch_size)) { uint32_t cat_i = label_cats[batch_idx]; float y = out_act[idx]; float dx2 = y; if ((uint32_t)(i) == cat_i) { dx2 -= 1.0f; } dx2 *= (1.0f - 2.0f * y) * weights[batch_idx] * jac_targ[batch_idx]; in_delta2[idx] = dx2; } } extern "C" void neuralops_cuda_softmax_nll_loss_bwd2( const float *out_act, size_t dim, size_t batch_size, const uint32_t *label_cats, const float *weights, const float *jac_targ, float *in_delta2, cudaStream_t stream) { int n = dim * batch_size; softmax_nll_loss_bwd2_kernel<<<(n+1024-1)/1024, 1024, 0, stream>>>( out_act, dim, batch_size, label_cats, weights, jac_targ, in_delta2); } __global__ void softmax_nll_loss_rfwd_kernel( const float *out_r_val, uint32_t dim, uint32_t batch_size, const float *r_mean, const uint32_t *labels, float *r_loss) { uint32_t batch_idx = threadIdx.x + blockIdx.x * blockDim.x; if (batch_idx < batch_size) { uint32_t cat_i = labels[batch_idx]; uint32_t idx = cat_i + batch_idx * dim; float r_y_i = out_r_val[idx] - r_mean[batch_idx]; r_loss[batch_idx] = -r_y_i; } } extern "C" void neuralops_cuda_softmax_nll_loss_rfwd( const float *out_r_val, size_t dim, size_t batch_size, const float *r_mean, const uint32_t *labels, float *r_loss, cudaStream_t stream) { uint32_t n = batch_size; softmax_nll_loss_rfwd_kernel<<<(n+1024-1)/1024, 1024, 0, stream>>>( out_r_val, dim, batch_size, r_mean, labels, r_loss); }
5,781
#include "slicer.cuh" #include "triangle.cuh" #include <thrust/functional.h> __device__ __forceinline__ void triangleCopy(void* src, void* dest, int id); __device__ __forceinline__ double min3(double a, double b, double c); __device__ __forceinline__ double max3(double a, double b, double c); __device__ __forceinline__ char atomicAdd(char* address, char val); __device__ __forceinline__ int pixelRayIntersection_point(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, int x, int y); __global__ void rectTriIntersection(double* tri_global, size_t num_tri, bool* out, unsigned base_layer) { size_t idx = (size_t)blockDim.x * (size_t)blockIdx.x + (size_t)threadIdx.x; size_t num_per_thread = num_tri / (NUM_BLOCKS << LOG_THREADS) + 1; size_t base_idx = idx; double* x1_base = tri_global; double* y1_base = tri_global + num_tri; double* z1_base = tri_global + 2*num_tri; double* x2_base = tri_global + 3*num_tri; double* y2_base = tri_global + 4*num_tri; double* z2_base = tri_global + 5*num_tri; double* x3_base = tri_global + 6*num_tri; double* y3_base = tri_global + 7*num_tri; double* z3_base = tri_global + 8*num_tri; // iterate over all triangles assigned to this thread. for (size_t i = 0; i < num_per_thread; i++) { // Compute bounding box if (base_idx >= num_tri) break; double x1 = x1_base[base_idx]; double y1 = y1_base[base_idx]; double z1 = z1_base[base_idx]; double x2 = x2_base[base_idx]; double y2 = y2_base[base_idx]; double z2 = z2_base[base_idx]; double x3 = x3_base[base_idx]; double y3 = y3_base[base_idx]; double z3 = z3_base[base_idx]; long xMin = __double2ll_ru(min3(x1, x2, x3) / RESOLUTION); long zMin = __double2ll_ru(min3(z1, z2, z3) / RESOLUTION); long xMax = __double2ll_rd(max3(x1, x2, x3) / RESOLUTION); long zMax = __double2ll_rd(max3(z1, z2, z3) / RESOLUTION); base_idx += (NUM_BLOCKS << LOG_THREADS); // Make sure the bounds are inside the supported space xMax = min(xMax, X_MAX); xMin = max(xMin, X_MIN); long zMax_ub = min(NUM_LAYERS-1, (long)(base_layer+BLOCK_HEIGHT-1)); zMax = min(zMax, zMax_ub); zMin = max(zMin, (long)(base_layer)); if (xMax < xMin || zMax < zMin) continue; // iterate over all pixels inside the bounding box // Will likely cause (lots of) wrap divergence, but we'll deal with that later int x = xMin; int z = zMin; while (z <= zMax) { int curr_intersection = pixelRayIntersection_point(x1, y1, z1, x2, y2, z2, x3, y3, z3, x, z); if (curr_intersection >= Y_MIN && curr_intersection <= Y_MAX) { // Found a valid intersection int x_idx = x + (X_DIM >> 1); int y_idx = curr_intersection + (Y_DIM >> 1); char* temp_ptr = (char*) (out + (z-base_layer)*X_DIM*Y_DIM + y_idx*X_DIM + x_idx); atomicAdd(temp_ptr, 1); } // update coords bool nextLine = (x == xMax); z += (int)nextLine; x = nextLine ? xMin : (x+1); } } } __global__ void layerExtraction(bool* out) { size_t idx = (size_t)blockDim.x * (size_t)blockIdx.x + (size_t)threadIdx.x; size_t x_idx = idx % X_DIM; size_t z_idx = idx / X_DIM; bool isInside = false; char* out_ptr = (char*) (out); char intersection_count; for (size_t y = 0; y < Y_DIM; y++) { size_t full_idx = z_idx*X_DIM*Y_DIM + y*X_DIM + x_idx; intersection_count = out_ptr[full_idx]; bool flip = (bool)(intersection_count & 1); bool intersect = (intersection_count > 0); out[full_idx] = (isInside || intersect); isInside = isInside ^ flip; } } /** * pixelRayIntersection: helper function, computes the intersection of given triangle and pixel ray * Inputs: * t -- input triangle * x, y -- coordinates of the input pixel ray * Returns: * The layer on which they intersect, or -1 if no intersection */ __device__ __forceinline__ int pixelRayIntersection_point(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, int x, int z) { /* Let A, B, C be the 3 vertices of the given triangle Let S(x,y,z) be the intersection, where x,y are given We want to find some a, b such that AS = a*AB + b*AC If a >= 0, b >= 0, and a+b <= 1, S is a valid intersection. */ double x_pos = x * RESOLUTION; double z_pos = z * RESOLUTION; // double x_max = max3(x1, x2, x3); // double x_min = min3(x1, x2, x3); // if (x_pos < x_min || x_pos > x_max) return NONE; double x_d = x_pos - x1; double z_d = z_pos - z1; double xx1 = x2 - x1; double yy1 = y2 - y1; double zz1 = z2 - z1; double xx2 = x3 - x1; double yy2 = y3 - y1; double zz2 = z3 - z1; double a = (x_d * zz2 - xx2 * z_d) / (xx1 * zz2 - xx2 * zz1); double b = (x_d * zz1 - xx1 * z_d) / (xx2 * zz1 - xx1 * zz2); bool inside = (a >= 0) && (b >= 0) && (a+b <= 1); double intersection = (a * yy1 + b * yy2) + y1; // // divide by layer width int layer = inside ? (intersection / RESOLUTION) : INT_MIN; return layer; } // Copy (THREADS_PER_BLOCK) triangles from src to dest // Achieves 100% memory efficiency __device__ __forceinline__ void triangleCopy(void* src, void* dest, int id) { copy_unit_t* src_ptr = (copy_unit_t*) src; copy_unit_t* dest_ptr = (copy_unit_t*) dest; #pragma unroll for (int d = 0; d < unit_per_tri; d++) { size_t offset = d * THREADS_PER_BLOCK; dest_ptr[id + offset] = src_ptr[id + offset]; } } __device__ __forceinline__ double min3(double a, double b, double c) { // thrust::minimum<double> min; return min(a, min(b, c)); } __device__ __forceinline__ double max3(double a, double b, double c) { // thrust::maximum<double> max; return max(a, max(b, c)); } __device__ __forceinline__ char atomicAdd(char* address, char val) { // *address = *address + val; // return 0; size_t addr_offset = (size_t) address & 3; auto* base_address = (unsigned int*) ((size_t) address - addr_offset); unsigned int long_val = (unsigned int) val << (8 * addr_offset); unsigned int long_old = atomicAdd(base_address, long_val); // Overflow check. skipped for simplicity. // if (addr_offset == 3) { // return (char) (long_old >> 24); // } else { // // bits that represent the char value within long_val // unsigned int mask = 0x000000ff << (8 * addr_offset); // unsigned int masked_old = long_old & mask; // // isolate the bits that represent the char value within long_old, add the long_val to that, // // then re-isolate by excluding bits that represent the char value // unsigned int overflow = (masked_old + long_val) & ~mask; // if (overflow) { // atomicSub(base_address, overflow); // } // return (char) (masked_old >> 8 * addr_offset); // } return (char) ((long_old >> 8 * addr_offset) & 0xff); }
5,782
/** * gramschmidt.cu: This file is part of the PolyBench/GPU 1.0 test suite. * * * Contact: Scott Grauer-Gray <sgrauerg@gmail.com> * Louis-Noel Pouchet <pouchet@cse.ohio-state.edu> * Web address: http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU */ #include <unistd.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <cuda.h> #include "../../common/polybenchUtilFuncts.h" //define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 0.05 #define GPU_DEVICE 0 /* Problem size */ #define M 2048 #define N 2048 /* Thread block dimensions */ #define DIM_THREAD_BLOCK_X 256 #define DIM_THREAD_BLOCK_Y 1 /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void gramschmidt(DATA_TYPE* A, DATA_TYPE* R, DATA_TYPE* Q) { int i,j,k; DATA_TYPE nrm; for (k = 0; k < N; k++) { nrm = 0; for (i = 0; i < M; i++) { nrm += A[i*N + k] * A[i*N + k]; } R[k*N + k] = sqrt(nrm); for (i = 0; i < M; i++) { Q[i*N + k] = A[i*N + k] / R[k*N + k]; } for (j = k + 1; j < N; j++) { R[k*N + j] = 0; for (i = 0; i < M; i++) { R[k*N + j] += Q[i*N + k] * A[i*N + j]; } for (i = 0; i < M; i++) { A[i*N + j] = A[i*N + j] - Q[i*N + k] * R[k*N + j]; } } } } void init_array(DATA_TYPE* A) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { A[i*N + j] = ((DATA_TYPE) (i+1)*(j+1)) / (M+1); } } } void compareResults(DATA_TYPE* A, DATA_TYPE* A_outputFromGpu) { int i, j, fail; fail = 0; for (i=0; i < M; i++) { for (j=0; j < N; j++) { if (percentDiff(A[i*N + j], A_outputFromGpu[i*N + j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; printf("i: %d j: %d \n1: %f\n 2: %f\n", i, j, A[i*N + j], A_outputFromGpu[i*N + j]); } } } // Print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail); } void GPU_argv_init() { cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, GPU_DEVICE); printf("setting device %d with name %s\n",GPU_DEVICE,deviceProp.name); cudaSetDevice( GPU_DEVICE ); return; } __global__ void gramschmidt_kernel1(DATA_TYPE *a, DATA_TYPE *r, DATA_TYPE *q, int k) { int tid = blockIdx.x * blockDim.x + threadIdx.x; if(tid==0) { DATA_TYPE nrm = 0.0; int i; for (i = 0; i < M; i++) { nrm += a[i * N + k] * a[i * N + k]; } r[k * N + k] = sqrt(nrm); } } __global__ void gramschmidt_kernel2(DATA_TYPE *a, DATA_TYPE *r, DATA_TYPE *q, int k) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < M) { q[i * N + k] = a[i * N + k] / r[k * N + k]; } } __global__ void gramschmidt_kernel3(DATA_TYPE *a, DATA_TYPE *r, DATA_TYPE *q, int k) { int j = blockIdx.x * blockDim.x + threadIdx.x; if ((j > k) && (j < N)) { r[k*N + j] = 0.0; int i; for (i = 0; i < M; i++) { r[k*N + j] += q[i*N + k] * a[i*N + j]; } for (i = 0; i < M; i++) { a[i*N + j] -= q[i*N + k] * r[k*N + j]; } } } void gramschmidtCuda(DATA_TYPE* A, DATA_TYPE* R, DATA_TYPE* Q, DATA_TYPE* A_outputFromGpu) { double t_start, t_end; dim3 block(DIM_THREAD_BLOCK_X, DIM_THREAD_BLOCK_Y); dim3 gridKernel1(1, 1); dim3 gridKernel2((size_t)ceil(((float)N) / ((float)DIM_THREAD_BLOCK_X)), 1); dim3 gridKernel3((size_t)ceil(((float)N) / ((float)DIM_THREAD_BLOCK_X)), 1); DATA_TYPE *A_gpu; DATA_TYPE *R_gpu; DATA_TYPE *Q_gpu; cudaMalloc((void **)&A_gpu, sizeof(DATA_TYPE) * M * N); cudaMalloc((void **)&R_gpu, sizeof(DATA_TYPE) * M * N); cudaMalloc((void **)&Q_gpu, sizeof(DATA_TYPE) * M * N); cudaMemcpy(A_gpu, A, sizeof(DATA_TYPE) * M * N, cudaMemcpyHostToDevice); t_start = rtclock(); int k; for (k = 0; k < N; k++) { gramschmidt_kernel1<<<gridKernel1,block>>>(A_gpu, R_gpu, Q_gpu, k); cudaThreadSynchronize(); gramschmidt_kernel2<<<gridKernel2,block>>>(A_gpu, R_gpu, Q_gpu, k); cudaThreadSynchronize(); gramschmidt_kernel3<<<gridKernel3,block>>>(A_gpu, R_gpu, Q_gpu, k); cudaThreadSynchronize(); } t_end = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start); cudaMemcpy(A_outputFromGpu, A_gpu, sizeof(DATA_TYPE) * M * N, cudaMemcpyDeviceToHost); cudaFree(A_gpu); cudaFree(R_gpu); cudaFree(Q_gpu); } int main(int argc, char *argv[]) { double t_start, t_end; DATA_TYPE* A; DATA_TYPE* A_outputFromGpu; DATA_TYPE* R; DATA_TYPE* Q; A = (DATA_TYPE*)malloc(M*N*sizeof(DATA_TYPE)); A_outputFromGpu = (DATA_TYPE*)malloc(M*N*sizeof(DATA_TYPE)); R = (DATA_TYPE*)malloc(M*N*sizeof(DATA_TYPE)); Q = (DATA_TYPE*)malloc(M*N*sizeof(DATA_TYPE)); init_array(A); GPU_argv_init(); gramschmidtCuda(A, R, Q, A_outputFromGpu); t_start = rtclock(); gramschmidt(A, R, Q); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); compareResults(A, A_outputFromGpu); free(A); free(A_outputFromGpu); free(R); free(Q); return 0; }
5,783
#include<stdio.h> #include<cstdint> #include<thrust/device_ptr.h> #include<thrust/scan.h> typedef uint32_t u32; __global__ void count_gen(u32 *src, int nsrc, u32 *choice, int nchoices, int *ngen) { __shared__ u32 some[256]; int tid = threadIdx.x + blockIdx.x * blockDim.x; int nthreads = blockDim.x * gridDim.x; for (int i = threadIdx.x; i < nchoices; i += blockDim.x) { some[i] = choice[i]; } __syncthreads(); for (int i = tid; i < nsrc; i += nthreads) { int sum = 0; u32 a = src[i]; for (int j = 0; j < nchoices; j++) { if ((a & some[j]) == 0) { sum += 1; } } ngen[i] = sum; } } __global__ void gen(u32 *src, int nsrc, u32 *choice, int nchoices, u32 *dest, int *ngen) { __shared__ u32 some[256]; int tid = threadIdx.x + blockIdx.x * blockDim.x; int nthreads = blockDim.x * gridDim.x; for (int i = threadIdx.x; i < nchoices; i += blockDim.x) { some[i] = choice[i]; } __syncthreads(); for (int i = tid; i < nsrc; i += nthreads) { u32 a = src[i]; int pos = ngen[i]; for (int j = 0; j < nchoices; j++) { u32 added = a | some[j]; int canplace = (a & some[j]) == 0; if (canplace) { dest[pos] = added; } pos += canplace; } } } int main() { int nsrc = 1000000, nchoices = 100, bufsize = 30000000; u32 *gsrc, *gchoice, *gdest; int *gcnt; cudaMalloc(&gsrc, sizeof(u32) * nsrc); cudaMalloc(&gchoice, sizeof(u32) * nchoices); cudaMalloc(&gdest, sizeof(u32) * bufsize); cudaMalloc(&gcnt, sizeof(int) * (nsrc+1)); u32 *src, *choice, *dest; src = new u32[nsrc]; choice = new u32[nchoices]; dest = new u32[bufsize]; unsigned seed = 2; for (int i = 0; i < nsrc; i++) { src[i] = seed; seed = seed*0xdefaced + 1; } for (int i = 0; i < nchoices; i++) { u32 rr = seed; seed = seed*0xdefaced + 1; choice[i] = 0; for (int yy = 0; yy < 5; yy++) { choice[i] += 1<<(rr>>yy*5&31); } } cudaMemcpy(gsrc, src, sizeof(u32) * nsrc, cudaMemcpyHostToDevice); cudaMemcpy(gchoice, choice, sizeof(u32) * nchoices, cudaMemcpyHostToDevice); cudaMemset(gcnt, 0, sizeof(int) * (nsrc+1)); int ans = 0; count_gen<<<40, 256>>>(gsrc, nsrc, gchoice, nchoices, gcnt); thrust::device_ptr<int> thcnt = thrust::device_pointer_cast(gcnt); thrust::exclusive_scan(thcnt, thcnt + nsrc+1, thcnt); cudaMemcpy(&ans, gcnt+nsrc, sizeof(int), cudaMemcpyDeviceToHost); gen<<<40, 256>>>(gsrc, nsrc, gchoice, nchoices, gdest, gcnt); cudaMemcpy(dest, gdest, sizeof(u32) * ans, cudaMemcpyDeviceToHost); printf("generated: %d\n", ans); }
5,784
// // Created by ameen on 09/05/20. // #include "null.cuh" __device__ bool isNull(int *i){ return *i == INT_MIN; } __device__ bool isNull(char *data){ int i = 0; while (data[i] == 127) ++i; return data[i] == 0; } __device__ bool isNull(float *f){ return isnan(*f); } __device__ int getNullInt(){ return INT_MIN; } __device__ float getNullFlt(){ return NAN; } __device__ void getNullStr(char *data, int size){ int i=0; while(i < size-1){ data[i] = 127; i++; } data[size-1] = 0; }
5,785
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <time.h> #include <math.h> #include <string.h> #define EPSILON 1E-9 #define BLOCK_SIZE 1024 #define ALING 64 __device__ double distance( double* dx, double* dy, double* dz, const double Ax, const double Ay, const double Az, const double Bx, const double By, const double Bz){ double x = Ax - Bx; double y = Ay - By; double z = Az - Bz; *dx = x; *dy = y; *dz = z; x *= x; y *= y; z *= z; return 1.0 / sqrt((double)x + y + z + EPSILON); } __global__ void particleParticleForces_k ( double *px, double *py, double *pz, double *fx, double *fy, double *fz, double dt){ extern __shared__ double buff[]; double *sub_px = &buff[0], *sub_py = &buff[gridDim.x], *sub_pz = &buff[gridDim.x * 2]; int i = blockDim.x * blockIdx.x + threadIdx.x; double pX = px[i]; double pY = py[i]; double pZ = pz[i]; double fX = fx[i]; double fY = fy[i]; double fZ = fz[i]; for (int blk = 0; blk < gridDim.x; blk++){ sub_px[threadIdx.x] = px[ blockDim.x * blk + threadIdx.x]; sub_py[threadIdx.x] = py[ blockDim.x * blk + threadIdx.x]; sub_pz[threadIdx.x] = pz[ blockDim.x * blk + threadIdx.x]; __syncthreads(); for (int j = 0; j < blockDim.x; j++){ double dx = 0.0f, dy = 0.0f, dz = 0.0f; double d = distance(&dx, &dy, &dz, pX, pY, pZ, sub_px[j], sub_py[j], sub_pz[j]); fX += dx * d; fY += dy * d; fZ += dz * d; } __syncthreads(); } fx[i] = fX; fy[i] = fY; fz[i] = fZ; } __global__ void particleParticleVelocityPosition_k ( double *px, double *py, double *pz, double *vx, double *vy, double *vz, double *fx, double *fy, double *fz, double dt){ int i = blockDim.x * blockIdx.x + threadIdx.x; vx[i] += dt * fx[i]; vy[i] += dt * fy[i]; vz[i] += dt * fz[i]; px[i] += dt * vx[i]; py[i] += dt * vy[i]; pz[i] += dt * vz[i]; } void particleParticle (double *px, double *py, double *pz, double *vx, double *vy, double *vz, double *fx, double *fy, double *fz, int nParticles, int timesteps, double dt){ int threads = BLOCK_SIZE, blocks = nParticles / BLOCK_SIZE; if (nParticles < 1024){ blocks = 1; threads = nParticles; } fprintf(stdout, "\n B(%d) T(%d) shared memory %d \n", blocks, threads, 3 * threads * sizeof(double)); for (int t = 0; t < timesteps; t++){ particleParticleForces_k<<<blocks, threads, 3 * threads * sizeof(double) >>>(px, py, pz, fx, fy, fz, dt); particleParticleVelocityPosition_k<<<blocks, threads >>>(px, py, pz, vx, vy, vz, fx, fy, fz, dt); assert( cudaDeviceSynchronize() == cudaSuccess); }//end-for (int t = 0; t < timesteps; t++){ }//end-void particleParticle //----------------------------------------------------------------------------------------------------- void printLog(double *px, double *py, double *pz, double *vx, double *vy, double *vz, double *fx, double *fy, double *fz, int nParticles, int timestep); void initialCondition(double *px, double *py, double *pz, double *vx, double *vy, double *vz, double *fx, double *fy, double *fz, int nParticles); //----------------------------------------------------------------------------------------------------- int main (int ac, char **av){ int timesteps = atoi(av[1]), nParticles = atoi(av[2]), flagSave = atoi(av[3]); double dt = 0.00001f, *h_px = NULL, *h_py = NULL, *h_pz = NULL, *h_vx = NULL, *h_vy = NULL, *h_vz = NULL, *h_fx = NULL, *h_fy = NULL, *h_fz = NULL, *d_px = NULL, *d_py = NULL, *d_pz = NULL, *d_vx = NULL, *d_vy = NULL, *d_vz = NULL, *d_fx = NULL, *d_fy = NULL, *d_fz = NULL; fprintf(stdout, "\nParcile system particle to particle \n"); fprintf(stdout, "Memory used %lu bytes \n", nParticles * sizeof(double) * 9); h_px = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_px != NULL); h_py = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_py != NULL); h_pz = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_pz != NULL); //------------------------- h_vx = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_vx != NULL); h_vy = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_vy != NULL); h_vz = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_vz != NULL); //------------------------- h_fx = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_fx != NULL); h_fy = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_fy != NULL); h_fz = (double *) aligned_alloc(ALING, nParticles * sizeof(double)); assert(h_fz != NULL); //------------------------- initialCondition(h_px, h_py, h_pz, h_vx, h_vy, h_vz, h_fx, h_fy, h_fz, nParticles); assert(cudaMalloc((void**) &d_px, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_px, h_px, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); assert(cudaMalloc((void**) &d_py, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_py, h_py, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); assert(cudaMalloc((void**) &d_pz, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_pz, h_pz, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); //----- assert(cudaMalloc((void**) &d_vx, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_vx, h_vx, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); assert(cudaMalloc((void**) &d_vy, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_vy, h_vy, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); assert(cudaMalloc((void**) &d_vz, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_vz, h_vz, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); //----- assert(cudaMalloc((void**) &d_fx, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_fx, h_fx, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); assert(cudaMalloc((void**) &d_fy, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_fy, h_fy, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); assert(cudaMalloc((void**) &d_fz, nParticles * sizeof(double)) == cudaSuccess); assert(cudaMemcpy(d_fz, h_fz, nParticles * sizeof(double), cudaMemcpyHostToDevice) == cudaSuccess); particleParticle(d_px, d_py, d_pz, d_vx, d_vy, d_vz, d_fx, d_fy, d_fz, nParticles, timesteps, dt); assert(cudaMemcpy(h_px, d_px, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_py, d_py, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_pz, d_pz, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_vx, d_vx, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_vy, d_vy, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_vz, d_vz, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_fx, d_fx, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_fy, d_fy, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); assert(cudaMemcpy(h_fz, d_fz, nParticles * sizeof(double), cudaMemcpyDeviceToHost) == cudaSuccess); // printLog(h_px, h_py, h_pz, h_vx, h_vy, h_vz, h_fx, h_fy, h_fz, nParticles, timesteps); if (flagSave == 1) printLog(h_px, h_py, h_pz, h_vx, h_vy, h_vz, h_fx, h_fy, h_fz, nParticles, timesteps); free(h_px);free(h_py); free(h_pz); free(h_vx);free(h_vy); free(h_vz); free(h_fx);free(h_fy); free(h_fz); cudaFree(d_px);cudaFree(d_py); cudaFree(d_pz); cudaFree(d_vx);cudaFree(d_vy); cudaFree(d_vz); cudaFree(d_fx);cudaFree(d_fy); cudaFree(d_fz); } /*Declarando as structs de particula e forca*/ void printLog(double *px, double *py, double *pz, double *vx, double *vy, double *vz, double *fx, double *fy, double *fz, int nParticles, int timestep){ char fileName[128]; sprintf(fileName, "%s-%d-log.bin", __FILE__, timestep); fprintf(stdout, "Saving file [%s] ", fileName); fflush(stdout); FILE *ptr = fopen(fileName, "w+"); for(int i = 0; i < nParticles; i++){ fprintf(ptr, "%d \t %.10f %.10f %.10f \t %.10f %.10f %.10f \t %.10f %.10f %.10f \n", i, px[i], py[i], pz[i], vx[i], vy[i], vz[i], fx[i], fy[i], fz[i]); } fclose(ptr); fprintf(stdout, "[OK]\n"); fflush(stdout); } void initialCondition(double *px, double *py, double *pz, double *vx, double *vy, double *vz, double *fx, double *fy, double *fz, int nParticles){ srand(42); memset(vx, 0x00, nParticles * sizeof(double)); memset(vy, 0x00, nParticles * sizeof(double)); memset(vz, 0x00, nParticles * sizeof(double)); memset(fx, 0x00, nParticles * sizeof(double)); memset(fy, 0x00, nParticles * sizeof(double)); memset(fz, 0x00, nParticles * sizeof(double)); for (int i = 0; i < nParticles ; i++){ px[i] = 2.0 * (rand() / (double)RAND_MAX) - 1.0; py[i] = 2.0 * (rand() / (double)RAND_MAX) - 1.0; pz[i] = 2.0 * (rand() / (double)RAND_MAX) - 1.0; }//end-for (int i = 0; i < nParticles ; i++){ }
5,786
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/time.h> void genRandomString(char *str,int length) { for(int i=0;i<length-1;++i) { str[i] = 'a' + rand()%26; } str[length-1] = '\0'; } void genRandomSubString(char *str,int length,int sub_len) { for(int i=0;i<length-1;++i) { if(i>0 && ((i+1)%sub_len==0)) str[i] = '\0'; else str[i] = 'a' + rand()%26; } str[length-1] = '\0'; } /*__global__ void my_strstr(char *str,char *sub_string,char ** position,int str_len,int sub_len,int num_sub) { int id = threadIdx.x; char *sub = &sub_string[id*sub_len]; char *string = str; char *a,*b; b = sub; printf("in GPU string is %s sub is %s\n",string,b); for(;*string != '\0';++string){ a = string; if(*a == *b){ printf("thread %d find a possible sub %s\n",id,b); while(*(++a) == *(++b)){ printf("thread %d find a more and more possible sub %s\n",id,b); if(*(b+1) == '\0'){ printf("thread %d find a sub %s\n",id,b); position[id] = string; printf("sting match in %s\n",position[id]); } } } b = sub; } }*/ char * my_strstr(char *str,char *sub,int str_len,int sub_len) { if(str_len < sub_len) return NULL; if(str_len != 0 && sub_len == 0) return NULL; if(str_len == 0 && sub_len == 0) return NULL; int m, n; for(int i=0;i<str_len;++i){ m = 0; n = i; if(str[n]==sub[m]){ while(str[++n] == sub[++m]){ if(sub[m+1] == '\0') return str+i; } } } return NULL; } __global__ void my_strstr(char *str,char *sub_string,char ** position,int str_len,int sub_len,int num_sub) { int id = threadIdx.x; //char *sub = &sub_string[id*sub_len]; char *result = NULL; char sub[24]; //load sub in register,great improve for(int i=0;i<sub_len;++i){ sub[i] = sub_string[id*sub_len+i];} //best case using Shared memory extern __shared__ char s_string[]; //every thread has to fetch how many values from global memory to shared memory int each_num = str_len/blockDim.x; for(int i=0;i<each_num;++i){ s_string[i*blockDim.x+id] = str[i*blockDim.x+id];} if( ((each_num*blockDim.x+id) < str_len) && (blockDim.x > each_num) ) s_string[each_num*blockDim.x+id] = str[each_num*blockDim.x+id]; char *string = s_string; char *a,*b; //b point to the sub address in register rather than in global memory b = sub; //result == NULL to judge if we find a match;rather than use goto or break in loop which harm the calculation for(int i = 0;(*string != '\0')&&(result == NULL);i++){ //printf("i am %d\n",id); a = string; while(*a++ == *b++){ if(*(b+1) == '\0'){ result = string; } } b = sub; ++string; } //coalesced global memory store, no effect since we only store once position[id] = result; } int main() { int LENGTH = 4096, len = 24, num_sub = 100; int num_block,num_thread; if(num_sub < 512){ num_block = 1; num_thread = num_sub; } else{ num_block = num_sub / 512; num_thread = 512; } char haystack[LENGTH]; char subs[num_sub*len]; char *position[num_sub]; char *h_position[num_sub]; genRandomString(haystack,LENGTH); genRandomSubString(subs,len*num_sub,len); char *d_string,*d_subs; char **d_position; cudaMalloc((void**)&d_string,sizeof(char)*LENGTH); cudaMalloc((void**)&d_subs,sizeof(char)*num_sub*len); cudaMalloc((void***)&d_position,sizeof(char*)*num_sub); cudaMemset(d_position,0,sizeof(char*)*num_sub); memset(h_position,0,sizeof(char*)*num_sub); const size_t smem = sizeof(char)*LENGTH; char h_subs[num_sub][len]; for(int i=0;i<num_sub;++i){ for(int j=0;j<len;++j){ h_subs[i][j] = subs[i*len+j]; } } /*CPU*/ char *ret; struct timeval start,end; gettimeofday(&start, NULL ); for(int i=0;i<num_sub;++i) { ret = my_strstr(haystack,h_subs[i],LENGTH,len); if(ret != NULL){ printf("find one sub string in %d sub\n",i); printf("%s\n",ret); } position[i] = ret; } gettimeofday(&end, NULL ); float timeuse =1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; printf("CPU time=%f\n",timeuse /1000.0); /*GPU*/ gettimeofday(&start, NULL ); for(int i=0;i<50;++i) { cudaMemcpy(d_string,haystack,sizeof(char)*LENGTH,cudaMemcpyHostToDevice); cudaMemcpy(d_subs,subs,sizeof(char)*num_sub*len,cudaMemcpyHostToDevice); my_strstr<<<num_block,num_thread,smem>>>(d_string,d_subs,d_position,LENGTH,len,num_sub); cudaDeviceSynchronize(); cudaMemcpy(h_position,d_position,sizeof(char*)*num_sub,cudaMemcpyDeviceToHost); } gettimeofday(&end, NULL ); timeuse =1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; printf("GPU time=%f\n",timeuse /1000.0/50); /*check*/ //in small size GPU works well /*for(int i=0;i<num_sub;++i){ if(h_position[i] == position[i]){ printf("ok in %d sub\n",i); if(position[i] != NULL){ printf("%s\n",position[i]); } } else{ printf("error !!!!!!"); if(position[i] != NULL){ printf("CPU find match %s\n",position[i]);} //because h_position[i] point to the address in GPU , causing segment error if(h_position[i] != NULL){ printf("GPU find match %s\n",h_position[i]);} } }*/ return(0); }
5,787
//pass //--gridDim=[32768,1,1] --blockDim=[512,1,1] __global__ void increment_kernel(int *g_data, int inc_value) { int idx = blockIdx.x * blockDim.x + threadIdx.x; g_data[idx] = g_data[idx] + inc_value; }
5,788
#include <stdio.h> // declaração de uma constante (compartilhada c/ somente leitura c/ todas as threads) __device__ const char *STR = "HELLO WORLD!"; const char STR_LENGTH = 12; // GPU: Função imprime um letra por fluxo de execução. __global__ void hello() { printf("%c", STR[threadIdx.x % STR_LENGTH]); } // CPU: Função principal int main (int argc, char ** argv) { int nthreads = 12; int nblocos = 1; if (argc == 3) { nblocos = atoi(argv[1]); nthreads = atoi(argv[2]); } else { printf ("\n ############# \n"); printf ("./02_hello <nblocos> <nthreads>\n"); printf ("Caso não haja passagem de parâmetros, atribuiu-se:\n(1) nblocos c/ 1 e nthreads definido c/ 12\n"); } // Função que será executada em GPU // Parâmetros do kernel (número de blocos e número de threads) // A função não recebe parâmetros hello<<<nblocos,nthreads>>>(); // Sincronização das threads cudaDeviceSynchronize(); printf("\n"); return 0; }
5,789
#include "includes.h" __global__ void tovalue_kernal(float* data, const float value, const int totaltc) { const uint idx = threadIdx.x + (blockIdx.x + blockIdx.y*gridDim.x)*MAX_THREADS; if(idx < totaltc){ data[idx] = value; } }
5,790
#include <iostream> #include <unistd.h> #include "cuda.h" int main() { // show memory usage of GPU size_t free_byte ; size_t total_byte ; while (true ) { cudaError_t cuda_status = cudaMemGetInfo( &free_byte, &total_byte ) ; if ( cudaSuccess != cuda_status ){ std::cout << "Error: cudaMemGetInfo fails, " << cudaGetErrorString(cuda_status) << std::endl; exit(1); } double free_db = (double)free_byte ; double total_db = (double)total_byte ; double used_db = total_db - free_db ; std::cout << "GPU memory usage: used = " << used_db/1024.0/1024.0 << ", free = " << free_db/1024.0/1024.0 << " MB, total = " << total_db/1024.0/1024.0 << " MB" << std::endl; sleep(1); } return 0; }
5,791
#include<stdio.h> // Example 1: This is the standard C that runs on the host // Run nvcc hello_world.cu in order to compile programs with no device code int main(void) { printf("Hello World!\n"); return 0; }
5,792
#include "includes.h" using namespace std; #define CUDA_THREAD_NUM 1024 // must be a multiply of 2 void dotProductCPU(); __global__ void dotProductCuda(float *a, float *b, float *c) { __shared__ float se[CUDA_THREAD_NUM]; // Calculate a.*b se[threadIdx.x]=a[threadIdx.x+blockIdx.x*CUDA_THREAD_NUM]*b[threadIdx.x+blockIdx.x*CUDA_THREAD_NUM]; __syncthreads(); // Sum Reducto int numActiveThreads=CUDA_THREAD_NUM/2; while(numActiveThreads>0) { if(threadIdx.x<numActiveThreads) { se[threadIdx.x]=se[threadIdx.x]+se[threadIdx.x+numActiveThreads]; } numActiveThreads=numActiveThreads/2; __syncthreads(); } if(threadIdx.x==0) { c[blockIdx.x]=se[0]; //printf("BlockId: %d, ThreadID: %d, %f \n",blockIdx.x,threadIdx.x,c[blockIdx.x]); } return; }
5,793
#include <cuda_runtime.h> #include <stdio.h> #include <sys/time.h> double cpuSecond() { struct timeval tp; gettimeofday(&tp,NULL); return ((double)tp.tv_sec + (double)tp.tv_usec*1.e-6); } __global__ void add1D(int* A, int* B, int* C, int nx, int ny) { int ix = threadIdx.x + blockIdx.x * blockDim.x; int iy = threadIdx.y + blockIdx.y * blockDim.y; int idx = iy * nx + ix; C[idx] = A[idx] + B[idx]; } __global__ void add2D(int* A, int* B, int* C, int nx, int ny) { int ix = threadIdx.x + blockIdx.x * blockDim.x; int iy = threadIdx.y + blockIdx.y * blockDim.y; int idx = iy * nx + ix; if (ix < nx && iy < ny) C[idx] = A[idx] + B[idx]; } __global__ void add1D1D(int* A, int* B, int* C, int nx, int ny) { unsigned int ix = threadIdx.x + blockIdx.x * blockDim.x; if (ix < nx) { for (int iy = 0; iy < ny; ++iy) { int idx = iy * nx + ix; C[idx] = A[idx] + B[idx]; } } } __global__ void add2D1D(int* A, int* B, int* C, int nx, int ny) { unsigned int ix = threadIdx.x + blockIdx.x * blockDim.x; unsigned int iy = blockIdx.y; unsigned int idx = iy*nx + ix; if (ix < nx && iy < ny) C[idx] = A[idx] + B[idx]; } void sumh (int *A, int *B, int *C, const int nx, const int ny) { int *ia = A; int *ib = B; int *ic = C; for (int iy = 0; iy < ny; iy++) { for (int ix = 0; ix < nx; ix++) { ic[ix] = ia[ix] + ib[ix]; } ia += nx; ib += nx; ic += nx; } } void checkres(int *host, int *gpu, const int N) { const double e = 1.0E-6; for (int i = 0; i < N; i++) { if (abs(host[i] - gpu[i]) > e) { printf("host ", host[i], " gpu ", gpu[i]); printf("Test failed\n\n"); break; } } } void getrandommatrix(int* m, int n) { for (int i=0; i < n; ++i) m[i] = rand()% 10; } int main( void ) { double time1, time2, time3, time4; // size of matrix unsigned int nx = 1 << 10; // столбцы unsigned int ny = 1 << 10; // строки int size = nx * ny; int* hA = (int*)malloc(size * sizeof(int)); int* hB = (int*)malloc(size * sizeof(int)); int* hC = (int*)malloc(size * sizeof(int)); int* cpuC = (int*)malloc(size * sizeof(int)); getrandommatrix(hA, size); getrandommatrix(hB, size); sumh(hA, hB, cpuC, nx, ny); int* dA; int* dB; cudaMalloc((void**)&dA, size * sizeof(int)); cudaMalloc((void**)&dB, size * sizeof(int)); cudaMemcpy(dA, hA, size * sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(dB, hB, size * sizeof(int), cudaMemcpyHostToDevice); printf("Started succesfylly\n"); // 1D int* dC1D; cudaMalloc((void**)&dC1D, size * sizeof(int)); cudaDeviceSynchronize(); time1 = cpuSecond(); add1D<<< ny, nx >>>(dA, dB, dC1D, nx, ny); cudaDeviceSynchronize(); time1 = cpuSecond() - time1; printf("1D <<<", nx, " ", ny, ">>> elapsed ", time1, " ms\n"); cudaMemcpy(hC, dC1D, size * sizeof(int), cudaMemcpyDeviceToHost); checkres(cpuC, hC, size); cudaFree(dC1D); // 2D int* dC2D; cudaMalloc((void**)&dC2D, size * sizeof(int)); int dimx = 32; int dimy = 16; dim3 block(dimx, dimy); dim3 grid((nx + block.x - 1) / block.x, (ny + block.y - 1) / block.y); cudaDeviceSynchronize(); time2 = cpuSecond(); add2D<<<grid, block>>>(dA, dB, dC2D, nx, ny); cudaDeviceSynchronize(); time2 = cpuSecond() - time2; printf("2D <<<", grid.x, grid.y, ", ", block.x, block.y, ">>> elapsed ", time2, " ms\n"); cudaMemcpy(hC, dC2D, size * sizeof(int), cudaMemcpyDeviceToHost); checkres(cpuC, hC, size); cudaFree(dC2D); // 1D-сетка, 1D-блоки int* dC1D1D; cudaMalloc((void**)&dC1D1D, size * sizeof(int)); block = dim3{128,1}; grid = dim3{(nx+block.x-1)/block.x,1}; cudaDeviceSynchronize(); time3 = cpuSecond(); add1D1D <<<grid, block>>> (dA, dB, dC1D1D, nx, ny); cudaDeviceSynchronize(); time3 = cpuSecond() - time3; printf("1D1D <<<", grid.x, grid.y, ", ", block.x, block.y, ">>> elapsed ", time3, " ms\n"); cudaMemcpy(hC, dC1D1D, size * sizeof(int), cudaMemcpyDeviceToHost); checkres(cpuC, hC, size); cudaFree(dC1D1D); // 2D-сетка, 1D-блоки int* dC2D1D; cudaMalloc((void**)&dC2D1D, size * sizeof(int)); block = dim3{256}; grid = dim3{(nx + block.x - 1) / block.x,ny}; cudaDeviceSynchronize(); time4 = cpuSecond(); add2D1D<<<grid, block>>> (dA, dB, dC2D1D, nx, ny); cudaDeviceSynchronize(); time4 = cpuSecond() - time4; printf("2D1D <<<", grid.x, grid.y, ", ", block.x, block.y, ">>> elapsed ", time3, " ms\n"); cudaMemcpy(hC, dC2D1D, size * sizeof(int), cudaMemcpyDeviceToHost); checkres(cpuC, hC, size); cudaFree(dC2D1D); cudaFree(dA); cudaFree(dB); free(hA); free(hB); free(hC); return 0; }
5,794
#include "Utils.cuh" #include "iostream" #include <curand.h> using namespace std; // Simple cuda error checking macro #define ErrChk(ans) \ { CudaAssert((ans), __FILE__, __LINE__); } inline void CudaAssert(cudaError_t code, const char* file, int line, bool abort = true) { if (code != cudaSuccess) { fprintf( stderr, "CudaAssert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } Tensor random_fill(std::initializer_list<unsigned> lst) { curandGenerator_t gen; Tensor A(lst); curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT); curandSetPseudoRandomGeneratorSeed(gen, 1234ULL); curandGenerateUniform(gen, A.m_data, A.size()); cudaDeviceSynchronize(); curandDestroyGenerator(gen); return A; }; __global__ void cp_recompose(float* __restrict__ Out, const float* __restrict__ FilterK, const float* __restrict__ FilterC, const float* __restrict__ FilterH, const float* __restrict__ FilterW, const unsigned rank, const unsigned FK, const unsigned FC, const unsigned FH, const unsigned FW) { // clang-format off for (unsigned fc = threadIdx.z + blockIdx.z * blockDim.z; fc < FC; fc += blockDim.z*gridDim.z) for (unsigned fh = threadIdx.y + blockIdx.y * blockDim.y; fh < FH; fh += blockDim.y*gridDim.y) for (unsigned fw = threadIdx.x + blockIdx.x * blockDim.x; fw < FW; fw += blockDim.x*gridDim.x) for (unsigned fk = 0; fk < FK; ++fk) { float pixel = 0.0f; for (unsigned rr = 0; rr < rank; ++rr) { pixel += FilterK[fk * rank + rr] * FilterC[fc * rank + rr] * FilterH[fh * rank + rr] * FilterW[fw * rank + rr]; } Out[fk*FC*FH*FW + fc*FH*FW + fh*FW + fw] = pixel; } // clang-format on } Tensor cp4recom(Tensor FilterK, Tensor FilterC, Tensor FilterH, Tensor FilterW) { const unsigned rank = FilterK.shape[1]; const unsigned FK = FilterK.shape[0]; const unsigned FC = FilterC.shape[0]; const unsigned FH = FilterH.shape[0]; const unsigned FW = FilterW.shape[0]; Tensor Out = { FK, FC, FH, FW }; const unsigned W_dim = (FW / 8) + ((FW % 8) != 0); const unsigned H_dim = (FH / 8) + ((FH % 8) != 0); const unsigned C_dim = (FC / 8) + ((FC % 8) != 0); const dim3 Gshp(W_dim, H_dim, C_dim); const dim3 Bshp(8, 8, 8); cp_recompose<<<Gshp, Bshp>>>(Out.m_data, FilterK.m_data, FilterC.m_data, FilterH.m_data, FilterW.m_data, rank, FK, FC, FH, FW); ErrChk(cudaPeekAtLastError()); ErrChk(cudaDeviceSynchronize()); return Out; } /* template <unsigned BlockSize> */ /* __device__ void warpMax(volatile float* sdata, unsigned tid) { */ /* if (BlockSize >= 64) sdata[tid] = fmaxf(sdata[tid], sdata[tid + 32]); */ /* if (BlockSize >= 32) sdata[tid] = fmaxf(sdata[tid], sdata[tid + 16]); */ /* if (BlockSize >= 16) sdata[tid] = fmaxf(sdata[tid], sdata[tid + 8]); */ /* if (BlockSize >= 8) sdata[tid] = fmaxf(sdata[tid], sdata[tid + 4]); */ /* if (BlockSize >= 4) sdata[tid] = fmaxf(sdata[tid], sdata[tid + 2]); */ /* if (BlockSize >= 2) sdata[tid] = fmaxf(sdata[tid], sdata[tid + 1]); */ /* } */ /* template <unsigned BlockSize> */ /* __global__ void maxCuda(bool* __restrict__ Over, */ /* const float* __restrict__ delta, */ /* const float tol, */ /* const unsigned n) { */ /* extern __shared__ float sdata[]; */ /* unsigned tid = threadIdx.x; */ /* unsigned stride = 2 * BlockSize * gridDim.x; */ /* sdata[tid] = 0; */ /* for (unsigned i = blockIdx.x * (2 * BlockSize) + tid; i < n; i += stride) */ /* sdata[tid] = fmaxf(delta[i], delta[i + BlockSize]); */ /* __syncthreads(); */ /* if (BlockSize >= 512) { */ /* if (tid < 256) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + 256]); } */ /* __syncthreads(); */ /* } */ /* if (BlockSize >= 256) { */ /* if (tid < 128) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + 128]); } */ /* __syncthreads(); */ /* } */ /* if (BlockSize >= 128) { */ /* if (tid < 64) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + 64]); } */ /* __syncthreads(); */ /* } */ /* if (tid < 32) warpMax(sdata, tid); */ /* if (tid == 0) Over[blockIdx.x] = sdata[0]; */ /* } */ __global__ void arrayRelativeDelta(int* Exceeds, const float tol, const int size, const float* __restrict__ A, const float* __restrict__ B) { unsigned tid = threadIdx.x + blockIdx.x * blockDim.x; if (tid >= size) return; float a = A[tid]; float b = B[tid]; float d = fabsf(a - b); float err = (a == 0 || b == 0) ? d : fmaxf(d / fabsf(a), d / fabsf(b)); if (err > tol) atomicAdd(Exceeds, 1); } bool AllClose(Tensor A, Tensor B, float tolerance) { if (A.size() != B.size()) { return false; } int* Exceeds; ErrChk(cudaMalloc(&Exceeds, sizeof(int))); ErrChk(cudaMemset(Exceeds, 0, sizeof(int))); unsigned BlockSize = A.size() < 512 ? A.size() : 512; unsigned GridSize = (A.size() / 512) + ((A.size() % 512) != 0); arrayRelativeDelta<<<GridSize, BlockSize>>>( Exceeds, tolerance, A.size(), A.m_data, B.m_data); ErrChk(cudaPeekAtLastError()); ErrChk(cudaDeviceSynchronize()); int host_Exceeds; ErrChk( cudaMemcpy(&host_Exceeds, Exceeds, sizeof(int), cudaMemcpyDeviceToHost)); return host_Exceeds == 0; }
5,795
#include "includes.h" __global__ void relu_f32 (float* vector, float* output, int len) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < len) { output[idx] = vector[idx] > 0.0 ? vector[idx] : 0.0; } }
5,796
// // Created by igor on 28.03.2021. // #include "Matrix4.cuh" __host__ __device__ double *Matrix4::operator[](unsigned long x) { return data[x]; } Matrix4::Matrix4(std::initializer_list<double> list) noexcept : data(){ int i = 0; for(double d: list){ data[0][i]=d; ++i; } } const Matrix4 Matrix4::IDENTITY = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; Matrix4 Matrix4::fromAxisAngle(Vector3 axis, double angle) { return {}; //TODO implement } Matrix4 Matrix4::fromScaleFactor(double x, double y, double z) { return {x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1}; } Matrix4 Matrix4::fromTranslationVector(const Vector3 &v) { return {1, 0, 0, v.x, 0, 1, 0, v.y, 0, 0, 1, v.z, 0, 0, 0, 1}; } Matrix4::Matrix4() :Matrix4{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}{}
5,797
/* * UpdaterHy1D.cpp * * Created on: 25 янв. 2016 г. * Author: aleksandr */ #include "UpdaterHy1D.h" __device__ void UpdaterHy1D::operator() (const int indx) { Hy[indx] = Chyh[indx]*Hy[indx] + Chye[indx]*(Ez[indx+1] - Ez[indx]); }
5,798
extern "C" { __global__ void expkernel_32(const int lengthA, const float *a, float *b) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i<lengthA) { b[i] = exp(a[i]); } } }
5,799
#include "cuda.h" #include <cstdio> static float *h_points; static float *d_points; static double *h_pointsd; static double *d_pointsd; static unsigned int *d_groups; static unsigned int d_psize; static float d_pmax; static float d_pmin; static double d_pmaxd; static double d_pmind; __global__ void groupKernel(float *points, unsigned int psize, float *codebook, unsigned int csize, unsigned int *groups) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < psize) { float d = abs(points[idx] - codebook[0]); float min = d; unsigned int g = 0; for(int i = 1; i < csize; i++) { d = abs(points[idx] - codebook[i]); g += (d < min) * (i - g); min -= (d < min) * (min - d); } groups[idx] = g; } } __global__ void groupKernel(double *points, unsigned int psize, double *codebook, unsigned int csize, unsigned int *groups) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < psize) { double d = abs(points[idx] - codebook[0]); double min = d; unsigned int g = 0; for(int i = 1; i < csize; i++) { d = abs(points[idx] - codebook[i]); g += (d < min) * (i - g); min -= (d < min) * (min - d); } groups[idx] = g; } } void setupLloyds(float *points, unsigned int psize, float pmax, float pmin) { d_psize = psize; d_pmax = pmax; d_pmin = pmin; h_points = points; cudaMalloc((void**)&d_points, sizeof(float)*psize); cudaMalloc((void**)&d_groups, sizeof(unsigned int)*psize); cudaMemcpy(d_points, points, sizeof(float) * psize, cudaMemcpyHostToDevice); } void setupLloyds(double *points, unsigned int psize, double pmax, double pmin) { d_psize = psize; d_pmaxd = pmax; d_pmind = pmin; h_pointsd = points; cudaMalloc((void**)&d_pointsd, sizeof(double)*psize); cudaMalloc((void**)&d_groups, sizeof(unsigned int)*psize); cudaMemcpy(d_pointsd, points, sizeof(double) * psize, cudaMemcpyHostToDevice); } void lloyd(float *codebook, unsigned int csize, float stop_criteria, float *table, float &dist, float &reldist, unsigned int *groups) { float *d_codebook; dist = 0; reldist = 0; // Calculate initial table //can be done in gpu if csize is big enough for(int i = 0; i < csize-1; i++) { table[i] = (codebook[i] + codebook[i+1]) / 2; } cudaMalloc((void**)&d_codebook, sizeof(float)*csize); cudaMemcpy(d_codebook, codebook, sizeof(float)*csize, cudaMemcpyHostToDevice); // Assign each point its codebook group unsigned int threads = 256; unsigned int blocks = (d_psize - 1) / threads + 1; groupKernel<<<blocks, threads>>>(d_points, d_psize, d_codebook, csize, d_groups); cudaMemcpy(groups, d_groups, sizeof(unsigned int) * d_psize, cudaMemcpyDeviceToHost); unsigned int *incode = (unsigned int*)calloc(csize, sizeof(unsigned int)); float *meancode = (float*)calloc(csize, sizeof(float)); // Calculate the mean of each codebook group and distortion for(int i = 0; i < d_psize; i++) { incode[groups[i]]++; meancode[groups[i]] += h_points[i]; dist += codebook[groups[i]] - h_points[i]; } dist /= d_psize; reldist = abs(dist); while(reldist > stop_criteria) { // Update codebook //can be done in gpu if csize is big enough for(int i = 0; i < csize; i++) { if(incode[i] != 0) { codebook[i] = meancode[i] / incode[i]; incode[i] = 0; } else if (i == 0) { codebook[i] = (table[0] + d_pmin) / 2; } else if (i == csize-1) { codebook[i] = (table[i-1] + d_pmax) / 2; } else { codebook[i] = (table[i-1] + table[i]) / 2; } meancode[i] = 0; } cudaMemcpy(d_codebook, codebook, sizeof(float)*csize, cudaMemcpyHostToDevice); // How to do this in CUDA efficiently? for(int i = 0; i < d_psize; i++) { for(int j = 0; j < csize-1; j++) { if((h_points[i] >= codebook[j]) && (h_points[i] < codebook[j+1])) { incode[j]++; meancode[j] += h_points[i]; break; } } } // Update table //can be done in gpu if csize is big enough for(int i = 0; i < csize-1; i++) { if(incode[i] != 0) { table[i] = meancode[i] / incode[i]; incode[i] = 0; } else { table[i] = (codebook[i] + codebook[i+1]) / 2; } meancode[i] = 0; } // Assign each point its codebook group groupKernel<<<blocks, threads>>>(d_points, d_psize, d_codebook, csize, d_groups); cudaMemcpy(groups, d_groups, sizeof(unsigned int) * d_psize, cudaMemcpyDeviceToHost); reldist = dist; dist = 0; // Calculate the mean of each codebook group and distortion for(int i = 0; i < d_psize; i++) { incode[groups[i]]++; meancode[groups[i]] += h_points[i]; dist += codebook[groups[i]] - h_points[i]; } dist /= d_psize; reldist = abs(reldist - dist); } // END WHILE cudaFree(d_codebook); free(incode); free(meancode); } void lloyd(double *codebook, unsigned int csize, double stop_criteria, double *table, double &dist, double &reldist, unsigned int *groups) { double *d_codebook; dist = 0; reldist = 0; // Calculate initial table //can be done in gpu if csize is big enough for(int i = 0; i < csize-1; i++) { table[i] = (codebook[i] + codebook[i+1]) / 2; } cudaMalloc((void**)&d_codebook, sizeof(double)*csize); cudaMemcpy(d_codebook, codebook, sizeof(double)*csize, cudaMemcpyHostToDevice); // Assign each point its codebook group unsigned int threads = 256; unsigned int blocks = (d_psize - 1) / threads + 1; groupKernel<<<blocks, threads>>>(d_pointsd, d_psize, d_codebook, csize, d_groups); cudaMemcpy(groups, d_groups, sizeof(unsigned int) * d_psize, cudaMemcpyDeviceToHost); unsigned int *incode = (unsigned int*)calloc(csize, sizeof(unsigned int)); double *meancode = (double*)calloc(csize, sizeof(double)); // Calculate the mean of each codebook group and distortion for(int i = 0; i < d_psize; i++) { incode[groups[i]]++; meancode[groups[i]] += h_pointsd[i]; dist += codebook[groups[i]] - h_pointsd[i]; } dist /= d_psize; reldist = abs(dist); while(reldist > stop_criteria) { // Update codebook //can be done in gpu if csize is big enough for(int i = 0; i < csize; i++) { if(incode[i] != 0) { codebook[i] = meancode[i] / incode[i]; incode[i] = 0; } else if (i == 0) { codebook[i] = (table[0] + d_pmind) / 2; } else if (i == csize-1) { codebook[i] = (table[i-1] + d_pmaxd) / 2; } else { codebook[i] = (table[i-1] + table[i]) / 2; } meancode[i] = 0; } cudaMemcpy(d_codebook, codebook, sizeof(double)*csize, cudaMemcpyHostToDevice); // How to do this in CUDA efficiently? for(int i = 0; i < d_psize; i++) { for(int j = 0; j < csize-1; j++) { if((h_pointsd[i] >= codebook[j]) && (h_pointsd[i] < codebook[j+1])) { incode[j]++; meancode[j] += h_pointsd[i]; break; } } } // Update table //can be done in gpu if csize is big enough for(int i = 0; i < csize-1; i++) { if(incode[i] != 0) { table[i] = meancode[i] / incode[i]; incode[i] = 0; } else { table[i] = (codebook[i] + codebook[i+1]) / 2; } meancode[i] = 0; } // Assign each point its codebook group groupKernel<<<blocks, threads>>>(d_pointsd, d_psize, d_codebook, csize, d_groups); cudaMemcpy(groups, d_groups, sizeof(unsigned int) * d_psize, cudaMemcpyDeviceToHost); reldist = dist; dist = 0; // Calculate the mean of each codebook group and distortion for(int i = 0; i < d_psize; i++) { incode[groups[i]]++; meancode[groups[i]] += h_pointsd[i]; dist += codebook[groups[i]] - h_pointsd[i]; } dist /= d_psize; reldist = abs(reldist - dist); } // END WHILE cudaFree(d_codebook); free(incode); free(meancode); } void finalize() { cudaFree(d_points); cudaFree(d_groups); } void finalized() { cudaFree(d_pointsd); cudaFree(d_groups); }
5,800
#include <stdio.h> #include <assert.h> #include <cuda.h> #include <cuda_runtime.h> #define MAX(a,b) ( a>b ? a : b) __global__ void vector_add(float *a, float *b, float *c, int N) { int gtid = blockIdx.x*blockDim.x + threadIdx.x; if (gtid < N) { c[gtid] = a[gtid] + b[gtid]; } } bool bPinGenericMemory = false; #define MEMORY_ALIGNMENT 4096 #define ALIGN_UP(x,size) ( ((size_t)x + (size-1))&(~(size-1)) ) // ??? int main(int argc, char **argv) { int n, nelem, deviceCount; int idev = 0; char *device = NULL; unsigned int flags; size_t bytes; float *a, *b, *c; float *a_UA, *b_UA, *c_UA; float *d_a, *d_b, *d_c; float errorNorm, refNorm, ref, diff; cudaDeviceProp deviceProp; bPinGenericMemory = true; cudaSetDevice(idev); cudaSetDeviceFlags(cudaDeviceMapHost); nelem = 1048576; bytes = nelem*sizeof(float); if (bPinGenericMemory) { a_UA = (float *)malloc(bytes + MEMORY_ALIGNMENT); b_UA = (float *)malloc(bytes + MEMORY_ALIGNMENT); c_UA = (float *)malloc(bytes + MEMORY_ALIGNMENT); a = (float *) ALIGN_UP(a_UA, MEMORY_ALIGNMENT); b = (float *) ALIGN_UP(b_UA, MEMORY_ALIGNMENT); c = (float *) ALIGN_UP(c_UA, MEMORY_ALIGNMENT); cudaHostRegister(a, bytes, CU_MEMHOSTALLOC_DEVICEMAP); cudaHostRegister(b, bytes, CU_MEMHOSTALLOC_DEVICEMAP); cudaHostRegister(c, bytes, CU_MEMHOSTALLOC_DEVICEMAP); } else { flags = cudaHostAllocMapped; cudaHostAlloc((void **)&a, bytes, flags); cudaHostAlloc((void **)&b, bytes, flags); cudaHostAlloc((void **)&c, bytes, flags); } for (n=0;n<nelem;n++) { a[n] = rand() / (float)RAND_MAX; b[n] = rand() / (float)RAND_MAX; } cudaHostGetDevicePointer((void **)&d_a, (void *)a, 0); cudaHostGetDevicePointer((void **)&d_b, (void *)b, 0); cudaHostGetDevicePointer((void **)&d_c, (void *)c, 0); dim3 dim_block(256); dim3 dim_grid((unsigned int)ceil(nelem/(float)dim_block.x)); vector_add<<<dim_block,dim_grid>>>(d_a,d_b,d_c,nelem); cudaDeviceSynchronize(); if (bPinGenericMemory) { cudaHostUnregister(a); cudaHostUnregister(b); cudaHostUnregister(c); free(a_UA); free(b_UA); free(c_UA); } else { cudaFreeHost(a); cudaFreeHost(b); cudaFreeHost(c); } cudaDeviceReset(); return 0; }