serial_no
int64
1
24.2k
cuda_source
stringlengths
11
9.01M
5,801
#include "includes.h" #define FLOAT_N 3214212.01 __global__ void calcmean(double* d_data, double* d_mean, int M, int N) { int i; int j = blockDim.x * blockIdx.x + threadIdx.x+1; if (j<=(M+1)) { d_mean[j] = 0.0; for (i = 1; i < (N+1); i++) { d_mean[j] += d_data[i*(M+1) + j]; } d_mean[j] /= FLOAT_N; } }
5,802
/** * CUDA Thrust example showing addition of 2 vectors * (compare with that of raw CUDA) * * Danny George 2012 */ #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/fill.h> #include <thrust/functional.h> #include <thrust/transform.h> #include <iostream> template <class T> void print_vector_naive(T& v) { if (v.size() > 50) { // print first and last bits of vector for (int i=0; i<10; i++) { std::cout << "[" << i << "] = " << v[i] << std::endl; } std::cout << " ....... " << std::endl; for (int i=v.size()-10; i<v.size(); i++) { std::cout << "[" << i << "] = " << v[i] << std::endl; } } else { // print the whole thing... for (int i=0; i<v.size(); i++) { std::cout << "[" << i << "] = " << v[i] << std::endl; } } } int main(int argc, char *argv[]) { const int N = 10000; thrust::host_vector<int> h1(N); thrust::host_vector<int> h2(N); // initialize host vectors (would be more efficient to do this on the device) thrust::fill(h1.begin(), h1.end(), 111); thrust::fill(h2.begin(), h2.end(), 222); // init & copy host data to device vectors thrust::device_vector<int> d1(h1); thrust::device_vector<int> d2(h2); thrust::device_vector<int> dr(N); thrust::plus<int> binary_op; // transform is essentially a 'map' operation (std::map is used for a container) // perform 'binary_op' on each pairwise element from d1 to d2 and store in dr thrust::transform(d1.begin(), d1.end(), d2.begin(), dr.begin(), binary_op); // NOTE: you MUST ensure that 'd2' and 'dr' have room for // at least d1.end() - d1.begin() elements // copy result back to host h1 = dr; print_vector_naive(h1); return 0; }
5,803
#include <stdio.h> /* using printf in kernel, don't forget to call cudaDeviceSynchronize() after kernel call in the host */ __global__ void helloCUDA(float f) { printf("Hello thread %d, f=%f\n", threadIdx.x, f); } int main() { helloCUDA<<<1, 5>>>(1.2345f); cudaDeviceSynchronize(); return 0; }
5,804
/* The matrix addition example on CUDA This program first reads two matrices from two text files namely matA.txt and matB.txt Then it does matrix addition on the two matrices Finally it saves the answer matrix in a text file named ans.txt The program also measures the time taken for matrix operation on CUDA */ #include <stdio.h> //define file names here #define MATRIXA "matA.txt" #define MATRIXB "matB.txt" #define MATRIXANS "ans.txt" //define the sizes of the matrices here #define ROWS 16 #define COLS 16 #define SIZE ROWS*COLS //kernel that does the matrix addition. Just add each element to the respective one __global__ void addMatrix(int *ans_cuda,int *matA_cuda,int *matB_cuda){ int row = threadIdx.y; int col = threadIdx.x; int position = row*COLS + col; ans_cuda[position]=matA_cuda[position]+matB_cuda[position]; } int main(){ //open the files FILE *filematA = fopen(MATRIXA, "r"); FILE *filematB = fopen(MATRIXB, "r"); FILE *fileans = fopen(MATRIXANS, "w"); //allocate matrices int matA[SIZE]; int matB[SIZE]; int ans[SIZE]; //read the input matrices from file int row,col; for(row=0;row<ROWS;row++){ for(col=0;col<COLS;col++){ int position = row*COLS + col; fscanf(filematA, "%d", &matA[position]); fscanf(filematB, "%d", &matB[position]); ans[position]=0; } } /*************************CUDA STUFF STARTS HERE************************/ //variables for time measurements cudaEvent_t start,stop; float elapsedtime; //pointers for cuda memory locations int *matA_cuda; int *matB_cuda; int *ans_cuda; //the moment at which we start measuring the time cudaEventCreate(&start); cudaEventRecord(start,0); //allocate memory in cuda cudaMalloc((void **)&matA_cuda,sizeof(int)*SIZE); cudaMalloc((void **)&matB_cuda,sizeof(int)*SIZE); cudaMalloc((void **)&ans_cuda,sizeof(int)*SIZE); //copy contents from ram to cuda cudaMemcpy(matA_cuda, matA, sizeof(int)*SIZE, cudaMemcpyHostToDevice); cudaMemcpy(matB_cuda, matB, sizeof(int)*SIZE, cudaMemcpyHostToDevice); //thread configuration dim3 numBlocks(1,1); dim3 threadsPerBlock(COLS,ROWS); //do the matrix addition on CUDA addMatrix<<<numBlocks,threadsPerBlock>>>(ans_cuda,matA_cuda,matB_cuda); //copy the answer back cudaMemcpy(ans, ans_cuda, sizeof(int)*SIZE, cudaMemcpyDeviceToHost); //the moment at which we stop measuring time cudaEventCreate(&stop); cudaEventRecord(stop,0); cudaEventSynchronize(stop); //free the memory we allocated on CUDA cudaFree(matA_cuda); cudaFree(matB_cuda); cudaFree(ans_cuda); /*************************CUDA STUFF ENDS HERE************************/ //write the answer to the text file for(row=0;row<ROWS;row++){ for(col=0;col<COLS;col++){ int position = row*COLS + col; fprintf(fileans, "%d ", ans[position]); } fprintf(fileans, "\n"); } //Find and print the elapsed time cudaEventElapsedTime(&elapsedtime,start,stop); printf("Time spent for operation is %.10f seconds\n",elapsedtime/(float)1000); fclose(filematA); fclose(filematB); fclose(fileans); return 0; }
5,805
#include <stdlib.h> #include <stdio.h> void square_this(int *array, int n){ int i; for(i = 0 ; i<n ; i++) array[i] *= array[i]; } __global__ void cuda_square_this(int *deviceArray){ int me =threadIdx.x; deviceArray[me] *= 2; } int main(){ int *hostArray, *deviceArray; int n = 10; int arraySize = n*sizeof(int); hostArray = (int *) malloc(arraySize); cudaMalloc((void **) &deviceArray, arraySize); int i; for(i = 0; i<n ; i++) hostArray[i] = i+1; cudaMemcpy(deviceArray, hostArray, arraySize, cudaMemcpyHostToDevice); cuda_square_this<<<1,n>>>(deviceArray); square_this(hostArray, n); for(i = 0; i<n; i++) printf("%d\n",hostArray[i]); cudaMemcpy(hostArray, deviceArray, arraySize, cudaMemcpyDeviceToHost); for(i=0;i<n;i++) printf("%d\n", hostArray[i]); return 0; }
5,806
#include <device_launch_parameters.h> __global__ void vectorAdd(const float* A, const float* B, float* C, int numElements) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < numElements) { C[i] = A[i] + B[i]; } }
5,807
//Time-stamp: <2013-11-28 11:35:34 hamada> // FMA performance metor by Tsuyoshi Hamada #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> //#define REAL float #define REAL double #define DEVICE_ID (0) #define NUM_MP (15) // MultiProcessor (G92-GTS = 16, GT280 = 30) #define NUM_SP_PER_BLOCK (192) #define NUM_THREADS_PER_BLOCK (NUM_SP_PER_BLOCK*5) #define NUM_BLOCKS (NUM_MP * 16) #define NUM_ITERATIONS (1<<10) /* #define NUM_MP (16) #define NUM_THREADS_PER_SM (384) #define NUM_THREADS_PER_BLOCK (192) #define NUM_BLOCKS ((NUM_THREADS_PER_SM / NUM_THREADS_PER_BLOCK) * NUM_MP) #define NUM_ITERATIONS 30 */ /* #define NUM_MP (30) // MultiProcessor (G92-GTS = 16, GT280 = 30) #define NUM_THREADS_PER_BLOCK (128) #define NUM_THREADS_PER_SM (128*16) #define NUM_BLOCKS ((NUM_THREADS_PER_SM / NUM_THREADS_PER_BLOCK) * NUM_MP) #define NUM_ITERATIONS (2048) */ /* #define NUM_MP (30) // MultiProcessor (G92-GTS = 16, GT280 = 30) #define NUM_THREADS_PER_BLOCK (128) #define NUM_THREADS_PER_SM (128*16) #define NUM_BLOCKS ((NUM_THREADS_PER_SM / NUM_THREADS_PER_BLOCK) * NUM_MP) #define NUM_ITERATIONS (2048) */ // 128 MAD instructions #define FMAD128(a, b) \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ a *= b * a + b; \ b *= a * b + a; \ __shared__ REAL result[NUM_THREADS_PER_BLOCK]; __device__ void fma128x16(REAL& a, REAL& b) { FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); FMAD128(a, b); } __global__ void gpu_func() { REAL a = result[threadIdx.x]; // this ensures the mads don't get compiled out REAL b = 1.01f; for(int i=0; i<NUM_ITERATIONS; i++){ fma128x16(a, b); // 1 fma128x16(a, b); // 2 fma128x16(a, b); // 3 fma128x16(a, b); // 4 fma128x16(a, b); // 5 fma128x16(a, b); // 6 fma128x16(a, b); // 7 fma128x16(a, b); // 8 fma128x16(a, b); // 9 } /* fma128x16(a, b); // 10 fma128x16(a, b); // 11 fma128x16(a, b); // 12 fma128x16(a, b); // 13 fma128x16(a, b); // 14 fma128x16(a, b); // 15 fma128x16(a, b); // 16 */ result[threadIdx.x] = a + b; } #include <sys/time.h> #include <sys/resource.h> double get_time(void) { static struct timeval tv; static struct timezone tz; gettimeofday(&tv, &tz); return ((double)(tv.tv_sec + tv.tv_usec*1.0e-6)); } int run(int devid) { int n_dev = -1; cudaGetDeviceCount(&n_dev); assert(0 < n_dev); printf("# of devices: %d\n", n_dev); // set Device ID as Round-robin devid = devid % n_dev; cudaSetDevice(devid); cudaGetDevice(&devid); printf("devid: %d\n", devid); cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, devid); printf("[%d]: Device PCI Bus ID / PCI location ID: %x / %x\n", devid, deviceProp.pciBusID, deviceProp.pciDeviceID); cudaThreadSynchronize(); // execute kernel double time = get_time(); gpu_func<<<NUM_BLOCKS, NUM_THREADS_PER_BLOCK>>>(); cudaThreadSynchronize(); time = get_time() - time; // output results printf( "[%d]: Time: %f (ms)\n", devid, time*1000.0); const double num_fma = 16. * 9. * (double)NUM_ITERATIONS; const double flop = (double)(64. * 3. * num_fma) * (double)(NUM_BLOCKS * NUM_THREADS_PER_BLOCK); const double flops = flop/time; // printf("[%d]: flop: %e\n", devid, flop); printf("[%d]: Gflops: %f\n", devid, flops / 1.0e+9 ); printf("\n"); return (0); } int main(int argc, char** argv) { int devid = DEVICE_ID; printf("N_BLOCK: %d\n", NUM_BLOCKS); printf("N_THREAD: %d\n", NUM_THREADS_PER_BLOCK); if(argc > 1){ devid = atoi(argv[1]); run(devid); }else{ for(devid = 0; devid < 16; devid++) run(devid); } return 0; }
5,808
template<typename T> __device__ void getIndexedValues(const T* matrix, const int* rowsIndices, const int* colsIndices, T* result, const int rows, const int cols, const int indices_length) { int bx = blockIdx.x; int tx = threadIdx.x; int index = bx * blockDim.x + tx; if (index < indices_length) { int row = rowsIndices[index]; int col = colsIndices[index]; result[index] = matrix[row * cols + col]; } } template<typename T> __device__ void setIndexedValues(T* matrix, const int* rowsIndices, const int* colsIndices, const T* values, const int rows, const int cols, const int indices_length) { int bx = blockIdx.x; int tx = threadIdx.x; int index = bx * blockDim.x + tx; if (index < indices_length) { int row = rowsIndices[index]; int col = colsIndices[index]; matrix[row * cols + col] = values[index]; } } template<typename T> __device__ void setIndexedValue(T* matrix, const int* rowsIndices, const int* colsIndices, const T value, const int rows, const int cols, const int indices_length) { int bx = blockIdx.x; int tx = threadIdx.x; int index = bx * blockDim.x + tx; if (index < indices_length) { int row = rowsIndices[index]; int col = colsIndices[index]; matrix[row * cols + col] = value; } }
5,809
#include "includes.h" // Contains GPU Cuda code that executes BFS algorithm // STL // Internal Headers // taken from global_memory.cu, Creates event and records time __global__ void BFSLevels(int *vertices, int *edges, int *distances, int *predecessors, int *vertIndices, int *edgeSize, bool *levels, bool *visitedVertices, bool *foundDest, int numVert, int destination) { // Grab ThreadID int thrID = threadIdx.x + blockIdx.x * blockDim.x; __shared__ bool destFound; destFound = false; if (thrID < numVert && !destFound) { int curVert = vertices[thrID]; // Iterate through level if true if (levels[curVert]) { levels[curVert] = false; visitedVertices[curVert] = true; // Grab indexes for curVert edges in edge array int edgesEnd = edgeSize[thrID] + vertIndices[thrID]; // Iterate through all edges for current vertex for (int edgeIter = vertIndices[thrID]; edgeIter < edgesEnd; ++edgeIter) { // Grab next Vertex at end of edge int nextVert = edges[edgeIter]; // If it hasn't been visited store info // for distance and predecessors and set level // to true for next level of vertices if (!visitedVertices[nextVert]) { distances[nextVert] = distances[curVert] + 1; levels[nextVert] = true; predecessors[nextVert] = curVert; // Set found destination to true and sync threads if (nextVert == destination) { *foundDest = true; destFound = true; __syncthreads(); } } } } } }
5,810
#include <bits/stdc++.h> #include <cuda.h> #define N 15 #define M 4096 __global__ void histogram_creation(int *A, int *hist, int no_of_threads) { int global_x = blockDim.x * blockIdx.x + threadIdx.x; __shared__ int local_hist[N+1]; for(int i = threadIdx.x; i<=N; i = i + (blockDim.x ) ){ local_hist[i] = 0; } __syncthreads(); for(int i = global_x; i <= M; i = i + (blockDim.x * no_of_threads)) { atomicAdd(&local_hist[A[i]],1); } __syncthreads(); for(int i = threadIdx.x ; i <= N; i = i + (blockDim.x) ) { atomicAdd(&hist[i],local_hist[i]); printf("%d histogram_local %d \n",local_hist[i],i); } __syncthreads(); } __global__ void histogram_saturation(int *hist) { int index = threadIdx.x; if(hist[index] > 127) { hist[index] = 127; } } void handle_error(cudaError_t error) { if (error != cudaSuccess) { printf("Cuda Error. Exiting....\n"); exit(0); } } void init_matrix( int A[], long long n) { for (long long i = 0; i< n; i++) { A[i] = rand() % 4096 + 1; } } int main() { int A[M]; int hist[N +1]; for(int i=0; i < N + 1; i++) { hist[i] = 0; } init_matrix(A, M); int *deviceA; int *deviceHist; size_t size_histogram = (N + 1) * sizeof(int); size_t size_array = M * sizeof(int); handle_error(cudaMalloc((void**) &deviceA, size_array)); handle_error(cudaMalloc((void**) &deviceHist, size_histogram)); cudaMemcpy(A, deviceA, size_array, cudaMemcpyHostToDevice); cudaMemcpy(hist, deviceHist, size_histogram, cudaMemcpyHostToDevice); dim3 grid_dim(256,1,1); dim3 block_dim(256,1,1); histogram_creation<<<grid_dim, block_dim>>>(deviceA, deviceHist,256); cudaMemcpy(hist, deviceHist, size_histogram, cudaMemcpyDeviceToHost); histogram_saturation<<<1,4096>>>(deviceHist); cudaMemcpy(hist, deviceHist, size_histogram, cudaMemcpyDeviceToHost); for(int i=0;i<=4096; i++) { printf("%d\n", hist[i]); } }
5,811
#include<iostream> #include<cstdio> #include<cstdlib> #include<cuda_runtime.h> using namespace std; __global__ void Min(float* InputArray, int ArraySize){ int tid = threadIdx.x; int ThreadCount = blockDim.x; do{ if(tid<ThreadCount){ if((tid + ThreadCount)<ArraySize) if(InputArray[tid] > InputArray[tid + ThreadCount]) InputArray[tid] = InputArray[tid + ThreadCount]; } ThreadCount = (ThreadCount+1)>>1; ArraySize = (ArraySize + 1)>>1; }while(ThreadCount>1); if(InputArray[0] > InputArray[1]) InputArray[0] = InputArray[1]; } __global__ void Max(float* InputArray, int ArraySize){ int tid = threadIdx.x; int ThreadCount = blockDim.x; do{ if(tid<ThreadCount){ if((tid + ThreadCount)<ArraySize) if(InputArray[tid] < InputArray[tid + ThreadCount]) InputArray[tid] = InputArray[tid + ThreadCount]; } ThreadCount = (ThreadCount+1)>>1; ArraySize = (ArraySize + 1)>>1; }while(ThreadCount>1); if(InputArray[0] < InputArray[1]) InputArray[0] = InputArray[1]; } __global__ void Sum(float* InputArray, int ArraySize){ int tid = threadIdx.x; int ThreadCount = blockDim.x; do{ if(tid<ThreadCount){ if((tid + ThreadCount)<ArraySize) InputArray[tid] += InputArray[tid + ThreadCount]; } ThreadCount = (ThreadCount+1)>>1; ArraySize = (ArraySize + 1)>>1; }while(ThreadCount>1); InputArray[0] += InputArray[1]; } __global__ void Average(float* InputArray, int ArraySize){ int tid = threadIdx.x; int ThreadCount = blockDim.x; int TempArraySize = ArraySize; do{ if(tid<ThreadCount){ if((tid + ThreadCount)<TempArraySize) InputArray[tid] += InputArray[tid + ThreadCount]; } ThreadCount = (ThreadCount+1)>>1; TempArraySize = (TempArraySize + 1)>>1; }while(ThreadCount>1); InputArray[0] += InputArray[1]; InputArray[0] /= ArraySize; } int main(){ //Read Array Size From User int ArraySize = -1; printf("Enter The Number Of Elements: : "); scanf("%d", &ArraySize); if(ArraySize<=0) return 0; //Declare The Float Array float *h_Array=new float[ArraySize]; printf("Enter The Elements In The Array: : "); //Read Elements From User for(int i=0;i<ArraySize;i++){ scanf("%f", &h_Array[i]); } int ArrayMemory=ArraySize*sizeof(float); int ThreadBlockSize = (ArraySize+1)>>1; float *d_Array; float result; cudaMalloc(&d_Array,ArrayMemory); // Copy Array To GPU For Minimum Function cudaMemcpy(d_Array, h_Array, ArrayMemory, cudaMemcpyHostToDevice); Min<<<1,ThreadBlockSize>>>(d_Array,ArraySize); cudaMemcpy(&result, d_Array, sizeof(float), cudaMemcpyDeviceToHost); printf("The Minimum Value In The Array: : %f\n", result); // Copy Array To GPU For Maximum Function cudaMemcpy(d_Array, h_Array, ArrayMemory, cudaMemcpyHostToDevice); Max<<<1,ThreadBlockSize>>>(d_Array,ArraySize); cudaMemcpy(&result, d_Array, sizeof(float), cudaMemcpyDeviceToHost); printf("The Maximum Value In The Array: : %f\n", result); // Copy Array To GPU For Sum Function cudaMemcpy(d_Array, h_Array, ArrayMemory, cudaMemcpyHostToDevice); Sum<<<1,ThreadBlockSize>>>(d_Array,ArraySize); cudaMemcpy(&result, d_Array, sizeof(float), cudaMemcpyDeviceToHost); printf("The Sum Of Numbers In The Array: : %f\n", result); // Copy Array To GPU For Average Function cudaMemcpy(d_Array, h_Array, ArrayMemory, cudaMemcpyHostToDevice); Average<<<1,ThreadBlockSize>>>(d_Array,ArraySize); cudaMemcpy(&result, d_Array, sizeof(float), cudaMemcpyDeviceToHost); printf("The Average Of Numbers In The Array: : %f\n", result); return 0; }
5,812
#include <cuda.h> #include <stdio.h> #include <stdlib.h> #define BLOCK_SIZE 16 __global__ void mandelKernel( int *d_out, float lowerX, float lowerY, float stepX, float stepY, int resX, int maxIters ) { // To avoid error caused by the floating number, use the following pseudo code // // float x = lowerX + thisX * stepX; // float y = lowerY + thisY * stepY; int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; int index = j*resX + i; float c_re = lowerX + i*stepX; float c_im = lowerY + j*stepY; float z_re = c_re; float z_im = c_im; int iter; for (iter = 0; iter < maxIters; ++iter) { if (z_re*z_re + z_im*z_im > 4.f) break; float new_re = z_re*z_re - z_im*z_im; float new_im = 2.f*z_re*z_im; z_re = c_re + new_re; z_im = c_im + new_im; } d_out[index] = iter; } // Host front-end function that allocates the memory and launches the GPU kernel void hostFE (float upperX, float upperY, float lowerX, float lowerY, int* img, int resX, int resY, int maxIterations) { float stepX = (upperX - lowerX) / resX; float stepY = (upperY - lowerY) / resY; int *h_out, *d_out; // Mandelbort result on host & device int size = resX * resY * sizeof(int); // Allocate memory on host & device. h_out = (int *)malloc(size); cudaMalloc((void **)&d_out, size); // CUDA kernel function. dim3 block_size(BLOCK_SIZE, BLOCK_SIZE); dim3 num_block(resX / BLOCK_SIZE, resY / BLOCK_SIZE); mandelKernel<<<num_block, block_size>>>(d_out, lowerX, lowerY, stepX, stepY, resX, maxIterations); // Wait for all CUDA threads to finish. cudaDeviceSynchronize(); // Store result from device to host. cudaMemcpy(h_out, d_out, size, cudaMemcpyDeviceToHost); memcpy(img, h_out, size); // Free memory. free(h_out); cudaFree(d_out); }
5,813
#include <iostream> #include <cmath> #include <vector> #include <functional> #include <fstream> #include <algorithm> #include <sstream> #include <string> #include <random> #include <thrust/random.h> #include <thrust/device_vector.h> #include <thrust/host_vector.h> #include <thrust/random/linear_congruential_engine.h> #include <thrust/random/uniform_int_distribution.h> using namespace std; int calc_satisfacao_atual(vector<vector<int>>& prefs, vector<int>& aluno_projeto){ int satisfacao_atual = 0; for(auto aluno_atual = 0; aluno_atual < aluno_projeto.size(); aluno_atual++){ satisfacao_atual += prefs[aluno_atual][aluno_projeto[aluno_atual]]; } return satisfacao_atual; } struct escolhe_alunos{ int *prefs; int *aluno_projeto; int n_alunos; int n_projetos; int seed; thrust::uniform_int_distribution<int> dist; escolhe_alunos (int *prefs, int *aluno_projeto, int n_alunos, int n_projetos, int seed, thrust::uniform_int_distribution<int> dist) : prefs(prefs), aluno_projeto(aluno_projeto), n_alunos(n_alunos), n_projetos(n_projetos), seed(seed), dist(dist){}; __device__ __host__ int operator()(const int &i) {; int random_int; thrust::default_random_engine rng(i+seed); rng.discard(i); int tmp1; for(int k=0; k < n_alunos; k++){ random_int = dist(rng); tmp1 = aluno_projeto[k+i*n_alunos]; aluno_projeto[k+i*n_alunos] = aluno_projeto[random_int+i*n_alunos]; //faz trocas no aluno projeto aleatoriamente aluno_projeto[random_int+i*n_alunos] = tmp1; } int satisfacao_local = 0; bool flag = true; //calcula satisfacao for(int c=0; c < n_alunos; c++){ satisfacao_local += prefs[c*n_projetos+aluno_projeto[c+i*n_alunos]]; } while(flag){ flag = false; for(int a=0; a < n_alunos; a++){ for(int b=0; b < n_alunos; b++){ if(b>a){ int satisfacao_tmp = 0; tmp1 = aluno_projeto[a+i*n_alunos]; aluno_projeto[a+i*n_alunos] = aluno_projeto[b+i*n_alunos]; //faz trocas no aluno projeto aluno_projeto[b+i*n_alunos] = tmp1; //calcula satisfacao for(int c=0; c < n_alunos; c++){ satisfacao_tmp += prefs[c*n_projetos+aluno_projeto[c+i*n_alunos]]; } if(satisfacao_tmp > satisfacao_local){ satisfacao_local = satisfacao_tmp; flag = true; } else{ tmp1 = aluno_projeto[a+i*n_alunos]; aluno_projeto[a+i*n_alunos] = aluno_projeto[b+i*n_alunos]; //destroca no aluno projeto aluno_projeto[b+i*n_alunos] = tmp1; } } } } } return satisfacao_local; } }; int main(){ string line; vector<int> v_entrada; int tmp_op; getline(cin, line); istringstream ss(line); while(ss >> tmp_op){ v_entrada.push_back(tmp_op); } int n_alunos, n_projetos, n_choices; n_alunos = v_entrada[0]; n_projetos = v_entrada[1]; n_choices = v_entrada[2]; vector<int> prefs(n_alunos*n_projetos); vector<int> projs; int proj_tmp; int seed = 0; int iterations = 100000; if(getenv("SEED")){ seed = atoi(getenv("SEED")); } if(getenv("ITER")){ iterations = atoi(getenv("ITER")); } for (int i=0; i<n_alunos; i++){ getline(cin, line); istringstream ss(line); projs.clear(); while(ss >> proj_tmp){ projs.push_back(proj_tmp); } for(int j = 0; j < n_choices; j++){ prefs[n_projetos*i+projs[j]] = pow(n_choices-j,2); } } vector<int> aluno_projeto_vector; //preenche aluno_projeto em ordem 0,0,0,1,1,1,2,2,2... for(int i=0; i<iterations; i++){ vector<int> vagas(n_projetos,3); for (int proj = 0; proj < vagas.size(); proj++){ while(vagas[proj]>0){ aluno_projeto_vector.push_back(proj); vagas[proj] -=1; } } } thrust::uniform_int_distribution<int> dist(0,n_alunos-1); //Fazer um vetor gigante com varios vetores aleatorios contidos dentro dele //Passar esse vetor gigante no lugar deste "dist" abaixo thrust::host_vector<int> aluno_projeto_cpu(aluno_projeto_vector); thrust::host_vector<int> satisfacao_atual_cpu(iterations,-1); thrust::device_vector<int> satisfacao_atual_gpu(satisfacao_atual_cpu); thrust::device_vector<int> aluno_projeto_gpu(aluno_projeto_cpu); thrust::device_vector<int> prefs_gpu(prefs); escolhe_alunos calc_satisfac(thrust::raw_pointer_cast(prefs_gpu.data()), thrust::raw_pointer_cast(aluno_projeto_gpu.data()), n_alunos, n_projetos, seed, dist); thrust::counting_iterator<int> iterator(0); thrust::transform(iterator, iterator+(iterations), satisfacao_atual_gpu.begin(), calc_satisfac); int index = 0; int best_index = 0; int best_result = 0; for (auto m = satisfacao_atual_gpu.begin(); m != satisfacao_atual_gpu.end(); m++){ if(*m > best_result){ best_result = *m; best_index = index; } index++; } cout << best_result << " 0\n"; for (int m = best_index*n_alunos; m < (best_index+1)*n_alunos; m++){ cout << aluno_projeto_gpu[m] << " "; } cout << "\n"; }
5,814
#include <stdio.h> #include <sys/time.h> __global__ void flops(int n, float c, float *x, float *y){ int i = blockIdx.x*blockDim.x + threadIdx.x; if(c==2.0f){ if (i < n) y[i] = c*x[i] + y[i]; }else{ if (i<n){}; } } __global__ void iops(int n, int c, int *a, int *b){ int i = blockIdx.x*blockDim.x + threadIdx.x; if (i < n) b[i] = c*a[i] + b[i]; } double read_timer(){ struct timeval start; gettimeofday( &start, NULL ); return (double)((start.tv_sec) + 1.0e-6 * (start.tv_usec))*1000; } int main(void){ printf("\n\nYou are executing the GPU Benchmarking\n\n"); int N = 20*(1<<20); float *x, *y, *dev_x, *dev_y; int *a, *b, *dev_a, *dev_b; x = (float*)malloc(N*sizeof(float)); y = (float*)malloc(N*sizeof(float)); a = (int*)malloc(N*sizeof(int)); b = (int*)malloc(N*sizeof(int)); cudaMalloc(&dev_x, N*sizeof(float)); cudaMalloc(&dev_y, N*sizeof(float)); cudaMalloc(&dev_a, N*sizeof(int)); cudaMalloc(&dev_b, N*sizeof(int)); for (int i = 0; i < N; i++) { x[i] = 1.0f; y[i] = 2.0f; a[i] = 1; b[i] = 2; } cudaMemcpy(dev_x, x, N*sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(dev_y, y, N*sizeof(float), cudaMemcpyHostToDevice); double b1=read_timer(); flops<<<(N+447)/448,448>>>(N, 2.0f, dev_x, dev_y); double e1=read_timer(); cudaMemcpy(y, dev_y, N*sizeof(float), cudaMemcpyDeviceToHost); double t1 = e1-b1; double b2=read_timer(); flops<<<(N+447)/448,448>>>(N, 1.0f, dev_x, dev_y); double e2=read_timer(); double t2 = e2-b2; double tf = t1 - t2; // 2 = flops per kernel (add and mult) printf("GFLOPS/s: %f \n", (2*N)/(tf*1e6)); cudaMemcpy(dev_a, a, N*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(dev_b, b, N*sizeof(int), cudaMemcpyHostToDevice); double b3=read_timer(); iops<<<(N+447)/448,448>>>(N, 2, dev_a, dev_b); double e3=read_timer(); cudaMemcpy(b, dev_b, N*sizeof(int), cudaMemcpyDeviceToHost); double t3=e3-b3; double ti = t3 - t2; // 2 = iops per kernel (add and mult) printf("GIOPS/s: %f \n", (2*N)/(ti*1e6)); cudaFree(dev_x); cudaFree(dev_y); cudaFree(dev_a); cudaFree(dev_b); }
5,815
#include <cuda_runtime.h> #include <stdio.h> #include <time.h> #include <stdlib.h> #include <sys/time.h> #define N 8388608 #define THREADS_PER_BLOCK 1024 //Kernel __global__ void add(int * A, int * B, int * C){ int thread = blockIdx.x*blockDim.x + threadIdx.x; C[thread] = A[thread] + B[thread]; } int main(){ struct timeval t1, t2; int *hA, *hB, *hC; //Host Arrays int *dA, *dB, *dC; //Device Arrays //Reserva de memoria Host hA = (int*)malloc(N*sizeof(int)); hB = (int*)malloc(N*sizeof(int)); hC = (int*)malloc(N*sizeof(int)); //Inicialización de vectores srand(time(NULL)); for (int i = 0; i < N; i++){ hA[i] = rand(); hB[i] = rand(); } //Reserva de memoria Device cudaMalloc((void **)&dA, N*sizeof(int)); cudaMalloc((void **)&dB, N*sizeof(int)); cudaMalloc((void **)&dC, N*sizeof(int)); //Copia de memoria Host->Device cudaMemcpy(dA, hA, N*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(dB, hB, N*sizeof(int), cudaMemcpyHostToDevice); int nblocks = N / THREADS_PER_BLOCK; gettimeofday(&t1, 0); //Función Kernel add<<<nblocks, THREADS_PER_BLOCK>>>(dA, dB, dC); cudaDeviceSynchronize(); gettimeofday(&t2, 0); //Copia de memoria Device->Host cudaMemcpy(hC, dC, N*sizeof(int), cudaMemcpyDeviceToHost); //Comprobación de errores bool error = false; for(int i = 0; i < N; i++){ if(hC[i] != hA[i] + hB[i]){ error = true; break; } } if(error) printf("La suma de vectores ha fallado.\n"); else printf("Suma de vectores correcta.\n"); double time = (1000000.0*(t2.tv_sec-t1.tv_sec) + t2.tv_usec-t1.tv_usec)/1000.0; printf("Tiempo: %f ms\n", time); //Liberar memoria Host y Device free(hA); free(hB); free(hC); cudaFree(dA); cudaFree(dB); cudaFree(dC); }
5,816
#include "includes.h" static unsigned int GRID_SIZE_N; static unsigned int GRID_SIZE_4N; static unsigned int MAX_STATE_VALUE; __global__ static void cudaPreTTGammaKernel(double *tipVector, double *l, double *r, double *umpX1, double *umpX2) { __shared__ volatile double ump[64]; const int tid = threadIdx.y * 4 + threadIdx.x; if (blockIdx.y == 0) { ump[tid] = tipVector[4 * blockIdx.x + threadIdx.x] * l[tid]; __syncthreads(); if (threadIdx.x <= 1) { ump[tid] += ump[tid + 2]; } __syncthreads(); if (threadIdx.x == 0) { ump[tid] += ump[tid + 1]; umpX1[blockIdx.x * 16 + threadIdx.y] = ump[tid]; } } else { ump[tid] = tipVector[4 * blockIdx.x + threadIdx.x] * r[tid]; __syncthreads(); if (threadIdx.x <= 1) { ump[tid] += ump[tid + 2]; } __syncthreads(); if (threadIdx.x == 0) { ump[tid] += ump[tid + 1]; umpX2[blockIdx.x * 16 + threadIdx.y] = ump[tid]; } } }
5,817
#include "includes.h" __global__ void computePositionParallel(float *agentsX, float *agentsY, float *destX, float *destY, float *destR, int n, int *reached) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n; i += stride) { // if there is no destination to go to if (destX[i] == -1 || destY[i] == -1) { continue; } // compute and update next position double diffX = destX[i] - agentsX[i]; double diffY = destY[i] - agentsY[i]; double length = sqrtf(diffX * diffX + diffY * diffY); agentsX[i] = (float)llrintf(agentsX[i] + diffX / length); agentsY[i] = (float)llrintf(agentsY[i] + diffY / length); // check if next position is inside the destination radius diffX = destX[i] - agentsX[i]; diffY = destY[i] - agentsY[i]; length = sqrtf(diffX * diffX + diffY * diffY); if (length < destR[i]) { reached[i] = 1; } } }
5,818
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <complex.h> #include <math.h> #include <sys/mman.h> #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) #define cuda_check(ret) _cuda_check((ret), __FILE__, __LINE__) inline void _cuda_check(cudaError_t ret, const char *file, int line) { if (ret != cudaSuccess) { fprintf(stderr, "CudaErr: %s (%s:%d)\n", cudaGetErrorString(ret), file, line); exit(1); } } void read_image(char **Input, size_t *width, size_t *height, size_t *max, unsigned char **pixels) { FILE *input_fd = fopen(*Input, "r+"); if (!input_fd) { fprintf(stderr, "file does not exist"); exit(1); } fseek(input_fd, 3, SEEK_CUR); //skip P5\n //printf("current line pos: %lu\n", ftell(input_fd)); char c; if (fscanf(input_fd, " %lu %lu %lu%c", width, height, max, &c) != 4) { fprintf(stderr, "Info reading error\n"); exit(1); } //printf("current line pos: %lu\n", ftell(input_fd)); // fprintf(stdout, "width %lu, height %lu, max %lu, c%d\n", *width, *height, *max, c == '\n'); //read the image into memory *pixels = (unsigned char*)calloc((*width) * (*height), sizeof(unsigned char)); if (fread(*pixels, sizeof(unsigned char), (*width) * (*height), input_fd) != (*width) * (*height)) { fprintf(stderr, "Image reading error\n"); exit(1); } fclose(input_fd); } // Write pgm format void write_image(unsigned char *g_map, size_t width, size_t height, size_t max, char *Output) { char *info = (char*)calloc(100, sizeof(char)); sprintf(info, "P5\n%lu %lu\n%lu\n", width, height, max); FILE *output_fd = fopen(Output, "w"); fwrite(info, sizeof(char), strlen(info), output_fd); fwrite(g_map, sizeof(unsigned char), width * height, output_fd); fprintf(output_fd, "\n"); fclose(output_fd); } float *gaussian_blur_matrix(size_t order, size_t sigma) { float *matrix = (float*)calloc(order * order, sizeof(float)); size_t x_0, y_0; x_0 = order / 2; y_0 = x_0; for (size_t y = 0; y < order; y++) { for (size_t x = 0; x < order; x++) { float x_dis = (float)x_0 - (float)x; float y_dis = (float)y_0 - (float)y; //printf("x_dis %f 7_dis %f\n", x_dis, y_dis); matrix[y * order + x] = expf((-1) * (x_dis * x_dis + y_dis * y_dis) / (2 * sigma * sigma)); } } return matrix; } //__shared__ width, height, order __device__ float blur_kernel_old(unsigned char* pixels, long width, long height, long x, long y, long order, float* mat){ long start_x = x - order / 2; long start_y = y - order / 2; long curr_x, curr_y; float val = 0; for (long j = 0; j < order; j++) { curr_y = start_y + j; for (long i = 0; i < order; i++) { curr_x = start_x + i; if ((curr_x < 0 || curr_x >= width) && (curr_y < 0 || curr_y >= height)) { if (curr_x < 0) curr_x = 0; else if (curr_x >= width) curr_x = width - 1; if (curr_y < 0) curr_y = 0; else if (curr_y >= height) curr_y = height - 1; } else if (curr_x < 0 || curr_x >= width) { if (curr_x < 0) curr_x = 0; else if (curr_x >= width) curr_x = width - 1; } else if (curr_y < 0 || curr_y >= height) { if (curr_y < 0) curr_y = 0; else if (curr_y >= height) curr_y = height - 1; } val += pixels[curr_y * width + curr_x] * mat[j * order + i]; } } return val; } __device__ float blur_kernel(unsigned char* pixels, long width, long height, long x, long y, long order, float* mat, float k){ long start_x = x - order / 2; long start_y = y - order / 2; long curr_x, curr_y; float val = 0; for (long j = 0; j < order; j++) { curr_y = start_y + j; if (curr_y < 0) curr_y = 0; else if (curr_y >= height) curr_y = height - 1; long pixel_row = curr_y * width; long mat_row = j * order; for (long i = 0; i < order; i++) { curr_x = start_x + i; if (curr_x < 0) curr_x = 0; else if (curr_x >= width) curr_x = width - 1; val += pixels[pixel_row + curr_x] * mat[mat_row + i]; } } val /= k; return val; } __global__ void gaussian_blur_kernel_old(unsigned char *pixels, float *mat, unsigned char *output, long width, long height, float max, long order, float k) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; // printf("row %d, col %d\n" row, col); // Discard out of bound coordinates if(row >= height || col >= width) return; //switched row and col float val = blur_kernel(pixels, width, height, col, row, order, mat, k); output[row * width + col] = (unsigned char)(val); } __global__ void gaussian_blur_kernel(unsigned char *pixels, float *mat, unsigned char *output, long width, long height, float max, long order, float k) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; // Discard out of bound coordinates if(row >= height || col >= width) return; long start_y = row - order / 2; long start_x = col - order / 2; long curr_x, curr_y; float val = 0; for (long j = 0; j < order; j++) { curr_y = start_y + j; if (curr_y < 0) curr_y = 0; else if (curr_y >= height) curr_y = height - 1; long pixel_row = curr_y * width; long mat_row = j * order; for (long i = 0; i < order; i++) { curr_x = start_x + i; if (curr_x < 0) curr_x = 0; else if (curr_x >= width) curr_x = width - 1; val += pixels[pixel_row + curr_x] * mat[mat_row + i]; } } val /= k; output[row * width + col] = (unsigned char)(val); } unsigned char *gaussian_blur_apply_cuda(unsigned char *pixels, long width, long height, float sigma, float max) { // long order = (sigma * 6 % 2) == 0 ? sigma * 6 + 1 : sigma * 6; unsigned char *out_pixels_device, *out_pixels, *pixels_device; float *mat_device; //new long order = (long)(ceilf(sigma * 6)); order = order % 2 == 0 ? order + 1 : order; // printf("order: %long\n", order); // Allocate needed matrices locally float *mat = gaussian_blur_matrix(order, sigma); //__shared__ out_pixels = (unsigned char*)calloc(width * height, sizeof(unsigned char)); //new float k = (2 * M_PI * sigma * sigma); int image_size = width * height * sizeof(unsigned char); // allocate memory on device for needed matrices cuda_check(cudaMalloc(&out_pixels_device, image_size)); cuda_check(cudaMalloc(&pixels_device, image_size)); cuda_check(cudaMalloc(&mat_device, order * order * sizeof(float))); // Copy data onto device cuda_check(cudaMemcpy(pixels_device, pixels, image_size, cudaMemcpyHostToDevice)); cuda_check(cudaMemcpy(mat_device, mat, order * order * sizeof(float), cudaMemcpyHostToDevice)); //Invoke kernel function dim3 block_dim(32, 32); dim3 grid_dim(DIV_ROUND_UP(width, block_dim.x), DIV_ROUND_UP(height, block_dim.y)); // Catch errors gaussian_blur_kernel_old<<<grid_dim, block_dim>>>(pixels_device, mat_device, out_pixels_device, width, height, max, order, k); cuda_check(cudaPeekAtLastError()); /* Catch configuration errors */ cuda_check(cudaDeviceSynchronize()); /* Catch execution errors */ // Copy output from device back to host cuda_check(cudaMemcpy(out_pixels, out_pixels_device, image_size, cudaMemcpyDeviceToHost)); // Free memory on device cuda_check(cudaFree(out_pixels_device)); cuda_check(cudaFree(mat_device)); cuda_check(cudaFree(pixels_device)); // unsigned char *out_pixels = calloc(width * height, sizeof(unsigned char)); free(mat); return out_pixels; } int main(int argc, char *argv[]) { char *Input = (char*)calloc(100, sizeof(char)); unsigned char *pixels = NULL; unsigned char *out_pixels = NULL; char *Output = (char*)calloc(100, sizeof(char)); float sigma; size_t width, height, max; if (argc != 4) { fprintf(stderr, "Usage: ./mandelbrot_serial order xcenter ycenter zoom cutoff\n"); exit(1); } sscanf(argv[1], " %s", Input); sscanf(argv[2], " %s ", Output); sscanf(argv[3], " %f ", &sigma); //fprintf(stdout, "%s %s %lu\n", Input, Output, sigma); //read in original image read_image(&Input, &width, &height, &max, &pixels); //gaussian_blur the image out_pixels = gaussian_blur_apply_cuda(pixels, (long)width, (long)height, sigma, (float)max); //write out the final image write_image(out_pixels, width, height, max, Output); //writes the unprocessed image free(Input); free(Output); free(pixels); return 0; }
5,819
#include "includes.h" __global__ void KerFtCalcForcesRes(unsigned ftcount,bool simulate2d,double dt ,const float3 *ftoomega,const float3 *ftovel,const double3 *ftocenter,const float3 *ftoforces ,float3 *ftoforcesres,double3 *ftocenterres) { const unsigned cf=blockIdx.x*blockDim.x + threadIdx.x; //-Floating number. if(cf<ftcount){ //-Compute fomega. float3 fomega=ftoomega[cf]; { const float3 omegaace=ftoforces[cf*2+1]; fomega.x=float(dt*omegaace.x+fomega.x); fomega.y=float(dt*omegaace.y+fomega.y); fomega.z=float(dt*omegaace.z+fomega.z); } float3 fvel=ftovel[cf]; //-Zero components for 2-D simulation. | Anula componentes para 2D. float3 face=ftoforces[cf*2]; if(simulate2d){ face.y=0; fomega.x=0; fomega.z=0; fvel.y=0; } //-Compute fcenter. double3 fcenter=ftocenter[cf]; fcenter.x+=dt*fvel.x; fcenter.y+=dt*fvel.y; fcenter.z+=dt*fvel.z; //-Compute fvel. fvel.x=float(dt*face.x+fvel.x); fvel.y=float(dt*face.y+fvel.y); fvel.z=float(dt*face.z+fvel.z); //-Store data to update floating. | Guarda datos para actualizar floatings. ftoforcesres[cf*2]=fomega; ftoforcesres[cf*2+1]=fvel; ftocenterres[cf]=fcenter; } }
5,820
#include "includes.h" __global__ void ResetLayerKernel( float *layer, float value, int count ) { 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 < count) { layer[threadId] = value; } }
5,821
#include "shape.cuh" Shape::Shape(size_t x, size_t y) { this->x = x; this->y = y; } std::ostream& operator<< (std::ostream& o, const Shape& shape) { o << "["<< shape.x << ", "<< shape.y << "]"; return o; }
5,822
#include <stdio.h> # define N 500 __global__ void sum(float *array, float *sum){ for(int i=0; i<N; i++){ *sum += *(array + i); } } int main(){ float *array, *summation, avg; float *a, summation_host = 0.0f; int size = sizeof(float); for(int i=0; i < N; i++){ *(a + i) = i * 2.0f; } cudaMalloc(&array, N*size); cudaMalloc(&summation, size); cudaMemcpy(array, &a, N*size, cudaMemcpyHostToDevice); cudaMemcpy(summation, &summation_host, size, cudaMemcpyHostToDevice); sum<<<1, 10>>>(array, summation); cudaDeviceSynchronize(); cudaMemcpy(&summation_host, summation, sizeof(float), cudaMemcpyDeviceToHost); avg = summation_host / N; cudaFree(array); cudaFree(summation); printf("avg is: %f", avg); return 0; }
5,823
#include <stdio.h> #include <assert.h> #include <cuda_runtime.h> __global__ void testKernel() { printf("\n I am thread %d", threadIdx.x); } int main(int argc, char **argv) { testKernel<<<1, 1>>>(); cudaDeviceSynchronize(); return EXIT_SUCCESS; }
5,824
// Number of threads per block. #define NT 1024 // Overall counter variable in global memory. __device__ unsigned long long int devCount; // Per-thread counter variables in shared memory. __shared__ unsigned long long int shrCount [NT]; //Kernel function to compute the Totient value. It just takes the number on which the //totient should be computed and computes the totient for the current thread number + //size of the totals threads the GPU can create. extern "C" __global__ void ComputeTotient(unsigned long long int N){ //Variable declarations int thr, size, rank; unsigned long long int count=0, b, temp, a; //Rank and size computations thr = threadIdx.x; size = gridDim.x*NT; rank = blockIdx.x*NT + thr; //loop to compute the totient for current thread rank for (unsigned long long int x = rank; x < N; x += size){ a=x; b=N; while (b > 0){ temp = b; b = a % b; a = temp; } if(a==1) ++count; } // assigning the counter value to the shared memory variable shrCount[thr] = count; __syncthreads(); //reduction of the shared variables in parallel for (int i = NT/2; i > 0; i >>= 1){ if (thr < i) shrCount[thr] += shrCount[thr+i]; __syncthreads(); } // Adding the total of each block to global variable if (thr == 0) atomicAdd (&devCount, shrCount[0]); }
5,825
#include <stdio.h> // error checking macro #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) const size_t DSIZE = 16384; // matrix side dimension const int block_size = 256; // CUDA maximum is 1024 // matrix row-sum kernel // we will assign one block per row __global__ void row_sums(const float *A, float *sums, size_t ds){ int idx = blockIdx.x; // our block index becomes our row indicator if (idx < ds){ __shared__ float sdata[block_size]; int tid = threadIdx.x; sdata[tid] = 0.0f; size_t tidx = tid; while (tidx < ds) { // block stride loop to load data sdata[tid] += A[idx*ds+tidx]; tidx += blockDim.x; } for (unsigned int s=blockDim.x/2; s>0; s>>=1) { __syncthreads(); if (tid < s) // parallel sweep reduction sdata[tid] += sdata[tid + s]; } if (tid == 0) sums[idx] = sdata[0]; } } // matrix column-sum kernel __global__ void column_sums(const float *A, float *sums, size_t ds){ int idx = threadIdx.x+blockDim.x*blockIdx.x; // create typical 1D thread index from built-in variables if (idx < ds){ float sum = 0.0f; for (size_t i = 0; i < ds; i++) sum += A[idx+ds*i]; // write a for loop that will cause the thread to iterate down a column, keeeping a running sum, and write the result to sums sums[idx] = sum; }} bool validate(float *data, size_t sz){ for (size_t i = 0; i < sz; i++) if (data[i] != (float)sz) {printf("results mismatch at %lu, was: %f, should be: %f\n", i, data[i], (float)sz); return false;} return true; } int main(){ float *h_A, *h_sums, *d_A, *d_sums; h_A = new float[DSIZE*DSIZE]; // allocate space for data in host memory h_sums = new float[DSIZE](); for (int i = 0; i < DSIZE*DSIZE; i++) // initialize matrix in host memory h_A[i] = 1.0f; cudaMalloc(&d_A, DSIZE*DSIZE*sizeof(float)); // allocate device space for A cudaMalloc(&d_sums, DSIZE*sizeof(float)); // allocate device space for vector d_sums cudaCheckErrors("cudaMalloc failure"); // error checking // copy matrix A to device: cudaMemcpy(d_A, h_A, DSIZE*DSIZE*sizeof(float), cudaMemcpyHostToDevice); cudaCheckErrors("cudaMemcpy H2D failure"); //cuda processing sequence step 1 is complete row_sums<<<DSIZE, block_size>>>(d_A, d_sums, DSIZE); cudaCheckErrors("kernel launch failure"); //cuda processing sequence step 2 is complete // copy vector sums from device to host: cudaMemcpy(h_sums, d_sums, DSIZE*sizeof(float), cudaMemcpyDeviceToHost); //cuda processing sequence step 3 is complete cudaCheckErrors("kernel execution failure or cudaMemcpy H2D failure"); if (!validate(h_sums, DSIZE)) return -1; printf("row sums correct!\n"); cudaMemset(d_sums, 0, DSIZE*sizeof(float)); column_sums<<<(DSIZE+block_size-1)/block_size, block_size>>>(d_A, d_sums, DSIZE); cudaCheckErrors("kernel launch failure"); //cuda processing sequence step 2 is complete // copy vector sums from device to host: cudaMemcpy(h_sums, d_sums, DSIZE*sizeof(float), cudaMemcpyDeviceToHost); //cuda processing sequence step 3 is complete cudaCheckErrors("kernel execution failure or cudaMemcpy H2D failure"); if (!validate(h_sums, DSIZE)) return -1; printf("column sums correct!\n"); return 0; }
5,826
#include<iostream> #include<math.h> __global__ void add(int n, float *x, float *y){ for(int i=0; i<n; i++){ y[i]=x[i]+y[i]; } } int main(){ int N = 1<<20; float *x, *y; // Allocate Unified Memory – accessible from CPU or GPU cudaMallocManaged(&x, N*sizeof(float)); cudaMallocManaged(&y, N*sizeof(float)); // initialize x and y arrays on the host for (int i = 0; i < N; i++) { x[i] = 1.0f; y[i] = 2.0f; } add<<<1,1>>>(N,x,y); cudaDeviceSynchronize(); float maxError = 0.0f; for(int i=0; i<N; i++) maxError = fmax(maxError, fabs(y[i]-3.0f)); std::cout << "Max error: " << maxError << std::endl; // Free memory cudaFree(x); cudaFree(y); return 0; }
5,827
#include "includes.h" __global__ void InitLabelKernel (double *Label, double xp, double yp, double rhill, double *Rmed, int nrad, int nsec) { int j = threadIdx.x + blockDim.x*blockIdx.x; int i = threadIdx.y + blockDim.y*blockIdx.y; if (i<nrad && j<nsec){ double distance, angle, x, y; angle = (double)j / (double)nsec*2.0*PI; x = Rmed[i] * cos(angle); y = Rmed[i] * sin(angle); distance = sqrt((x - xp) * (x - xp) + (y - yp)*(y -yp)); if (distance < rhill) Label[i*nsec + j] = 1.0; else Label[i*nsec + j] = 0.0; } }
5,828
//nvcc -ptx EM6.cu -ccbin "F:Visual Studio\VC\Tools\MSVC\14.12.25827\bin\Hostx64\x64" __device__ void EM1( double *r, double *z, double * a, double * b, int * parDelete, const int parNum, const int gridR, const int gridZ, const double dr, const double dz) { int globalBlockIndex = blockIdx.x + blockIdx.y * gridDim.x; int localThreadIdx = threadIdx.x + blockDim.x * threadIdx.y; int threadsPerBlock = blockDim.x*blockDim.y; int n = localThreadIdx + globalBlockIndex*threadsPerBlock; if ( n >= parNum ){ return; } double r0 = r[n]; double z0 = z[n]; int ar,az,a1,a2,a3,a4; double b1,b2,b3,b4; ar = floor(r0/dr-0.5); az = floor(z0/dz-0.5); if (ar<0){ if (az<0){ a1 = 1; a2 = 1; a3 = 1; a4 = (ar+1) + (az+1) * gridR + 1; b1 = 0; b2 = 0; b3 = 0; b4 = 1; } else if (az>=gridZ-1){ a1 = 1; a2 = (ar+1) + az * gridR + 1; a3 = 1; a4 = 1; b1 = 0; b2 = 1; b3 = 0; b4 = 0; } else{ a1 = 1; a2 = (ar+1) + az * gridR + 1; a3 = 1; a4 = (ar+1) + (az+1) * gridR + 1; b1 = 0; b2 = ((az+1.5)*dz-z0)/(dz); b3 = 0; b4 = (z0-(az+0.5)*dz)/(dz); } } else if (ar>=gridR-1){ if( az<0 ){ a1 = 1; a2 = 1; a3 = ar + (az+1) * gridR + 1; a4 = 1; b1 = 0; b2 = 0; b3 = 1; b4 = 0; } else if (az>=gridZ-1){ a1 = ar + az * gridR + 1; a2 = 1; a3 = 1; a4 = 1; b1 = 1; b2 = 0; b3 = 0; b4 = 0; } else{ a1 = ar + az * gridR + 1; a2 = 1; a3 = ar + (az+1) * gridR + 1; a4 = 1; b1 = ((az+1.5)*dz-z0)/(dz); b2 = 0; b3 = (z0-(az+0.5)*dz)/(dz); b4 = 0; } } else{ if( az<0 ){ a1 = 1; a2 = 1; a3 = ar + (az+1) * gridR + 1; a4 = (ar+1) + (az+1) * gridR + 1; b1 = 0; b2 = 0; b3 = ((ar+1.5)*dr-r0)/(dr); b4 = (r0-(ar+0.5)*dr)/(dr); } else if (az>=gridZ-1){ a1 = ar + az * gridR + 1; a2 = (ar+1) + az * gridR + 1; a3 = 1; a4 = 1; b1 = ((ar+1.5)*dr-r0)/(dr); b2 = (r0-(ar+0.5)*dr)/(dr); b3 = 0; b4 = 0; } else{ a1 = ar + az * gridR + 1; a2 = (ar+1) + az * gridR + 1; a3 = ar + (az+1) * gridR + 1; a4 = (ar+1) + (az+1) * gridR + 1; b1 = ((ar+1.5)*dr-r0)*((az+1.5)*dz-z0)/(dr*dz); b2 = (r0-(ar+0.5)*dr)*((az+1.5)*dz-z0)/(dr*dz); b3 = ((ar+1.5)*dr-r0)*(z0-(az+0.5)*dz)/(dr*dz); b4 = (r0-(ar+0.5)*dr)*(z0-(az+0.5)*dz)/(dr*dz); } } if (parDelete[n]==1){ a1 = 1; a2 = 1; a3 = 1; a4 = 1; b1 = 0; b2 = 0; b3 = 0; b4 = 0; } a[n] = a1; a[n+parNum] = a2; a[n+2*parNum] = a3; a[n+3*parNum] = a4; b[n] = b1; b[n+parNum] = b2; b[n+2*parNum] = b3; b[n+3*parNum] = b4; } __global__ void processMandelbrotElement( double *r, double *z, double * a, double * b, int * parDelete, const int parNum, const int gridR, const int gridZ, const double dr, const double dz) { EM1(r, z, a, b, parDelete, parNum, gridR, gridZ, dr, dz); }
5,829
#define BLOCK_SIZE 512 __global__ void histogram_kernel( float* lats, float* lons, unsigned int* histo_d, unsigned int line_count, unsigned int histo_row_count, unsigned int histo_col_count, float lat_max, float lat_min, float lon_max, float lon_min) { //Dynamic Shared Memory extern __shared__ unsigned int histogram_private[]; unsigned int histo_size = histo_col_count * histo_row_count; //Initialize private hisogram int i = 0; while((blockDim.x * i + threadIdx.x) < histo_size) { histogram_private[blockDim.x * i + threadIdx.x] = 0.0f; i++; } __syncthreads(); //Compute the private histograms i = blockDim.x * blockIdx.x + threadIdx.x; while(i < line_count) { int col = (lats[i] - lat_min) * histo_col_count / (lat_max - lat_min); int row = (lons[i] - lon_min) * histo_row_count / (lon_max - lon_min); atomicAdd(&(histogram_private[row * histo_col_count + col]), 1); i += blockDim.x * gridDim.x; } __syncthreads(); //Compute the global histogram i = 0; while((blockDim.x * i + threadIdx.x) < histo_size) { atomicAdd(&(histo_d[blockDim.x * i + threadIdx.x]), histogram_private[blockDim.x * i + threadIdx.x]); i++; } } void histogram(float* lats, float* lons, unsigned int* histo_d, unsigned int line_count, unsigned int histo_row_count, unsigned int histo_col_count, float lat_max, float lat_min, float lon_max, float lon_min) { int MAX_GRID_SIZE = 12; int GRID_SIZE = ((line_count - 1) / BLOCK_SIZE) + 1; GRID_SIZE = GRID_SIZE > MAX_GRID_SIZE ? MAX_GRID_SIZE : GRID_SIZE; dim3 DimGrid(GRID_SIZE, 1, 1); dim3 DimBlock(BLOCK_SIZE, 1, 1); histogram_kernel<<<DimGrid, DimBlock, histo_col_count * histo_row_count * sizeof(unsigned int)>>>( lats, lons, histo_d, line_count, histo_row_count, histo_col_count, lat_max, lat_min, lon_max, lon_min); }
5,830
/*************************************************** * Module that negs all the elements on a matrix * Author: Alonso Vidales <alonso.vidales@tras2.es> * * To be compiled with nvcc -ptx matrix_remove_bias_top.cu * Debug: nvcc -arch=sm_20 -ptx matrix_remove_bias_top.cu * **************************************************/ //#include <stdio.h> #ifdef __cplusplus extern "C" { #endif // CUDA Kernel __global__ void matrixRemoveBiasTop(double* C, double* A, int width, int resW, int resH, int resultSize) { int x = threadIdx.x + (blockIdx.x * resW); int y = threadIdx.y + (blockIdx.y * resH); int resultPos = y * width + x; if (resultPos < resultSize && x < width) { C[resultPos] = A[resultPos + width]; } } #ifdef __cplusplus } #endif
5,831
//#include "cuda_runtime.h" //#include "device_launch_parameters.h" // //#include <iostream> // //#ifndef MAX_MASK_WIDTH //#define MAX_MASK_WIDTH 10 //__constant__ float MASK[MAX_MASK_WIDTH]; //#endif ////this kernel is example for unefficent memory access. ////this implementation considers only 1D grid. and assumes that mask width is odd number ////We are going to use constant memory to store the mask //__global__ void convolution_1d_dram_and_constant(float * input, float* output, int array_lenght, int mask_width) //{ // int thread_index = blockIdx.x*blockDim.x + threadIdx.x; // float temp_value = 0; // // int offset = thread_index - mask_width / 2; // for (int i = 0; i < mask_width; i++) // { // if ((offset + i) >= 0 && (offset + i) < array_lenght) // { // temp_value += input[offset + i] * MASK[i]; // } // } // // output[thread_index] = temp_value; //} // //void run_code_convolution_2() //{ // int array_lenght = 128 * 2; // int mask_width = 5; // // int array_byte_size = sizeof(float)*array_lenght; // int mask_byte_size = sizeof(float)*mask_width; // // float *h_input_array, *h_mask, *h_output; // float *d_input_array, *d_output; // // //host memory allocation // h_input_array = (float*)malloc(array_byte_size); // h_output = (float*)malloc(array_byte_size); // h_mask = (float*)malloc(mask_byte_size); // // //initialize array // for (int i = 0; i < array_lenght; i++) // { // h_input_array[i] = 1.0f; // } // // //initialize mask // for (int i = 0; i < mask_width; i++) // { // h_mask[i] = 1.0f; // } // // dim3 grid(32); // dim3 block((array_lenght) / grid.x); // // //device memory allocation // cudaMalloc((float**)&d_input_array, array_byte_size); // cudaMalloc((float**)&d_output, array_byte_size); // // //transfer the initiazed arrays to device // cudaMemcpy(d_input_array, h_input_array, array_byte_size, cudaMemcpyHostToDevice); // cudaMemcpyToSymbol(MASK, h_mask, mask_byte_size); // // //kernel launch // convolution_1d_dram_and_constant << <grid, block >> > (d_input_array, d_output, array_lenght, mask_width); // //test_kernel << <grid,block >>> (d_input_array); // cudaDeviceSynchronize(); // // //copy the output back to the host // cudaMemcpy(h_output, d_output, array_byte_size, cudaMemcpyDeviceToHost); // // //free the device memory // cudaFree(d_input_array); // cudaFree(d_output); // // //free the host memory // free(h_input_array); // free(h_output); // free(h_mask); //} // ////int main() ////{ //// run_code_convolution_2(); //// system("pause"); //// return 0; ////}
5,832
//xfail:REPAIR_ERROR //--gridDim=1 --blockDim=2 --no-inline //This kernel is racy. // //It uses uses struct-assignment, which is translated into a memcpy by clang and //dealt with as a series of reads/writes by bugle. typedef struct { short x; short y; } pair_t; __global__ void k(pair_t *pairs) { pair_t fresh; pairs[42] = fresh; }
5,833
#include <iostream> #include <cuda.h> #include <cuda_runtime.h> using namespace std; // #define N 10 __global__ void addPair(int *dev_vec, int *N) { int index = 2 * threadIdx.x; if (index + 1 < *N) { int sum = dev_vec[index] + dev_vec[index + 1]; // cout << "A[" << index << "] + A[" << index + 1 << "] = " << sum << endl; printf("A[%d] + A[%d] = %d\n", index, index + 1, sum ); } } int main() { int *vec, *dev_vec, *n_c, N = 10; int size = N * sizeof(int); vec = (int*)malloc(size); cout << "Enter 10 elements"; for(int i = 0; i < N; i++) { cin >> vec[i]; } cudaMalloc(&dev_vec, size); cudaMalloc(&n_c, sizeof(int)); cudaMemcpy(dev_vec, vec, size, cudaMemcpyHostToDevice); cudaMemcpy(n_c, &N, sizeof(int), cudaMemcpyHostToDevice); addPair<<<5,2>>>(dev_vec, n_c); cudaMemcpy(vec, dev_vec, size, cudaMemcpyDeviceToHost); cudaDeviceSynchronize(); return 0; }
5,834
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cuda.h> #define INFTY 99999 int **A_Matrix, **D_Matrix; __global__ void floyd_warshall_parallel_kernel(int* dev_dist, int N, int k) {\ int tid = (blockIdx.y * gridDim.x + blockIdx.x) * blockDim.x + threadIdx.x; int i, j; int dist1, dist2, dist3; if (tid < N*N) { i = tid / N; j = tid - i*N; dist1 = dev_dist[tid]; dist2 = dev_dist[i*N +k]; dist3 = dev_dist[k*N +j]; if (dist1 > dist2 + dist3) dev_dist[tid] = dist2 + dist3; } } void makeAdjacency(int n){ //Set initial values to node distances int N=n; int i,j; A_Matrix = (int **)malloc(N * sizeof(int *)); for (i = 0; i < N; i++) { A_Matrix[i] = (int *)malloc(N * sizeof(int)); } srand(0); for(i = 0; i < N; i++) { for(j = i; j < N; j++) { if(i == j){ A_Matrix[i][j] = 0; } else{ int r = rand() % 10; int val = (r == 5)? INFTY: r; A_Matrix[i][j] = val; A_Matrix[j][i] = val; } } } } int main(int argc, char **argv){ int N; N = atoi(argv[1]); //Read the console inputs int i; D_Matrix = (int **)malloc(N * sizeof(int *)); for (i = 0; i < N; i++) { D_Matrix[i] = (int *)malloc(N * sizeof(int)); } makeAdjacency(N); int gridx = pow(2, N - 4), gridy = pow(2, N - 4); int blockx = pow(2, 4), blocky = pow(2, 4); dim3 dimGrid(gridx, gridy); dim3 dimBlock(blockx, blocky); int* device_dist; cudaMalloc( (void**)&device_dist, N*N * sizeof (int) ); for (int i = 0; i < N; i++) cudaMemcpy(device_dist +i*N, A_Matrix[i], N * sizeof (int), cudaMemcpyHostToDevice); clock_t start = clock(); for (int k = 0; k < N; k++) { floyd_warshall_parallel_kernel<<<dimGrid,dimBlock>>>(device_dist,N,k); } clock_t end = clock(); float seconds = (float)(end - start) / CLOCKS_PER_SEC; printf("Elapsed time on gpu = %f sec\n", seconds); // return results to dist matrix on host for (int i = 0; i < N; i++) cudaMemcpy(D_Matrix[i], device_dist +i*N, N * sizeof (int), cudaMemcpyDeviceToHost); }
5,835
#include <stdio.h> #include <stdlib.h> #define SIZE 10 __global__ void Multiply(float *A, float *B , float * C){ //compute thread's row int row = blockIdx.y * blockDim.y + threadIdx.y; //compute thread's column int col = blockIdx.x * blockDim.x + threadIdx.x; float s = 0; for(int i = 0; i < SIZE; i++){ s+= A[row*SIZE + i] * B[i*SIZE+col]; } C[row*SIZE+col] = s; // assign result back to C } int main(){ float A[SIZE*SIZE]; float B[SIZE*SIZE]; float C[SIZE*SIZE]; cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); float * d_A, * d_B, *d_C; int BLOCKSIZE; printf("Choose block size : "); scanf("%d",&BLOCKSIZE); int GRIDSIZE = int(4096/BLOCKSIZE); dim3 dimBlock(BLOCKSIZE,BLOCKSIZE); // 20 dim3 dimGrid(GRIDSIZE,GRIDSIZE); size_t size = SIZE*SIZE*sizeof(float); for(int i = 0; i < SIZE; i++){ for(int j = 0; j < SIZE; j++){ A[i*SIZE+j] = rand()%10; B[i*SIZE+j] = rand()%10; C[i*SIZE+j] = 0; } // 30 } cudaEventRecord(start); 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); cudaMemcpy(d_C,C,size,cudaMemcpyHostToDevice); Multiply<<<dimGrid,dimBlock>>>(d_A, d_B,d_C); cudaEventRecord(stop); cudaMemcpy(C, d_C, size, cudaMemcpyDeviceToHost); cudaEventSynchronize(stop); float elapsed = 0; cudaEventElapsedTime(&elapsed, start, stop); printf("Using Grid Size [%d, %d] and Block Size [%d, %d]..\n", dimGrid.x, dimGrid.y,dimBlock.x, dimBlock.y); printf("Execution time : %f miliseconds\n", elapsed); cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); }
5,836
#include "includes.h" __global__ void tonemap( float* d_x, float* d_y, float* d_log_Y, float* d_cdf_norm, float* d_r_new, float* d_g_new, float* d_b_new, float min_log_Y, float max_log_Y, float log_Y_range, int num_bins, int num_pixels_y, int num_pixels_x ) { int ny = num_pixels_y; int nx = num_pixels_x; int2 image_index_2d = make_int2( ( blockIdx.x * blockDim.x ) + threadIdx.x, ( blockIdx.y * blockDim.y ) + threadIdx.y ); int image_index_1d = ( nx * image_index_2d.y ) + image_index_2d.x; if ( image_index_2d.x < nx && image_index_2d.y < ny ) { float x = d_x[ image_index_1d ]; float y = d_y[ image_index_1d ]; float log_Y = d_log_Y[ image_index_1d ]; int bin_index = min( num_bins - 1, int( (num_bins * ( log_Y - min_log_Y ) ) / log_Y_range ) ); float Y_new = d_cdf_norm[ bin_index ]; float X_new = x * ( Y_new / y ); float Z_new = ( 1 - x - y ) * ( Y_new / y ); float r_new = ( X_new * 3.2406f ) + ( Y_new * -1.5372f ) + ( Z_new * -0.4986f ); float g_new = ( X_new * -0.9689f ) + ( Y_new * 1.8758f ) + ( Z_new * 0.0415f ); float b_new = ( X_new * 0.0557f ) + ( Y_new * -0.2040f ) + ( Z_new * 1.0570f ); d_r_new[ image_index_1d ] = r_new; d_g_new[ image_index_1d ] = g_new; d_b_new[ image_index_1d ] = b_new; } }
5,837
#include <cstdio> void initialize(float* polynomial, const size_t N) { for (size_t i = 0; i < N; ++i) polynomial[i] = static_cast<float>(i); } __global__ void kernel(float* polynomial, const size_t N) { int thread = blockIdx.x * blockDim.x + threadIdx.x; if (thread < N) { float x = polynomial[thread]; polynomial[thread] = 3 * x * x - 7 * x + 5; } } int main(int argc, char** argv) { const size_t BLOCK_DIM = 128; const size_t N_STREAMS = 4; // Number of elements in the arrays size_t n_elem = 1u << 27u; size_t n_bytes = n_elem * sizeof(float); // Allocating the array in pinned host memory for async memcpy float* h_polynomial; cudaHostAlloc(&h_polynomial, n_bytes, cudaHostAllocDefault); // Initializing data on host initialize(h_polynomial, n_elem); // Allocating the device array float* d_polynomial; cudaMalloc(&d_polynomial, n_bytes); // Number of elements per stream size_t n_elem_per_stream = n_elem / N_STREAMS; size_t n_bytes_per_stream = n_elem_per_stream * sizeof(float); // Events for time recording cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); // Grid and block dim3 block(BLOCK_DIM); dim3 grid((n_elem_per_stream + block.x - 1) / block.x); // Creating streams cudaStream_t* streams = new cudaStream_t[N_STREAMS]; for (size_t i = 0; i < N_STREAMS; ++i) cudaStreamCreate(&streams[i]); cudaEventRecord(start, 0); //------------------------------------------------------- Asynchronous work for (size_t i = 0; i < N_STREAMS; ++i) { size_t offset = i * n_elem_per_stream; cudaMemcpyAsync(&d_polynomial[offset], &h_polynomial[offset], n_bytes_per_stream, cudaMemcpyHostToDevice, streams[i]); kernel<<<grid, block>>>(d_polynomial + offset, n_elem_per_stream); cudaMemcpyAsync(&h_polynomial[offset], &d_polynomial[offset], n_bytes_per_stream, cudaMemcpyDeviceToHost, streams[i]); } //------------------------------------------------------------------------- cudaEventRecord(stop, 0); cudaEventSynchronize(stop); float time; cudaEventElapsedTime(&time, start, stop); printf("Elapsed time: %.5f\n", time); // Destroying events cudaEventDestroy(stop); cudaEventDestroy(start); // Freeing memory delete[] streams; cudaFree(d_polynomial); cudaFreeHost(h_polynomial); }
5,838
#include<stdio.h> #include<stdlib.h> #include<time.h> #define Width 4096 //Image Width and Height. # define Tile_Width 32 #define N (Width*Width) __global__ void Matrix_Multiplication(int *D_M, int *D_N, int *D_P) { int tx=blockIdx.x*Tile_Width+threadIdx.x; int ty=blockIdx.y*Tile_Width+threadIdx.y; int Sum=0; //int M,N; for(int k=0;k<Width;k++) { //int M=D_M[ty*Width+k]; //int N=D_N[k*Width+tx]; //Sum+=M*N; Sum+=D_M[ty*Width+k]*D_N[k*Width+tx]; } D_P[ty*Width+tx]=Sum; } int main(void) { int *H_M, *H_N, *H_P, *H_Y; int *D_M, *D_N, *D_P; int i,j,k; int a,b; int Sum; int Size=N*sizeof(int); clock_t Time_Start, Time_End, Time_Difference; // Clock used to measure time for CPU Matrix Multiplication execution. double Time; printf("This is a Square Matrix Multiplication Program! \n"); printf("\n"); printf("The Matrices are of Dimension %d\n",Width); printf("\n"); H_M=(int *)malloc(Size); H_N=(int *)malloc(Size); H_P=(int *)malloc(Size); H_Y=(int *)malloc(Size); cudaMalloc(&D_M,Size); cudaMalloc(&D_N,Size); cudaMalloc(&D_P,Size); printf("Initializing the M and N Matrices on Host... \n"); printf("\n"); for(i=0;i<Width;i++) for(j=0;j<Width;j++) { H_M[i*Width+j]=1; H_N[i*Width+j]=1; H_P[i*Width+j]=1; } printf ("CPU Executing Matrix Multiplication Kernel...\n") ; printf("\n"); Time_Start=clock(); // Start Time for CPU Multiplication Kernel for(i=0;i<Width;i++) for(j=0;j<Width;j++) { Sum=0; for(k=0;k<Width;k++) { a=H_M[i*Width+k]; b=H_N[k*Width+j]; Sum+=a*b; } H_P[i*Width+j]=Sum; } Time_End=clock(); Time_Difference=Time_End-Time_Start; Time=Time_Difference/(double)CLOCKS_PER_SEC ; printf("\n"); cudaEvent_t start, stop; // Cuda API to measure time for Cuda Kernel Execution. cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start); cudaMemcpy(D_M,H_M,Size,cudaMemcpyHostToDevice); // Copying Matrix M to GPU Memory. cudaMemcpy(D_N,H_N,Size,cudaMemcpyHostToDevice); // Copying Matrix N to GPU Memory. dim3 dimBlock(Tile_Width,Tile_Width); // Two Dimesional blocks with two dimensional threads. dim3 dimGrid(Width/Tile_Width,Width/Tile_Width); // 16*16=256, max number of threads per block is 512. printf ("GPU Executing Matrix Multiplication Kernel...\n") ; printf("\n"); Matrix_Multiplication<<<dimGrid,dimBlock>>>(D_M,D_N,D_P); // Kernel Launch configuration. cudaMemcpy(H_Y,D_P,Size,cudaMemcpyDeviceToHost); // Copying results back to Host Memory. cudaEventRecord(stop); cudaEventSynchronize(stop); float milliseconds = 0; cudaEventElapsedTime(&milliseconds, start, stop); /*for(i=0;i<Width;i++) { for(j=0;j<Width;j++) { printf("%d ",H_Y[i*Width+j]); } printf("\n"); }*/ printf("\n"); printf ("CPU time for Matrix Multiplication = %f ms\n", Time*1000) ; printf("GPU Execution Time for Convolution Kernel: %fn\n", milliseconds); //GPU Execution Time. printf("Effective Bandwidth (GB/s): %fn\n", N*4*2/milliseconds/1e6); printf("\n"); cudaFree(H_M); cudaFree(H_N); cudaFree(H_P); free(H_M); free(H_N); free(H_P); free(H_Y); }
5,839
#include "includes.h" __global__ void sum(const float *input, float *output, int numElements) { float val = 0.f; for (int i = 0; i < numElements; ++i) { val += input[i]; } *output = val; }
5,840
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { printf("Hola mundo\n"); return 0; }
5,841
#include "includes.h" __device__ float activationProbability(float x, float sigma) { return 1.0 / (1.0 + expf(-sigma * x)); } __global__ void RBMForwardAndStoreKernel( float *inputPtr, float *outputPtr, float *weightPtr, float *biasPtr, float *storedOutputPtr, float sigma, int prevLayerSize, int thisLayerSize, bool useDropout, float *dropoutMask ) { // i: prev. layer neuron id // j: current layer neuron id int i; int j = blockDim.x * blockIdx.y * gridDim.x //rows preceeding current row in grid + blockDim.x * blockIdx.x //blocks preceeding current block + threadIdx.x; if (j < thisLayerSize) { // dropout this neuron if (useDropout && !dropoutMask[j]) { outputPtr[j] = 0; storedOutputPtr[j] = 0; } else { float sum = 0.0; int index = j; for (i = 0; i < prevLayerSize; i++) { sum += weightPtr[index] * inputPtr[i]; index += thisLayerSize; } // add bias sum += biasPtr[j]; float result = activationProbability(sum, sigma); // set output value outputPtr[j] = result; // store output value storedOutputPtr[j] = result; } } }
5,842
#define d_vx(z,x) d_vx[(x)*(nz)+(z)] #define d_vy(z,x) d_vy[(x)*(nz)+(z)] #define d_vz(z,x) d_vz[(x)*(nz)+(z)] #define d_szz(z,x) d_szz[(x)*(nz)+(z)] // Pressure #define d_mem_dvz_dz(z,x) d_mem_dvz_dz[(x)*(nz)+(z)] #define d_mem_dvx_dx(z,x) d_mem_dvx_dx[(x)*(nz)+(z)] #define d_Lambda(z,x) d_Lambda[(x)*(nz)+(z)] #define d_Den(z,x) d_Den[(x)*(nz)+(z)] #define d_mat_dvz_dz(z,x) d_mat_dvz_dz[(x)*(nz)+(z)] #define d_mat_dvx_dx(z,x) d_mat_dvx_dx[(x)*(nz)+(z)] #define d_Cp(z,x) d_Cp[(x)*(nz)+(z)] #define d_CpGrad(z,x) d_CpGrad[(x)*(nz)+(z)] __global__ void image_vel(float *d_szz, \ int nz, int nx, float dt, float dz, float dx, int nPml, int nPad, \ float *d_Cp, float *d_Den, float *d_mat_dvz_dz, float *d_mat_dvx_dx, float * d_CpGrad){ int gidz = blockIdx.x*blockDim.x + threadIdx.x; int gidx = blockIdx.y*blockDim.y + threadIdx.y; if (gidz>=nPml && gidz<=nz-nPad-nPml-1 && gidx>=nPml && gidx<=nx-nPml-1) { // compute the Vp kernel on the fly d_CpGrad(gidz, gidx) += -2.0 * d_Cp(gidz, gidx) * d_Den(gidz, gidx) *\ (d_mat_dvz_dz(gidz, gidx) + d_mat_dvx_dx(gidz, gidx)) * d_szz(gidz, gidx) * dt; } else { return; } }
5,843
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #define error 1e-6 #define NUM_ITERATIONS 1000 #define NUM_PARTICLES 100000 #define BLOCK_SIZE 256 #define NSTREAMS 4 #define SIZE_BATCH struct particle { float position[3]; float velocity[3]; }; double cpuSecond() { struct timeval tp; gettimeofday(&tp,NULL); return ((double)tp.tv_sec + (double)tp.tv_usec*1.e-6); } __host__ __device__ void uptdateParticle(particle *particula, int iter, int id, int num_p){ //update the velocity: particula[id].velocity[0] = (3*id + iter) % num_p; particula[id].velocity[1] = (4*id + iter) % num_p; particula[id].velocity[2] = (5*id + iter) % num_p; //update the position: particula[id].position[0] = particula[id].position[0] + particula[id].velocity[0]; particula[id].position[1] = particula[id].position[1] + particula[id].velocity[1]; particula[id].position[2] = particula[id].position[2] + particula[id].velocity[2]; } __global__ void timeStep(particle *particles, int iter, int num_p, int offset, int s, int streamSize){ const int id = offset + threadIdx.x + blockIdx.x*blockDim.x; if(id < num_p && id < ((s+1)*streamSize)){ uptdateParticle(particles, iter, id, num_p); } } void init_Array(particle *particulas){ for(int i = 0; i < NUM_PARTICLES; i++){ particulas[i].position[0] = rand() % 1000; particulas[i].position[1] = rand() % 1000; particulas[i].position[2] = rand() % 1000; particulas[i].velocity[0] = rand() % 1000; particulas[i].velocity[1] = rand() % 1000; particulas[i].velocity[2] = rand() % 1000; } } int main( int argc, char *argv[]){ bool bien = true; double start_GPU, stop_GPU; double start_CPU, stop_CPU; double diferencia_CPU, diferencia_GPU; particle *particlesCPU = (particle*)malloc(NUM_PARTICLES * sizeof(particle)); particle *particlesGPU; particle *resCPU; cudaMallocHost(&resCPU, NUM_PARTICLES * sizeof(particle)); cudaMalloc(&particlesGPU, NUM_PARTICLES * sizeof(particle)); init_Array(particlesCPU); cudaMemcpy(resCPU, particlesCPU, NUM_PARTICLES*sizeof(particle), cudaMemcpyHostToHost); const int streamSize = NUM_PARTICLES / NSTREAMS; const int StreamBytes = streamSize * sizeof(particle); cudaStream_t stream[NSTREAMS]; for(int i = 0; i < NSTREAMS; i++){ cudaStreamCreate(&stream[i]); } int GRID = (streamSize + BLOCK_SIZE - 1)/BLOCK_SIZE; // CPU part// start_CPU = cpuSecond(); for(int i = 0; i < NUM_ITERATIONS; i++){ for(int j = 0; j < NUM_PARTICLES; j++){ uptdateParticle(particlesCPU, i, j, NUM_PARTICLES); } }; stop_CPU = cpuSecond(); diferencia_CPU = stop_CPU - start_CPU; // Finish CPU part //Start GPU part start_GPU = cpuSecond(); for(int s = 0; s < NSTREAMS; s++){ int offset = s * streamSize; cudaMemcpyAsync(&particlesGPU[offset], &resCPU[offset], StreamBytes, cudaMemcpyHostToDevice, stream[s]); for(int i = 0; i < NUM_ITERATIONS; i++){ timeStep<<<GRID, BLOCK_SIZE, 0, stream[s]>>>(particlesGPU, i, NUM_PARTICLES, offset, s, streamSize); } cudaMemcpyAsync(&resCPU[offset], &particlesGPU[offset], StreamBytes, cudaMemcpyDeviceToHost, stream[s]); cudaStreamSynchronize(stream[s]); } stop_GPU = cpuSecond(); diferencia_GPU = stop_GPU - start_GPU; for(int i = 0; i < NUM_PARTICLES && bien; i++){ for(int dim = 0; dim < 3; dim++){ if(fabs(particlesCPU[i].position[dim] - resCPU[i].position[dim]) > error ){ bien = false; break; } } } printf("NUM_ITERATIONS: %d\n", NUM_ITERATIONS); printf("NUM_PARTICLES: %d\n", NUM_PARTICLES); printf("BLOCK_SIZE: %d\n", BLOCK_SIZE); if(bien){ printf("datos correctos\n"); }else{ printf("datos incorrectos\n"); } cudaFree(particlesGPU); cudaFreeHost(resCPU); delete[] particlesCPU; for(int i = 0; i < NSTREAMS; i++){ cudaStreamDestroy(stream[i]); } printf("Duration of the CPU: %f\n", diferencia_CPU); printf("Duration of the GPU: %f\n", diferencia_GPU); printf("--------------------------------------------\n"); return 0; }
5,844
#include <stdio.h> #define NBR 68 __global__ void histo_kernel(unsigned char *buffer,long size, unsigned int *histo){ __shared__ unsigned int temp[68]; int dt = 32; temp[threadIdx.x]=0; int i = threadIdx.x + blockIdx.x *blockDim.x; int offset = blockDim.x *gridDim.x; while(i<size){ if (buffer[i] >= 32 && buffer[i] < 97) // histo[buffer[i]-dt]++; atomicAdd(&temp[buffer[i]-dt],1); if (buffer[i] >=97 && buffer[i] <= 122) atomicAdd(&temp[buffer[i] -dt -32],1); // histo[buffer[i] - dt - 32]++; if (buffer[i] > 122 && buffer[i] <= 127 ) // histo[buffer[i] - dt - 32 - 26]++; atomicAdd(&temp[buffer[i]-dt -32-26],1); i+=offset; } __syncthreads(); atomicAdd( &(histo[threadIdx.x]), temp[threadIdx.x] ); } int main(int argc, char *argv[]){ // unsigned char *buffer = (unsigned char *) big_random_block(SIZE); if(argc <= 2){ fprintf(stderr, "Arguments non valide"); return 1; } /*For file input file and output file*/ FILE *f_input; FILE *f_output; /*Will content the number of char in the input file*/ long lSize; /*will content the file in char format*/ char *buffer; /*Open the */ f_input = fopen ( argv[1] ,"r" ); f_output = fopen( argv[2],"w"); if( !f_input ) perror(argv[1]),exit(1); fseek( f_input , 0L , SEEK_END); lSize = ftell( f_input ); rewind( f_input ); //buffer = calloc( 1, lSize+1 ); buffer =(char*) malloc(lSize); if( !buffer ) fclose(f_input),fputs("memory alloc fails",stderr),exit(1); if( 1!=fread( buffer , lSize, 1 , f_input) ) fclose(f_input),free(buffer),fputs("entire read fails",stderr),exit(1); /*Create event for co;pute running time*/ cudaEvent_t start, stop; cudaEventCreate( &start ); cudaEventCreate( &stop ); /*Launch event to specify the start of running*/ cudaEventRecord( start, 0); /*allocate device memory*/ unsigned char *dev_buffer; unsigned int *dev_histo; /*Give space in Global memory of GPU to store different variable*/ cudaMalloc( (void**)&dev_buffer, lSize); /*Copy from CPU Global memory to GPU Global memory*/ cudaMemcpy( dev_buffer, buffer, lSize, cudaMemcpyHostToDevice ); /*Create space for histo variable and initialize at 0 each slopt*/ cudaMalloc( (void**)&dev_histo, NBR * sizeof( long)); cudaMemset( dev_histo, 0, NBR * sizeof( int )); /*Define of the configuration for kernel running*/ cudaDeviceProp proprieties; cudaGetDeviceProperties( &proprieties, 0 ); int multiproc = proprieties.multiProcessorCount; dim3 blocks(multiproc*2,1,1); dim3 threads(NBR, 1, 1); histo_kernel<<<blocks,threads>>>( dev_buffer, lSize, dev_histo ); /*Define histo vqriqble and copy on GPU global memory*/ unsigned int histo[NBR]; cudaMemcpy( histo, dev_histo,NBR * sizeof( int ),cudaMemcpyDeviceToHost); int dt =32; for(int i =0;i< NBR;i++){ if((i>=0 && i<= 31 && (i+dt != 42) && (i+dt != 36)) || (i>58 && i<=64) ) fprintf(f_output, "%c:%d\n",i+dt,histo[i]); if(i>31 && i<= 58 ) fprintf(f_output, "%c:%d\n",i+dt+32,histo[i]); // if(i> 58 && i <=64) // fprintf(f_output, "%c:%d\n",i+dt,histo[i]); if(i>64) fprintf(f_output, "%c:%d\n",i+dt+26,histo[i]); } /*Get event at the end of loop*/ cudaEventRecord( stop, 0 ); cudaEventSynchronize( stop ); float elapsedTime; cudaEventElapsedTime( &elapsedTime, start, stop ); printf( "Time of running : %3.1f ms\n", elapsedTime ); /*Destroy event for running time*/ cudaEventDestroy( start ); cudaEventDestroy( stop ); /*Free memory and close the files**/ cudaFree( dev_histo ); cudaFree( dev_buffer ); fclose(f_input); fclose(f_output); free( buffer ); return 0; }
5,845
#include <cuda.h> #include <iostream> #include <sys/time.h> using namespace std; /* example showing multiple threads writing same memory location */ __global__ void doubleWrite(int n, double *a) { int t = threadIdx.x; // access order is not defined. result would change in different runs a[0] = t; } int main() { int n = 128*128*128*4; double *data = (double*) malloc(n * sizeof(double)); for (int i=0; i<n; i++) { data[i] = i; } double *data_dev; cudaMalloc((void**) &data_dev, n * sizeof(double)); int nBlocks = 1; int nThreads = 512; // runs the kernel 100 times for (int i=0; i<100; i++) { cudaMemcpy(data_dev, data, n * sizeof(double) , cudaMemcpyHostToDevice); doubleWrite <<< nBlocks, nThreads >>>(n, data_dev); cudaMemcpy(data, data_dev, n * sizeof(double) , cudaMemcpyDeviceToHost); cout << "data[0] = " << data[0] << endl; } cudaFree(data_dev); free(data); }
5,846
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <iostream> __global__ void check_index() { printf(" threadidx:(%d,%d,%d) blockidx:(%d,%d,%d) blockdim:(%d,%d,%d) griddim:(%d,%d,%d) \n", threadIdx.x,threadIdx.y,threadIdx.z,blockIdx.x,blockIdx.y,blockIdx.z, blockDim.x,blockDim.y,blockDim.z,gridDim.x,gridDim.y,gridDim.z); } //int main() //{ // int element_count = 6; // // dim3 block(3); // dim3 grid((element_count+block.x -1)/block.x); // // printf("grid.x:%d grid.y:%d grid.z:%d \n",grid.x,grid.y,grid.z); // printf("block.x:%d block.y:%d block.z:%d \n", block.x, block.y, block.z); // // check_index << <grid,block >> > (); // cudaDeviceReset(); // // system("pause"); // return 0; //}
5,847
#include <stdio.h> __global__ void cudaHello() { int const threadId = blockIdx.x * blockDim.x + threadIdx.x; printf("Hello World! My threadId is %d\n", threadId); } int main() { int const TB = 1; // Number of thread blocks int const TPB = 256; // Number of threads per block cudaHello<<<TB, TPB>>>(); cudaDeviceSynchronize(); }
5,848
#include <stdint.h> #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <iostream> #include <stdio.h> #include <algorithm> #include <stddef.h> // helper functions and utilities to work with CUDA // #include <helper_functions.h> // #include <helper_cuda.h> #define CORRECTNONCE 235472032 #define MAXNONCE 10000000 #define NUMTHREAD 131072 #define BLOCKSIZE 256 #define NO_DEVICE 1 #define STARTATNONCE CORRECTNONCE-MAXNONCE+1 // ----------------------------------------------------------------------------------------------------------------------------------- typedef unsigned char BYTE; // 8-bit byte typedef uint32_t WORD; // 32-bit word // ----------------------------------------------------------------------------------------------------------------------------------- #define ipad_elm 0x36363636 #define opad_elm 0x5c5c5c5c #define SUM(a,b) (a+b) & 0xffffffff // ----------------------------------------------------------------------------------------------------------------------------------- #define h0 0x6a09e667 #define h1 0xbb67ae85 #define h2 0x3c6ef372 #define h3 0xa54ff53a #define h4 0x510e527f #define h5 0x9b05688c #define h6 0x1f83d9ab #define h7 0x5be0cd19 // Macros #define SHA256_BLOCK_SIZE 32 #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) #define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z))) #define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ (ROTRIGHT(x,22))) #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ (ROTRIGHT(x,25))) #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3)) #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10)) typedef struct SHA256_CTX { BYTE data[64]; WORD datalen; unsigned long long bitlen; WORD state[8]; } SHA256_CTX; typedef struct SHA256_CTX_W { WORD data[16]; WORD datalen; unsigned long long bitlen; WORD state[8]; } SHA256_CTX_W; typedef struct SCRYPT_PKG{ SHA256_CTX_W ctx; WORD input[20]; WORD output[8]; WORD mem[1024][32]; WORD salt[21]; WORD hmac_out[8]; WORD in_ihash[37]; WORD in_2_ihash[49]; WORD pbkdf2_rm_out[32]; WORD ihash[8]; WORD khash[8]; WORD in_ohash[24]; }SCRYPT_PKG; // ----------------------------------------------------------------------------------------------------------------------------------- #define SALSA_MIX(destination ,a1, a2, b) (destination ^ (ROTLEFT(SUM(a1,a2),b))) #define ipad_elm 0x36363636 #define opad_elm 0x5c5c5c5c #define SUM(a,b) (a+b) & 0xffffffff __device__ BYTE hex_char_to_byte(char hex_char){ if(hex_char >= 'a' && hex_char <='f'){ return hex_char - 'a' + 10; } else if(hex_char >='A' && hex_char <= 'F'){ return hex_char - 'A' + 10; } else if (hex_char >='0' && hex_char <= '9') { return hex_char - '0'; } return 0; } BYTE hex_char_to_byte_host(char hex_char){ if(hex_char >= 'a' && hex_char <='f'){ return hex_char - 'a' + 10; } else if(hex_char >='A' && hex_char <= 'F'){ return hex_char - 'A' + 10; } else if (hex_char >='0' && hex_char <= '9') { return hex_char - '0'; } return 0; } __device__ void hex_string_to_bytes(char hex_str_in[], unsigned long hex_str_len, BYTE bytes_out[]){ for (int i = 0; i<hex_str_len-1; i+=2){ bytes_out[i/2] = ((hex_char_to_byte(hex_str_in[i])) << 4) | (hex_char_to_byte(hex_str_in[i+1])); } } __device__ void hex_string_to_words(char hex_str_in[], unsigned long hex_str_len, WORD words_out[]){ for (int i = 0; i<hex_str_len-1; i+=8){ words_out[i/8] = (\ hex_char_to_byte(hex_str_in[i])<<28|\ (hex_char_to_byte(hex_str_in[i+1])<<24 & 0x0f000000)|\ (hex_char_to_byte(hex_str_in[i+2])<<20 & 0x00f00000)|\ (hex_char_to_byte(hex_str_in[i+3])<<16 & 0x000f0000)|\ (hex_char_to_byte(hex_str_in[i+4])<<12 & 0x0000f000)|\ (hex_char_to_byte(hex_str_in[i+5])<<8 & 0x00000f00)|\ (hex_char_to_byte(hex_str_in[i+6])<<4 & 0x000000f0)|\ (hex_char_to_byte(hex_str_in[i+7]) & 0x0000000f)\ ); // printf("%08x %d\n", words_out[i/8], i/8); } } void hex_string_to_words_host(char hex_str_in[], unsigned long hex_str_len, WORD words_out[]){ for (int i = 0; i<hex_str_len-1; i+=8){ words_out[i/8] = (\ hex_char_to_byte_host(hex_str_in[i])<<28|\ (hex_char_to_byte_host(hex_str_in[i+1])<<24 & 0x0f000000)|\ (hex_char_to_byte_host(hex_str_in[i+2])<<20 & 0x00f00000)|\ (hex_char_to_byte_host(hex_str_in[i+3])<<16 & 0x000f0000)|\ (hex_char_to_byte_host(hex_str_in[i+4])<<12 & 0x0000f000)|\ (hex_char_to_byte_host(hex_str_in[i+5])<<8 & 0x00000f00)|\ (hex_char_to_byte_host(hex_str_in[i+6])<<4 & 0x000000f0)|\ (hex_char_to_byte_host(hex_str_in[i+7]) & 0x0000000f)\ ); // printf("%08x %d\n", words_out[i/8], i/8); } } __device__ void half_byte_to_hex(BYTE half_byte_in, char *hex){ BYTE half_byte_conv = half_byte_in & 0x0f; if(half_byte_conv<16){ if (half_byte_conv>=10){ *hex = 'a'+ half_byte_conv - 10; // printf("%c\n", *hex); return; } else{ *hex = '0' + half_byte_conv; // printf("%c\n", *hex); return; } } printf("The half byte must be in range of [0:15]\n"); } void half_byte_to_hex_host(BYTE half_byte_in, char *hex){ BYTE half_byte_conv = half_byte_in & 0x0f; if(half_byte_conv<16){ if (half_byte_conv>=10){ *hex = 'a'+ half_byte_conv - 10; // printf("%c\n", *hex); return; } else{ *hex = '0' + half_byte_conv; // printf("%c\n", *hex); return; } } printf("The half byte must be in range of [0:15]\n"); } __device__ void word_to_hex_eight(WORD word_in, char *hex_eight, unsigned long hex_eight_size){ if(hex_eight_size==8){ half_byte_to_hex(word_in>>28, &hex_eight[0]); half_byte_to_hex(word_in>>24, &hex_eight[1]); half_byte_to_hex(word_in>>20, &hex_eight[2]); half_byte_to_hex(word_in>>16, &hex_eight[3]); half_byte_to_hex(word_in>>12, &hex_eight[4]); half_byte_to_hex(word_in>>8, &hex_eight[5]); half_byte_to_hex(word_in>>4, &hex_eight[6]); half_byte_to_hex(word_in, &hex_eight[7]); // printf("%c", hex_eight[0]); // printf("%d", word_in>>24); return; } printf("The hex_pair must have the length of two characters: %d\n", (int)hex_eight_size); } void word_to_hex_eight_host(WORD word_in, char *hex_eight, unsigned long hex_eight_size){ if(hex_eight_size==8){ half_byte_to_hex_host(word_in>>28, &hex_eight[0]); half_byte_to_hex_host(word_in>>24, &hex_eight[1]); half_byte_to_hex_host(word_in>>20, &hex_eight[2]); half_byte_to_hex_host(word_in>>16, &hex_eight[3]); half_byte_to_hex_host(word_in>>12, &hex_eight[4]); half_byte_to_hex_host(word_in>>8, &hex_eight[5]); half_byte_to_hex_host(word_in>>4, &hex_eight[6]); half_byte_to_hex_host(word_in, &hex_eight[7]); // printf("%c", hex_eight[0]); // printf("%d", word_in>>24); return; } printf("The hex_pair must have the length of two characters: %d\n", (int)hex_eight_size); } __device__ void words_to_hex_string(WORD *words_in, unsigned long words_len, char hex_str[], unsigned long hex_str_len){ char hex_eight[8]; if(hex_str_len == 8*words_len){ for (int i = 0; i<words_len; ++i){ // printf("\n w: %08x", words_in[i]); word_to_hex_eight(words_in[i], hex_eight, sizeof(hex_eight)); hex_str[8*i] = hex_eight[0]; hex_str[8*i+1] = hex_eight[1]; hex_str[8*i+2] = hex_eight[2]; hex_str[8*i+3] = hex_eight[3]; hex_str[8*i+4] = hex_eight[4]; hex_str[8*i+5] = hex_eight[5]; hex_str[8*i+6] = hex_eight[6]; hex_str[8*i+7] = hex_eight[7]; // printf("%c \n", hex_eight[7]); } // printf("\n%s", hex_str); return; } printf("The hex_string must have the lenght of 4*bytes_len: %d\n", (int)hex_str_len); } __device__ void add_two_words_array_512_bit(WORD *a, WORD *b){ for (int i = 15; i>=0; i--){ a[i] += b[i]; } } __device__ void add_two_words_array_512_bit_with_carry(WORD *a, WORD *b){ WORD sum = 0; WORD sum1 = 0; for (int i = 15; i>=0; i--){ sum = ((a[i]&0x0000ffff)+(b[i]&0x0000ffff)+(sum1>>16)); sum1 = ((a[i]>>16)+(b[i]>>16)+(sum>>16)); a[i]= (sum & 0x0000ffff) + (sum1<<16); } } __device__ void print_words_inline(WORD *w, unsigned long w_len){ printf("\n"); for (int i = 0; i< w_len; i++){ printf("%08x", w[i]); } printf("\n"); } void print_words_inline_host(WORD *w, unsigned long w_len){ printf("\n"); for (int i = 0; i< w_len; i++){ printf("%08x", w[i]); } printf("\n"); } void print_words_multiline_host(WORD *w, unsigned long w_len){ printf("\n"); for (int i = 0; i< w_len; i++){ printf("%08x\n", w[i]); } printf("\n"); } __device__ void print_words_multiline(WORD *w, unsigned long w_len){ printf("\n"); for (int i = 0; i< w_len; i++){ printf("%08x\n", w[i]); } printf("\n"); } __device__ void endian_cvt(WORD *w){ WORD out; out = (*w>>24)|((*w>>8)&0x0000ff00)|((*w<<8)&0x00ff0000)|(*w<<24); *w = out; } __device__ void endian_full(WORD *w, unsigned long w_len){ for (int i = 0; i < w_len; i++) { endian_cvt(&w[i]); } } void little_endian(char *c, unsigned long w_len){ char *dc = (char*)malloc(w_len); for (int i = 0; i< w_len; i+=2){ dc[w_len-2-i] = c[i]; dc[w_len-1-i] = c[i+1]; } for (int i = 0; i< w_len; i++){ c[i] = dc[i]; } c[w_len] = '\0'; } void endian_cvt_host(WORD *w){ WORD out; out = (*w>>24)|((*w>>8)&0x0000ff00)|((*w<<8)&0x00ff0000)|(*w<<24); *w = out; } // Create init state for SHA-256 __device__ void sha256_init(SHA256_CTX *ctx) { ctx->datalen = 0; ctx->bitlen = 0; ctx->state[0] = h0; ctx->state[1] = h1; ctx->state[2] = h2; ctx->state[3] = h3; ctx->state[4] = h4; ctx->state[5] = h5; ctx->state[6] = h6; ctx->state[7] = h7; } // Create init state for SHA-256 __device__ void sha256_init_words(SHA256_CTX_W *ctx) { ctx->datalen = 0; ctx->bitlen = 0; ctx->state[0] = h0; ctx->state[1] = h1; ctx->state[2] = h2; ctx->state[3] = h3; ctx->state[4] = h4; ctx->state[5] = h5; ctx->state[6] = h6; ctx->state[7] = h7; } __device__ void sha256_transform(SHA256_CTX *ctx, BYTE data[]) { static const WORD k[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, \ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, \ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, \ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, \ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, \ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, \ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, \ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; // m is W in hardware design WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; // Calculate the first 16 m elements. for (i = 0, j = 0; i < 16; ++i, j += 4) m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]); // Calculate the remain elements. for ( ; i < 64; ++i) m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; // update the new value of state after each block a = ctx->state[0]; b = ctx->state[1]; c = ctx->state[2]; d = ctx->state[3]; e = ctx->state[4]; f = ctx->state[5]; g = ctx->state[6]; h = ctx->state[7]; // process 64 rounds for (i = 0; i < 64; ++i) { t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; t2 = EP0(a) + MAJ(a,b,c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } ctx->state[0] += a; ctx->state[1] += b; ctx->state[2] += c; ctx->state[3] += d; ctx->state[4] += e; ctx->state[5] += f; ctx->state[6] += g; ctx->state[7] += h; } __device__ void sha256_transform_words(SHA256_CTX_W *ctx, WORD data[]) { static const WORD k[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, \ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, \ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, \ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, \ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, \ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, \ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, \ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; // m is W in hardware design WORD a, b, c, d, e, f, g, h, i, t1, t2, m[64]; // Calculate the first 16 m elements. for (i = 0; i < 16; ++i) m[i] = data[i]; // Calculate the remain elements. for ( ; i < 64; ++i) m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; // update the new value of state after each block a = ctx->state[0]; b = ctx->state[1]; c = ctx->state[2]; d = ctx->state[3]; e = ctx->state[4]; f = ctx->state[5]; g = ctx->state[6]; h = ctx->state[7]; // process 64 rounds for (i = 0; i < 64; ++i) { t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; t2 = EP0(a) + MAJ(a,b,c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } ctx->state[0] += a; ctx->state[1] += b; ctx->state[2] += c; ctx->state[3] += d; ctx->state[4] += e; ctx->state[5] += f; ctx->state[6] += g; ctx->state[7] += h; } // the total length of the message has to be specified __device__ void sha256_update(SHA256_CTX *ctx, BYTE data[], size_t len) { WORD i; for (i = 0; i < len; ++i){ ctx->data[ctx->datalen] = data[i]; // Pad data (message) for each 512-block in --> transform ctx->datalen++; // after browse for 64 bytes (512-bit block) -> transform the block. if(ctx->datalen == 64){ sha256_transform(ctx, ctx->data); ctx->bitlen += 512; // increase the bit length by 512 ctx->datalen = 0; } } } __device__ void sha256_update_words(SHA256_CTX_W *ctx, WORD data[], size_t len) { WORD i; for (i = 0; i < len; ++i){ ctx->data[ctx->datalen] = data[i]; // Pad data (message) for each 512-block in --> transform ctx->datalen++; // after browse for 64 bytes (512-bit block) -> transform the block. if(ctx->datalen == 16){ sha256_transform_words(ctx, ctx->data); ctx->bitlen += 512; // increase the bit length by 512 ctx->datalen = 0; } } } // this function processes for the last block -> after all real data is browsed __device__ void sha256_final(SHA256_CTX *ctx, WORD *hash){ WORD i; // padding is processed from here i = ctx->datalen; if (ctx->datalen < 56){ // add byte 0x80 at the first if the datalength is lower than 56 ctx->data[i++] = 0x80; // pad the zero bytes until the byte 56th while (i<56) { ctx->data[i++]=0x00; } } else{ // add byte at the first ctx->data[i++]=0x80; // pad zero bytes until the last block while (i<64){ ctx->data[i++]=0x00; } // transform this block --> it's not the last block sha256_transform(ctx, ctx->data); // set 56 zero bytes from last_block[0:55] memset(ctx->data, 0, 56); } // Append to the padding the total message's length in bits and transform. ctx->bitlen += ctx->datalen * 8; ctx->data[63] = ctx->bitlen; ctx->data[62] = ctx->bitlen >> 8; ctx->data[61] = ctx->bitlen >> 16; ctx->data[60] = ctx->bitlen >> 24; ctx->data[59] = ctx->bitlen >> 32; ctx->data[58] = ctx->bitlen >> 40; ctx->data[57] = ctx->bitlen >> 48; ctx->data[56] = ctx->bitlen >> 56; // end padding sha256_transform(ctx, ctx->data); // Since this implementation uses little endian byte ordering and SHA uses big endian, // reverse all the bytes when copying the final state to the output hash. hash[0] = ctx->state[0]; hash[1] = ctx->state[1]; hash[2] = ctx->state[2]; hash[3] = ctx->state[3]; hash[4] = ctx->state[4]; hash[5] = ctx->state[5]; hash[6] = ctx->state[6]; hash[7] = ctx->state[7]; } // this function processes for the last block -> after all real data is browsed __device__ void sha256_final_words(SHA256_CTX_W *ctx, WORD *hash){ WORD i; // padding is processed from here i = ctx->datalen; if (ctx->datalen < 14){ // add byte 0x80 at the first if the datalength is lower than 56 ctx->data[i++] = 0x80000000; // pad the zero bytes until the byte 56th while (i<14) { ctx->data[i++]=0x00000000; } } else{ // add bit 1 at the first ctx->data[i++]=0x80000000; // pad zero bytes until the last block while (i<16){ ctx->data[i++]=0x00000000; } // transform this block --> it's not the last block sha256_transform_words(ctx, ctx->data); // set 56 zero bytes from last_block[0:55] ctx->data[0] =0x00000000; ctx->data[1] =0x00000000; ctx->data[2] =0x00000000; ctx->data[3] =0x00000000; ctx->data[4] =0x00000000; ctx->data[5] =0x00000000; ctx->data[6] =0x00000000; ctx->data[7] =0x00000000; ctx->data[8] =0x00000000; ctx->data[9] =0x00000000; ctx->data[10]=0x00000000; ctx->data[11]=0x00000000; ctx->data[12]=0x00000000; ctx->data[13]=0x00000000; } // Append to the padding the total message's length in bits and transform. ctx->bitlen += ctx->datalen * 32; ctx->data[15] = ctx->bitlen; ctx->data[14] = ctx->bitlen>>32; // end padding sha256_transform_words(ctx, ctx->data); // Since this implementation uses little endian byte ordering and SHA uses big endian, // reverse all the bytes when copying the final state to the output hash. hash[0] = ctx->state[0]; hash[1] = ctx->state[1]; hash[2] = ctx->state[2]; hash[3] = ctx->state[3]; hash[4] = ctx->state[4]; hash[5] = ctx->state[5]; hash[6] = ctx->state[6]; hash[7] = ctx->state[7]; } __device__ void sha256_in_words(SHA256_CTX_W *ctx, WORD *words_in, unsigned long words_in_len, WORD *hash_w){ // printf("\n%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", words_in[0], words_in[1], words_in[2], words_in[3], words_in[4], words_in[5], words_in[6], words_in[7], words_in[8], words_in[9], words_in[10], words_in[11], words_in[12], words_in[13], words_in[14], words_in[15], words_in[16], words_in[17], words_in[18], words_in[19], words_in[20], words_in[21], words_in[22], words_in[23]); // true sha256_init_words(ctx); sha256_update_words(ctx, words_in, words_in_len); // print_words_inline(ctx->state, 8); sha256_final_words(ctx, hash_w); } __device__ void sha256_in_words_org(SHA256_CTX *ctx, WORD *words_in, unsigned long words_in_len, WORD *hash_w){ unsigned long bytes_in_len = words_in_len * 4; // printf("%d\n", words_in_len); // printf("\n%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", words_in[0], words_in[1], words_in[2], words_in[3], words_in[4], words_in[5], words_in[6], words_in[7], words_in[8], words_in[9], words_in[10], words_in[11], words_in[12], words_in[13], words_in[14], words_in[15], words_in[16], words_in[17], words_in[18], words_in[19], words_in[20], words_in[21], words_in[22], words_in[23]); // true BYTE *bytes_in = (BYTE *)malloc((bytes_in_len)*sizeof(BYTE)); for (int i = 0; i<words_in_len; i++){ bytes_in[4*i] = words_in[i] >> 24; bytes_in[4*i+1] = words_in[i] >> 16; bytes_in[4*i+2] = words_in[i] >> 8; bytes_in[4*i+3] = words_in[i]; // printf("%x %x %x %x ", bytes_in[4*i], bytes_in[4*i+1], bytes_in[4*i+2], bytes_in[4*i+3]); } sha256_init(ctx); sha256_update(ctx, bytes_in, bytes_in_len); // print_words_inline(ctx->state, 8); sha256_final(ctx, hash_w); } __device__ void sha256_in_words_test(SHA256_CTX_W *ctx, WORD *words_in, unsigned long words_in_len, WORD *hash_w){ // printf("%d\n", words_in_len); // printf("\n%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", words_in[0], words_in[1], words_in[2], words_in[3], words_in[4], words_in[5], words_in[6], words_in[7], words_in[8], words_in[9], words_in[10], words_in[11], words_in[12], words_in[13], words_in[14], words_in[15], words_in[16], words_in[17], words_in[18], words_in[19], words_in[20], words_in[21], words_in[22], words_in[23]); // true sha256_init_words(ctx); sha256_update_words(ctx, words_in, words_in_len); // print_words_inline(ctx->state, 8); sha256_final_words(ctx, hash_w); } __device__ void hmac(SHA256_CTX_W *ctx, WORD *salt, unsigned long salt_len, WORD *message, unsigned long message_len, WORD* out_hmac){ WORD IPAD[8] = {ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm}; // 256-bit 363636...36 WORD OPAD[8] = {opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm}; // 256-bit 5c5c5c...5c WORD *khash = (WORD*) malloc(sizeof(WORD)*8); // print_words_inline(message, 20); // OK sha256_in_words(ctx, message, message_len, khash); // print_words_inline(khash, 8); // OK // for(int i=0;i<8; i++){ // printf("%08x", khash[i]); // } WORD ixor[16] = {\ IPAD[0]^khash[0],\ IPAD[1]^khash[1],\ IPAD[2]^khash[2],\ IPAD[3]^khash[3],\ IPAD[4]^khash[4],\ IPAD[5]^khash[5],\ IPAD[6]^khash[6],\ IPAD[7]^khash[7],\ IPAD[0],\ IPAD[1],\ IPAD[2],\ IPAD[3],\ IPAD[4],\ IPAD[5],\ IPAD[6],\ IPAD[7],\ }; WORD oxor[16] = {\ OPAD[0]^khash[0],\ OPAD[1]^khash[1],\ OPAD[2]^khash[2],\ OPAD[3]^khash[3],\ OPAD[4]^khash[4],\ OPAD[5]^khash[5],\ OPAD[6]^khash[6],\ OPAD[7]^khash[7],\ OPAD[0],\ OPAD[1],\ OPAD[2],\ OPAD[3],\ OPAD[4],\ OPAD[5],\ OPAD[6],\ OPAD[7],\ }; WORD *in_ihash = (WORD*)malloc((sizeof(ixor)/sizeof(WORD)+salt_len)*sizeof(WORD)); unsigned long in_ihash_len = sizeof(ixor)/sizeof(WORD)+salt_len; int i; for(i = 0; i<sizeof(ixor)/sizeof(WORD); i++){ in_ihash[i] = ixor[i]; } for(;i<sizeof(ixor)/sizeof(WORD)+salt_len; i++){ in_ihash[i] = salt[i-sizeof(ixor)/sizeof(WORD)]; } WORD *ihash = (WORD*)malloc(8*sizeof(WORD)); // print_words_inline(in_ihash, sizeof(ixor)/sizeof(WORD)+salt_len); // Problem sha256_in_words(ctx, in_ihash, in_ihash_len, ihash); // Why it's wrong // print_words_inline(ihash, 8); // OK unsigned long in_ohash_len = sizeof(oxor)/sizeof(WORD)+8; WORD *in_ohash = (WORD*)malloc(in_ohash_len*sizeof(WORD)); // WORD[24] // printf("%d\n", (in_ohash_len)); // printf("%d\n", in_ohash_len); // 24 --> true for(i = 0; i<sizeof(oxor)/sizeof(WORD); i++){ in_ohash[i] = oxor[i]; } for(;i<sizeof(ixor)/sizeof(WORD)+salt_len; i++){ in_ohash[i] = ihash[i-sizeof(oxor)/sizeof(WORD)]; } // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x %d\n", in_ohash[0], in_ohash[1], in_ohash[2], in_ohash[3], in_ohash[4], in_ohash[5], in_ohash[6], in_ohash[7], in_ohash[8], in_ohash[9], in_ohash[10], in_ohash[11], in_ohash[12], in_ohash[13], in_ohash[14], in_ohash[15], in_ohash[16], in_ohash[17], in_ohash[18], in_ohash[19], in_ohash[20], in_ohash[21], in_ohash[22], in_ohash[23], in_ohash_len); // true WORD temp[] = {in_ohash[0], in_ohash[1], in_ohash[2], in_ohash[3], in_ohash[4], in_ohash[5], in_ohash[6], in_ohash[7], in_ohash[8], in_ohash[9], in_ohash[10], in_ohash[11], in_ohash[12], in_ohash[13], in_ohash[14], in_ohash[15], in_ohash[16], in_ohash[17], in_ohash[18], in_ohash[19], in_ohash[20], in_ohash[21], in_ohash[22], in_ohash[23]}; // static WORD ohash[8]; // printf("\n"); sha256_in_words(ctx, temp, in_ohash_len, out_hmac); // print_words_inline(ohash, 8); // OK // return ohash; } __device__ void hmac_2(SHA256_CTX_W *ctx, WORD *salt, unsigned long salt_len, WORD *message, unsigned long message_len, WORD* out_hmac, WORD khash[8], WORD in_ihash[49], WORD ihash[8], WORD in_ohash[24]){ WORD IPAD[8] = {ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm}; // 256-bit 363636...36 WORD OPAD[8] = {opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm}; // 256-bit 5c5c5c...5c // print_words_inline(message, 20); // OK // sha256_in_words(ctx, message, message_len, khash); // print_words_inline(khash, 8); // OK // for(int i=0;i<8; i++){ // printf("%08x", khash[i]); // } WORD ixor[16] = {\ IPAD[0]^khash[0],\ IPAD[1]^khash[1],\ IPAD[2]^khash[2],\ IPAD[3]^khash[3],\ IPAD[4]^khash[4],\ IPAD[5]^khash[5],\ IPAD[6]^khash[6],\ IPAD[7]^khash[7],\ IPAD[0],\ IPAD[1],\ IPAD[2],\ IPAD[3],\ IPAD[4],\ IPAD[5],\ IPAD[6],\ IPAD[7],\ }; WORD oxor[16] = {\ OPAD[0]^khash[0],\ OPAD[1]^khash[1],\ OPAD[2]^khash[2],\ OPAD[3]^khash[3],\ OPAD[4]^khash[4],\ OPAD[5]^khash[5],\ OPAD[6]^khash[6],\ OPAD[7]^khash[7],\ OPAD[0],\ OPAD[1],\ OPAD[2],\ OPAD[3],\ OPAD[4],\ OPAD[5],\ OPAD[6],\ OPAD[7],\ }; unsigned long in_ihash_len = sizeof(ixor)/sizeof(WORD)+salt_len; // printf("%d\n", (sizeof(ixor)/sizeof(WORD)+salt_len)); int i; for(i = 0; i<sizeof(ixor)/sizeof(WORD); i++){ in_ihash[i] = ixor[i]; } for(;i<sizeof(ixor)/sizeof(WORD)+salt_len; i++){ in_ihash[i] = salt[i-sizeof(ixor)/sizeof(WORD)]; } // print_words_inline(in_ihash, sizeof(ixor)/sizeof(WORD)+salt_len); // Problem sha256_in_words(ctx, in_ihash, in_ihash_len, ihash); // Why it's wrong // print_words_inline(ihash, 8); // OK unsigned long in_ohash_len = sizeof(oxor)/sizeof(WORD)+8; // printf("%d\n", in_ohash_len); // 24 --> true for(i = 0; i<sizeof(oxor)/sizeof(WORD); i++){ in_ohash[i] = oxor[i]; } for(;i<sizeof(ixor)/sizeof(WORD)+salt_len; i++){ in_ohash[i] = ihash[i-sizeof(oxor)/sizeof(WORD)]; } // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x %d\n", in_ohash[0], in_ohash[1], in_ohash[2], in_ohash[3], in_ohash[4], in_ohash[5], in_ohash[6], in_ohash[7], in_ohash[8], in_ohash[9], in_ohash[10], in_ohash[11], in_ohash[12], in_ohash[13], in_ohash[14], in_ohash[15], in_ohash[16], in_ohash[17], in_ohash[18], in_ohash[19], in_ohash[20], in_ohash[21], in_ohash[22], in_ohash[23], in_ohash_len); // true WORD temp[] = {in_ohash[0], in_ohash[1], in_ohash[2], in_ohash[3], in_ohash[4], in_ohash[5], in_ohash[6], in_ohash[7], in_ohash[8], in_ohash[9], in_ohash[10], in_ohash[11], in_ohash[12], in_ohash[13], in_ohash[14], in_ohash[15], in_ohash[16], in_ohash[17], in_ohash[18], in_ohash[19], in_ohash[20], in_ohash[21], in_ohash[22], in_ohash[23]}; // static WORD ohash[8]; // printf("\n"); sha256_in_words(ctx, temp, in_ohash_len, out_hmac); // print_words_inline(ohash, 8); // OK // return ohash; } __device__ void hmac_test(SHA256_CTX_W *ctx, WORD *salt, unsigned long salt_len, WORD *message, unsigned long message_len, WORD* out_hmac, WORD khash[8], WORD in_ihash[37], WORD ihash[8], WORD in_ohash[24]){ // WORD IPAD[8] = {ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm, ipad_elm}; // 256-bit 363636...36 // WORD OPAD[8] = {opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm, opad_elm}; // 256-bit 5c5c5c...5c // print_words_inline(message, 20); // OK sha256_in_words(ctx, message, message_len, khash); // print_words_inline(khash, 8); // OK // for(int i=0;i<8; i++){ // printf("%08x", khash[i]); // } WORD ixor[16] = {\ 0x36363636^khash[0],\ 0x36363636^khash[1],\ 0x36363636^khash[2],\ 0x36363636^khash[3],\ 0x36363636^khash[4],\ 0x36363636^khash[5],\ 0x36363636^khash[6],\ 0x36363636^khash[7],\ 0x36363636,\ 0x36363636,\ 0x36363636,\ 0x36363636,\ 0x36363636,\ 0x36363636,\ 0x36363636,\ 0x36363636,\ }; WORD oxor[16] = {\ 0x5C5C5C5C^khash[0],\ 0x5C5C5C5C^khash[1],\ 0x5C5C5C5C^khash[2],\ 0x5C5C5C5C^khash[3],\ 0x5C5C5C5C^khash[4],\ 0x5C5C5C5C^khash[5],\ 0x5C5C5C5C^khash[6],\ 0x5C5C5C5C^khash[7],\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ 0x5C5C5C5C,\ }; // print_words_inline(IPAD, 8); // print_words_inline(OPAD, 8); unsigned long in_ihash_len = 37; int i; for(i = 0; i<sizeof(ixor)/sizeof(WORD); i++){ in_ihash[i] = ixor[i]; } for(;i<sizeof(ixor)/sizeof(WORD)+salt_len; i++){ in_ihash[i] = salt[i-sizeof(ixor)/sizeof(WORD)]; } // print_words_inline(in_ihash, sizeof(ixor)/sizeof(WORD)+salt_len); // Problem sha256_in_words(ctx, in_ihash, in_ihash_len, ihash); // Why it's wrong // printf("OK hmac_tes before in_ohash_len\n"); // print_words_inline(ihash, 8); // OK unsigned long in_ohash_len = 24; // printf("in_ohash: %u\n", in_ohash); // 24 --> true for(i = 0; i<sizeof(oxor)/sizeof(WORD); i++){ in_ohash[i] = oxor[i]; // in_ohash[i] = 0x12341234; } for(;i<sizeof(ixor)/sizeof(WORD)+salt_len; i++){ in_ohash[i] = ihash[i-sizeof(oxor)/sizeof(WORD)]; } // printf("OK hmac_test in_ohash_len\n"); // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x %d\n", in_ohash[0], in_ohash[1], in_ohash[2], in_ohash[3], in_ohash[4], in_ohash[5], in_ohash[6], in_ohash[7], in_ohash[8], in_ohash[9], in_ohash[10], in_ohash[11], in_ohash[12], in_ohash[13], in_ohash[14], in_ohash[15], in_ohash[16], in_ohash[17], in_ohash[18], in_ohash[19], in_ohash[20], in_ohash[21], in_ohash[22], in_ohash[23], in_ohash_len); // true WORD temp[] = {in_ohash[0], in_ohash[1], in_ohash[2], in_ohash[3], in_ohash[4], in_ohash[5], in_ohash[6], in_ohash[7], in_ohash[8], in_ohash[9], in_ohash[10], in_ohash[11], in_ohash[12], in_ohash[13], in_ohash[14], in_ohash[15], in_ohash[16], in_ohash[17], in_ohash[18], in_ohash[19], in_ohash[20], in_ohash[21], in_ohash[22], in_ohash[23]}; // static WORD ohash[8]; // printf("\n"); sha256_in_words(ctx, temp, in_ohash_len, out_hmac); // print_words_inline(out_hmac, 8); // OK // return ohash; } __device__ void pbkdf2(SHA256_CTX_W *ctx, WORD *block, unsigned long block_len, int dklenP, WORD *pbkdf2_out, WORD salt[21]){ int num_loop = 1024/dklenP; // WORD *salt = (WORD*)malloc((block_len+1)*sizeof(WORD)); WORD *hmac_out = (WORD*)malloc(8*sizeof(WORD)); // int hmac_out_len = 8; // printf("pbkdf2: %08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", block[0], block[1], block[2], block[3], block[4], block[5], block[6], block[7], block[8], block[9], block[10], block[11], block[12], block[13], block[14], block[15], block[16], block[17], block[18], block[19]); for(int i = 0; i<block_len; i++){ salt[i]=block[i]; } for (int i = 1; i <= num_loop; i++) { salt[block_len] = i; hmac(ctx, salt, block_len+1, block, block_len, hmac_out); // print_words_inline(hmac_out, 8); // False for(int j = 0; j<8; j++){ pbkdf2_out[(i-1)*8+j] = hmac_out[j]; } // printf("%08x%08x%08x%08x%08x%08x%08x%08x\n", hmac_out[0], hmac_out[1], hmac_out[2], hmac_out[3], hmac_out[4], hmac_out[5], hmac_out[6], hmac_out[7]); // wrong // } } } __device__ void pbkdf2_test(SHA256_CTX_W *ctx, WORD block[20], unsigned long block_len, WORD pbkdf2_out[32], WORD salt[21], WORD hmac_out[8], WORD khash[8], WORD in_ihash[37], WORD ihash[8], WORD in_ohash[24]){ // printf("OK\n"); // int hmac_out_len = 8; // printf("pbkdf2: %08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", block[0], block[1], block[2], block[3], block[4], block[5], block[6], block[7], block[8], block[9], block[10], block[11], block[12], block[13], block[14], block[15], block[16], block[17], block[18], block[19]); for(int i = 0; i<block_len; i++){ salt[i]=block[i]; } // printf("pbkdf2_out: %u\n", pbkdf2_out); // 24 --> true // print_words_multiline(pbkdf2_out, 32); for (int i = 1; i <= 4; i++) { salt[block_len] = i; // printf("OK SALT\n"); hmac_test(ctx, salt, block_len+1, block, block_len, hmac_out, khash, in_ihash, ihash, in_ohash); // printf("OK HMAC\n"); // print_words_inline(hmac_out, 8); // False for(int j = 0; j<8; j++){ pbkdf2_out[(i-1)*8+j] = hmac_out[j]; // pbkdf2_out[(i-1)*8+j] = 0xffffffff; // printf("%08x, %d\n", pbkdf2_out[(i-1)*8+j], (i-1)*8+j); // print_words_multiline(pbkdf2_out, 32); } // printf("%08x%08x%08x%08x%08x%08x%08x%08x\n", hmac_out[0], hmac_out[1], hmac_out[2], hmac_out[3], hmac_out[4], hmac_out[5], hmac_out[6], hmac_out[7]); // wrong // } } // print_words_multiline(pbkdf2_out, 32); } __device__ void pbkdf2_2nd(SHA256_CTX_W *ctx, WORD *rm_out, unsigned long rm_out_len, WORD *block, unsigned long block_len, WORD* pbkdf2_out, WORD salt[21], WORD hmac_out[8], WORD khash[8], WORD in_ihash[37], WORD ihash[8], WORD in_ohash[24]){ // int hmac_out_len = 8; for(int i = 0; i<rm_out_len; i++){ salt[i]=rm_out[i]; } salt[rm_out_len] = 1; hmac_2(ctx, salt, rm_out_len+1, block, block_len, hmac_out, khash, in_ihash, ihash, in_ohash); pbkdf2_out[0] = hmac_out[0]; for(int j = 0; j<8; j++){ //pbkdf2_out[(i-1)*8+j] = hmac_out[j]; pbkdf2_out[j] = hmac_out[j]; //printf("%d: %08x \n", j, hmac_out[j]); // printf("%d: %08x \n", j, hmac_out[j]); } } __device__ void salsa_mix_func(WORD *des, WORD *a1, WORD *a2, WORD b){ // printf("%08x \n", *a1); WORD sum = *a1 + *a2; // printf("0x%08x + 0x%08x = 0x%08x \n", *a1, *a2, sum); WORD rotl = (sum<<b) | (sum>>(32-b)); WORD xorv = *des ^ rotl; *des = xorv; } __device__ void salsa_round(WORD *x1, WORD *x2, WORD *x3, WORD *x4){ salsa_mix_func(x1, x4, x3, 7); // printf("%08x \n", *x1); salsa_mix_func(x2, x1, x4, 9); salsa_mix_func(x3, x2, x1, 13); salsa_mix_func(x4, x3, x2, 18); } __device__ WORD * salsa20_8(WORD *x){ static WORD out[16]; // for(int i = 0; i<4; i++){ for(int i = 0; i<4; i++){ // if(i==0){ // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] ); // } salsa_round(&x[4], &x[8], &x[12], &x[0]); salsa_round(&x[9], &x[13], &x[1], &x[5]); salsa_round(&x[14], &x[2], &x[6], &x[10]); salsa_round(&x[3], &x[7], &x[11], &x[15]); salsa_round(&x[1], &x[2], &x[3], &x[0]); salsa_round(&x[6], &x[7], &x[4], &x[5]); salsa_round(&x[11], &x[8], &x[9], &x[10]); salsa_round(&x[12], &x[13], &x[14], &x[15]); } for(int i=0; i<16; i++){ out[i] = x[i]; } return out; } __device__ void blockmix(WORD *block){ WORD x_arr[16]; WORD x_arr_cpy[16]; // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", block[0], block[1], block[2], block[3], block[4], block[5], block[6], block[7], block[8], block[9], block[10], block[11], block[12], block[13], block[14], block[15]); for (int i = 0; i < 16; i++){ x_arr[i] = block[i]; // 1 } // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", x_arr[0], x_arr[1], x_arr[2], x_arr[3], x_arr[4], x_arr[5], x_arr[6], x_arr[7], x_arr[8], x_arr[9], x_arr[10], x_arr[11], x_arr[12], x_arr[13], x_arr[14], x_arr[15]); for (int i = 0; i<2; i++){ for (int j = 0; j < 16; j++){ x_arr_cpy[j] = x_arr[j] ^ block[j+16]; // 2 x_arr[j] ^= block[j+16]; // 3 } // printf("xcp %08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", x_arr_cpy[0], x_arr_cpy[1], x_arr_cpy[2], x_arr_cpy[3], x_arr_cpy[4], x_arr_cpy[5], x_arr_cpy[6], x_arr_cpy[7], x_arr_cpy[8], x_arr_cpy[9], x_arr_cpy[10], x_arr_cpy[11], x_arr_cpy[12], x_arr_cpy[13], x_arr_cpy[14], x_arr_cpy[15] ); salsa20_8(x_arr_cpy); add_two_words_array_512_bit(x_arr, x_arr_cpy); // 4 // printf("0x%08x + 0x%08x = 0x%08x\n", a[0], x_arr_cpy[0], x_arr[0]); for (int j = 0; j < 16; j++){ block[(16*i)+j] = x_arr[j]; // 5 } } } __device__ void romix(WORD *block, int N, WORD mem[1024][32]){ // WORD mem[1024][32]; int j; for (int i = 0; i<N; i++){ for (j = 0; j < 32; j++){ mem[i][j] = block[j]; //printf("N: %d, j: %d, i: %d, \n",N, j ,i); } // if(i == 1023){ // printf("i: %d, \n",N, i); // } blockmix(block); } // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", block[0], block[1], block[2], block[3], block[4], block[5], block[6], block[7], block[8], block[9], block[10], block[11], block[12], block[13], block[14], block[15], block[16], block[17], block[18], block[19], block[20], block[21], block[22], block[23], block[24], block[25], block[26], block[27], block[28], block[29], block[30], block[31]); for (int i = 0; i<N; i++){ j = (block[16] & 0x000003ff); for (int k = 0; k<32; k++){ // int a = block[k] ^ mem[j][k]; // printf("j: %u, i: %u, k: %u\n",j ,i, k); block[k] ^= mem[j][k]; // if(a != block[k]) } blockmix(block); } } __device__ void scrypt( SHA256_CTX_W *ctx,\ WORD *block, \ unsigned long block_len, \ WORD scrypt_out[8], \ WORD mem[1024][32], \ WORD salt[21], \ WORD hmac_out[8], \ WORD khash[8], \ WORD in_ihash[37], \ WORD in_2_ihash[49], \ WORD ihash[8], \ WORD in_ohash[24], \ WORD pbkdf2_rm_out[32]){ // WORD *pbkdf2_1_out = (WORD*)malloc(pbkdf2_out_len_1*sizeof(WORD)); // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", block[0], block[1], block[2], block[3], block[4], block[5], block[6], block[7], block[8], block[9], block[10], block[11], block[12], block[13], block[14], block[15], block[16], block[17], block[18], block[19]); // print_words_inline(&block[19], 1); // print_words_inline(block, 20); // OK pbkdf2_test(ctx, block, block_len, pbkdf2_rm_out, salt, hmac_out, khash, in_ihash, ihash, in_ohash); // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", pbkdf2_rm_out[0], pbkdf2_rm_out[1], pbkdf2_rm_out[2], pbkdf2_rm_out[3], pbkdf2_rm_out[4], pbkdf2_rm_out[5], pbkdf2_rm_out[6], pbkdf2_rm_out[7], pbkdf2_rm_out[8], pbkdf2_rm_out[9], pbkdf2_rm_out[10], pbkdf2_rm_out[11], pbkdf2_rm_out[12], pbkdf2_rm_out[13], pbkdf2_rm_out[14], pbkdf2_rm_out[15], pbkdf2_rm_out[16], pbkdf2_rm_out[17], pbkdf2_rm_out[18], pbkdf2_rm_out[19], pbkdf2_rm_out[20], pbkdf2_rm_out[21], pbkdf2_rm_out[22], pbkdf2_rm_out[23], pbkdf2_rm_out[24], pbkdf2_rm_out[25], pbkdf2_rm_out[26], pbkdf2_rm_out[27], pbkdf2_rm_out[28], pbkdf2_rm_out[29], pbkdf2_rm_out[30], pbkdf2_rm_out[31]); // printf("OK\n"); // print_words_multiline(pbkdf2_rm_out, 32); endian_full(pbkdf2_rm_out, 32); romix(pbkdf2_rm_out, 1024, mem); // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", pbkdf2_rm_out[0], pbkdf2_rm_out[1], pbkdf2_rm_out[2], pbkdf2_rm_out[3], pbkdf2_rm_out[4], pbkdf2_rm_out[5], pbkdf2_rm_out[6], pbkdf2_rm_out[7], pbkdf2_rm_out[8], pbkdf2_rm_out[9], pbkdf2_rm_out[10], pbkdf2_rm_out[11], pbkdf2_rm_out[12], pbkdf2_rm_out[13], pbkdf2_rm_out[14], pbkdf2_rm_out[15], pbkdf2_rm_out[16], pbkdf2_rm_out[17], pbkdf2_rm_out[18], pbkdf2_rm_out[19], pbkdf2_rm_out[20], pbkdf2_rm_out[21], pbkdf2_rm_out[22], pbkdf2_rm_out[23], pbkdf2_rm_out[24], pbkdf2_rm_out[25], pbkdf2_rm_out[26], pbkdf2_rm_out[27], pbkdf2_rm_out[28], pbkdf2_rm_out[29], pbkdf2_rm_out[30], pbkdf2_rm_out[31]); endian_full(pbkdf2_rm_out, 32); // print_words_multiline(pbkdf2_1_out, 32); pbkdf2_2nd(ctx, pbkdf2_rm_out, 32, block, block_len, scrypt_out, salt, hmac_out, khash, in_2_ihash, ihash, in_ohash); // printf("%08x%08x%08x%08x%08x%08x%08x%08x\n", pbkdf2_2_out[0],pbkdf2_2_out[1],pbkdf2_2_out[2],pbkdf2_2_out[3],pbkdf2_2_out[4],pbkdf2_2_out[5],pbkdf2_2_out[6],pbkdf2_2_out[7]); // print_words_inline(pbkdf2_2_out, 20); } cudaError_t scryptWithCuda(SCRYPT_PKG **pkgs, int block_per_grid, int thread_per_block); __global__ void scryptCuda(SCRYPT_PKG **pkgs) { int threadId = blockDim.x * blockIdx.x + threadIdx.x; // int blockId = blockIdx.y*gridDim.x+blockIdx.x; // uint32_t index = blockIdx.x * blockDim.x + threadIdx.x; // uint32_t stride = blockDim.x * gridDim.x; // char hex_str[65]; SHA256_CTX *ctx = new SHA256_CTX(); // int i; // for (i = 0; i<3000000000; i++){ // } //WORD T_Nonce = pkgs[threadId]->input[19]; if(threadId < NUMTHREAD){ // for (uint32_t threadId = index; threadId < MAXNONCE; threadId += stride){ WORD T_Nonce = pkgs[threadId]->input[19]; endian_cvt(&T_Nonce); // if(threadId == 1024) // printf("Thread id %d: %08x maxnonce: %u\n", threadId, T_Nonce, MAXNONCE/NUMTHREAD); for(int i = 0; i<MAXNONCE/NUMTHREAD; i++){ // if(threadId == NUMTHREAD-1 && i==MAXNONCE/NUMTHREAD-1){ // // print_words_inline(&in[20*threadId+19], 1); // // printf("Thread ID (%d) = %08x%08x%08x%08x%08x%08x%08x%08x\n", threadId, out[8*threadId],out[8*threadId+1],out[8*threadId+2],out[8*threadId+3],out[8*threadId+4],out[8*threadId+5],out[8*threadId+6],out[8*threadId+7]); // } // printf("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\n", pkgs[threadId]->input[0],pkgs[threadId]->input[1],pkgs[threadId]->input[2],pkgs[threadId]->input[3],pkgs[threadId]->input[4],pkgs[threadId]->input[5],pkgs[threadId]->input[6],pkgs[threadId]->input[7], pkgs[threadId]->input[8], pkgs[threadId]->input[9], pkgs[threadId]->input[10], pkgs[threadId]->input[11], pkgs[threadId]->input[12], pkgs[threadId]->input[13], pkgs[threadId]->input[14], pkgs[threadId]->input[15], pkgs[threadId]->input[16], pkgs[threadId]->input[17], pkgs[threadId]->input[18], pkgs[threadId]->input[19]); //printf("Thread id %08x \n",pkgs[threadId]->input[19]); scrypt( &(pkgs[threadId]->ctx), \ pkgs[threadId]->input, \ 20, \ pkgs[threadId]->output, \ pkgs[threadId]->mem, \ pkgs[threadId]->salt, \ pkgs[threadId]->hmac_out, \ pkgs[threadId]->khash, \ pkgs[threadId]->in_ihash, \ pkgs[threadId]->in_2_ihash, \ pkgs[threadId]->ihash, \ pkgs[threadId]->in_ohash, \ pkgs[threadId]->pbkdf2_rm_out\ ); // printf("!!!!Hello\n"); // if(threadId == NUMTHREAD-1){ // // printf("i: %d\n", i); // } if(threadId == NUMTHREAD-1 && i==MAXNONCE/NUMTHREAD-1){ printf("Thread ID (%d) = %08x%08x%08x%08x%08x%08x%08x%08x\n", threadId, pkgs[threadId]->output[0],pkgs[threadId]->output[1],pkgs[threadId]->output[2],pkgs[threadId]->output[3],pkgs[threadId]->output[4],pkgs[threadId]->output[5],pkgs[threadId]->output[6],pkgs[threadId]->output[7]); } endian_cvt(&pkgs[threadId]->input[19]); pkgs[threadId]->input[19]++; // printf("Thread id %d: %u maxnonce: %u\n", threadId, pkgs[threadId]->input[19], MAXNONCE/NUMTHREAD); endian_cvt(&pkgs[threadId]->input[19]); } // printf("[%d]\n",\ // threadId); // words_to_hex_string(out[threadId], 8, hex_str, 64); // printf("Thread ID: %d, %s", threadId, hex_str); // print_words_inline(&out[threadId], 8); } } int main() { // static char test_scrypt_in[] = "0000002056efd1943684c1fdc247d4759cc43b29afa1cac7ad14579de5f6abcbc6bdf448ee3de4c7b45e9496ab41ecde73d1a299ddbcc7a81aa52776e6c067e214233af097b6885c97df011aa004090e"; // static char test_scrypt_in[] = "0000002056efd1943684c1fdc247d4759cc43b29afa1cac7ad14579de5f6abcbc6bdf448ee3de4c7b45e9496ab41ecde73d1a299ddbcc7a81aa52776e6c067e214233af097b6885c97df011a"; char ver[]="20000000"; char prev_block[]="48f4bdc6cbabf6e59d5714adc7caa1af293bc49c75d447c2fdc1843694d1ef56"; char mrkl_root[]="f03a2314e267c0e67627a51aa8c7bcdd99a2d173deec41ab96945eb4c7e43dee"; char time[9]; char bits[9]; little_endian(ver, sizeof(ver) - 1); little_endian(prev_block, sizeof(prev_block) - 1); little_endian(mrkl_root, sizeof(mrkl_root) - 1); // Get time struct tm t; time_t t_of_day; t.tm_year = 2019-1900; // Year - 1900 t.tm_mon = 3-1; // Month, where 1 = jan t.tm_mday = 13; // Day of the month t.tm_hour = 7+9; t.tm_min = 51; t.tm_sec = 51; t.tm_isdst = -1; // Is DST on? 1 = yes, 0 = no, -1 = unknown t_of_day = mktime(&t); WORD *wtime = new WORD(t_of_day); endian_cvt_host(wtime); word_to_hex_eight_host(*wtime, time, 8); word_to_hex_eight_host(436330391, bits, 8); // bits -- input little_endian(bits, 8); char test_scrypt_in[153]; int in_index = 0; for(int i = 0; i < sizeof(ver)-1; i++){ test_scrypt_in[i]=ver[i]; } in_index += sizeof(ver)-1; for(int i = 0; i < sizeof(prev_block); i++){ test_scrypt_in[in_index+i] = prev_block[i]; } in_index += sizeof(prev_block)-1; for(int i = 0; i < sizeof(mrkl_root); i++){ test_scrypt_in[in_index+i] = mrkl_root[i]; } in_index += sizeof(mrkl_root)-1; for(int i = 0; i < sizeof(time); i++){ test_scrypt_in[in_index+i] = time[i]; } in_index += sizeof(time)-1; for(int i = 0; i < sizeof(bits); i++){ test_scrypt_in[in_index+i] = bits[i]; } WORD *nonce = (WORD*) malloc(sizeof(WORD)); // WORD *nonce = new WORD(235472032); // WORD test_scrypt_out_w[8][NUMTHREAD]; SCRYPT_PKG **pkgs = (SCRYPT_PKG**)malloc(NUMTHREAD*sizeof(SCRYPT_PKG*)); // for(int k = 0; k<NUMTHREAD; k++){ // hex_string_to_words_host(test_scrypt_in, sizeof(test_scrypt_in), &test_scrypt_in_w[20*k]); // *nonce = STARTATNONCE + (k * (MAXNONCE/NUMTHREAD)); // endian_cvt_host(nonce); // test_scrypt_in_w[20*k+19] = *nonce; // } for(int k = 0; k<NUMTHREAD; k++){ pkgs[k] = (SCRYPT_PKG*)malloc(sizeof(SCRYPT_PKG)); hex_string_to_words_host(test_scrypt_in, sizeof(test_scrypt_in), pkgs[k]->input); *nonce = STARTATNONCE + (k * (MAXNONCE/NUMTHREAD)); endian_cvt_host(nonce); pkgs[k]->input[19] = *nonce; // printf("%d \n", pkgs[k]); // printf("%08x", pkgs[k]->input); // print_words_inline_host(pkgs[k]->input, 20); } uint32_t threadsPerBlock = 256; uint32_t blocksPerGrid =(threadsPerBlock + MAXNONCE - 1) / threadsPerBlock; // Add vectors in parallel. cudaError_t cudaStatus = scryptWithCuda(pkgs, blocksPerGrid, threadsPerBlock); if (cudaStatus != cudaSuccess) { fprintf(stderr, "scryptWithCuda failed!\n"); 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; } return 0; } SCRYPT_PKG* pkg_init(WORD* indata){ SCRYPT_PKG* pkg; cudaMallocManaged(&pkg, sizeof(SCRYPT_PKG)); for (int j = 0; j < 20; j++){ pkg->input[j] = indata[j]; // printf("%08x\n", pkg->input[j]); } return pkg; } // Helper function for using CUDA to add vectors in parallel. cudaError_t scryptWithCuda(SCRYPT_PKG **pkgs, int block_per_grid, int thread_per_block) { SCRYPT_PKG **pkgs_dev; cudaError_t cudaStatus; // SCRYPT_PKG *pkg_pointer; // Choose which GPU to run on, change this on a multi-GPU system. cudaStatus = cudaSetDevice(NO_DEVICE); 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 = cudaMallocManaged((void**)&pkgs_dev, NUMTHREAD * sizeof(SCRYPT_PKG*)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } for(int i = 0; i<NUMTHREAD; i++){ // Copy input vectors from host memory to GPU buffers. pkgs_dev[i] = pkg_init(pkgs[i]->input); // print_words_inline_host(pkgs[i]->input, 20); // printf(" %08x\n", pkgs_dev[i]); // cudaStatus = cudaMemcpy(pkgs_dev[i]->input, pkgs[i]->input, 20*sizeof(WORD), cudaMemcpyHostToDevice); // if (cudaStatus != cudaSuccess) { // fprintf(stderr, "cudaMemcpy failed!"); // goto Error; // } } // Launch a kernel on the GPU with one thread for each element. scryptCuda<<<block_per_grid, thread_per_block>>>(pkgs_dev); // Check for any errors launching the kernel cudaStatus = cudaGetLastError(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "scryptCuda launch failed: %s\n", cudaGetErrorString(cudaStatus)); goto Error; } // 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 scryptCuda!\n", cudaStatus); goto Error; } // // Copy output vector from GPU buffer to host memory. // cudaStatus = cudaMemcpy(out, dev_out, NUMTHREAD * 8 * sizeof(WORD), cudaMemcpyDeviceToHost); // if (cudaStatus != cudaSuccess) { // fprintf(stderr, "cudaMemcpy launch failed: %s\n", cudaGetErrorString(cudaStatus)); // goto Error; // } Error: cudaFree(pkgs_dev); return cudaStatus; }
5,849
// GPU kernel for convoluting sine and cosine multiplication data with filter coefficients with hamming window .... #define BLOCK_SIZE 512 #define WINDOW 500 __global__ void conv(float *dev_op_sine, float *dev_op_cosine, float *dev_op_sine_conv, float *dev_op_cosine_conv, float *dev_lpf_hamming, int b, int windowLength){ int i,l; __shared__ float dats[BLOCK_SIZE]; __shared__ float datc[BLOCK_SIZE]; __shared__ float coeff[WINDOW]; int threadid = threadIdx.x; int idx = threadIdx.x + blockIdx.x * 256; float temp1, temp2; dats[threadid] = dev_op_sine[idx]; datc[threadid] = dev_op_cosine[idx]; if(threadid < windowLength){ coeff[threadid] = dev_lpf_hamming[threadid]; } __syncthreads(); if(threadid < 256){ temp1 = 0; temp2 = 0; for( i = 0; i < windowLength ; ++i){ l = windowLength - i; temp1 += dats[threadid+l] * coeff[i]; temp2 += datc[threadid+l] * coeff[i]; } dev_op_sine_conv[idx] = temp1; dev_op_cosine_conv[idx] = temp2; } }
5,850
#include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <cuda_runtime.h> #include <cstdlib> #include <sstream> #include <iomanip> using namespace std; //input, filter and output considering maximum dimension possible double a[1000][1000], h[10][10], c[1000][1000]; /** * CUDA Kernel Device code * * Computes the 2D convolution of input b with filter h and output c */ __global__ void convolution2D(double *a_1, double *h_1, double *c_1, int rows_a, int columns_a, int rows_h, int columns_h) { int idx = blockDim.x * blockIdx.x + threadIdx.x; int idy = blockDim.y * blockIdx.y + threadIdx.y; double sum; if((idx < (columns_h+columns_a - 1)) && (idy < (rows_h + rows_a - 1))) { sum = 0; for(int k=0; k< rows_h; k++) { for(int j=0; j< columns_h; j++) { if ((idy - k) >= 0 && (idx - j) >= 0 && (idy - k) < rows_a && (idx - j) < columns_a) { sum += a_1[((idy - k)*columns_a) + (idx - j)] * h_1[k*columns_h + j]; } } } c_1[idy*(columns_a + columns_h - 1) + idx] = sum; __syncthreads(); } } /** * Host main routine */ int main(int argc, char** argv) { // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; int columns_a, columns_h, rows_a, rows_h, size_a, size_h; columns_a = columns_h = 0; size_a = size_h = rows_a = rows_h = 0; char *ip_file; string line; double input; ip_file = argv[1]; int i, j, k; ifstream file(ip_file); if(file.is_open()) { i=0; while(getline(file, line) && line != "") { j=0; stringstream ss(line); while(ss >> input) { a[i][j] = input; size_a++; j++; } i++; rows_a++; } k=0; while(getline(file, line) && line != "") { j=0; stringstream ss(line); while(ss >> input) { h[k][j] = input; j++; size_h++; } k++; rows_h++; } } file.close(); columns_a = size_a/rows_a; columns_h = size_h/rows_h; int op_size = ((rows_a+rows_h-1)*(columns_a+columns_h-1)); size_t size_ax = size_a*sizeof(double); size_t size_hx = size_h*sizeof(double); size_t size_cx = op_size*sizeof(double); // Allocate the host input vector a double *h_a; cudaMallocManaged(&h_a, size_ax); // Allocate the host input vector h double *h_h; cudaMallocManaged(&h_h, size_hx); // Allocate the host output vector c double *h_c; cudaMallocManaged(&h_c, size_cx); for (int i = 0; i < rows_a; i++) { for(int j=0;j< columns_a; j++) { h_a[i*columns_a + j] = a[i][j]; } } for (int i = 0; i < rows_h; i++) { for(int j=0;j< columns_h; j++) { h_h[i*columns_h + j] = h[i][j]; } } // Launch the CUDA Kernel dim3 blocksPerGrid(((rows_a + rows_h - 2) / 32) + 1, ((columns_h + columns_a - 2) / 32) + 1, 1); dim3 threadsPerBlock(32,32,1); convolution2D<<<blocksPerGrid, threadsPerBlock>>>(h_a, h_h, h_c, rows_a, columns_a, rows_h, columns_h); err = cudaGetLastError(); if (err != cudaSuccess) { fprintf(stderr, "Failed to launch convolution2D kernel (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaDeviceSynchronize(); if (err != cudaSuccess) { fprintf(stderr, "Failed to synchronize (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// for (int i = 0; i < rows_a + rows_h - 1; i++) { for (int j = 0; j < columns_a + columns_h - 1; j++) { cout << fixed << setprecision(3) << h_c[(i*(columns_h+columns_a-1))+j] << " "; } cout << endl; } // Free device global memory err = cudaFree(h_a); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector a (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaFree(h_h); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector h (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } err = cudaFree(h_c); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector c (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Reset the device and exit // cudaDeviceReset causes the driver to clean up all state. While // not mandatory in normal operation, it is good practice. It is also // needed to ensure correct operation when the application is being // profiled. Calling cudaDeviceReset causes all profile data to be // flushed before the application exits err = cudaDeviceReset(); if (err != cudaSuccess) { fprintf(stderr, "Failed to deinitialize the device! error=%s\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printf("Done\n"); return 0; }
5,851
#include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <cmath> #include <cuda_runtime.h> //use INSTANTIATE when kernel is called from other files #define INSTANTIATE_LAYER_GPU_FORWARD(func) \ template __global__ void func<float>(float* d_out, const float* d_in, \ const float* d_kernel, const float* d_kernel_bias); \ template __global__ void func<double>(double* d_out, const double* d_in, \ const double* d_kernel, const double* d_kernel_bias); using namespace std; template <typename Dtype> int ConvKernel(string name, Dtype* d_out, const Dtype* d_in, const Dtype* d_kernel, const Dtype* d_kernel_bias){ cout << "Calling Conv Kernel " << name << endl; cerr<<"No Matching Convolution Code"<<endl; return -1; } template int ConvKernel<float>(string name, float* d_out, const float* d_in, const float* d_kernel, const float* d_kernel_bias); template int ConvKernel<double>(string name, double* d_out, const double* d_in, const double* d_kernel, const double* d_kernel_bias);
5,852
#include "includes.h" __global__ void kMultTransFast(float* a, float* b, float* dest, unsigned int width, unsigned int height, unsigned int bJumpWidth) { const unsigned int idxY = blockIdx.y * blockDim.y + threadIdx.y; const unsigned int idxX = blockIdx.x * blockDim.x + threadIdx.x; const unsigned int idx = idxY * width + idxX; __shared__ float smem[ADD_BLOCK_SIZE][ADD_BLOCK_SIZE + 1]; const unsigned int bBlockReadStart = blockDim.x * blockIdx.x * bJumpWidth + blockIdx.y * blockDim.y; smem[threadIdx.x][threadIdx.y] = b[bBlockReadStart + threadIdx.y * bJumpWidth + threadIdx.x]; __syncthreads(); dest[idx] = a[idx] * smem[threadIdx.y][threadIdx.x]; }
5,853
#include <stdio.h> #define N 500 __global__ void VecAdd(int* DA, int* DB, int* DC) { int i = blockIdx.x; DC[i] = DA[i] + DB[i]; } int main() { cudaFree(0); int HA[N], HB[N], HC[N]; int *DA, *DB, *DC; int i; int size = N*sizeof(int); cudaError_t aM,bM,cM, aN, bN, cN, e_kernel; //Guardar errores // reservamos espacio en la memoria global del device aM = cudaMalloc((void**)&DA, size); printf("%s \n",cudaGetErrorString(aM)); bM = cudaMalloc((void**)&DB, size); printf("%s \n",cudaGetErrorString(bM)); cM = cudaMalloc((void**)&DC, size); printf("%s \n",cudaGetErrorString(cM)); // inicializamos HA y HB for (i=0; i<N; i++) {HA[i]=-i; HB[i] = 3*i;} // copiamos HA y HB del host a DA y DB en el device, respectivamente aN = cudaMemcpy(DA, HA, size, cudaMemcpyHostToDevice); printf("%s \n",cudaGetErrorString(aN)); bN = cudaMemcpy(DB, HB, size, cudaMemcpyHostToDevice); printf("%s \n",cudaGetErrorString(bN)); // llamamos al kernel (1 bloque de N hilos) VecAdd <<<N, 1>>>(DA, DB, DC); // N hilos ejecutan el kernel en paralelo e_kernel = cudaGetLastError(); //Cojer ultimo error, ya que el kernel no devuelve ningun error_t printf("%s \n",cudaGetErrorString(e_kernel)); //Imprimir ultimo error // copiamos el resultado, que está en la memoria global del device, (DC) al host (a HC) cN = cudaMemcpy(HC, DC, size, cudaMemcpyDeviceToHost); printf("%s \n",cudaGetErrorString(cN)); // liberamos la memoria reservada en el device cudaFree(DA); cudaFree(DB); cudaFree(DC); // una vez que tenemos los resultados en el host, comprobamos que son correctos // esta comprobación debe quitarse una vez que el programa es correcto (p. ej., para medir el tiempo de ejecución) for (i = 0; i < N; i++) // printf("%d + %d = %d\n",HA[i],HB[i],HC[i]); if (HC[i]!= (HA[i]+HB[i])) {printf("error en componente %d\n", i); break;} return 0; }
5,854
#include "includes.h" // ERROR CHECKING MACROS ////////////////////////////////////////////////////// __global__ void randControls(int noPaths, int nYears, int noControls, float* randCont, int* control) { int idx = blockIdx.x*blockDim.x + threadIdx.x; if (idx < noPaths*nYears) { control[idx] = (int)(randCont[idx]*noControls); if (control[idx] == noControls) { control[idx]--; } } }
5,855
__global__ void t_sum(float *a, float *out, int n_elements) { const int i = blockDim.x * blockIdx.x + threadIdx.x; if (i == 0) out[0] = 0; __syncthreads(); if (i < n_elements) atomicAdd(out, a[i]); }
5,856
#include "includes.h" __global__ void kAdagrad(float *history, float *grad, float delta, int len) { const unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x; const unsigned int numThreads = blockDim.x * gridDim.x; for (unsigned int i = idx; i < len; i += numThreads) { float curr_norm = history[i] - delta; history[i] = delta + sqrt(curr_norm * curr_norm + grad[i] * grad[i]); } }
5,857
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdbool.h> #include <cuda.h> #include <cuda_runtime.h> #include<bits/stdc++.h> #define MAX_ARGS 100000 extern "C" int count; extern "C" char ** words_array; static inline char ** parse_read(char * buffer, int * Length, int in_len){ char ** array; //array = (char **)calloc(MAX_ARGS, sizeof(char *)); cudaMallocManaged(&array, MAX_ARGS*sizeof(int)); int len=in_len; // delimit commands by space and newline char * pch; pch = strtok (buffer,",\n \r\n"); while (pch != NULL){ *(array+len)=(char *)calloc(50, sizeof(char)); strcpy(*(array+len), pch); //printf("psh: %s\n", pch); len++; pch = strtok (NULL, ",\n \r\n"); } array[len]=NULL; //NULL terminate array for use in execv *Length=len; return array; } static inline void cudaInitMaster(int rank, int nprocs, char * text, int * length, int in_len){ int cE, cudaDeviceCount; if((cE = cudaGetDeviceCount( &cudaDeviceCount)) != cudaSuccess ){ printf(" Unable to determine cuda device count, error is %d, count is %d\n", cE, cudaDeviceCount ); exit(-1); } if((cE = cudaSetDevice( rank % cudaDeviceCount )) != cudaSuccess ){ printf(" Unable to have rank %d set to cuda device %d, error is %d \n", rank, (rank % cudaDeviceCount), cE); exit(-1); } words_array = parse_read(text, length, in_len); } extern "C" void initMaster(int rank, int nprocs, char * text, int * length, int in_len){ cudaInitMaster(rank, nprocs, text, length, in_len); } __global__ void countSubstring(char** string, int length, char** to_find, int find, int * counter) { unsigned int index = blockIdx.x * blockDim.x + threadIdx.x; unsigned int stride = blockDim.x * gridDim.x; for(unsigned int i = index; i<length; i+=stride){ int found = 1; if(i+(2*stride)<length){ for(int j =0; j<find;j++){ if(string[i+(j*stride)] == to_find[j]) found = 0; } } if(found)*counter++; } } extern "C" void kernelCall(char ** array, int length, ushort threadsCount, int numBlocks, char ** to_find, int find, int * counter){ countSubstring<<<numBlocks, threadsCount>>>(array, length, to_find, find, counter); }
5,858
#include <stdio.h> #include <cuda_profiler_api.h> #include <unistd.h> #include <curand.h> #include <curand_kernel.h> #define SHARED_MEM_ELEMENTS 1024 #define GLOBAL_MEM_ELEMENTS 4096 //#define GLOBAL_MEM_ELEMENTS 131072 //#define GLOBAL_MEM_ELEMENTS 196608 int num_blocks; int num_threads_per_block; int num_iterations; int divergence; __global__ void init_memory (unsigned long long ** my_ptr_array, unsigned long long * my_array, int stride, int num_blocks_k, int num_threads_per_block_k) { int block_id; int warp_id; int i; int index; int tid = blockDim.x * blockIdx.x + threadIdx.x; void **ptr_array = (void **)my_ptr_array; unsigned long long *array = (unsigned long long *)my_array; if (tid == 0) { // int elements_per_block = GLOBAL_MEM_ELEMENTS / num_blocks_k; int num_warps_per_block = num_threads_per_block_k / 32; //int elements_per_warp = elements_per_block / num_warps_per_block; int elements_per_warp = GLOBAL_MEM_ELEMENTS / num_warps_per_block; // for (block_id = 0; block_id < num_blocks_k; block_id++) { for (warp_id = 0; warp_id < num_warps_per_block; warp_id++) { for (i = 0; i < elements_per_warp; i++) { //index = (block_id * elements_per_block) + (warp_id * elements_per_warp); index = (warp_id * elements_per_warp); ptr_array[index + i] = (void*)&array[(index + ((i + 16) % elements_per_warp))]; } } /* for (i = 0; i < GLOBAL_MEM_ELEMENTS; i++) { ptr_array[i] = (void*)&array[(i + 32)%GLOBAL_MEM_ELEMENTS]; } */ for (i = 0; i < GLOBAL_MEM_ELEMENTS; i++) { //array[i] = (unsigned long long)ptr_array[(i+stride)%GLOBAL_MEM_ELEMENTS]; array[i] = (unsigned long long)ptr_array[i]; } } __syncthreads(); } __global__ void shared_latency (unsigned long long ** my_ptr_array, unsigned long long * my_array, int array_length, int iterations, unsigned long long * duration, int stride, int divergence, int num_blocks_k, int num_threads_per_block_k, unsigned long long ** my_end_ptr_array) { unsigned long long int start_time, end_time; unsigned long long int sum_time = 0; int i, k; int tid = blockDim.x * blockIdx.x + threadIdx.x; int block_id = blockIdx.x; int warp_id = threadIdx.x / 32; int warp_thread_id = threadIdx.x % 32; // int elements_per_block = GLOBAL_MEM_ELEMENTS / num_blocks_k; int num_warps_per_block = num_threads_per_block_k / 32; // int elements_per_warp = elements_per_block / num_warps_per_block; int elements_per_warp = GLOBAL_MEM_ELEMENTS / num_warps_per_block; //int index1 = (block_id * elements_per_block) + (warp_id * elements_per_warp) + warp_thread_id; int index1 = (warp_id * elements_per_warp) + warp_thread_id; void **ptr_array = (void **)my_ptr_array; unsigned long long int *array = (unsigned long long int *)my_array; void **tmp_ptr; //tmp_ptr = (void *)sdata; //tmp_ptr = (void **)(&(ptr_array[(threadIdx.x * stride)%GLOBAL_MEM_ELEMENTS])); //tmp_ptr = (void **)(&(ptr_array[(tid * stride)%GLOBAL_MEM_ELEMENTS])); tmp_ptr = (void **)(&(ptr_array[index1])); //#define ONCE tmp_ptr = *(void**)tmp_ptr; #define ONCE tmp_ptr = (void**)(*tmp_ptr); #define REPEAT_FOUR_TIMES ONCE ONCE ONCE ONCE #define REPEAT_SIXTEEN_TIMES REPEAT_FOUR_TIMES REPEAT_FOUR_TIMES REPEAT_FOUR_TIMES REPEAT_FOUR_TIMES #define REPEAT_SIXTYFOUR_TIMES REPEAT_SIXTEEN_TIMES REPEAT_SIXTEEN_TIMES REPEAT_SIXTEEN_TIMES REPEAT_SIXTEEN_TIMES if ((threadIdx.x % 32) < divergence) { for(k = 0; k <= iterations; k++) { // tmp_ptr = (void**)(*tmp_ptr); if (k == 0) { sum_time = 0; } start_time = clock(); // ONCE REPEAT_SIXTYFOUR_TIMES; REPEAT_SIXTYFOUR_TIMES; REPEAT_SIXTYFOUR_TIMES; REPEAT_FOUR_TIMES; REPEAT_FOUR_TIMES; end_time = clock(); sum_time += (end_time - start_time); } } my_end_ptr_array[tid] = (unsigned long long*)(*tmp_ptr); duration[tid] = sum_time; } // Shared memory array size is N-2. Last two elements are used as dummy variables. void parametric_measure_shared(int N, int iterations, int stride) { cudaProfilerStop(); int i; unsigned long long int * h_a; unsigned long long int * d_a; unsigned long long ** h_ptr_a; unsigned long long ** d_ptr_a; unsigned long long ** h_end_ptr_a; unsigned long long ** d_end_ptr_a; unsigned long long * duration; unsigned long long * latency; cudaError_t error_id; /* allocate array on CPU */ h_a = (unsigned long long *)malloc(sizeof(unsigned long long int) * N); h_ptr_a = (unsigned long long **)malloc(sizeof(unsigned long long int*)*N); latency = (unsigned long long *)malloc(sizeof(unsigned long long) * num_threads_per_block * num_blocks); h_end_ptr_a = (unsigned long long **)malloc(sizeof(unsigned long long int*) * num_threads_per_block * num_blocks); /* initialize array elements on CPU */ for (i = 0; i < N; i++) { h_ptr_a[i] = (unsigned long long *)&h_a[i]; } for (i = 0; i < N; i++) { h_a[i] = (unsigned long long)h_ptr_a[(i + 1 + stride) % N]; } /* allocate arrays on GPU */ cudaMalloc ((void **) &d_a, sizeof(unsigned long long int) * N ); cudaMalloc ((void **) &d_ptr_a, sizeof(unsigned long long int*) * N ); cudaMalloc ((void **) &duration, sizeof(unsigned long long) * num_threads_per_block * num_blocks); cudaMalloc ((void **) &d_end_ptr_a, sizeof(unsigned long long *) * num_threads_per_block * num_blocks); cudaThreadSynchronize (); error_id = cudaGetLastError(); if (error_id != cudaSuccess) { printf("Error 1 is %s\n", cudaGetErrorString(error_id)); } /* copy array elements from CPU to GPU */ cudaMemcpy((void *)d_a, (void *)h_a, sizeof(unsigned long long int) * N, cudaMemcpyHostToDevice); cudaMemcpy((void *)d_ptr_a, (void *)h_ptr_a, sizeof(unsigned long long int *) * N, cudaMemcpyHostToDevice); cudaMemcpy((void *)duration, (void *)latency, sizeof(unsigned long long) * num_threads_per_block * num_blocks, cudaMemcpyHostToDevice); cudaMemcpy((void *)d_end_ptr_a, (void *)h_end_ptr_a, sizeof(unsigned long long *) * num_threads_per_block * num_blocks, cudaMemcpyHostToDevice); cudaThreadSynchronize (); error_id = cudaGetLastError(); if (error_id != cudaSuccess) { printf("Error 2 is %s\n", cudaGetErrorString(error_id)); } init_memory <<<1, 1>>>(d_ptr_a, d_a, stride, num_blocks, num_threads_per_block); cudaDeviceSynchronize(); /* launch kernel*/ //dim3 Db = dim3(13); //dim3 Dg = dim3(768,1,1); //printf("Launch kernel with parameters: %d, N: %d, stride: %d\n", iterations, N, stride); // int sharedMemSize = sizeof(unsigned long long int) * N ; for (int i = 0; i < 1; i++) { cudaEvent_t start, stop; float time; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start, 0); cudaProfilerStart(); cudaFuncSetCacheConfig(shared_latency, cudaFuncCachePreferL1); //shared_latency <<<Dg, Db, sharedMemSize>>>(d_a, N, iterations, duration); //shared_latency <<<num_blocks, num_threads_per_block, sharedMemSize>>>(d_a, N, num_iterations, duration, stride, divergence); shared_latency <<<num_blocks, num_threads_per_block>>>(d_ptr_a, d_a, N, num_iterations, duration, stride, divergence, num_blocks, num_threads_per_block, d_end_ptr_a); cudaDeviceSynchronize(); ///cudaThreadSynchronize (); cudaProfilerStop(); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&time, start, stop); error_id = cudaGetLastError(); if (error_id != cudaSuccess) { printf("Error 3 is %s\n", cudaGetErrorString(error_id)); } /* copy results from GPU to CPU */ cudaMemcpy((void *)h_a, (void *)d_a, sizeof(unsigned long long int) * N, cudaMemcpyDeviceToHost); cudaMemcpy((void *)latency, (void *)duration, sizeof(unsigned long long) * num_threads_per_block * num_blocks, cudaMemcpyDeviceToHost); cudaMemcpy((void *)h_end_ptr_a, (void *)d_end_ptr_a, sizeof(unsigned long long *) * num_threads_per_block * num_blocks, cudaMemcpyDeviceToHost); cudaThreadSynchronize (); /* print results*/ unsigned long long max_dur = latency[0]; unsigned long long min_dur = latency[0]; unsigned long long avg_lat = latency[0]; for (int i = 1; i < num_threads_per_block * num_blocks; i++) { if (latency[i] > 0) { avg_lat += latency[i]; if (latency[i] > max_dur) { max_dur = latency[i]; } else if (latency[i] < min_dur) { min_dur = latency[i]; } } } printf(" %d, %f, %f, %f, %f\n",stride,(double)(avg_lat/(num_threads_per_block * (divergence / 32.0) * num_blocks * 200.0 *num_iterations)), (double)(min_dur/(200.0 * num_iterations)), (double)(max_dur/(200.0 * num_iterations)), time); //printf(" %d, %f, %f, %f, %f\n",stride,(double)(avg_lat/(num_threads_per_block * num_blocks * 200.0 *num_iterations)), (double)(min_dur/(200.0 * num_iterations)), (double)(max_dur/(200.0 * num_iterations)), time); //printf("%f\n", time); } /* free memory on GPU */ cudaFree(d_a); cudaFree(d_ptr_a); cudaFree(d_end_ptr_a); cudaFree(duration); cudaThreadSynchronize (); /*free memory on CPU */ free(h_a); free(h_ptr_a); free(h_end_ptr_a); free(latency); } void usage() { printf("Usage ./binary <num_blocks> <num_threads_per_block> <iterations> <threads active per warp> <stride>\n"); } int main(int argc, char **argv) { int N, stride; // initialize upper bounds here // int stride_upper_bound = 1; if(argc != 6) { usage(); exit(1); } num_blocks = atoi(argv[1]); num_threads_per_block = atoi(argv[2]); num_iterations = atoi(argv[3]); divergence = atoi(argv[4]); stride = atoi(argv[5]); // printf("Shared memory latency for varying stride.\n"); // printf("stride (bytes), latency (clocks)\n"); // N = SHARED_MEM_ELEMENTS; N = GLOBAL_MEM_ELEMENTS; // N = num_threads_per_block; // stride_upper_bound = 1; // for (stride = 1; stride <= stride_upper_bound; stride += 1) { parametric_measure_shared(N, 10, stride); // } return 0; }
5,859
#include<stdio.h> #define K 32 //tile size is KxK #define N 1024 //matrix size is NxN __global__ void transpose_serial(int *in, int *out) { for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ out[i*N+j]=in[j*N+i]; } } } __global__ void transpose_per_row(int *in, int *out) { int i=threadIdx.x; for(int j=0;j<N;j++){ out[i*N+j]=in[j*N+i]; } } __global__ void transpose_per_element(int *in, int *out) { int i=blockIdx.x*K+threadIdx.x; int j=blockIdx.y*K+threadIdx.y; out[i*N+j]=in[j*N+i]; } __global__ void transpose_per_element_tiled(int *in, int *out) { int in_i=blockIdx.x*K; //Corner point to start reading int in_j=blockIdx.y*K; int out_i=blockIdx.y*K; //Corner point to start writing int out_j=blockIdx.x*K; int x=threadIdx.x; int y=threadIdx.y; __shared__ int tile[K][K]; tile[y][x] = in[(in_i+x)+(in_j+y)*N]; __syncthreads(); out[(out_i+x)+(out_j+y)*N] = tile[x][y]; } int main(void) { int *in,*out; int *d_in,*d_out; int size = sizeof(int) * N * N; in= (int *)(malloc(size)); out= (int *)(malloc(size)); //printf("Elements of in \n"); for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { in[i+j*N]=j; } } cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); cudaMalloc((void **)&d_in,size); cudaMalloc((void **)&d_out,size); cudaMemcpy(d_in,in,size,cudaMemcpyHostToDevice); dim3 block(N/K,N/K); dim3 thread(K,K); cudaEventRecord(start); //transpose_per_element_tiled<<<block,thread>>>(d_in,d_out); transpose_per_element_tiled<<<block,thread>>>(d_in,d_out); //tranpose_per_row<<<1,N>>> //transpose_serial<<<1,1>>> cudaEventRecord(stop); cudaEventSynchronize(stop); float ms; cudaEventElapsedTime(&ms,start,stop); cudaMemcpy(out,d_out,size,cudaMemcpyDeviceToHost); //printf("Elements of out\n"); // for(int i=0;i<N;i++) //{ //for(int j=0;j<N;j++) // { // printf("%d\t",out[i+j*N]); // } // } printf("Time taken = %f \n",ms); cudaFree(d_in); cudaFree(d_out); return 0; }
5,860
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define GET_TIME(X, Y) (((Y).tv_sec - (X).tv_sec) + ((Y).tv_nsec - (X).tv_nsec) / 1000000000.0) #define THREADS_PER_BLOCK 1024 __constant__ __device__ int IE_d; __constant__ __device__ int JE_d; __constant__ __device__ float cb_d; __constant__ __device__ int is_d; __constant__ __device__ float pi_d; __constant__ __device__ float freq_d; __constant__ __device__ float dt_d; __constant__ __device__ float db_d; __global__ void ezCalc ( float *ez, float *hx, float *hy ) { int i, j = blockIdx.x; for (i = threadIdx.x; i < IE_d; i += blockDim.x) { if (i == 0 || i == IE_d - 1) ez[j * IE_d + i] = 0.0; if (j != 0 && !(i == 0 || i == IE_d - 1)) { // at x=0 ez[j * IE_d + i] = ez[j * IE_d + i] + cb_d * (hy[j * IE_d + i] - hy[j * IE_d + (i - 1)] + hx[(j - 1 + JE_d) * IE_d + i] - hx[j * IE_d + i]); } else if (!(i == 0 || i == IE_d - 1)) ez[j * IE_d + i] = ez[j * IE_d + i] + cb_d * (hy[j * IE_d + i] - hy[j * IE_d + (i - 1)] + hx[(j - 1) * IE_d + i] - hx[j * IE_d + i]); } } __global__ void ezCalc2 ( float *ez , int n ) { int j; for (j = threadIdx.x; j < JE_d; j += blockDim.x) { ez[j * IE_d + is_d] = cos(2 * pi_d * freq_d * n * dt_d); } } __global__ void hCalc ( float *ez, float *hx, float *hy ) { int i, j = blockIdx.x; for (i = threadIdx.x; i < IE_d; i += blockDim.x) { if (j + 1 == JE_d) hx[j * IE_d + i] = hx[j * IE_d + i] + db_d * (ez[j * IE_d + i] - ez[i]); else hx[j * IE_d + i] = hx[j * IE_d + i] + db_d * (ez[j * IE_d + i] - ez[(j + 1) * JE_d + i]); if (i == IE_d - 1) hy[j * JE_d + i] = hy[j * JE_d + i] + db_d * (0 - ez[j * JE_d + i]); else hy[j * JE_d + i] = hy[j * JE_d + i] + db_d * (ez[j * JE_d + (i + 1)] - ez[j * JE_d + i]); } } int main(int argc, char * argv[]) { int IE, JE, nsteps; int i, j, n, is; float pi = 3.141592653589793238462643; float * ez, * hx, * hy; float * ez_d, *hx_d, * hy_d; float dx, dt, epsz, mu, courant, cb, db, c, freq; int size; struct timespec Begin, Step0, Step1, Step2, Step3, End; FILE * fp; if (argc != 4) { printf("Invalid arguments... please type:\n"); printf(" %s IE JE steps\n", argv[0]); exit(0); } IE = atoi(argv[1]); JE = atoi(argv[2]); nsteps = atoi(argv[3]); printf("Running 2D FDTD algorithm with matrix of size %d x %d (%d steps)\n", IE, JE, nsteps); cudaMemcpyToSymbol(pi_d, &pi, sizeof(float), 0, cudaMemcpyHostToDevice); is = 10; cudaMemcpyToSymbol(is_d, &is, sizeof(int), 0, cudaMemcpyHostToDevice); epsz = 8.854e-12; mu = 4.0 * pi * 1.0e-7; c = 3.0e8; courant = 0.5; dx = 0.001; dt = (courant * dx) / (sqrt(2) * c); cudaMemcpyToSymbol(dt_d, &dt, sizeof(float), 0, cudaMemcpyHostToDevice); cb = dt / (epsz * dx); db = dt / (mu * dx); cudaMemcpyToSymbol(cb_d, &cb, sizeof(float), 0, cudaMemcpyHostToDevice); cudaMemcpyToSymbol(db_d, &db, sizeof(float), 0, cudaMemcpyHostToDevice); printf("Coefficients are: dt=%g cb=%g db=%g\n", dt, cb, db); size = IE * JE; ez = (float * ) calloc(size, sizeof(float)); hx = (float * ) calloc(size, sizeof(float)); hy = (float * ) calloc(size, sizeof(float)); cudaMalloc( (void **) &ez_d, size * sizeof(float)); cudaMalloc( (void **) &hx_d, size * sizeof(float)); cudaMalloc( (void **) &hy_d, size * sizeof(float)); freq = 50e9; cudaMemcpyToSymbol(freq_d, &freq, sizeof(float), 0, cudaMemcpyHostToDevice); cudaMemcpyToSymbol(JE_d, &JE, sizeof(float), 0, cudaMemcpyHostToDevice); cudaMemcpyToSymbol(IE_d, &IE, sizeof(float), 0, cudaMemcpyHostToDevice); if (clock_gettime(CLOCK_REALTIME, &Begin) == -1) { perror("Error in gettime"); exit(1); } // Transfer initial matrices to gpu cudaMemcpy( ez_d, ez, size * sizeof(float), cudaMemcpyHostToDevice ); cudaMemcpy( hx_d, hx, size * sizeof(float), cudaMemcpyHostToDevice ); cudaMemcpy( hy_d, hy, size * sizeof(float), cudaMemcpyHostToDevice ); for (n = 0; n < nsteps; n++) { // TIME if (clock_gettime(CLOCK_REALTIME, &Step0) == -1) { perror("Error in gettime"); exit(1); } //Calculate the Ez field ezCalc<<<JE, THREADS_PER_BLOCK>>>( ez_d, hx_d, hy_d ); clock_gettime(CLOCK_REALTIME, &Step1); //Ez field generator (line) ezCalc2<<<1, THREADS_PER_BLOCK>>>( ez_d , n ); clock_gettime(CLOCK_REALTIME, &Step2); //Calculate the H field hCalc<<<JE, THREADS_PER_BLOCK>>>( ez_d, hx_d, hy_d ); if (clock_gettime(CLOCK_REALTIME, &Step3) == -1) { perror("Error in gettime"); exit(1); } } // Retrieve matrices from gpu cudaMemcpy( ez, ez_d, size * sizeof(float), cudaMemcpyDeviceToHost ); cudaMemcpy( hx, hx_d, size * sizeof(float), cudaMemcpyDeviceToHost ); cudaMemcpy( hy, hy_d, size * sizeof(float), cudaMemcpyDeviceToHost ); if (clock_gettime(CLOCK_REALTIME, &End) == -1) { perror("Error in gettime"); exit(1); } printf("\n\n====Total time: %f\n", GET_TIME(Begin, End)); // write output to file fp = fopen("output_gpu_v4.txt", "w"); fprintf(fp, "==================== Ez MATRIX ========================\n"); for (i = 0, j = 0; (i < IE * JE) && (i < 1000); i++, j++) { if (j == 8) { fprintf(fp, "\n"); j = 0; } fprintf(fp, "%8f ", ez[i]); } fprintf(fp, "==================== Hx MATRIX ========================\n"); for (i = 0, j = 0; (i < IE * JE) && (i < 1000); i++, j++) { if (j == 8) { fprintf(fp, "\n"); j = 0; } fprintf(fp, "%8f ", hx[i]); } fprintf(fp, "==================== Hy MATRIX ========================\n"); for (i = 0, j = 0; (i < IE * JE) && (i < 1000); i++, j++) { if (j == 8) { fprintf(fp, "\n"); j = 0; } fprintf(fp, "%8f ", hy[i]); } free(ez); free(hy); free(hx); cudaFree( ez_d ); cudaFree( hx_d ); cudaFree( hy_d ); return 0; }
5,861
#include <cstddef> #include <stdexcept> namespace impala { void* allocatePinnedMemory(std::size_t size) { void* ptr; auto ret = cudaMallocHost(&ptr, size); if (ret != cudaSuccess) { throw std::runtime_error("cudaMallocHost failed"); } return ptr; } void freePinnedMemory(void* ptr) { auto ret = cudaFreeHost(ptr); if (ret != cudaSuccess) { throw std::runtime_error("cudaFreeHost failed"); } } } // namespace impala
5,862
#include "includes.h" __global__ void mm(float *dA, float *dB, float *dC, int DIM, int N, int GPUN) { int id = blockIdx.x * blockDim.x + threadIdx.x; if (id <= GPUN) { int i = id / DIM; int j = id % DIM; float sum = 0.0f; for (int k = 0; k < DIM; k++) { sum += dA[i*DIM+k] * dB[k*DIM+j]; } dC[id] = sum; } }
5,863
#include <stdio.h> #include <stdlib.h> /** * Computes the log of reaction rate. * @param a: Pointer to coefficient matrix. * @param temp: Pointer to temperature array. * @param lam: Matrix to write the results to. * @param nsets: Number of sets / number of rows in coefficient matrix. * @param ncells: Number of cells / length of temperature array. * @param ncoeff: Number of coefficients / number of columns in coefficient matrix. */ template <class dtype> __device__ void rates(dtype *a, dtype *temp, dtype *lam, int nsets, int ncells, int ncoeff) { int istart = blockIdx.x * blockDim.x + threadIdx.x; int istep = blockDim.x * gridDim.x; int jstart = blockIdx.y * blockDim.y + threadIdx.y; int jstep = blockDim.y * gridDim.y; int kstart = blockIdx.z * blockDim.z + threadIdx.z; int kstep = blockDim.z * gridDim.z; for(int i = istart; i < nsets; i += istep) { for(int j = jstart; j < ncells; j += jstep) { dtype temp9 = temp[j] * 1.0e-9; for(int k = kstart; k < ncoeff; k += kstep) { switch(k) { case 0: atomicAdd(&lam[i * ncells + j], a[i * ncoeff + k]); break; case 6: atomicAdd(&lam[i * ncells + j], a[i * ncoeff + k] * log(temp9)); break; default: atomicAdd(&lam[i * ncells + j], a[i * ncoeff + k] * pow(temp9, (2 * k - 5) / 3.0)); break; } } } } } template <> __device__ void rates<float>(float *a, float *temp, float *lam, int nsets, int ncells, int ncoeff) { int istart = blockIdx.x * blockDim.x + threadIdx.x; int istep = blockDim.x * gridDim.x; int jstart = blockIdx.y * blockDim.y + threadIdx.y; int jstep = blockDim.y * gridDim.y; int kstart = blockIdx.z * blockDim.z + threadIdx.z; int kstep = blockDim.z * gridDim.z; for(int i = istart; i < nsets; i += istep) { for(int j = jstart; j < ncells; j += jstep) { float temp9 = temp[j] * 1.0e-9; for(int k = kstart; k < ncoeff; k += kstep) { switch(k) { case 0: atomicAdd(&lam[i * ncells + j], a[i * ncoeff + k]); break; case 6: atomicAdd(&lam[i * ncells + j], a[i * ncoeff + k] * logf(temp9)); break; default: atomicAdd(&lam[i * ncells + j], a[i * ncoeff + k] * powf(temp9, (2 * k - 5) / 3.0f)); break; } } } } } template <class dtype, int nsets, int ncells, int ncoeff> __global__ void exec(dtype* lam) { // Tensors __shared__ dtype a[nsets * ncoeff]; __shared__ dtype temp[ncells]; int xInd = blockIdx.x * blockDim.x + threadIdx.x; int yInd = blockIdx.y * blockDim.y + threadIdx.y; int ySize = blockDim.y * gridDim.y; int zInd = blockIdx.z * blockDim.z + threadIdx.z; int zSize = blockDim.z * gridDim.z; int ind = xInd * ySize * zSize + yInd * zSize + zInd; /******************************** * Initialize coefficient matrix * ********************************/ if(ind < nsets * ncoeff) { if(ind % ncoeff != 7) { a[ind] = ind - (ind / ncoeff - 1); } else { a[ind] = 0.0; } } /****************************************** * Initialize the temperature in each cell * ******************************************/ if(ind < ncells) { temp[ind] = (ind + 1) * 1e9; } /**************************** * Zero the array of results * ****************************/ if(ind < nsets * ncells) { lam[ind] = 0.0; } /******************************************* * Compute ln(lambda) for each set and cell * *******************************************/ rates<dtype>(a, temp, lam, nsets, ncells, ncoeff); } int main() { // Tensor dimensions const int nsets = 4, ncells = 4, ncoeff = 8; // Results and elapsed time float *lam; cudaMallocManaged(&lam, nsets * ncells * sizeof(float)); // Compute the rates dim3 threadsPerBlock(nsets, ncells, ncoeff); dim3 numBlocks(1, 1, 1); exec<float, nsets, ncells, ncoeff><<<numBlocks, threadsPerBlock>>>(lam); // Print ln(lambda) cudaDeviceSynchronize(); printf("lambda:\n"); for(int i = 0; i < nsets; i++) { for(int j = 0; j < ncells; j++) { printf("%.3f\t", lam[i * ncells + j]); } printf("\n"); } return 0; }
5,864
#include <stdio.h> #define OUTER_LOOP_COUNT 1000 #define INNER_LOOP_COUNT 1000 __global__ void warmUp(int* out, int* in, int size) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx >= size) return; out[idx] = in[idx]; } __global__ void branchKernel(int* out, int* in, int size) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx >= size) return; int data = in[idx]; for (int x = 0; x < OUTER_LOOP_COUNT; x++) { for (int y = 0; y < INNER_LOOP_COUNT; y++) { if (x % 2 == 0) { out[idx] += data; } if (y % 2 == 0) { out[idx] += data; } if ((x + y) % 2 == 0) { out[idx] += data; } } } } __global__ void calculateKernel(int* out, int* in, int size) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx >= size) return; int data = in[idx]; for (int x = 0; x < OUTER_LOOP_COUNT; x++) { for (int y = 0; y < INNER_LOOP_COUNT; y++) { out[idx] += data * (x % 2 == 0); out[idx] += data * (y % 2 == 0); out[idx] += data * ((x + y) % 2 == 0); } } } int main(void) { int dataCount = 1000; int* h_data = (int*)malloc(dataCount*sizeof(int)); dim3 block(32); dim3 grid((block.x + dataCount - 1) / block.x); int *d_data, *d_result; cudaMalloc(&d_data, dataCount*sizeof(int)); cudaMalloc(&d_result, dataCount*sizeof(int)); cudaMemcpy(d_data, h_data, dataCount*sizeof(int), cudaMemcpyHostToDevice); warmUp<<<grid, block>>>(d_result, d_data, dataCount); cudaDeviceSynchronize(); branchKernel<<<grid, block>>>(d_result, d_data, dataCount); cudaDeviceSynchronize(); calculateKernel<<<grid, block>>>(d_result, d_data, dataCount); cudaDeviceSynchronize(); cudaFree(d_result); cudaFree(d_data); free(h_data); return 0; }
5,865
#include <iostream> #include <cstdio> __global__ void helloFromGPU() { printf("Hello World from GPU!\n"); } int main(void) { printf("Hello World from CPU!\n"); std::cout << "hello c++" << std::endl; helloFromGPU <<<1, 10>>>(); cudaDeviceReset(); return 0; }
5,866
#include <stdio.h> #include <assert.h> #define epsilon (float)1e-5 #define DATA float #define THREADxBLOCKalongXorY 16 void MatrixMulOnHost(DATA* M, DATA* N, DATA* P, int Width) { for (int i = 0; i < Width; ++i) { for (int j = 0; j < Width; ++j) { DATA pvalue = 0; for (int k = 0; k < Width; ++k) { DATA a = M[i * Width + k]; DATA b = N[k * Width + j]; pvalue += a * b; } P[i * Width + j] = pvalue; } } } __global__ void MatrixMulKernel(DATA* dM, DATA* dN, DATA* dP, int Width) { // INSERT CODE: index definitions int j = blockDim.x * blockIdx.x + threadIdx.x; int i = blockDim.y * blockIdx.y + threadIdx.y; // INSERT CODE: fastest index to threads along x direction if (i < Width && j < Width) { DATA pvalue = 0; for (int k = 0; k < Width; ++k) { DATA a = dM[i * Width + k]; DATA b = dN[k * Width + j]; pvalue += a * b; } dP[i * Width + j] = pvalue; } } void MatrixMulOnDevice(DATA* M, DATA* N, DATA* P, int Width) { int size = Width * Width * sizeof(DATA); float mflops; DATA *dM, *dN, *dP; // CUDA grid management int gridsize = Width/THREADxBLOCKalongXorY; if(gridsize*THREADxBLOCKalongXorY<Width) { gridsize=gridsize+1; } dim3 dimGrid(gridsize,gridsize); dim3 dimBlock(THREADxBLOCKalongXorY, THREADxBLOCKalongXorY); printf("Gridsize: %d\n", gridsize); cudaMalloc(&dM, size); cudaMemcpy(dM, M, size, cudaMemcpyHostToDevice); cudaMalloc(&dN, size); cudaMemcpy(dN, N, size, cudaMemcpyHostToDevice); cudaMalloc(&dP, size); // cudaGetLastError call to reset previous CUDA errors // INSERT CODE cudaError_t mycudaerror ; mycudaerror = cudaGetLastError() ; // Create start and stop CUDA events // INSERT CODE cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start, 0); // kernel launch MatrixMulKernel<<<dimGrid, dimBlock>>>(dM, dN, dP, Width); // device synchronization and cudaGetLastError call // INSERT CODE mycudaerror = cudaGetLastError() ; if(mycudaerror != cudaSuccess) { fprintf(stderr,"%s\n",cudaGetErrorString(mycudaerror)) ; exit(1); } // event record, synchronization, elapsed time and destruction // INSERT CODE cudaEventRecord(stop, 0); cudaEventSynchronize(stop); float elapsed; cudaEventElapsedTime(&elapsed, start, stop); elapsed = elapsed/1000.f; // convert to seconds cudaEventDestroy(start); cudaEventDestroy(stop); // calculate Mflops // INSERT CODE printf("Kernel elapsed time %fs \n", elapsed); mflops = 2.*Width*Width*Width ; mflops = mflops/(1000.f*1000.f*elapsed) ; printf("Mflops: %f\n", mflops); // copy back results from device cudaMemcpy(P, dP, size, cudaMemcpyDeviceToHost); // free memory on device cudaFree(dM); cudaFree(dN); cudaFree(dP); } // main int main(int argc, char** argv) { int Width; DATA *M, *N, *hP, *gP; if(argc<2) { fprintf(stderr,"Usage: %s Width\n",argv[0]); exit(1); } Width=atoi(argv[1]); if(Width<1) { fprintf(stderr,"Error Width=%d, must be > 0\n",Width); exit(1); } M=(DATA *)malloc(Width*Width*sizeof(DATA)); N=(DATA *)malloc(Width*Width*sizeof(DATA)); hP=(DATA *)malloc(Width*Width*sizeof(DATA)); gP=(DATA *)malloc(Width*Width*sizeof(DATA)); if(M==NULL) { fprintf(stderr,"Could not get memory for M\n"); exit(1); } if(N==NULL) { fprintf(stderr,"Could not get memory for N\n"); exit(1); } if(hP==NULL) { fprintf(stderr,"Could not get memory for hP\n"); exit(1); } if(gP==NULL) { fprintf(stderr,"Could not get memory for gP\n"); exit(1); } memset(gP,0,Width*Width*sizeof(DATA)); memset(hP,0,Width*Width*sizeof(DATA)); for(int y=0; y<Width; y++){ for(int x=0; x<Width; x++) { M[y*Width+x]=(DATA)(((y+1)*Width+x+1)/(Width)); N[y*Width+x]=(DATA)(((y+1)*Width+x+1)/(Width)); } } MatrixMulOnHost(M, N, hP, Width); MatrixMulOnDevice(M, N, gP, Width); int errCnt = 0; for(int y=0; y<Width; y++){ for(int x=0; x<Width; x++) { DATA it = hP[y*Width+x]; if(fabs(it - gP[y*Width+x])> epsilon*it) { printf("failing x=%d, y=%d: %f!=%f \n",x,y,it,gP[y*Width+x]); errCnt++; } } } if(errCnt==0) printf("\nTEST PASSED\n"); else printf("\n\nTEST FAILED: number of errors: %d\n", errCnt); }
5,867
#include "includes.h" #define SIZE 2048*1024 #define BLOCKS 1000 #define THREADS 256 __global__ void histo_MultiBlock( unsigned char *buffer,long size,unsigned int *histo ) { __shared__ unsigned int temp[256]; int i = threadIdx.x + blockIdx.x * THREADS; int offset= THREADS * BLOCKS; int memoffset = blockIdx.x * THREADS; if(threadIdx.x <256) temp[threadIdx.x] = 0; __syncthreads(); while(i<size){ atomicAdd( &temp[buffer[i]], 1); i+=offset; } __syncthreads(); if(threadIdx.x <256) atomicAdd( &(histo[threadIdx.x+memoffset]), temp[threadIdx.x] ); }
5,868
#include <iostream> #include <string> #include <stdlib.h> #include <time.h> #include <algorithm> #include <utility> #include <vector> #include <ctime> using namespace std; int N = 26; //Size of the alphabet to encrypt, N has to be even. int THREADS = 64; __device__ int dmod(int k, int n){ return ((k %= n) < 0) ? k+n : k; } int mod(int k, int n) { return ((k %= n) < 0) ? k+n : k; } //GPU encrypt __global__ void crypt_gpu(int msg_length, int N,char *dmessage_encrypted, int *disk3, int *disk2, int *disk1, int *mirror, int offset, int *keyboard){ int i = blockIdx.x * blockDim.x + threadIdx.x; if (i<msg_length){ int M = N*2; offset = (offset + i)*2; int esymbol = keyboard[(dmessage_encrypted[i]-'a')*2]; //Forward pass esymbol = dmod(disk1[dmod(esymbol+offset,M)] - offset,M); esymbol = dmod(disk2[dmod(esymbol+offset/M,M)] - offset/M,M); esymbol = dmod(disk3[dmod(esymbol+offset/M*M,M)] - offset/M,M); esymbol = mirror[esymbol]; //Reflect pass esymbol = dmod(mirror[dmod(esymbol+offset/M*M,M) + 1] - offset/M*M,M); esymbol = dmod(disk3[dmod(esymbol+offset/M,M) + 1] - offset/M,M); esymbol = dmod(disk2[dmod(esymbol+offset,M) + 1] - offset,M); esymbol = keyboard[esymbol]; dmessage_encrypted[i] = esymbol/2 + 'a'; } } string crypt_cpu(string message,int *mirror ,int *disk3 ,int *disk2 ,int *disk1 ,int *keyboard ,int offset){ string res = ""; int M = N*2; for(int i = 0; i<message.size(); ++i){ int esymbol = keyboard[(message.at(i)-'a')*2]; //Forward pass esymbol = mod(disk1[mod(esymbol+offset,M)] - offset,M); esymbol = mod(disk2[mod(esymbol+offset/M,M)] - offset/M,M); esymbol = mod(disk3[mod(esymbol+offset/M*M,M)] - offset/M,M); esymbol = mirror[esymbol]; //Reflect pass esymbol = mod(mirror[mod(esymbol+offset/M*M,M) + 1] - offset/M*M,M); esymbol = mod(disk3[mod(esymbol+offset/M,M) + 1] - offset/M,M); esymbol = mod(disk2[mod(esymbol+offset,M) + 1] - offset,M); esymbol = keyboard[esymbol]; char encrypted = esymbol/2 + 'a'; res+=encrypted; offset+=2; } return res; } void configureDisk(int* disk){ vector<int> aux(N); for(int i=0; i<N;++i) aux[i] = i*2; random_shuffle(aux.begin(),aux.end()); for(int i=0; i<N; i+=1) { disk[i*2] = aux[i]; } } void randomPairs(int* mirror, int i){ if(i<N*2){ if(mirror[i] == -1){ bool foundPair = false; int j = 0; while(!foundPair){ foundPair = (mirror[j] == -1 && rand()%N == 0 && i!=j); if(foundPair){ mirror[j] = i; mirror[i] = j; } j = (j+2)%(2*N); } } randomPairs(mirror,i+2); } } void join(int* diskTop, int* diskUnder){ for (int i = 0; i<2*N;i+=2){ diskTop[diskUnder[i]+1] = i; } } void CheckCudaError(char sms[], int line); float GetTime(void); int main(){ char message[] = "supercalifragilispicoespialidos"; srand (time(NULL)); int numBytes = N*2*sizeof(int); cudaEvent_t E0, E1; float TiempoTotal; float t1,t2; cudaEventCreate(&E0); cudaEventCreate(&E1); //HOST DATA: int *hdisk1, *hdisk2, *hdisk3, *hmirror, *hkeyboard; char* hmessage_encrypted; //host space allocation: hdisk1 = (int*) malloc(numBytes); hdisk2 = (int*) malloc(numBytes); hdisk3 = (int*) malloc(numBytes); hmirror = (int*) malloc(numBytes); hkeyboard = (int*) malloc(numBytes); hmessage_encrypted = (char*) malloc(strlen(message)*sizeof(char)); //initialization: for(int i = 0; i<N*2;++i) hmirror[i] = hdisk3[i] = hdisk2[i] = hdisk1[i] = hkeyboard[i] = -1; configureDisk(hdisk3);configureDisk(hdisk2);configureDisk(hdisk1); randomPairs(hmirror,0);randomPairs(hkeyboard,0); join(hmirror,hdisk3); join(hdisk3,hdisk2); join(hdisk2,hdisk1); //DEVICE DATA: int *ddisk1,*ddisk2,*ddisk3,*dmirror,*dkeyboard; char *dmessage_encrypted; cudaEventRecord(E0, 0); cudaEventSynchronize(E0); //device space allocation cudaMalloc((int**)&ddisk3, numBytes); cudaMalloc((int**)&ddisk2, numBytes); cudaMalloc((int**)&ddisk1, numBytes); cudaMalloc((int**)&dmirror, numBytes); cudaMalloc((int**)&dkeyboard, numBytes); cudaMalloc((char**)&dmessage_encrypted,strlen(message)*sizeof(char)); CheckCudaError((char *) "Obtener Memoria en el device", __LINE__); //Copy data host --> device cudaMemcpy(ddisk1, hdisk1, numBytes, cudaMemcpyHostToDevice); cudaMemcpy(ddisk2, hdisk2, numBytes, cudaMemcpyHostToDevice); cudaMemcpy(ddisk3, hdisk3, numBytes, cudaMemcpyHostToDevice); cudaMemcpy(dmirror, hmirror, numBytes, cudaMemcpyHostToDevice); cudaMemcpy(dkeyboard, hkeyboard, numBytes, cudaMemcpyHostToDevice); cudaMemcpy(dmessage_encrypted, message, strlen(message)*sizeof(char),cudaMemcpyHostToDevice); CheckCudaError((char *) "Copiar Datos Host --> Device", __LINE__); int nBlocks = (strlen(message) + THREADS - 1)/THREADS; dim3 dimGrid(nBlocks, 1, 1); dim3 dimBlock(THREADS, 1, 1); int disk_offset = 0; // Ejecutar el kernel crypt_gpu<<<dimGrid, dimBlock>>>(strlen(message),N,dmessage_encrypted, ddisk3, ddisk2, ddisk1, dmirror, disk_offset, dkeyboard); CheckCudaError((char *) "Invocar Kernel", __LINE__); cudaMemcpy(hmessage_encrypted,dmessage_encrypted,strlen(message)*sizeof(char),cudaMemcpyDeviceToHost); CheckCudaError((char *) "Copiar Datos Device --> Host", __LINE__); cudaEventRecord(E1, 0); cudaEventSynchronize(E1); cudaEventElapsedTime(&TiempoTotal, E0, E1); cudaFree(ddisk1); cudaFree(ddisk2); cudaFree(ddisk3); cudaFree(dmirror); cudaFree(dkeyboard); cudaFree(dmessage_encrypted); clock_t begin = clock(); string res = crypt_cpu(message,hmirror,hdisk3,hdisk2,hdisk1,hkeyboard,disk_offset); clock_t end = clock(); t2 = double(end - begin) / CLOCKS_PER_SEC; string rec = crypt_cpu(res,hmirror,hdisk3,hdisk2,hdisk1,hkeyboard,disk_offset); cout << "Original message: " << message << endl; cout << "Encrypted message CPU: " << res << endl; cout << "Encrypted message GPU: " << hmessage_encrypted << endl; cout << "GPU time to encrypt: " << TiempoTotal << endl; cout << "CPU time to encrypt: " << t2 << endl; } void CheckCudaError(char sms[], int line) { cudaError_t error; error = cudaGetLastError(); if (error) { printf("(ERROR) %s - %s in %s at line %d\n", sms, cudaGetErrorString(error), __FILE__, line); exit(EXIT_FAILURE); } }
5,869
#include "includes.h" __device__ int clamp(int value, int bound) { if (value < 0) { return 1; } if (value < bound) { return value; } return bound - 1; } __device__ int index(int x, int y, int width) { return (y * width) + x; } __device__ const int FILTER_SIZE = 9; __device__ const int FILTER_HALFSIZE = FILTER_SIZE >> 1; __device__ void sort_bubble(float *x, int n_size) { for (int i = 0; i < n_size - 1; i++) { for(int j = 0; j < n_size - i - 1; j++) { if (x[j] > x[j+1]) { float temp = x[j]; x[j] = x[j+1]; x[j+1] = temp; } } } } __global__ void median_filter_2d_sm(unsigned char* input, unsigned char* output, int width, int height) { __shared__ int sharedPixels[BLOCKDIM + FILTER_SIZE][BLOCKDIM + FILTER_SIZE]; const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; int xBlockLimit_max = blockDim.x - FILTER_HALFSIZE - 1; int yBlockLimit_max = blockDim.y - FILTER_HALFSIZE - 1; int xBlockLimit_min = FILTER_HALFSIZE; int yBlockLimit_min = FILTER_HALFSIZE; if (threadIdx.x > xBlockLimit_max && threadIdx.y > yBlockLimit_max) { int i = index(clamp(x + FILTER_HALFSIZE,width), clamp(y + FILTER_HALFSIZE,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x + 2*FILTER_HALFSIZE][threadIdx.y + 2*FILTER_HALFSIZE] = pixel; } if (threadIdx.x > xBlockLimit_max && threadIdx.y < yBlockLimit_min) { int i = index(clamp(x + FILTER_HALFSIZE,width), clamp(y - FILTER_HALFSIZE,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x + 2*FILTER_HALFSIZE][threadIdx.y] = pixel; } if (threadIdx.x < xBlockLimit_min && threadIdx.y > yBlockLimit_max) { int i = index(clamp(x - FILTER_HALFSIZE,width), clamp(y + FILTER_HALFSIZE,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x][threadIdx.y + 2*FILTER_HALFSIZE] = pixel; } if (threadIdx.x < xBlockLimit_min && threadIdx.y < yBlockLimit_min) { int i = index(clamp(x - FILTER_HALFSIZE,width), clamp(y - FILTER_HALFSIZE,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x][threadIdx.y] = pixel; } if (threadIdx.x < xBlockLimit_min) { int i = index(clamp(x - FILTER_HALFSIZE,width), clamp(y,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x][threadIdx.y + FILTER_HALFSIZE] = pixel; } if (threadIdx.x > xBlockLimit_max) { int i = index(clamp(x + FILTER_HALFSIZE,width), clamp(y,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x + 2*FILTER_HALFSIZE][threadIdx.y + FILTER_HALFSIZE] = pixel; } if (threadIdx.y < yBlockLimit_min) { int i = index(clamp(x,width), clamp(y - FILTER_HALFSIZE,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x + FILTER_HALFSIZE][threadIdx.y] = pixel; } if (threadIdx.y > yBlockLimit_max) { int i = index(clamp(x,width), clamp(y + FILTER_HALFSIZE,height), width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x + FILTER_HALFSIZE][threadIdx.y + 2*FILTER_HALFSIZE] = pixel; } int i = index(x, y, width); unsigned int pixel = input[i]; sharedPixels[threadIdx.x + FILTER_HALFSIZE][threadIdx.y + FILTER_HALFSIZE] = pixel; __syncthreads(); if((x<width) && (y<height)) { const int color_tid = y * width + x; float windowMedian[MAX_WINDOW*MAX_WINDOW]; int windowElements = 0; for (int x_iter = 0; x_iter < FILTER_SIZE; x_iter ++) { for (int y_iter = 0; y_iter < FILTER_SIZE; y_iter++) { if (0<=x_iter && x_iter < width && 0 <= y_iter && y_iter < height) { windowMedian[windowElements++] = sharedPixels[threadIdx.x + x_iter][threadIdx.y + y_iter]; } } } sort_bubble(windowMedian,windowElements); output[color_tid] = windowMedian[windowElements/2]; } }
5,870
/** Giving a large number of arrays {A_i}1<=i<=N and {B_i}1<=i<=N with |A_i| + |B_i| = d < 1024, merges arrays twos by two and return a list of arrays {M_i}1<=i<=N @file batchMerge.cu @author Dang Vu Laurent Durand Homer @version 1.0 14/12/20 */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <ctime> #include <string> #include <iostream> #include <stdlib.h> /** Verify cuda calls and return cuda error if any */ #define gpuCheck(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); } } /** Initialise ascendant array with random values @param array : the array to fill with random ascendant values size : Size of the arrays adder : Each x_i is higher than x_i-1 of a random value between 0 and adder */ void init_array(int* array, int size, int const adder=10) { if (size >=1) { array[0] = rand()%adder; if (size >=2) { for(int i = 1; i < size;i++) { array[i] = array[i-1] + rand()%adder; } } } } /** Initialise two lists of ascendant arrays A and B with random values @param A : the first list of arrays to fill with random ascendant values B : the Second list of arrays to fill with random ascendant values sizes : Sizes of each subarrays d : for all 1<=i<=N, |A_i| + |B_i| = d N : number of subarrays in A and B */ void init_list_array(int **A, int **B, int N, int d, int2 *sizes) { int sizeAi, sizeBi; for (int i = 0; i < N; i++) { //Initialiser les tailles de Ai et Bi sizeAi = rand()%d; sizeBi = d - sizeAi; //Stocker les tailles dans sizes sizes[i].x = sizeAi; sizes[i].y = sizeBi; //Allocation A et B A[i] = (int*)malloc(sizes[i].x*sizeof(int)); B[i] = (int*)malloc(sizes[i].y*sizeof(int)); //Initialisation A et B init_array(A[i], sizes[i].x); init_array(B[i], sizes[i].y); } } /** Return first indices of each arrays wich have their sizes in sizes for A and B as flat arrays @param indices : INdices of first element of each subarrays in A and B sizes : Sizes of each subarrays in A and B N : number of subarrays in A and B */ void indices_array(int2 *indices, int2 *sizes, int N) { indices[0].x=0; indices[0].y=0; for (int i = 1; i < N; i++) { indices[i].x = indices[i-1].x+sizes[i-1].x; indices[i].y = indices[i-1].y+sizes[i-1].y; } } /** Return total sizes of A and B with A and B as flat arrays @param sizes : Sizes of each subarrays in A and B N : number of subarrays in A and B */ int2 get_totalSizes(int2 *sizes, int N) { int2 totalSizes; totalSizes.x = 0; totalSizes.y = 0; for (int i = 0; i < N; i++) { totalSizes.x = totalSizes.x + sizes[i].x; totalSizes.y = totalSizes.y + sizes[i].y; } return totalSizes; } /** Return flat arrays of A and B @param flatA : flat version of A flat B : flat version of B A : 2D array of int B : 2D array of int2 N : Number of subarrays in A and B d : |A_i| + |B_i| = d sizes : sizes of subarrays in A and B */ void flat_arrays(int *flatA, int *flatB, int **A, int **B, int N, int d, int2 *sizes) { int ia = 0; int ib = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < sizes[i].x; j++) { flatA[ia] = A[i][j]; ia = ia +1; } for (int j = 0; j < sizes[i].y; j++) { flatB[ib] = B[i][j]; ib = ib +1; } } } /** Return 2D version of a flat array with N subarrays of sizes d @param unFlatM : unFLatversion of M flatM : flat version of M N : Number of subarrays in M d : Sizes of subarrays */ void unflat_arrays(int **unFlatM, int *flatM, int N, int d) { for (int i = 0; i < N; i++) { for (int j = 0; j < d; j++) { unFlatM[i][j] = flatM[i*d + j]; } } } /** Print an array of size size @param a : array to print size : size of arrays */ void print_array(int* a, int size) { printf("["); for(int i = 0; i < size;i++) { //printf("i = %d | v = %d " ,i, a[i]); printf("%d " ,a[i]); } printf("]\n"); } /** Sequential version of merge @param a_k, b_k : array to merge m_k : merge of a and b n_a, n_b, n_b : respective sizes of a_k, b_k, m_k */ void mergeSeq(int *a_k, int *b_k, int *m_k, int n_a, int n_b, int n_m) { int i, j; i=0; j=0; while(i+j < n_m) { if (i>= n_a) { m_k[i+j]=b_k[j]; j++; } else if (j>= n_b || a_k[i] < b_k[j]) { m_k[i+j]=a_k[i]; i++; } else { m_k[i+j]=b_k[j]; j++; } } } void mergeSeqBatch(int **a, int **b, int **m, int N, int d, int2 *sizes) { for (int i = 0; i < N; i++) { mergeSeq(a[i], b[i], m[i], sizes[i].x, sizes[i].y, d); } } /** Globall version of parallel merge of {A_i} and {B_i} in {M_i} with |M|<1024 @param aGPU : flat version of arrays {A_i} in device bGPU : flat version of array {B_i } in device mGPU : flat version of array {M_i} in device d : |A| + |B| = |M| = d N : number of subarrays in A and B indices : indices of the start of each subarrays in A and B sizes : sizes of each subarrays in A and B */ __global__ void mergeSmallBatch_k(int* aGPU, int* bGPU, int* mGPU, int d, int N, int2 *indices, int2 *sizes) { int tidx = threadIdx.x%d; // The indice of the thread in the "new" blocks of size d int Qt = (threadIdx.x-tidx)/d; int gbx = Qt + blockIdx.x*(blockDim.x/d); // The indice of "new" blocks of size d int i = gbx*d + tidx; // The global indice of the thread if(i < N*d) { int2 K; int2 P; int2 Q; if(tidx > sizes[gbx].x) { K.x = tidx - sizes[gbx].x; K.y = sizes[gbx].x; P.x = sizes[gbx].x; P.y = tidx - sizes[gbx].x; } else { K.x = 0; K.y = tidx; P.x = tidx; P.y = 0; } int offset = 0; while(1) { offset = abs(K.y - P.y)/2; Q.x = K.x + offset; Q.y = K.y - offset; if(Q.y >= 0 && Q.x <= sizes[gbx].y && (Q.y == sizes[gbx].x || Q.x == 0 || aGPU[indices[gbx].x + Q.y] > bGPU[indices[gbx].y + Q.x - 1])) { if(Q.x == sizes[gbx].y || Q.y == 0 || aGPU[indices[gbx].x + Q.y - 1] <= bGPU[indices[gbx].y + Q.x]) { if(Q.y < sizes[gbx].x && (Q.x == sizes[gbx].y || aGPU[indices[gbx].x + Q.y] <= bGPU[indices[gbx].y + Q.x])) { mGPU[i] = aGPU[indices[gbx].x + Q.y]; } else { mGPU[i] = bGPU[indices[gbx].y + Q.x]; } break; } else { K.x = Q.x + 1; K.y = Q.y - 1; } } else { P.x = Q.x - 1; P.y = Q.y + 1; } } } } /** verify that each tab_i < tab_i+1 in tab @param tab : array @return : 0 any tab_i > tab_i+1, either 1 */ int assertOrder(int *tab, int size){ for (int i=0; i<size-1; i++){ if (tab[i] > tab[i+1]){ printf("WARNING : Unsuccessful merge or sort ... : unordered array on indice %d ...\n", i); printf("tab[i]= %d > tab[i+1] = %d\n", tab[i], tab[i+1]); return 0; } } return 1; } /** verify that each element of tab is in tab_2 @param tab : first array n1 : size of tab tab2 : second array n2 : size of tab2 @return : 0 any tab_i > tab_i+1, either 1 */ int assertMergeAllValuesPresent(int *tab, int n1, int *tab2, int n2, int* m, int size) { int verif[size]; //tableau avec des 1 là où l'on a déjà vérifié qu'il correspond déjà à un élément de a ou de b for(int i = 0;i<size;i++){ verif[i] = 0; } for (int i=0; i<size; i++){ for(int j = 0;j < n1;j++){ if(tab[j] == m[i] && verif[i] == 0){ //si il y a une valeur identique et que celle-ci n'a pas été vérifiée verif[i] = 1; } } } for (int i=0; i<size; i++){ for(int j = 0;j < n2;j++){ if(tab2[j] == m[i] && verif[i] == 0){ verif[i] = 1; } } } for(int i = 0;i<size;i++){ if(verif[i] != 1){ printf("\nWARNING : Unsuccessful merge : incorrect elements...\n"); return 0; } } return 1; } /** verify that m is sortes and that it merges tab and tab2 @param tab et tab2 : les deux tableaux qu'on veut fusionner m : le tableau qui est la fusion triée de tab et tab2 @return : 0 any error, either 1 */ int assertMerge(int *tab, int n1, int *tab2, int n2, int* m, int size){ int successfulOrder = assertOrder(m, size); int successfulElements = assertMergeAllValuesPresent(tab, n1, tab2, n2, m, size); //assertMergeAllValuesPresent(int *tab, int n1, int *tab2, int n2, int* m, int size) if(successfulOrder && successfulElements){ // printf("\nSuccessful merge !\n"); return 1; } else{ // printf("\nUnsuccessful merge !\n"); return 0; } } /** verify that a list of arrays {M_i}1<=i<=N have correctly merge {A_i} and {B_i} @param A : First list of arrays to merge B : Second list of arrays to merge M : Merge of A and B sizes : sizes of subarrays A_i and B_i N : number of subarrays in A and B @return : 0 any error, either 1 */ int assertMerge2D(int **A, int **B, int **M, int2 *sizes, int N) { for (int i = 0; i < N; i++) { if (assertMerge(A[i], sizes[i].x, B[i], sizes[i].y, M[i], sizes[i].x + sizes[i].y) == 0) { printf("Unsuccessful merge on array %d !\n", i); return 0; } } printf("Successful merge !\n"); return 1; } /** Merge 2 lists of arrays {A_i} and {B_i} in {M_i}1<=i<=N @param argv[1] : number of subarrays in A and B argv[2] : size of |A_i| + |B_i| */ int main(int argc, char *argv[]) { std::clock_t startS, endS; float seqMergeTime, parMergeTime, DoH, HoD; srand(time(NULL)); int **A, **B, **unFlatM, **M; int *flatM, *flatA, *flatB, *aGPU, *bGPU, *mGPU; int N, d; int2 *sizes, *indices, *sizesGPU, *indicesGPU; int2 totalSizes; if(argc== 3) { N = atoi(argv[1]); d = atoi(argv[2]); } else { N= 1000; d = 4; } A = (int**)malloc(N*sizeof(int*)); B = (int**)malloc(N*sizeof(int*)); M = (int**)malloc(N*sizeof(int*)); for (int i = 0; i < N; i++) { M[i] = (int*)malloc(d*sizeof(int)); } sizes = (int2*)malloc(N*sizeof(int2)); // Sizes of each subarrays in A and B indices = (int2*)malloc(N*sizeof(int2)); // First indices of each subarrays in flat version of A and B init_list_array(A, B, N, d, sizes); indices_array(indices, sizes, N); totalSizes = get_totalSizes(sizes, N); //Flat versions of A, B and M to give to devices flatA = (int*)malloc(totalSizes.x*sizeof(int)); flatB = (int*)malloc(totalSizes.y*sizeof(int)); flatM = (int*)malloc(N*d*sizeof(int)); flat_arrays(flatA, flatB, A, B, N, d, sizes); //Falt A and B to give them to devices //Allocation of devies objects gpuCheck(cudaMalloc(&mGPU, N*d*sizeof(int))); gpuCheck(cudaMalloc(&aGPU, totalSizes.x*sizeof(int))); gpuCheck(cudaMalloc(&bGPU, totalSizes.y*sizeof(int))); gpuCheck(cudaMalloc(&sizesGPU, N*sizeof(int2))); gpuCheck(cudaMalloc(&indicesGPU, N*sizeof(int2))); //Copy host to device of arrays to merge, with their respective sizes and indices startS = std::clock(); gpuCheck( cudaMemcpy(aGPU, flatA, totalSizes.x*sizeof(int), cudaMemcpyHostToDevice) ); gpuCheck( cudaMemcpy(bGPU, flatB, totalSizes.y*sizeof(int), cudaMemcpyHostToDevice) ); gpuCheck( cudaMemcpy(sizesGPU, sizes, N*sizeof(int2), cudaMemcpyHostToDevice) ); gpuCheck( cudaMemcpy(indicesGPU, indices, N*sizeof(int2), cudaMemcpyHostToDevice) ); endS = std::clock(); HoD = (endS - startS) / (float) CLOCKS_PER_SEC; //Merge of batches parallel printf("======== batch merge =======\n"); printf("* Number of batches : %d\n* Sizes of batches : %d\n", N, d); startS = std::clock(); mergeSmallBatch_k<<<N*d/1024+1, d*1024/d>>>(aGPU, bGPU, mGPU, d, N, indicesGPU, sizesGPU); gpuCheck(cudaPeekAtLastError()); gpuCheck( cudaDeviceSynchronize() ); endS = std::clock(); parMergeTime = (endS - startS) / (float) CLOCKS_PER_SEC; startS = std::clock(); gpuCheck( cudaMemcpy(flatM, mGPU, N*d*sizeof(int), cudaMemcpyDeviceToHost) ); endS = std::clock(); DoH = (endS - startS) / (float) CLOCKS_PER_SEC; //Merge of batches parallel startS = std::clock(); mergeSeqBatch(A, B, M, N, d, sizes); endS = std::clock(); seqMergeTime = (endS - startS) / (float) CLOCKS_PER_SEC; //Allocation unFlat version of M unFlatM = (int**)malloc(N*sizeof(int*)); for (int i = 0; i < N; i++) { unFlatM[i] = (int*)malloc(d*sizeof(int)); } //unflat M unflat_arrays(unFlatM, flatM, N, d); //Verify that M is correctly merge printf("\n========= Sequential merge : =============\n"); printf("Total time elapsed : %f s\n", seqMergeTime); assertMerge2D(A, B, M, sizes, N); printf("\n"); printf("========= Parallel merge : =============\n"); printf("Total time elapsed : %f s\n", parMergeTime+DoH+HoD); printf("Time running algorithm : %f s\n", parMergeTime); printf("Time to copy Host to Device : %f s\n", HoD); printf("Time to copy Device to Host : %f s\n", DoH); assertMerge2D(A, B, unFlatM, sizes, N); printf("Parrallel algorithm is %f times faster than sequential merge !\n", seqMergeTime/parMergeTime); printf("Parrallel merge is %f times faster than sequential merge !\n", seqMergeTime/(parMergeTime+HoD+DoH)); //Free device mermory gpuCheck(cudaFree(aGPU)); gpuCheck(cudaFree(bGPU)); gpuCheck(cudaFree(mGPU)); gpuCheck(cudaFree(indicesGPU)); gpuCheck(cudaFree(sizesGPU)); //Free host memory free(A); free(B); free(unFlatM); free(flatM); free(flatA); free(flatB); free(sizes); free(indices); return 0; }
5,871
#include <stdio.h> #include <cuda_runtime.h> __global__ void kernel() { printf("%d, %d\n", threadIdx.x, blockIdx.x); return; } int main() { // main iteration kernel <<<16, 4, 0>>>(); return 0; } /* Exercice 2 : CUDA C++ extends C++ by allowing the programmer to define C++ functions, called kernels, that, when called, are executed N times in parallel by N different CUDA threads Each thread that executes the kernel is given a unique thread ID that is accessible within the kernel through built-in variables. (threadIdx.x) The number of threads per block and the number of blocks per grid specified in the <<<...>>> syntax can be of type int or dim3. Each block within the grid can be identified by a one-dimensional, two-dimensional, or three-dimensional unique index accessible within the kernel through the built-in blockIdx variable. */ // Va tourner sur le GPU // 4 thread into 16 blocks
5,872
#include "includes.h" __global__ void kernel(float* polynomial, const size_t N) { int thread = blockIdx.x * blockDim.x + threadIdx.x; if (thread < N) { float x = polynomial[thread]; polynomial[thread] = 3 * x * x - 7 * x + 5; } }
5,873
#include <iostream> using namespace std; __global__ void add(int a, int b, int *c) { *c = a + b; } int main() { int c(32); int *dev_c; cudaError_t alloc = cudaMalloc((void**)&dev_c, sizeof(int)); if (alloc != cudaSuccess) { cerr << "Impossible to allocate memory: " << cudaGetErrorString(alloc) << endl; exit(EXIT_FAILURE); } add<<<1, 1>>>(2, 7, dev_c); cudaMemcpy(&c, dev_c, sizeof(int), cudaMemcpyDeviceToHost); cout << "2 + 7 = " << c << endl; cudaFree(dev_c); cout << "CUDA" << endl; int count; cudaGetDeviceCount(&count); cout << "nb CUDA compatible devices: " << count << endl; cudaDeviceProp prop; cudaGetDeviceProperties(&prop, 0); cout << "Properties" << endl; cout << "major: " << prop.major << endl; cout << "minor: " << prop.minor << endl; cout << "texture max dim: " << prop.maxTexture2D[0] << " " << prop.maxTexture2D[1] << endl; cout << "nb multiprocessors: " << prop.multiProcessorCount << endl; cout << "max threads per block " << prop.maxThreadsPerBlock << endl; cout << "max thread dim: " << prop.maxThreadsDim[0] << " " << prop.maxThreadsDim[1] << " " << prop.maxThreadsDim[2] << endl; cout << "max grid dim: " << prop.maxGridSize[0] << " " << prop.maxGridSize[1] << " " << prop.maxGridSize[2] << endl; cout << "device name: " << prop.name << endl; cout << "total global mem " << prop.totalGlobalMem << endl; cout << "max shared mem per block: " << prop.sharedMemPerBlock << endl; cout << "nb registers per block: " << prop.regsPerBlock << endl; cout << "nb thread in a warp: " << prop.warpSize << endl; return 0; }
5,874
#include "includes.h" __global__ void sumMatrixOnGPU1D(float *MatA, float *MatB, float *MatC, 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; MatC[idx] = MatA[idx] + MatB[idx]; } }
5,875
// simple increment kernel #include <cuda.h> #include <stdio.h> __global__ void inc(unsigned n, float *d_data) { d_data[0]+=2; } int main(void) { // create host array and initialize int n = 1; // one element size_t bytes = n * sizeof(float); float *h_data = (float *)malloc(bytes); h_data[0] = 40; // print original value printf("original: %g\n", h_data[0]); // allocate device memory float *d_data; cudaMalloc((void **)&d_data, bytes); // memcpy to device cudaMemcpy(d_data, h_data, bytes, cudaMemcpyHostToDevice); // launch the increment kernel inc<<<1,1>>>(n, d_data); // memcpy results back to host cudaMemcpy(h_data, d_data, bytes, cudaMemcpyDeviceToHost); // print new value printf("new: %g\n", h_data[0]); return 0; }
5,876
//pass //--blockDim=32 --gridDim=2 #include "../common.h" __global__ void Pathcalc_Portfolio_KernelGPU2(float *d_v) { const int tid = blockDim.x * blockIdx.x + threadIdx.x; const int threadN = blockDim.x * gridDim.x; int i, path; float L[NN], z[NN]; /* Monte Carlo LIBOR path calculation*/ for(path = tid; path < NPATH; path += threadN){ // initialise the data for current thread for (i=0; i<N; i++) { // for real application, z should be randomly generated z[i] = 0.3; L[i] = 0.05; } path_calc(L, z); d_v[path] = portfolio(L); } }
5,877
#include <stdio.h> #include <cuda.h> #include <time.h> #include <iostream> #define HANDLE_ERROR( err ) ( HandleError( err, __FILE__, __LINE__ ) ) static void HandleError( cudaError_t err, const char *file, int line ) { if (err != cudaSuccess) { printf( "%s in %s at line %d\n", cudaGetErrorString( err ), file, line ); exit( EXIT_FAILURE ); } } //#include <pcl/point_types.h> typedef struct{ float x,y,z,u; }PointXYZ; //~ struct Mat_Structure{ //~ float _11_, _21_, _31_, _41_; //~ float _12_, _22_, _32_, _42_; //~ float _13_, _23_, _33_, _43_; //~ float _14_, _24_, _34_, _44_; //~ }; __global__ void kernel(float *vec, float *mat, float *out, int problem_size){ int tid = blockDim.x * blockIdx.x + threadIdx.x; //threadIdx.x; if(tid < problem_size) { #pragma unroll for(int i = 0; i<4; i++) { out[4*tid+i] = 0; } #pragma unroll for(int i=0; i<4; i++) { #pragma unroll for(int j=0; j<4; j++) { out[4*tid+i] += vec[4*tid+j] * mat[4*i+j]; } } } } __global__ void transform_kernel(PointXYZ *vec, float *mat, int problem_size){ int tid = blockDim.x * blockIdx.x + threadIdx.x; //threadIdx.x; if(tid < problem_size) { float x = 0; float y = 0; float z = 0; x = vec[tid].x * mat[0] + vec[tid].y * mat[1] + vec[tid].z * mat[2] + mat[3]; y = vec[tid].x * mat[4] + vec[tid].y * mat[5] + vec[tid].z * mat[6] + mat[7]; z = vec[tid].x * mat[8] + vec[tid].y * mat[9] + vec[tid].z * mat[10] + mat[11]; vec[tid].x = x; vec[tid].y = y; vec[tid].z = z; } } int testmain(float* vector_array, float* result_array, const int array_size, float* mat_4x4) { float *dev_array, *dev_mat, *dev_result; cudaMalloc((void**)&dev_array, sizeof(float)*4*array_size); cudaMalloc((void**)&dev_mat, sizeof(float)*16); cudaMalloc((void**)&dev_result, sizeof(float)*4*array_size); cudaMemcpy(dev_array, vector_array, sizeof(float)*4*array_size, cudaMemcpyHostToDevice); cudaMemcpy(dev_mat, mat_4x4, sizeof(float)*16, cudaMemcpyHostToDevice); //~ printf("\n\nRunning Kernel...\n\n"); //kernel<<<1, array_size>>>(dev_array, dev_mat, dev_result); // Invoke kernel int threadsPerBlock = 1024; int blocksPerGrid = (array_size + threadsPerBlock - 1) / threadsPerBlock; kernel<<<blocksPerGrid, threadsPerBlock>>>(dev_array, dev_mat, dev_result, array_size); cudaMemcpy(result_array, dev_result, sizeof(float)*4*array_size, cudaMemcpyDeviceToHost); cudaFree(dev_array); cudaFree(dev_mat); cudaFree(dev_result); return 0; }; int point_transform(PointXYZ * points, const int array_size, float* mat_4x4) { //~ printf("\n\nRunning Kernel...\n\n"); PointXYZ *dev_array; float *dev_mat; HANDLE_ERROR(cudaMalloc(&dev_array, sizeof(PointXYZ)*array_size)); HANDLE_ERROR(cudaMalloc(&dev_mat, sizeof(float)*16)); //~ cudaMalloc((void**)&dev_array, sizeof(PointXYZ)*array_size); //~ cudaMalloc((void**)&dev_mat, sizeof(float)*16); //~ std::cout << "cudalib: (" << points[0].x << "," << points[0].y << "," << points[0].z << ")" << std::endl; HANDLE_ERROR(cudaMemcpy(dev_array, points, sizeof(PointXYZ)*array_size, cudaMemcpyHostToDevice)); HANDLE_ERROR(cudaMemcpy(dev_mat, mat_4x4, sizeof(float)*16, cudaMemcpyHostToDevice)); // Invoke kernel //~ int threadsPerBlock = 128; //~ int blocksPerGrid = (array_size + threadsPerBlock - 1) / threadsPerBlock; //~ transform_kernel<<<blocksPerGrid, threadsPerBlock>>>(dev_array, dev_mat, array_size); transform_kernel<<<16, 128>>>(dev_array, dev_mat, array_size); HANDLE_ERROR(cudaMemcpy(points, dev_array, sizeof(PointXYZ)*array_size, cudaMemcpyDeviceToHost)); //~ std::cout << "cudalib after: (" << points[0].x << "," << points[0].y << "," << points[0].z << ")" << std::endl; cudaFree(dev_array); cudaFree(dev_mat); return 0; }; int point_transform3(PointXYZ * points, const int array_size, PointXYZ * result_points, float* mat_4x4) { PointXYZ *dev_array; float *dev_mat; cudaMalloc((void**)&dev_array, sizeof(PointXYZ)*array_size); cudaMalloc((void**)&dev_mat, sizeof(float)*16); cudaMemcpy(dev_array, points, sizeof(PointXYZ)*array_size, cudaMemcpyHostToDevice); cudaMemcpy(dev_mat, mat_4x4, sizeof(float)*16, cudaMemcpyHostToDevice); // Invoke kernel int threadsPerBlock = 1024; int blocksPerGrid = (array_size + threadsPerBlock - 1) / threadsPerBlock; transform_kernel<<<blocksPerGrid, threadsPerBlock>>>(dev_array, dev_mat, array_size); cudaMemcpy(result_points, dev_array, sizeof(PointXYZ)*array_size, cudaMemcpyDeviceToHost); cudaFree(dev_array); cudaFree(dev_mat); return 0; };
5,878
//#include "stdafx.h" #include <stdio.h> #include <math.h> #include <time.h> #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <cuda.h> struct pixel { unsigned char r; unsigned char g; unsigned char b; }; __device__ int power(int a,int b){ for (int i=0;i<b;i++){ a*=a; } return a; } __device__ void hamming_code(long *a) { long z=*a; int d1,d2,d3,d4,d6,d7,d8,p1,p2,p3,tmp1,tmp2; tmp2=power(10,7); tmp1=z/tmp2; tmp2=tmp1%10; d1=tmp2; tmp2=power(10,6); tmp1=z/tmp2; tmp2=tmp1%10; d2=tmp2; tmp2=power(10,5); tmp1=z/tmp2; tmp2=tmp1%10; d3=tmp2; tmp2=power(10,4); tmp1=z/tmp2; tmp2=tmp1%10; d4=tmp2; tmp2=power(10,2); tmp1=z/tmp2; tmp2=tmp1%10; d6=tmp2; tmp2=power(10,1); tmp1=z/tmp2; tmp2=tmp1%10; d7=tmp2; tmp2=(*a)%10; d8=tmp2; p1=d1^d2^d3; p2=d1^d2^d4; p3=d1^d3^d4; *a=(*a)-100*d6-10*d7-d8+100*p1+10*p2+p3; return ; } __device__ void bit_rotation(long *a) { long z=*a,tmp,tmp1,tmp2,p1,p2,p3; tmp1=z/power(10,2); tmp2=tmp1%10; p1=tmp2; tmp1=z/power(10,1); tmp2=tmp1%10; p2=tmp2; tmp2=*a%10; p3=tmp2; *a=(*a)-100*p1-10*p2-p3; tmp=p1; p1=p2; p2=p3; p3=tmp; *a=(*a)+100*p1+10*p2+p3; return; } __device__ void rev_bit_rotation(long *a) { long z=*a,tmp1,tmp2,p1,p2,p3,tmp; tmp1=z/power(10,2); tmp2=tmp1%10; p1=tmp2; tmp1=z/power(10,1); tmp2=tmp1%10; p2=tmp2; tmp2=*a%10; p3=tmp2; *a=(*a)-100*p1-10*p2-p3; tmp=p3; p3=p2; p2=p1; p1=tmp; //printf("%d\n",*a); *a=(*a)+100*p1+10*p2+p3; //printf("%d",*a); return; } __device__ void Torus_Auromorphism(int *a,int *b,int c) { //k=1 int x,y; x = (*a+*b)%c; y= (*a + 2*(*b))%c; *a=x;*b=y; return; } __device__ void Anti_Torus(int *a,int *b,int c) { int x,y; x=(2*(*a)+(-1)*(*b)+100000*c)%c; y=((-1)*(*a)+*b+10000*c)%c; //printf("a=%d b=%d x=%d y=%d\n",*a,*b,x,y); *a=x;*b=y; //if(*a=2&&*b2) //*a=x;*b=y; } __device__ int DecToBinary(int num) { int count=0, remainder, base = 1, binary = 0, no_of_1s = 0; while (num > 0) { count++; remainder = num % 2; if (remainder == 1) { no_of_1s++; } binary = binary + remainder * base; num = num / 2; base = base * 10; } binary+=100000000; // printf("binary = %d\n",binary); return binary; } __device__ int BinToDec(int num){ num-=100000000; int dec=0,k=1,i=0; //printf("%d",num); while(1){ dec=dec + k*(num%10); if(i==0) i=1; else i=2*i; if(num==0) { break; } k=2*i; num/=10; } //printf("\n%d",dec); return dec; } __global__ void PictureKernel(struct pixel* IPimage, struct pixel* OPimage,long* R,long* G,long* B,int w,int h) { // Calculate the row # of the d_Pin and d_Pout element int Col = blockIdx.x*blockDim.x + threadIdx.x; // Calculate the column # of the d_Pin and d_Pout element int Row = blockIdx.y*blockDim.y + threadIdx.y; // each thread computes one element of d_Pout if in range int tmp1,tmp2; tmp2=Col;tmp1=Row; Anti_Torus(&tmp1,&tmp2,w); //Anti Torus OPimage[tmp1*w+tmp2]=IPimage[Row*w+Col]; R[Col+Row*w]=DecToBinary(IPimage[Col+Row*w].r); G[Col+Row*w]=DecToBinary(IPimage[Col+Row*w].g); B[Col+Row*w]=DecToBinary(IPimage[Col+Row*w].b); rev_bit_rotation(&R[Col+Row*w]);rev_bit_rotation(&G[Col+Row*w]);rev_bit_rotation(&B[Col+Row*w]); IPimage[Col+Row*w].r=BinToDec(R[Col+Row*w]); IPimage[Col+Row*w].g=BinToDec(G[Col+Row*w]); IPimage[Col+Row*w].b=BinToDec(B[Col+Row*w]); return; } int main(void) { int i, w, h; char blah[3]; FILE *f, *f2; f=fopen("encrypted.ppm", "rb"); f2=fopen("plldecrypted.ppm", "wb"); fscanf(f, "%s\n", blah); fscanf(f, "%d %d\n", &w, &h); fscanf(f, "%d\n", &i); struct pixel image[h][w]; fread(&image, sizeof(image), 1, f); // clock_t end = clock(); //double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; //printf("%f",time_spent); //long R[h][w],G[h][w],B[h][w]; struct pixel *d_A,*d_F; long *d_R,*d_G,*d_B; long n=w*h; //const long size=n; const long bytes = 3*sizeof(unsigned char)*n; //clock_t begin = clock(); //Assigning memory in device cudaMalloc((void **)&d_A,sizeof(pixel)*n); cudaMalloc((void **)&d_F,sizeof(pixel)*n); cudaMalloc((void **)&d_R,sizeof(long)*n); cudaMalloc((void **)&d_G,sizeof(long)*n); cudaMalloc((void **)&d_B,sizeof(long)*n); cudaMemcpy(d_A,image,bytes,cudaMemcpyHostToDevice); clock_t begin = clock(); dim3 threadsPerBlock(32, 32); dim3 numBlocks(w/threadsPerBlock.x,h/threadsPerBlock.y); PictureKernel<<<numBlocks,threadsPerBlock>>>(d_A,d_F,d_R,d_G,d_B,w,h); clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("%f microseconds\n",time_spent*1000000); cudaMemcpy(image,d_F,bytes,cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_F); cudaFree(d_R); cudaFree(d_G); cudaFree(d_B); fprintf(f2, "%s\n", blah); fprintf(f2, "%d %d\n", w, h); fprintf(f2, "%d\n", 255); fwrite(&image, sizeof(image), 1, f2); fclose(f); fclose(f2); return 0; }
5,879
/* @Author: 3sne ( Mukur Panchani ) @FileName: q2StringReverse.cu @Task: CUDA program that the reverses given string. */ #include <cuda_runtime.h> #include <stdio.h> #include <stdlib.h> #include <string.h> __global__ void reverse(char *str, char *rev, int len) { int tid = threadIdx.x; rev[len - tid - 1] = str[tid]; } int main() { char *dstr, *drev; char str[256], rev[256]; printf("Enter the string >> "); scanf("%s", str); int len = strlen(str); cudaMalloc((void **)&dstr, len * sizeof(char)); cudaMalloc((void **)&drev, len * sizeof(char)); cudaMemcpy(dstr, str, len * sizeof(char), cudaMemcpyHostToDevice); reverse<<<1, len>>>(dstr, drev, len); cudaMemcpy(rev, drev, len * sizeof(char), cudaMemcpyDeviceToHost); printf("Reverse: %s\n", rev); }
5,880
#include "includes.h" /* * This project is dual licensed. You may license this software under one of the following licences: + Creative Commons Attribution-Share Alike 3.0 Unported License http://creativecommons.org/licenses/by-nc-sa/3.0/ + GNU GENERAL PUBLIC LICENSE v3, designated as a "BY-SA Compatible License" as defined in BY-SA 4.0 on 8 October 2015 * See the LICENSE file in the root directory of this source tree for full copyright disclosure, and other details. */ /* Header files */ /* Constants */ #define threads 256 /* It's the number of threads we are going to use per block on the GPU */ using namespace std; /* Kernels */ /* This kernel counts the number of pairs in the data file */ /* We will use this kernel to calculate real-real pairs and random-random pairs */ /* This kernel counts the number of pairs that there are between two data groups */ /* We will use this kernel to calculate real-random pairs and real_1-real_2 pairs (cross-correlation) */ /* NOTE that this kernel has NOT been merged with 'binning' above: this is for speed optimization, we avoid passing extra variables to the GPU */ __global__ void binning_mix(float *xd_real, float *yd_real, float *zd_real, float *xd_sim, float *yd_sim, float *zd_sim, float *ZY, int lines_number_1, int lines_number_2, int points_per_degree, int number_of_degrees) { /* We define variables (arrays) in shared memory */ float angle; __shared__ float temp[threads]; /* We define an index to run through these two arrays */ int index = threadIdx.x; /* This variable is necesary to accelerate the calculation, it's due that "temp" was definied in the shared memory too */ temp[index]=0; float x,y,z; //MCM float xx,yy,zz; //MCM /* We start the counting */ for (int i=0;i<lines_number_1;i++) { x = xd_real[i];//MCM y = yd_real[i];//MCM z = zd_real[i];//MCM /* The "while" replaces the second for-loop in the sequential calculation case (CPU). We use "while" rather than "if" as recommended in the book "Cuda by Example" */ for(int dim_idx = blockIdx.x * blockDim.x + threadIdx.x; dim_idx < lines_number_2; dim_idx += blockDim.x * gridDim.x) { xx = xd_sim[dim_idx];//MCM yy = yd_sim[dim_idx];//MCM zz = zd_sim[dim_idx];//MCM /* We make the dot product */ angle = x * xx + y * yy + z * zz;//MCM //angle[index]=xd[i]*xd[dim_idx]+yd[i]*yd[dim_idx]+zd[i]*zd[dim_idx];//MCM //__syncthreads();//MCM /* Sometimes "angle" is higher than one, due to numnerical precision, to solve it we use the next sentence */ angle=fminf(angle,1.0); angle=acosf(angle)*180.0/M_PI; //__syncthreads();//MCM /* We finally count the number of pairs separated an angular distance "angle", always in shared memory */ if(angle < number_of_degrees) { atomicAdd( &temp[int(angle*points_per_degree)], 1.0); } __syncthreads(); } } /* We copy the number of pairs from shared memory to global memory */ atomicAdd( &ZY[threadIdx.x] , temp[threadIdx.x]); __syncthreads(); }
5,881
#include <stdlib.h> #include <iostream> #include <time.h> using namespace std; #define BLOCK_SIZE 256 #define SEED 1337 #define ARR_LENGTH 5000 __global__ void sum_cud(float * in, float * out, int len) { __shared__ float sum[2*BLOCK_SIZE]; unsigned int th_num = threadIdx.x; unsigned int pointer = blockIdx.x * blockDim.x; if (pointer + th_num < len) sum[th_num] = in[pointer + th_num]; else sum[th_num] = 0; for (unsigned int stride = blockDim.x/2; stride >= 1; stride >>= 1) { if (th_num < stride) sum[th_num] += sum[th_num+stride]; __syncthreads(); } if (th_num == 0) out[blockIdx.x] = sum[0]; } float randInRange(float min, float max) { return min + (float) (rand() / (double) (RAND_MAX + 1) * (max - min + 1)); } int main(int argc, char ** argv) { srand(SEED); float * input; float * output; float * d_input; float * d_output; int lenInput = ARR_LENGTH; int lenOutput; input = (float*) malloc(lenInput * sizeof(float)); for (int i = 0; i < lenInput; ++i) { input[i] = randInRange(0.0, 10.0); } clock_t Time; Time = clock(); float sum = 0.0; for (int i = 0; i < lenInput; i++) { sum += input[i]; } cout << "CPU result: " << sum << endl; Time = clock() - Time; float Time_ = (float) Time / CLOCKS_PER_SEC; cout << "CPU time is: " << Time_ << endl; cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); float time_; cudaEventRecord(start, 0); do { lenOutput = lenInput / (BLOCK_SIZE); if (lenInput % (BLOCK_SIZE)) { lenOutput++; } output = (float*) malloc(lenOutput * sizeof(float)); cudaMalloc(&d_input, sizeof(float) * lenInput); cudaMalloc(&d_output, sizeof(float) * lenInput); cudaMemcpy(d_input, input, sizeof(float) * lenInput, cudaMemcpyHostToDevice); dim3 dimGrid(lenOutput); dim3 dimBlock(BLOCK_SIZE); sum_cud<<<dimGrid, dimBlock>>>(d_input, d_output, lenInput); cudaMemcpy(output, d_output, sizeof(float) * lenOutput, cudaMemcpyDeviceToHost); input = output; lenInput = lenOutput; } while (lenOutput > 1); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&time_, start, stop); printf("GPU ime is: %f\n", time_/1000); cudaEventDestroy(start); cudaEventDestroy(stop); cudaDeviceSynchronize(); cout << "Cuda result: " << output[0] << endl; cudaFree(d_input); cudaFree(d_output); free(input); free(output); return 0; }
5,882
#include"cuda_runtime.h" #include"device_launch_parameters.h" #include<stdio.h> #include<string.h> __global__ void Toggle(char *a, char *b, int n) { int tid; tid = threadIdx.x; if(a[tid]>='A' && a[tid]<='Z') { b[tid]=a[tid]+32; } else { b[tid]=a[tid]-32; } } int main() { char a[100],b[100]; int i,n,size; char *d_a, *d_b; printf("\nEnter the string\n"); scanf("%s",a); n = strlen(a); printf("\nNo of charcaters is\t%d", n); size = sizeof(char); printf("\nSize is \t%d\n", size); cudaMalloc((void **)&d_a,n*size); cudaMalloc((void **)&d_b,n*size); cudaMemcpy(d_a,a,n*size,cudaMemcpyHostToDevice); Toggle<<<1,n>>>(d_a,d_b,n); cudaMemcpy(b,d_b,n*size,cudaMemcpyDeviceToHost); printf("\nToggled string is \n"); for(i=0;i<n;i++) printf("%c",b[i]); cudaFree(d_a); cudaFree(d_b); return 0; }
5,883
// ### // ### // ### Practical Course: GPU Programming in Computer Vision // ### // ### // ### Technical University Munich, Computer Vision Group // ### Summer Semester 2017, September 11 - October 9 // ### #include <cuda_runtime.h> #include <iostream> using namespace std; // cuda error checking #define CUDA_CHECK cuda_check(__FILE__,__LINE__) void cuda_check(string file, int line) { cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { cout << endl << file << ", line " << line << ": " << cudaGetErrorString(e) << " (" << e << ")" << endl; exit(1); } } __device__ float square(float a) {return a*a;} __global__ void g_square(float*a, int n) { int ind = threadIdx.x + blockDim.x * blockIdx.x; if(ind<n) a[ind]=square(a[ind]); } int main(int argc, char **argv) { // alloc and init input arrays on host (CPU) int n = 10; float *a = new float[n]; for(int i=0; i<n; i++) a[i] = i; // CPU computation for(int i=0; i<n; i++) { float val = a[i]; val = val*val; a[i] = val; } // print result cout << "CPU:"<<endl; for(int i=0; i<n; i++) cout << i << ": " << a[i] << endl; cout << endl; // GPU computation // reinit data for(int i=0; i<n; i++) a[i] = i; // ### // ### TODO: Implement the "square array" operation on the GPU and store the result in "a" // ### // ### Notes: // ### 1. Remember to free all GPU arrays after the computation // ### 2. Always use the macro CUDA_CHECK after each CUDA call, e.g. "cudaMalloc(...); CUDA_CHECK;" // ### For convenience this macro is defined directly in this file, later we will only include "helper.h" dim3 block = dim3(10,1,1); dim3 grid = dim3((n+block.x-1)/block.x,1,1); float *d_a; cudaMalloc(&d_a,n*sizeof(float)); CUDA_CHECK; cudaMemcpy( d_a, a, n * sizeof(float), cudaMemcpyHostToDevice );CUDA_CHECK; g_square<<<grid,block>>>(d_a,n); cudaMemcpy( a, d_a, n * sizeof(float), cudaMemcpyDeviceToHost );CUDA_CHECK; cudaFree(d_a);CUDA_CHECK; // print result cout << "GPU:" << endl; for(int i=0; i<n; i++) cout << i << ": " << a[i] << endl; cout << endl; // free CPU arrays delete[] a; }
5,884
#include "includes.h" __global__ void CalculateTransSample( const float *input, float *output, const int wtss, const int htss, const int wts, const int hts, const int ratio ){ const int yts = blockIdx.y * blockDim.y + threadIdx.y; const int xts = blockIdx.x * blockDim.x + threadIdx.x; const int curst = wts * yts + xts; const int yt = yts * ratio, xt = xts * ratio; if (yts < hts && xts < wts){ for (int i=0; i<ratio; i++){ for (int j=0; j<ratio; j++){ if (yt + i < htss && xt + j < wtss){ const int curt = wtss * (yt+i) + (xt+j); output[curt*3+0] = input[curst*3+0]; output[curt*3+1] = input[curst*3+1]; output[curt*3+2] = input[curst*3+2]; } } } } }
5,885
#define BLOCK_SIZE 512 #define BLOCK_MASK (BLOCK_SIZE)*2 __global__ void avg_kernel(float* in_vec, float* out_vec, int len) { __shared__ float shared_seg_sum[2 * BLOCK_SIZE]; unsigned int p = 0; do { if (len > blockIdx.x * BLOCK_MASK + threadIdx.x + p * BLOCK_SIZE) shared_seg_sum[threadIdx.x + p * BLOCK_SIZE] = in_vec[blockIdx.x * BLOCK_MASK + threadIdx.x + p * BLOCK_SIZE]; else shared_seg_sum[threadIdx.x + p * BLOCK_SIZE] = 0.0f; p++; } while (p <= 1); for (unsigned int m = BLOCK_SIZE; m >= 1; m /= 2) { if (m > threadIdx.x) { shared_seg_sum[threadIdx.x] += shared_seg_sum[threadIdx.x + m]; } __syncthreads(); } (threadIdx.x == 0) ? out_vec[blockIdx.x] = shared_seg_sum[threadIdx.x] / (1.0*len) : 0.0f; }
5,886
#include <stdio.h> #define size 5 __global__ void addvec(int *c, const int *a, const int *b) { int i = threadIdx.x; c[i] = a[i] + b[i]; } int main() { const int a[size] = {1, 2, 3, 4, 5}; const int b[size] = {10, 20, 30, 40, 50}; int c[size] = {0}; int *da, *db, *dc; cudaMalloc((void**)& dc, size*sizeof(int)); cudaMalloc((void**)& da, size*sizeof(int)); cudaMalloc((void**)& db, size*sizeof(int)); cudaMemcpy(da, a, size*sizeof(int), cudaMemcpyHostToDevice); cudaMemcpy(db, b, size*sizeof(int), cudaMemcpyHostToDevice); addvec<<<1, size>>>(dc, da, db); cudaMemcpy(c, dc, size*sizeof(int), cudaMemcpyDeviceToHost); printf("{1, 2, 3, 4, 5} + {10, 20, 30, 40, 50} = {%d, %d, %d, %d, %d}\n", c[0], c[1], c[2], c[3], c[4]); cudaThreadSynchronize(); cudaFree(dc); cudaFree(da); cudaFree(db); return 0; }
5,887
#include <stdio.h> //const int N = 16; const int blocksize = 16; __global__ void hello(int *a, int *b) { int z = blockDim.x * blockIdx.x + threadIdx.x; a[z] = b[z]* b[z] * b[z]; //a[threadIdx.x] = 5; } int main(int argc, char** argv) { int SIZE = atoi(argv[1]); int *a =(int*) malloc(SIZE * sizeof(int)); int *b =(int*) malloc(SIZE * sizeof(int)); for(int i=0; i<SIZE; i++) { a[i]=0; b[i]=rand()%100+1; } // int a[N] = {}; //int b[N] = {16, 10, 6, 0, -11, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int *ad; int *bd; const int csize = SIZE*sizeof(int); const int isize = SIZE*sizeof(int); printf("input "); for (int i=0;i<SIZE;i++) printf("%d ", b[i]); printf("\n"); 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 ); //hello<<<dimGrid, dimBlock>>>(ad, bd); int cores = 512; //int blocks = SIZE/cores + 16; int blocks = 16; int threadsPerBlock = 256; //int blocksPerGrid =(SIZE + threadsPerBlock – 1) / threadsPerBlock; int blocksPerGrid = ( SIZE + threadsPerBlock -1) / threadsPerBlock; printf("blocks = %d cores = %d\n", blocks, cores); hello<<<blocksPerGrid, threadsPerBlock>>>(ad, bd); cudaMemcpy( a, ad, csize, cudaMemcpyDeviceToHost ); cudaFree( ad ); cudaFree( bd ); printf("ouput "); for (int i=0;i<SIZE;i++) printf("%d ", a[i]); printf("\n"); //printf("%s\n", a); free(a); free(b); return EXIT_SUCCESS; }
5,888
#include <stdio.h> __global__ void d_sigmoid(float *data){ *data = (1.0 - *data) * *data; } int main(){ float *d_data, h_data = 0; cudaMalloc((void **)&d_data, sizeof(float)); cudaMemcpy(d_data, &h_data, sizeof(float), cudaMemcpyHostToDevice); d_sigmoid<<<1,1>>>(d_data); cudaMemcpy(&h_data, d_data, sizeof(float), cudaMemcpyDeviceToHost); printf("data = %d\n", h_data); return 0; }
5,889
#include "includes.h" __global__ void mult_shared( int *A, int *B, int *result, int n) { int k; int kk; const int bx = BLOCK_X, by = BLOCK_Y; const int col = blockIdx.x*bx + threadIdx.x; const int row = blockIdx.y*by + threadIdx.y; __shared__ int a[BLOCK_X][BLOCK_Y] , b[BLOCK_X][BLOCK_Y]; if ((col < n) && (row < n)) { int c = 0; for (k=0; k < n; k++) { a[threadIdx.x][threadIdx.y] = A[ col * n + k*by + threadIdx.y]; b[threadIdx.y][threadIdx.x] = B[ row + n * (k*bx+threadIdx.x)]; __syncthreads(); // Synchronizes all threads in a block for (kk=0; kk< bx; kk++) c += a[kk][threadIdx.x]*b[kk][threadIdx.y]; __syncthreads(); // Avoids memory hazards } result[col*n+row] = c; } }
5,890
#include "includes.h" #define FALSE 0 #define TRUE !FALSE #define NUMTHREADS 16 #define THREADWORK 32 __global__ void gpuMeans(const float * vectsA, size_t na, const float * vectsB, size_t nb, size_t dim, float * means, float * numPairs) { size_t offset, stride, bx = blockIdx.x, by = blockIdx.y, tx = threadIdx.x; float a, b; __shared__ float threadSumsA[NUMTHREADS], threadSumsB[NUMTHREADS], count[NUMTHREADS]; if((bx >= na) || (by >= nb)) return; threadSumsA[tx] = 0.f; threadSumsB[tx] = 0.f; count[tx] = 0.f; for(offset = tx; offset < dim; offset += NUMTHREADS) { a = vectsA[bx * dim + offset]; b = vectsB[by * dim + offset]; if(!(isnan(a) || isnan(b))) { threadSumsA[tx] += a; threadSumsB[tx] += b; count[tx] += 1.f; } } __syncthreads(); for(stride = NUMTHREADS >> 1; stride > 0; stride >>= 1) { if(tx < stride) { threadSumsA[tx] += threadSumsA[tx + stride]; threadSumsB[tx] += threadSumsB[tx + stride]; count[tx] += count[tx+stride]; } __syncthreads(); } if(tx == 0) { means[bx*nb*2+by*2] = threadSumsA[0] / count[0]; means[bx*nb*2+by*2+1] = threadSumsB[0] / count[0]; numPairs[bx*nb+by] = count[0]; } }
5,891
#include "includes.h" __global__ void relu(float *inout, float *bias, int rows, int cols) { int j = blockIdx.x * blockDim.x + threadIdx.x; int i = blockIdx.y * blockDim.y + threadIdx.y; if (j >= cols || i >= rows) return; inout[i * cols + j] = fmaxf(0.0, inout[i * cols + j] + bias[i]); }
5,892
#include <thrust/device_vector.h> #include <thrust/host_vector.h> #include <thrust/functional.h> #include <thrust/transform.h> #include <iostream> int main() { thrust::device_vector<double> AAPL; thrust::device_vector<double> MSFT; thrust::device_vector<double> MEAN_DIF(2518,0); double stocks_AAPL, stocks_MSFT, mean; for(int i =0; i < 2518; i++){ std::cin >> stocks_AAPL >> stocks_MSFT; AAPL.push_back(stocks_AAPL); MSFT.push_back(stocks_MSFT); } thrust::transform(AAPL.begin(), AAPL.end(), MSFT.begin(), MEAN_DIF.begin(), thrust::minus<double>()); double val = thrust::reduce(MEAN_DIF.begin(), MEAN_DIF.end()); mean = val/2517; std::cout << "Média: " << fabs(mean) << "\n"; }
5,893
// #include "headers.h" // #define dimension TILE_SIZE+MAX_MASK_WIDTH-1 __global__ void conv(float *N, float *M, float *P, int mask_width, int width, int TILE_SIZE) { int i = blockIdx.x*blockDim.x + threadIdx.x; int j = blockIdx.y*blockDim.y + threadIdx.y; // int dimension = TILE_SIZE + mask_width - 1; __shared__ float N_ds[6][6]; int halo_index_left = (blockIdx.x - 1)*blockDim.x + threadIdx.x; int halo_index_right = (blockIdx.x+1)*blockDim.x + threadIdx.x ; int halo_index_up = (blockIdx.y - 1)*blockDim.y + threadIdx.y; int halo_index_down = (blockIdx.y+1)*blockDim.y+threadIdx.y ; int n = mask_width/2; // Outer corners if(threadIdx.x >= blockDim.x-n && threadIdx.y >= blockDim.y-n) N_ds[threadIdx.y-(blockDim.y-n)][threadIdx.x-(blockDim.x-n)] = (halo_index_left<0 || halo_index_up < 0)?0:N[halo_index_up*width + halo_index_left]; if(threadIdx.y >= blockDim.y-n && threadIdx.x<n) N_ds[threadIdx.y-(blockDim.y-n)][n+blockDim.x+threadIdx.x] = (halo_index_right>=width || halo_index_up<0)?0:N[halo_index_up*width + halo_index_right]; if(threadIdx.y<n && threadIdx.x>=blockDim.x-n) N_ds[n+blockDim.y+threadIdx.y][threadIdx.x+(blockDim.x-n)] = (halo_index_left<0 || halo_index_down>=width)?0:N[halo_index_down*width + halo_index_left]; if(threadIdx.x<n && threadIdx.y<n) N_ds[n+blockDim.y+threadIdx.y][n+blockDim.x+threadIdx.x] = (halo_index_right>=width || halo_index_down>=width)?0:N[halo_index_down*width+halo_index_right]; //Tile elements N_ds[n+threadIdx.y][n+threadIdx.x] = N[(blockIdx.y*blockDim.y+threadIdx.y)*width + blockIdx.x*blockDim.x+threadIdx.x]; if(threadIdx.y >= blockDim.y-n) N_ds[threadIdx.y-(blockDim.y-n)][n+threadIdx.x] = (halo_index_up<0)?0:N[halo_index_up*width +threadIdx.x]; if(threadIdx.x >= blockDim.x-n) N_ds[n+threadIdx.y][threadIdx.x-(blockDim.x-n)] = (halo_index_left<0)?0:N[(n+threadIdx.y)*width + halo_index_left]; if(threadIdx.x<n) N_ds[n+threadIdx.y][n+blockDim.x+threadIdx.x] = (halo_index_right>=width)?0:N[(n+threadIdx.x)*width + halo_index_right]; if(threadIdx.y<n) N_ds[n+blockDim.y+threadIdx.y][n+threadIdx.x] = (halo_index_down>-width)?0:N[halo_index_down*width+threadIdx.x]; __syncthreads(); float Pvalue = 0; for(int a=0; a<mask_width;a++) for(int b=0; b<mask_width; b++) Pvalue += N_ds[threadIdx.y+a][threadIdx.x+b]*M[a*mask_width+b]; P[j*width + i] = Pvalue; }
5,894
__global__ void conv3(int *inp, int *out) { int i = 0; if (inp[0] == out[0]) { while ( i < 10) { int tmp = inp[i]; if (tmp == i) break; __syncthreads(); out[i] = tmp; i++; } __syncthreads(); out[i] = 31; } }
5,895
#include "includes.h" // ERROR CHECKING MACROS ////////////////////////////////////////////////////// __global__ void rovCorrection(int noPoints, int noDims, int dimRes, int nYears, int noControls, int year, int control, float* regression) { // Global thread index int idx = blockIdx.x*blockDim.x + threadIdx.x; if (idx < noPoints) { float currVal = regression[year*noControls*(dimRes*noDims + (int)pow(dimRes,noDims)*2) + control*(dimRes*noDims + (int)pow(dimRes,noDims)*2) + dimRes*noDims + idx]; // The surrogate value cannot be greater than zero by definition if (currVal > 0) { regression[year*noControls*(dimRes*noDims + (int)pow(dimRes, noDims)*2) + control*(dimRes*noDims + (int)pow(dimRes, noDims)*2) + dimRes*noDims + idx] = 0.0; } } }
5,896
static const int kOpsPerThread = 1; __global__ void kernel_local(float *out, int input) { float reg[8] = { 1 }; for (int i = 0; i < kOpsPerThread; ++i) { reg[threadIdx.x] += threadIdx.y; } out[0] = reg[0]; } __global__ void kernel_reg(float *out) { float reg = threadIdx.x % 2; const int block_size = blockDim.y * blockDim.x; for (int i = 0; i < kOpsPerThread; ++i) { reg = reg + i % 7 + i % 8; } out[0] = reg; } __global__ void kernel_shared(float *out) { __shared__ float reg[128]; reg[threadIdx.y * blockDim.x + threadIdx.x] = 0; int offset = threadIdx.y * blockDim.x + threadIdx.x; for (int i = 0; i < kOpsPerThread; ++i) { reg[offset + i % 7] += reg[i % 8]; } out[0] = reg[0]; }
5,897
#include <cuda.h> #include <stdio.h> #include <time.h> //#define N 4 //> Kernel definition __global__ void gpuMatmult(int* m1, int* m2, int* ans, int n){ int k, sum = 0; int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; if (i < n && j < n) { for (k = 0; k < n; k++) { sum += m1[j * n + k] * m2[k * n + i]; } ans[j * n + i] = sum; } } int main(int argc, char** argv ){ //> Variables definition int N = 0; double timeGPU; int *h_m1, *h_m2, *h_ans, *d_m1, *d_m2, *d_ans; //> Arguments check if(argc != 2){ N = 4; }else{ N = atoi(argv[1]);//> Set size } size_t bytes = N * N * sizeof(int);//> Set data size //> Host memory allocation h_m1 = (int *)malloc(bytes); h_m2 = (int *)malloc(bytes); h_ans = (int *)malloc(bytes); //> Inititializations for(int i = 0; i < N * N ; i++){ h_m1[i] = i; h_m2[i] = i; h_ans[i] = 0; } //> Device memory allocation if (cudaSuccess != cudaMalloc((void **) &d_m1, bytes)) printf("Error allocating mem. for d_m1\n"); if (cudaSuccess != cudaMalloc((void **) &d_m2, bytes)) printf("Error allocating mem. for d_m2\n"); if (cudaSuccess != cudaMalloc((void **) &d_ans, bytes)) printf("Error allocating mem. for d_ans\n"); //> Data copy H -> D if (cudaSuccess != cudaMemcpy(d_m1, h_m1, bytes, cudaMemcpyHostToDevice)) printf("Error copying data for d_m1\n"); if (cudaSuccess != cudaMemcpy(d_m2, h_m2, bytes, cudaMemcpyHostToDevice)) printf("Error copying data for d_m2\n"); //> Struct defitinitions for kernel call dim3 blockDim(32,32); dim3 gridDim((int)ceil((float)N/blockDim.x), (int)ceil((float)N/blockDim.y)); clock_t startGPU = clock();//> Starting timer //> Kernel call gpuMatmult<<<gridDim, blockDim>>>(d_m1, d_m2, d_ans, N); if (cudaSuccess != cudaGetLastError()) printf("Error calling kernel\n"); //> Data copy back D -> H if (cudaSuccess != cudaMemcpy(h_ans, d_ans, bytes, cudaMemcpyDeviceToHost)) printf("Error copying data for d_ans\n"); timeGPU = ((double)(clock() - startGPU))/CLOCKS_PER_SEC;//> Ending timer printf("Size m1 = %d x %d, m2 = %d x %d\n",N,N,N,N); printf("GPU time = %.6f seconds\n",timeGPU);//> Print time (include data copy back) //> Print result if (N <= 4){ for(int m = 0; m < N; m++){ for(int n = 0; n < N; n++){ printf("%d,",h_ans[m * N + n]); } printf("\n"); } } //> Free memory free(h_m1); free(h_m2); free(h_ans); cudaFree(d_m1); cudaFree(d_m2); cudaFree(h_ans); return 0; }
5,898
#include <stdio.h> #include <stdlib.h> #include <math.h> __global__ void matrixMultGPU(int *a_ll,int *a_lr,int *a_ul, int *a_ur,int *b_ll,int *b_lr,int *b_ul, int *b_ur, int *c_ll,int *c_lr,int *c_ul, int *c_ur, int *t_ll,int *t_lr,int *t_ul, int *t_ur,int N){ int k, sum_cur = 0,sum_cul = 0,sum_cll = 0,sum_clr = 0,sum_tur = 0,sum_tul = 0,sum_tll = 0,sum_tlr = 0; int col = threadIdx.x + blockDim.x * blockIdx.x; int fil = threadIdx.y + blockDim.y * blockIdx.y; if (col < N && fil < N) { for (k = 0; k < N; k++) { sum_cul += a_ul[fil * N + k] * b_ul[k * N + col]; sum_cur += a_ul[fil * N + k] * b_ur[k * N + col]; sum_cll += a_ll[fil * N + k] * b_ul[k * N + col]; sum_clr += a_ll[fil * N + k] * b_ur[k * N + col]; sum_tul += a_ur[fil * N + k] * b_ll[k * N + col]; sum_tur += a_ur[fil * N + k] * b_lr[k * N + col]; sum_tll += a_lr[fil * N + k] * b_ll[k * N + col]; sum_tlr += a_lr[fil * N + k] * b_lr[k * N + col]; } c_ul[fil * N + col] = sum_cul; c_ur[fil * N + col] = sum_cur; c_ll[fil * N + col] = sum_cll; c_lr[fil * N + col] = sum_clr; t_ul[fil * N + col] = sum_tul; t_ll[fil * N + col] = sum_tll; t_lr[fil * N + col] = sum_tlr; t_ur[fil * N + col] = sum_tur; __syncthreads(); c_ul[fil * N + col]+=t_ul[fil * N + col]; c_ll[fil * N + col]+=t_ll[fil * N + col]; c_lr[fil * N + col]+=t_lr[fil * N + col]; c_ur[fil * N + col]+=t_ur[fil * N + col]; } } int main (void){ //Creación de variables del sistema int *a, *b, *c, N,NN; int *a_ul,*a_ur,*a_ll,*a_lr,*b_ul,*b_ur,*b_ll,*b_lr,*c_ul,*c_ur,*c_ll,*c_lr; int *da_ul,*da_ur,*da_ll,*da_lr,*db_ul,*db_ur,*db_ll,*db_lr,*dc_ul,*dc_ur,*dc_ll,*dc_lr,*dt_ul,*dt_ur,*dt_ll,*dt_lr; int i,j; int T,div=1, iteraciones=10,ind=0; float elapsedTime; printf("Ingrese el tamano deseado para las matrices:\n"); scanf("%d",&NN); if(NN%2!=0 || NN<2) { printf("El tamaño debe ser mayor a dos y par\n"); exit(1); } N=(int)NN/2; //Creación de variables de tiempo cudaEvent_t start,stop; cudaEventCreate(&start); cudaEventCreate(&stop); printf("Creando espacio e inicializando matrices...\n"); //Asignación e inicialización de memoria a=(int*)malloc(NN*NN*sizeof(int)); b=(int*)malloc(NN*NN*sizeof(int)); c=(int*)malloc(NN*NN*sizeof(int)); a_ll=(int*)malloc(N*N*sizeof(int)); a_lr=(int*)malloc(N*N*sizeof(int)); a_ul=(int*)malloc(N*N*sizeof(int)); a_ur=(int*)malloc(N*N*sizeof(int)); b_ll=(int*)malloc(N*N*sizeof(int)); b_lr=(int*)malloc(N*N*sizeof(int)); b_ul=(int*)malloc(N*N*sizeof(int)); b_ur=(int*)malloc(N*N*sizeof(int)); c_ll=(int*)malloc(N*N*sizeof(int)); c_lr=(int*)malloc(N*N*sizeof(int)); c_ul=(int*)malloc(N*N*sizeof(int)); c_ur=(int*)malloc(N*N*sizeof(int)); //Inicialización de Matrices for(i=0;i<NN;i++) { for(j=0;j<NN;j++) { a[i*NN+j]=i*j; b[i*NN+j]=i*j; } } //Creación de submatrices for(i=0;i<N;i++) { for(j=0;j<N;j++) { a_ul[i*N+j]=a[i*NN+j]; a_ur[i*N+j]=a[i*NN+j+N]; a_ll[i*N+j]=a[(i+N)*NN+j]; a_lr[i*N+j]=a[(i+N)*NN+j+N]; b_ul[i*N+j]=b[i*NN+j]; b_ur[i*N+j]=b[i*NN+j+N]; b_ll[i*N+j]=b[(i+N)*NN+j]; b_lr[i*N+j]=b[(i+N)*NN+j+N]; } } { if(cudaMalloc(&da_ll,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&da_ul,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&da_ur,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&da_lr,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&db_ll,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&db_lr,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&db_ul,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&db_ur,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dc_ur,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dc_ul,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dc_ll,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dc_lr,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dt_ur,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dt_ul,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dt_ll,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } if(cudaMalloc(&dt_lr,N*N*sizeof(int))!=cudaSuccess) { printf("########\nHubo un problema en la asignacion de memoria en la GPU\n########\n"); exit(1); } } printf("Asignacion de memoria correcta\n"); //Cálculo de bloques e hilos while((float)N/(float)div>32) { div++; } float f_N=(float)N,f_div=(float)div; T=(int)ceil(f_N/f_div); dim3 ThreadsBloque(T,T); dim3 Bloques(div, div); printf("Se va a realizar la suma con %d bloques y %d hilos\n",div,T); printf("Se va a realizar %d iteraciones de matrices %dx%d\n",iteraciones,NN,NN); //Ejecución de kernel cudaEventRecord(start,0); { //Copia de memoria a GPU if(cudaMemcpy(da_ll,a_ll,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(da_lr,a_lr,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(da_ul,a_ul,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(da_ur,a_ur,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(db_ll,b_ll,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(db_lr,b_lr,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(db_ul,b_ul,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } if(cudaMemcpy(db_ur,b_ur,N*N*sizeof(int),cudaMemcpyHostToDevice)!=cudaSuccess) { printf("#########\nHubo un problema en la copia de memoria a la GPU\n#########\n"); exit(1); } } while(ind<iteraciones) { matrixMultGPU<<<Bloques, ThreadsBloque>>>(da_ll,da_lr,da_ul,da_ur,db_ll,db_lr,db_ul,db_ur,dc_ll,dc_lr,dc_ul,dc_ur,dt_ll,dt_lr,dt_ul,dt_ur,N); ind++; } cudaMemcpy(c_ll,dc_ll,N*N*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(c_lr,dc_lr,N*N*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(c_ur,dc_ur,N*N*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(c_ul,dc_ul,N*N*sizeof(int),cudaMemcpyDeviceToHost); cudaEventRecord(stop,0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime,start,stop); printf("El tiempo tomado para %d iteraciones fue de %3.5f ms\n",iteraciones,elapsedTime); for(i=0;i<N;i++) { for(j=0;j<N;j++) { c[i*NN+j]=c_ul[i*N+j]; c[i*NN+j+N]=c_ur[i*N+j]; c[(i+N)*NN+j]=c_ll[i*N+j]; c[(i+N)*NN+j+N]=c_lr[i*N+j]; } } printf("Por ejemplo %d deberia ser 0\n",c[3*NN]); printf("Por ejemplo %d deberia ser 0\n",c[(int)NN/2]); printf("Por ejemplo %d deberia ser %d\n",c[NN+1],(int)((2*pow(NN-1,3)+3*pow(NN-1,2)+NN-1)/6)); /* for(i=0;i<NN;i++) { printf("\n"); for(j=0;j<NN;j++) { printf("\t%d",a[i*NN+j]); } //printf("\t"); for(j=0;j<NN;j++) { printf("\t%d",b[i*NN+j]); } //printf("\t"); for(j=0;j<NN;j++) { printf("\t%d",c[i*NN+j]); } } */ free(a); free(a_ll); free(a_lr); free(a_ul); free(a_ur); free(b_ur); free(b_ll); free(b_lr); free(b_ul); free(c_ll); free(c_lr); free(c_ul); free(c_ur); free(b); free(c); cudaFree(da_ll); cudaFree(da_lr); cudaFree(da_ul); cudaFree(da_ur); cudaFree(db_ll); cudaFree(db_lr); cudaFree(db_ul); cudaFree(db_ur); cudaFree(dc_ll); cudaFree(dc_lr); cudaFree(dc_ul); cudaFree(dc_ur); cudaFree(dt_ll); cudaFree(dt_lr); cudaFree(dt_ul); cudaFree(dt_ur); return 0; }
5,899
#include <iostream> #include <iomanip> #include <fstream> #include <cmath> #define INFINITE 1000000000 int* distance_host; int* distance_dev; __global__ void FW1(int *distance_dev, int r, int vertexPadded){ int i = r * blockDim.x + threadIdx.y; int j = r * blockDim.x + threadIdx.x; int offset = i * vertexPadded; extern __shared__ int dist[]; dist[threadIdx.y * blockDim.x + threadIdx.x] = distance_dev[ offset + j ]; __syncthreads(); for(int k=0; k<blockDim.x; ++k){ dist[ threadIdx.y * blockDim.x + threadIdx.x ] = min(dist[ threadIdx.y * blockDim.x + threadIdx.x ], dist[ threadIdx.y * blockDim.x + k ] + dist[ k * blockDim.x + threadIdx.x ]); __syncthreads(); } distance_dev[ offset + j ] = dist[threadIdx.y * blockDim.x + threadIdx.x]; } __global__ void FW2(int *distance_dev, int r, int vertexPadded, int total_round){ int block_i, block_j; if(blockIdx.y == 0){ block_i = r; block_j = (blockIdx.x + r + 1) % total_round; }else{ block_j = r; block_i = (blockIdx.x + r + 1) % total_round; } int i = block_i * blockDim.x + threadIdx.y; int j = block_j * blockDim.x + threadIdx.x; int offset = i * vertexPadded; int index = threadIdx.y * blockDim.x + threadIdx.x; int blockSize_squard = blockDim.x * blockDim.x; extern __shared__ int dist[]; dist[index] = distance_dev[offset + j]; dist[blockSize_squard + index] = distance_dev[offset + threadIdx.x + r * blockDim.x]; dist[2*blockSize_squard + index] = distance_dev[(threadIdx.y + r * blockDim.x) * vertexPadded + j ]; __syncthreads(); for (int k = 0; k < blockDim.x; k++) { int ik = threadIdx.y * blockDim.x + blockSize_squard + k; int kj = k * blockDim.x + 2 * blockSize_squard + threadIdx.x; dist[index] = min(dist[index], dist[ik] + dist[kj]); __syncthreads(); } distance_dev[offset + j] = dist[index]; } __global__ void FW3(int *distance_dev, int r, int vertexPadded, int total_round){ int block_i = (r + blockIdx.y + 1) % total_round; int block_j = (r + blockIdx.x + 1) % total_round; int i = block_i * blockDim.x + threadIdx.y; int j = block_j * blockDim.x + threadIdx.x; int offset = i * vertexPadded; int index = threadIdx.y * blockDim.x + threadIdx.x; int blockSize_squard = blockDim.x * blockDim.x; extern __shared__ int dist[]; dist[index] = distance_dev[offset + j]; //block(i,j) dist[blockSize_squard + index] = distance_dev[offset + threadIdx.x + r * blockDim.x]; //block(i,r) dist[2*blockSize_squard + index] = distance_dev[(threadIdx.y + r * blockDim.x) * vertexPadded + j ]; //block(r,j) __syncthreads(); for (int k = 0; k < blockDim.x; k++) { int ik = threadIdx.y * blockDim.x + blockSize_squard + k; int kj = k * blockDim.x + 2 * blockSize_squard + threadIdx.x; dist[index] = min(dist[index], dist[ik] + dist[kj]); __syncthreads(); } distance_dev[offset + j] = dist[index]; } void block_FW(int blockSize, int vertexNum, int vertexPadded) { int round = vertexPadded / blockSize; dim3 block(blockSize, blockSize); dim3 grid2(round-1, 2); dim3 grid3(round-1, round-1); cudaMalloc(&distance_dev, sizeof(int) * vertexPadded * vertexPadded); cudaMemcpy(distance_dev, distance_host, sizeof(int) * vertexPadded * vertexPadded, cudaMemcpyHostToDevice); for (int r = 0; r < round; ++r) { FW1<<< 1, block, blockSize * blockSize * sizeof(int) >>>(distance_dev, r, vertexPadded); FW2<<< grid2, block, 3 * blockSize * blockSize * sizeof(int) >>>(distance_dev, r, vertexPadded, round); FW3<<< grid3, block, 3 * blockSize * blockSize * sizeof(int) >>>(distance_dev, r, vertexPadded, round); } cudaMemcpy(distance_host, distance_dev, sizeof(int) * vertexPadded * vertexPadded, cudaMemcpyDeviceToHost); } int main(int argc, char **argv){ //get number of threads per block cudaSetDevice(0); cudaDeviceProp prop; cudaGetDeviceProperties(&prop, 0); int ThreadsPerBlock = (int) sqrt(prop.maxThreadsPerBlock); int blockSize = ThreadsPerBlock; //read input file std::ifstream inputFile(argv[1], std::ios::in | std::ios::binary); unsigned vertexNum, edgeNum; inputFile.read((char*)&vertexNum, 4); inputFile.read((char*)&edgeNum, 4); //calculate block number, vertex number in a block if(vertexNum < blockSize) blockSize = vertexNum; int blockNum = ceil( 1.0 * vertexNum / blockSize); int vertexPadded = blockSize * blockNum; //Allocate memory (pinned) cudaMallocHost(&distance_host, sizeof(int) * vertexPadded * vertexPadded); for(unsigned i=0; i<vertexPadded; ++i){ for(unsigned j=0; j<vertexPadded; ++j){ if( i>=vertexNum || j>=vertexNum) distance_host[ i * vertexPadded + j ] = INFINITE; else if( i == j) distance_host[ i * vertexPadded + j ] = 0; else distance_host[ i * vertexPadded + j ] = INFINITE; } } int source, destination, weight; while( inputFile.read((char*)&source, 4) ){ inputFile.read((char*)&destination, 4); inputFile.read((char*)&weight, 4); distance_host[ source * vertexPadded + destination ] = weight; } inputFile.close(); block_FW(blockSize, vertexNum, vertexPadded); //write answer to output file std::ofstream outputFile(argv[2], std::ios::out | std::ios::binary); for(int i=0; i<vertexNum; ++i){ for(int j=0; j<vertexNum; ++j){ outputFile.write( (char*)&distance_host[ i * vertexPadded + j ], 4); } } outputFile.close(); cudaFree(distance_host); cudaFree(distance_dev); return 0; }
5,900
#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 hypterm (double * flux_0, double * flux_1, double * flux_2, double * flux_3, double * flux_4, double * cons_1, double * cons_2, double * cons_3, double * cons_4, double * q_1, double * q_2, double * q_3, double * q_4, double dxinv0, double dxinv1, double dxinv2, int L, int M, int N) { //Determining the block's indices int blockdim_i= (int)(blockDim.x); int i0 = (int)(blockIdx.x)*(blockdim_i-8); int i = i0 + (int)(threadIdx.x); int blockdim_j= (int)(blockDim.y); int j0 = (int)(blockIdx.y)*(blockdim_j)+4; int j = j0 + (int)(threadIdx.y); //Declarations double reg_cons_1_m4=0, reg_cons_1_m3=0, reg_cons_1_m2=0, reg_cons_1_m1=0, __shared__ sh_cons_1_c0[24][16], reg_cons_1_p1=0, reg_cons_1_p2=0, reg_cons_1_p3=0, reg_cons_1_p4=0; double reg_cons_2_m4=0, reg_cons_2_m3=0, reg_cons_2_m2=0, reg_cons_2_m1=0, __shared__ sh_cons_2_c0[24][16], reg_cons_2_p1=0, reg_cons_2_p2=0, reg_cons_2_p3=0, reg_cons_2_p4=0; double reg_cons_3_m4=0, reg_cons_3_m3=0, reg_cons_3_m2=0, reg_cons_3_m1=0, __shared__ sh_cons_3_c0[24][16], reg_cons_3_p1=0, reg_cons_3_p2=0, reg_cons_3_p3=0, reg_cons_3_p4=0; double reg_cons_4_m4=0, reg_cons_4_m3=0, reg_cons_4_m2=0, reg_cons_4_m1=0, __shared__ sh_cons_4_c0[24][16], reg_cons_4_p1=0, reg_cons_4_p2=0, reg_cons_4_p3=0, reg_cons_4_p4=0; double __shared__ sh_q_1_c0[24][16]; double __shared__ sh_q_2_c0[24][16]; double reg_q_3_m4=0, reg_q_3_m3=0, reg_q_3_m2=0, reg_q_3_m1=0, reg_q_3_c0=0, reg_q_3_p1=0, reg_q_3_p2=0, reg_q_3_p3=0, reg_q_3_p4=0; double reg_q_4_m4=0, reg_q_4_m3=0, reg_q_4_m2=0, reg_q_4_m1=0, __shared__ sh_q_4_c0[24][16], reg_q_4_p1=0, reg_q_4_p2=0, reg_q_4_p3=0, reg_q_4_p4=0; //Value Initialization if (j <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { reg_cons_1_m4 = cons_1[0 + j*N + i]; reg_cons_1_m3 = cons_1[1*M*N + j*N + i]; reg_cons_1_m2 = cons_1[2*M*N + j*N + i]; reg_cons_1_m1 = cons_1[3*M*N + j*N + i]; sh_cons_1_c0[j-j0+4][i-i0] = cons_1[4*M*N + j*N + i]; reg_cons_1_p1 = cons_1[5*M*N + j*N + i]; reg_cons_1_p2 = cons_1[6*M*N + j*N + i]; reg_cons_1_p3 = cons_1[7*M*N + j*N + i]; reg_cons_2_m4 = cons_2[0 + j*N + i]; reg_cons_2_m3 = cons_2[1*M*N + j*N + i]; reg_cons_2_m2 = cons_2[2*M*N + j*N + i]; reg_cons_2_m1 = cons_2[3*M*N + j*N + i]; sh_cons_2_c0[j-j0+4][i-i0] = cons_2[4*M*N + j*N + i]; reg_cons_2_p1 = cons_2[5*M*N + j*N + i]; reg_cons_2_p2 = cons_2[6*M*N + j*N + i]; reg_cons_2_p3 = cons_2[7*M*N + j*N + i]; reg_cons_3_m4 = cons_3[0 + j*N + i]; reg_cons_3_m3 = cons_3[1*M*N + j*N + i]; reg_cons_3_m2 = cons_3[2*M*N + j*N + i]; reg_cons_3_m1 = cons_3[3*M*N + j*N + i]; sh_cons_3_c0[j-j0+4][i-i0] = cons_3[4*M*N + j*N + i]; reg_cons_3_p1 = cons_3[5*M*N + j*N + i]; reg_cons_3_p2 = cons_3[6*M*N + j*N + i]; reg_cons_3_p3 = cons_3[7*M*N + j*N + i]; reg_cons_4_m4 = cons_4[0 + j*N + i]; reg_cons_4_m3 = cons_4[1*M*N + j*N + i]; reg_cons_4_m2 = cons_4[2*M*N + j*N + i]; reg_cons_4_m1 = cons_4[3*M*N + j*N + i]; sh_cons_4_c0[j-j0+4][i-i0] = cons_4[4*M*N + j*N + i]; reg_cons_4_p1 = cons_4[5*M*N + j*N + i]; reg_cons_4_p2 = cons_4[6*M*N + j*N + i]; reg_cons_4_p3 = cons_4[7*M*N + j*N + i]; reg_q_3_m4 = q_3[0 + j*N + i]; reg_q_3_m3 = q_3[1*M*N + j*N + i]; reg_q_3_m2 = q_3[2*M*N + j*N + i]; reg_q_3_m1 = q_3[3*M*N + j*N + i]; reg_q_3_c0 = q_3[4*M*N + j*N + i]; reg_q_3_p1 = q_3[5*M*N + j*N + i]; reg_q_3_p2 = q_3[6*M*N + j*N + i]; reg_q_3_p3 = q_3[7*M*N + j*N + i]; reg_q_4_m4 = q_4[0 + j*N + i]; reg_q_4_m3 = q_4[1*M*N + j*N + i]; reg_q_4_m2 = q_4[2*M*N + j*N + i]; reg_q_4_m1 = q_4[3*M*N + j*N + i]; sh_q_4_c0[j-j0+4][i-i0] = q_4[4*M*N + j*N + i]; reg_q_4_p1 = q_4[5*M*N + j*N + i]; reg_q_4_p2 = q_4[6*M*N + j*N + i]; reg_q_4_p3 = q_4[7*M*N + j*N + i]; } if(threadIdx.y < 4) { int jj = (j-4); if (jj <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { sh_cons_1_c0[jj-j0+4][i-i0] = cons_1[4*M*N + jj*N + i]; sh_cons_2_c0[jj-j0+4][i-i0] = cons_2[4*M*N + jj*N + i]; sh_cons_3_c0[jj-j0+4][i-i0] = cons_3[4*M*N + jj*N + i]; sh_cons_4_c0[jj-j0+4][i-i0] = cons_4[4*M*N + jj*N + i]; sh_q_4_c0[jj-j0+4][i-i0] = q_4[4*M*N + jj*N + i]; } } else if(threadIdx.y < 8) { int jj = (j-4)+16; if (jj <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { sh_cons_1_c0[jj-j0+4][i-i0] = cons_1[4*M*N + jj*N + i]; sh_cons_2_c0[jj-j0+4][i-i0] = cons_2[4*M*N + jj*N + i]; sh_cons_3_c0[jj-j0+4][i-i0] = cons_3[4*M*N + jj*N + i]; sh_cons_4_c0[jj-j0+4][i-i0] = cons_4[4*M*N + jj*N + i]; sh_q_4_c0[jj-j0+4][i-i0] = q_4[4*M*N + jj*N + i]; } } //Rest of the computation for (int k=4; k<=L-5; ++k) { //Fetch new plane if (j <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { reg_cons_1_p4 = cons_1[(k+4)*M*N + j*N + i]; reg_cons_2_p4 = cons_2[(k+4)*M*N + j*N + i]; reg_cons_3_p4 = cons_3[(k+4)*M*N + j*N + i]; reg_cons_4_p4 = cons_4[(k+4)*M*N + j*N + i]; sh_q_1_c0[j-j0+4][i-i0] = q_1[k*M*N + j*N + i]; sh_q_2_c0[j-j0+4][i-i0] = q_2[k*M*N + j*N + i]; reg_q_3_p4 = q_3[(k+4)*M*N + j*N + i]; reg_q_4_p4 = q_4[(k+4)*M*N + j*N + i]; } if(threadIdx.y < 4) { int jj = (j-4); if (jj <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { sh_cons_1_c0[jj-j0+4][i-i0] = cons_1[k*M*N + jj*N + i]; sh_cons_2_c0[jj-j0+4][i-i0] = cons_2[k*M*N + jj*N + i]; sh_cons_3_c0[jj-j0+4][i-i0] = cons_3[k*M*N + jj*N + i]; sh_cons_4_c0[jj-j0+4][i-i0] = cons_4[k*M*N + jj*N + i]; } } else if(threadIdx.y < 8) { int jj = (j-4)+16; if (jj <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { sh_cons_1_c0[jj-j0+4][i-i0] = cons_1[k*M*N + jj*N + i]; sh_cons_2_c0[jj-j0+4][i-i0] = cons_2[k*M*N + jj*N + i]; sh_cons_3_c0[jj-j0+4][i-i0] = cons_3[k*M*N + jj*N + i]; sh_cons_4_c0[jj-j0+4][i-i0] = cons_4[k*M*N + jj*N + i]; } } else if(threadIdx.y < 12) { int jj = (j-12); if (jj <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { sh_q_1_c0[jj-j0+4][i-i0] = q_1[k*M*N + jj*N + i]; sh_q_2_c0[jj-j0+4][i-i0] = q_2[k*M*N + jj*N + i]; sh_q_4_c0[jj-j0+4][i-i0] = q_4[k*M*N + jj*N + i]; } } else { int jj = (j-12)+16; if (jj <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { sh_q_1_c0[jj-j0+4][i-i0] = q_1[k*M*N + jj*N + i]; sh_q_2_c0[jj-j0+4][i-i0] = q_2[k*M*N + jj*N + i]; sh_q_4_c0[jj-j0+4][i-i0] = q_4[k*M*N + jj*N + i]; } } __syncthreads (); double r0,r1,r2,r3,r4; if ((j <= M-5) & i >= max (i0+4, 4) & i <= min (i0+blockdim_i-5, N-5)) { r0=flux_0[k*M*N + j*N + i], r1=flux_1[k*M*N + j*N + i], r2=flux_2[k*M*N + j*N + i], r3=flux_3[k*M*N + j*N + i], r4 = flux_4[k*M*N + j*N + i]; // double r0=0.0f,r1=0.0f,r2=0.0f,r3=0.0f,r4=0.0f; r0 -= (((((0.8f * (sh_cons_1_c0[j-j0+4][i-i0+1] - sh_cons_1_c0[j-j0+4][i-i0-1])) - (0.2f * (sh_cons_1_c0[j-j0+4][i-i0+2] - sh_cons_1_c0[j-j0+4][i-i0-2]))) + (0.038f * (sh_cons_1_c0[j-j0+4][i-i0+3] - sh_cons_1_c0[j-j0+4][i-i0-3]))) - (0.0035f * (sh_cons_1_c0[j-j0+4][i-i0+4] - sh_cons_1_c0[j-j0+4][i-i0-4]))) * dxinv0); r0 -= (((((0.8f * (sh_cons_2_c0[j-j0+4+1][i-i0] - sh_cons_2_c0[j-j0+4-1][i-i0])) - (0.2f * (sh_cons_2_c0[j-j0+4+2][i-i0] - sh_cons_2_c0[j-j0+4-2][i-i0]))) + (0.038f * (sh_cons_2_c0[j-j0+4+3][i-i0] - sh_cons_2_c0[j-j0+4-3][i-i0]))) - (0.0035f * (sh_cons_2_c0[j-j0+4+4][i-i0] - sh_cons_2_c0[j-j0+4-4][i-i0]))) * dxinv1); r0 -= (((((0.8f * (reg_cons_3_p1 - reg_cons_3_m1)) - (0.2f * (reg_cons_3_p2 - reg_cons_3_m2))) + (0.038f * (reg_cons_3_p3 - reg_cons_3_m3))) - (0.0035f * (reg_cons_3_p4 - reg_cons_3_m4))) * dxinv2); flux_0[k*M*N + j*N + i] = r0; r1 -= (((((0.8f * (((sh_cons_1_c0[j-j0+4][i-i0+1] * sh_q_1_c0[j-j0+4][i-i0+1]) - (sh_cons_1_c0[j-j0+4][i-i0-1] * sh_q_1_c0[j-j0+4][i-i0-1])) + (sh_q_4_c0[j-j0+4][i-i0+1] - sh_q_4_c0[j-j0+4][i-i0-1]))) - (0.2f * (((sh_cons_1_c0[j-j0+4][i-i0+2] * sh_q_1_c0[j-j0+4][i-i0+2]) - (sh_cons_1_c0[j-j0+4][i-i0-2] * sh_q_1_c0[j-j0+4][i-i0-2])) + (sh_q_4_c0[j-j0+4][i-i0+2] - sh_q_4_c0[j-j0+4][i-i0-2])))) + (0.038f * (((sh_cons_1_c0[j-j0+4][i-i0+3] * sh_q_1_c0[j-j0+4][i-i0+3]) - (sh_cons_1_c0[j-j0+4][i-i0-3] * sh_q_1_c0[j-j0+4][i-i0-3])) + (sh_q_4_c0[j-j0+4][i-i0+3] - sh_q_4_c0[j-j0+4][i-i0-3])))) - (0.0035f * (((sh_cons_1_c0[j-j0+4][i-i0+4] * sh_q_1_c0[j-j0+4][i-i0+4]) - (sh_cons_1_c0[j-j0+4][i-i0-4] * sh_q_1_c0[j-j0+4][i-i0-4])) + (sh_q_4_c0[j-j0+4][i-i0+4] - sh_q_4_c0[j-j0+4][i-i0-4])))) * dxinv0); r1 -= (((((0.8f * ((sh_cons_1_c0[j-j0+4+1][i-i0] * sh_q_2_c0[j-j0+4+1][i-i0]) - (sh_cons_1_c0[j-j0+4-1][i-i0] * sh_q_2_c0[j-j0+4-1][i-i0]))) - (0.2f * ((sh_cons_1_c0[j-j0+4+2][i-i0] * sh_q_2_c0[j-j0+4+2][i-i0]) - (sh_cons_1_c0[j-j0+4-2][i-i0] * sh_q_2_c0[j-j0+4-2][i-i0])))) + (0.038f * ((sh_cons_1_c0[j-j0+4+3][i-i0] * sh_q_2_c0[j-j0+4+3][i-i0]) - (sh_cons_1_c0[j-j0+4-3][i-i0] * sh_q_2_c0[j-j0+4-3][i-i0])))) - (0.0035f * ((sh_cons_1_c0[j-j0+4+4][i-i0] * sh_q_2_c0[j-j0+4+4][i-i0]) - (sh_cons_1_c0[j-j0+4-4][i-i0] * sh_q_2_c0[j-j0+4-4][i-i0])))) * dxinv1); r1 -= (((((0.8f * ((reg_cons_1_p1 * reg_q_3_p1) - (reg_cons_1_m1 * reg_q_3_m1))) - (0.2f * ((reg_cons_1_p2 * reg_q_3_p2) - (reg_cons_1_m2 * reg_q_3_m2)))) + (0.038f * ((reg_cons_1_p3 * reg_q_3_p3) - (reg_cons_1_m3 * reg_q_3_m3)))) - (0.0035f * ((reg_cons_1_p4 * reg_q_3_p4) - (reg_cons_1_m4 * reg_q_3_m4)))) * dxinv2); flux_1[k*M*N + j*N + i] = r1; r2 -= (((((0.8f * ((sh_cons_2_c0[j-j0+4][i-i0+1] * sh_q_1_c0[j-j0+4][i-i0+1]) - (sh_cons_2_c0[j-j0+4][i-i0-1] * sh_q_1_c0[j-j0+4][i-i0-1]))) - (0.2f * ((sh_cons_2_c0[j-j0+4][i-i0+2] * sh_q_1_c0[j-j0+4][i-i0+2]) - (sh_cons_2_c0[j-j0+4][i-i0-2] * sh_q_1_c0[j-j0+4][i-i0-2])))) + (0.038f * ((sh_cons_2_c0[j-j0+4][i-i0+3] * sh_q_1_c0[j-j0+4][i-i0+3]) - (sh_cons_2_c0[j-j0+4][i-i0-3] * sh_q_1_c0[j-j0+4][i-i0-3])))) - (0.0035f * ((sh_cons_2_c0[j-j0+4][i-i0+4] * sh_q_1_c0[j-j0+4][i-i0+4]) - (sh_cons_2_c0[j-j0+4][i-i0-4] * sh_q_1_c0[j-j0+4][i-i0-4])))) * dxinv0); r2 -= (((((0.8f * (((sh_cons_2_c0[j-j0+4+1][i-i0] * sh_q_2_c0[j-j0+4+1][i-i0]) - (sh_cons_2_c0[j-j0+4-1][i-i0] * sh_q_2_c0[j-j0+4-1][i-i0])) + (sh_q_4_c0[j-j0+4+1][i-i0] - sh_q_4_c0[j-j0+4-1][i-i0]))) - (0.2f * (((sh_cons_2_c0[j-j0+4+2][i-i0] * sh_q_2_c0[j-j0+4+2][i-i0]) - (sh_cons_2_c0[j-j0+4-2][i-i0] * sh_q_2_c0[j-j0+4-2][i-i0])) + (sh_q_4_c0[j-j0+4+2][i-i0] - sh_q_4_c0[j-j0+4-2][i-i0])))) + (0.038f * (((sh_cons_2_c0[j-j0+4+3][i-i0] * sh_q_2_c0[j-j0+4+3][i-i0]) - (sh_cons_2_c0[j-j0+4-3][i-i0] * sh_q_2_c0[j-j0+4-3][i-i0])) + (sh_q_4_c0[j-j0+4+3][i-i0] - sh_q_4_c0[j-j0+4-3][i-i0])))) - (0.0035f * (((sh_cons_2_c0[j-j0+4+4][i-i0] * sh_q_2_c0[j-j0+4+4][i-i0]) - (sh_cons_2_c0[j-j0+4-4][i-i0] * sh_q_2_c0[j-j0+4-4][i-i0])) + (sh_q_4_c0[j-j0+4+4][i-i0] - sh_q_4_c0[j-j0+4-4][i-i0])))) * dxinv1); r2 -= (((((0.8f * ((reg_cons_2_p1 * reg_q_3_p1) - (reg_cons_2_m1 * reg_q_3_m1))) - (0.2f * ((reg_cons_2_p2 * reg_q_3_p2) - (reg_cons_2_m2 * reg_q_3_m2)))) + (0.038f * ((reg_cons_2_p3 * reg_q_3_p3) - (reg_cons_2_m3 * reg_q_3_m3)))) - (0.0035f * ((reg_cons_2_p4 * reg_q_3_p4) - (reg_cons_2_m4 * reg_q_3_m4)))) * dxinv2); flux_2[k*M*N + j*N + i] = r2; r3 -= (((((0.8f * ((sh_cons_3_c0[j-j0+4][i-i0+1] * sh_q_1_c0[j-j0+4][i-i0+1]) - (sh_cons_3_c0[j-j0+4][i-i0-1] * sh_q_1_c0[j-j0+4][i-i0-1]))) - (0.2f * ((sh_cons_3_c0[j-j0+4][i-i0+2] * sh_q_1_c0[j-j0+4][i-i0+2]) - (sh_cons_3_c0[j-j0+4][i-i0-2] * sh_q_1_c0[j-j0+4][i-i0-2])))) + (0.038f * ((sh_cons_3_c0[j-j0+4][i-i0+3] * sh_q_1_c0[j-j0+4][i-i0+3]) - (sh_cons_3_c0[j-j0+4][i-i0-3] * sh_q_1_c0[j-j0+4][i-i0-3])))) - (0.0035f * ((sh_cons_3_c0[j-j0+4][i-i0+4] * sh_q_1_c0[j-j0+4][i-i0+4]) - (sh_cons_3_c0[j-j0+4][i-i0-4] * sh_q_1_c0[j-j0+4][i-i0-4])))) * dxinv0); r3 -= (((((0.8f * ((sh_cons_3_c0[j-j0+4+1][i-i0] * sh_q_2_c0[j-j0+4+1][i-i0]) - (sh_cons_3_c0[j-j0+4-1][i-i0] * sh_q_2_c0[j-j0+4-1][i-i0]))) - (0.2f * ((sh_cons_3_c0[j-j0+4+2][i-i0] * sh_q_2_c0[j-j0+4+2][i-i0]) - (sh_cons_3_c0[j-j0+4-2][i-i0] * sh_q_2_c0[j-j0+4-2][i-i0])))) + (0.038f * ((sh_cons_3_c0[j-j0+4+3][i-i0] * sh_q_2_c0[j-j0+4+3][i-i0]) - (sh_cons_3_c0[j-j0+4-3][i-i0] * sh_q_2_c0[j-j0+4-3][i-i0])))) - (0.0035f * ((sh_cons_3_c0[j-j0+4+4][i-i0] * sh_q_2_c0[j-j0+4+4][i-i0]) - (sh_cons_3_c0[j-j0+4-4][i-i0] * sh_q_2_c0[j-j0+4-4][i-i0])))) * dxinv1); r3 -= (((((0.8f * (((reg_cons_3_p1 * reg_q_3_p1) - (reg_cons_3_m1 * reg_q_3_m1)) + (reg_q_4_p1 - reg_q_4_m1))) - (0.2f * (((reg_cons_3_p2 * reg_q_3_p2) - (reg_cons_3_m2 * reg_q_3_m2)) + (reg_q_4_p2 - reg_q_4_m2)))) + (0.038f * (((reg_cons_3_p3 * reg_q_3_p3) - (reg_cons_3_m3 * reg_q_3_m3)) + (reg_q_4_p3 - reg_q_4_m3)))) - (0.0035f * (((reg_cons_3_p4 * reg_q_3_p4) - (reg_cons_3_m4 * reg_q_3_m4)) + (reg_q_4_p4 - reg_q_4_m4)))) * dxinv2); flux_3[k*M*N + j*N + i] = r3; r4 -= (((((0.8f * (((sh_cons_4_c0[j-j0+4][i-i0+1] * sh_q_1_c0[j-j0+4][i-i0+1]) - (sh_cons_4_c0[j-j0+4][i-i0-1] * sh_q_1_c0[j-j0+4][i-i0-1])) + ((sh_q_4_c0[j-j0+4][i-i0+1] * sh_q_1_c0[j-j0+4][i-i0+1]) - (sh_q_4_c0[j-j0+4][i-i0-1] * sh_q_1_c0[j-j0+4][i-i0-1])))) - (0.2f * (((sh_cons_4_c0[j-j0+4][i-i0+2] * sh_q_1_c0[j-j0+4][i-i0+2]) - (sh_cons_4_c0[j-j0+4][i-i0-2] * sh_q_1_c0[j-j0+4][i-i0-2])) + ((sh_q_4_c0[j-j0+4][i-i0+2] * sh_q_1_c0[j-j0+4][i-i0+2]) - (sh_q_4_c0[j-j0+4][i-i0-2] * sh_q_1_c0[j-j0+4][i-i0-2]))))) + (0.038f * (((sh_cons_4_c0[j-j0+4][i-i0+3] * sh_q_1_c0[j-j0+4][i-i0+3]) - (sh_cons_4_c0[j-j0+4][i-i0-3] * sh_q_1_c0[j-j0+4][i-i0-3])) + ((sh_q_4_c0[j-j0+4][i-i0+3] * sh_q_1_c0[j-j0+4][i-i0+3]) - (sh_q_4_c0[j-j0+4][i-i0-3] * sh_q_1_c0[j-j0+4][i-i0-3]))))) - (0.0035f * (((sh_cons_4_c0[j-j0+4][i-i0+4] * sh_q_1_c0[j-j0+4][i-i0+4]) - (sh_cons_4_c0[j-j0+4][i-i0-4] * sh_q_1_c0[j-j0+4][i-i0-4])) + ((sh_q_4_c0[j-j0+4][i-i0+4] * sh_q_1_c0[j-j0+4][i-i0+4]) - (sh_q_4_c0[j-j0+4][i-i0-4] * sh_q_1_c0[j-j0+4][i-i0-4]))))) * dxinv0); r4 -= (((((0.8f * (((sh_cons_4_c0[j-j0+4+1][i-i0] * sh_q_2_c0[j-j0+4+1][i-i0]) - (sh_cons_4_c0[j-j0+4-1][i-i0] * sh_q_2_c0[j-j0+4-1][i-i0])) + ((sh_q_4_c0[j-j0+4+1][i-i0] * sh_q_2_c0[j-j0+4+1][i-i0]) - (sh_q_4_c0[j-j0+4-1][i-i0] * sh_q_2_c0[j-j0+4-1][i-i0])))) - (0.2f * (((sh_cons_4_c0[j-j0+4+2][i-i0] * sh_q_2_c0[j-j0+4+2][i-i0]) - (sh_cons_4_c0[j-j0+4-2][i-i0] * sh_q_2_c0[j-j0+4-2][i-i0])) + ((sh_q_4_c0[j-j0+4+2][i-i0] * sh_q_2_c0[j-j0+4+2][i-i0]) - (sh_q_4_c0[j-j0+4-2][i-i0] * sh_q_2_c0[j-j0+4-2][i-i0]))))) + (0.038f * (((sh_cons_4_c0[j-j0+4+3][i-i0] * sh_q_2_c0[j-j0+4+3][i-i0]) - (sh_cons_4_c0[j-j0+4-3][i-i0] * sh_q_2_c0[j-j0+4-3][i-i0])) + ((sh_q_4_c0[j-j0+4+3][i-i0] * sh_q_2_c0[j-j0+4+3][i-i0]) - (sh_q_4_c0[j-j0+4-3][i-i0] * sh_q_2_c0[j-j0+4-3][i-i0]))))) - (0.0035f * (((sh_cons_4_c0[j-j0+4+4][i-i0] * sh_q_2_c0[j-j0+4+4][i-i0]) - (sh_cons_4_c0[j-j0+4-4][i-i0] * sh_q_2_c0[j-j0+4-4][i-i0])) + ((sh_q_4_c0[j-j0+4+4][i-i0] * sh_q_2_c0[j-j0+4+4][i-i0]) - (sh_q_4_c0[j-j0+4-4][i-i0] * sh_q_2_c0[j-j0+4-4][i-i0]))))) * dxinv1); r4 -= (((((0.8f * (((reg_cons_4_p1 * reg_q_3_p1) - (reg_cons_4_m1 * reg_q_3_m1)) + ((reg_q_4_p1 * reg_q_3_p1) - (reg_q_4_m1 * reg_q_3_m1)))) - (0.2f * (((reg_cons_4_p2 * reg_q_3_p2) - (reg_cons_4_m2 * reg_q_3_m2)) + ((reg_q_4_p2 * reg_q_3_p2) - (reg_q_4_m2 * reg_q_3_m2))))) + (0.038f * (((reg_cons_4_p3 * reg_q_3_p3) - (reg_cons_4_m3 * reg_q_3_m3)) + ((reg_q_4_p3 * reg_q_3_p3) - (reg_q_4_m3 * reg_q_3_m3))))) - (0.0035f * (((reg_cons_4_p4 * reg_q_3_p4) - (reg_cons_4_m4 * reg_q_3_m4)) + ((reg_q_4_p4 * reg_q_3_p4) - (reg_q_4_m4 * reg_q_3_m4))))) * dxinv2); flux_4[k*M*N + j*N + i] = r4; } __syncthreads (); //Value rotation if (j <= M-1 & i <= min (i0+blockdim_i-1, N-1)) { reg_cons_1_m4 = reg_cons_1_m3; reg_cons_1_m3 = reg_cons_1_m2; reg_cons_1_m2 = reg_cons_1_m1; reg_cons_1_m1 = sh_cons_1_c0[j-j0+4][i-i0]; sh_cons_1_c0[j-j0+4][i-i0] = reg_cons_1_p1; reg_cons_1_p1 = reg_cons_1_p2; reg_cons_1_p2 = reg_cons_1_p3; reg_cons_1_p3 = reg_cons_1_p4; reg_cons_2_m4 = reg_cons_2_m3; reg_cons_2_m3 = reg_cons_2_m2; reg_cons_2_m2 = reg_cons_2_m1; reg_cons_2_m1 = sh_cons_2_c0[j-j0+4][i-i0]; sh_cons_2_c0[j-j0+4][i-i0] = reg_cons_2_p1; reg_cons_2_p1 = reg_cons_2_p2; reg_cons_2_p2 = reg_cons_2_p3; reg_cons_2_p3 = reg_cons_2_p4; reg_cons_3_m4 = reg_cons_3_m3; reg_cons_3_m3 = reg_cons_3_m2; reg_cons_3_m2 = reg_cons_3_m1; reg_cons_3_m1 = sh_cons_3_c0[j-j0+4][i-i0]; sh_cons_3_c0[j-j0+4][i-i0] = reg_cons_3_p1; reg_cons_3_p1 = reg_cons_3_p2; reg_cons_3_p2 = reg_cons_3_p3; reg_cons_3_p3 = reg_cons_3_p4; reg_cons_4_m4 = reg_cons_4_m3; reg_cons_4_m3 = reg_cons_4_m2; reg_cons_4_m2 = reg_cons_4_m1; reg_cons_4_m1 = sh_cons_4_c0[j-j0+4][i-i0]; sh_cons_4_c0[j-j0+4][i-i0] = reg_cons_4_p1; reg_cons_4_p1 = reg_cons_4_p2; reg_cons_4_p2 = reg_cons_4_p3; reg_cons_4_p3 = reg_cons_4_p4; reg_q_3_m4 = reg_q_3_m3; reg_q_3_m3 = reg_q_3_m2; reg_q_3_m2 = reg_q_3_m1; reg_q_3_m1 = reg_q_3_c0; reg_q_3_c0 = reg_q_3_p1; reg_q_3_p1 = reg_q_3_p2; reg_q_3_p2 = reg_q_3_p3; reg_q_3_p3 = reg_q_3_p4; reg_q_4_m4 = reg_q_4_m3; reg_q_4_m3 = reg_q_4_m2; reg_q_4_m2 = reg_q_4_m1; reg_q_4_m1 = sh_q_4_c0[j-j0+4][i-i0]; sh_q_4_c0[j-j0+4][i-i0] = reg_q_4_p1; reg_q_4_p1 = reg_q_4_p2; reg_q_4_p2 = reg_q_4_p3; reg_q_4_p3 = reg_q_4_p4; } } } extern "C" void host_code (double *h_flux_0, double *h_flux_1, double *h_flux_2, double *h_flux_3, double *h_flux_4, double *h_cons_1, double *h_cons_2, double *h_cons_3, double *h_cons_4, double *h_q_1, double *h_q_2, double *h_q_3, double *h_q_4, double dxinv0, double dxinv1, double dxinv2, int L, int M, int N) { double *flux_0; cudaMalloc (&flux_0, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for flux_0\n"); cudaMemcpy (flux_0, h_flux_0, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *flux_1; cudaMalloc (&flux_1, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for flux_1\n"); cudaMemcpy (flux_1, h_flux_1, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *flux_2; cudaMalloc (&flux_2, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for flux_2\n"); cudaMemcpy (flux_2, h_flux_2, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *flux_3; cudaMalloc (&flux_3, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for flux_3\n"); cudaMemcpy (flux_3, h_flux_3, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *flux_4; cudaMalloc (&flux_4, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for flux_4\n"); cudaMemcpy (flux_4, h_flux_4, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *cons_1; cudaMalloc (&cons_1, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for cons_1\n"); cudaMemcpy (cons_1, h_cons_1, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *cons_2; cudaMalloc (&cons_2, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for cons_2\n"); cudaMemcpy (cons_2, h_cons_2, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *cons_3; cudaMalloc (&cons_3, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for cons_3\n"); cudaMemcpy (cons_3, h_cons_3, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *cons_4; cudaMalloc (&cons_4, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for cons_4\n"); cudaMemcpy (cons_4, h_cons_4, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *q_1; cudaMalloc (&q_1, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for q_1\n"); cudaMemcpy (q_1, h_q_1, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *q_2; cudaMalloc (&q_2, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for q_2\n"); cudaMemcpy (q_2, h_q_2, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *q_3; cudaMalloc (&q_3, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for q_3\n"); cudaMemcpy (q_3, h_q_3, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); double *q_4; cudaMalloc (&q_4, sizeof(double)*L*M*N); check_error ("Failed to allocate device memory for q_4\n"); cudaMemcpy (q_4, h_q_4, sizeof(double)*L*M*N, cudaMemcpyHostToDevice); dim3 blockconfig_1 (16, 16, 1); dim3 gridconfig_1 (ceil(N, blockconfig_1.x-8), ceil(M-8, blockconfig_1.y), 1); hypterm <<<gridconfig_1, blockconfig_1>>> (flux_0, flux_1, flux_2, flux_3, flux_4, cons_1, cons_2, cons_3, cons_4, q_1, q_2, q_3, q_4, dxinv0, dxinv1, dxinv2, L, M, N); cudaMemcpy (h_flux_0, flux_0, sizeof(double)*L*M*N, cudaMemcpyDeviceToHost); cudaMemcpy (h_flux_1, flux_1, sizeof(double)*L*M*N, cudaMemcpyDeviceToHost); cudaMemcpy (h_flux_2, flux_2, sizeof(double)*L*M*N, cudaMemcpyDeviceToHost); cudaMemcpy (h_flux_3, flux_3, sizeof(double)*L*M*N, cudaMemcpyDeviceToHost); cudaMemcpy (h_flux_4, flux_4, sizeof(double)*L*M*N, cudaMemcpyDeviceToHost); //Free allocated memory cudaFree (flux_0); cudaFree (flux_1); cudaFree (flux_2); cudaFree (flux_3); cudaFree (flux_4); cudaFree (cons_1); cudaFree (cons_2); cudaFree (cons_3); cudaFree (cons_4); cudaFree (q_1); cudaFree (q_2); cudaFree (q_3); cudaFree (q_4); }