hip_filename
stringlengths
5
84
hip_content
stringlengths
79
9.69M
cuda_filename
stringlengths
4
83
cuda_content
stringlengths
19
9.69M
473125bfd51ad2fb2ad2d449bb40e753f996bc48.hip
// !!! This is a file automatically generated by hipify!!! #ifdef _WIN32 #define WINDOWS_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #endif //////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////// #include "bucketsort.cuh" #include "helper_cuda.h" #include "histogram1024.cuh" #include <GL/glew.h> #include <GL/glut.h> #include <cuda_gl_interop.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gloop/gloop.h> #include <gloop/statistics.h> //////////////////////////////////////////////////////////////////////////////// // Forward declarations //////////////////////////////////////////////////////////////////////////////// void calcPivotPoints(float* histogram, int histosize, int listsize, int divisions, float min, float max, float* pivotPoints, float histo_width); //////////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////////// const int histosize = 1024; unsigned int* h_offsets = NULL; unsigned int* d_offsets = NULL; int* d_indice = NULL; float* pivotPoints = NULL; float* historesult = NULL; float* l_pivotpoints = NULL; unsigned int* d_prefixoffsets = NULL; unsigned int* l_offsets = NULL; //////////////////////////////////////////////////////////////////////////////// // Initialize the bucketsort algorithm //////////////////////////////////////////////////////////////////////////////// void init_bucketsort(int listsize) { gloop::Statistics::Scope<gloop::Statistics::Type::DataInit> scope; h_offsets = (unsigned int*)malloc(histosize * sizeof(int)); pivotPoints = (float*)malloc(DIVISIONS * sizeof(float)); historesult = (float*)malloc(histosize * sizeof(float)); { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(hipMalloc((void**)&d_offsets, histosize * sizeof(unsigned int))); checkCudaErrors(hipMalloc((void**)&l_pivotpoints, DIVISIONS * sizeof(float))); checkCudaErrors(hipMalloc((void**)&l_offsets, DIVISIONS * sizeof(int))); checkCudaErrors(hipMalloc((void**)&d_indice, listsize * sizeof(int))); int blocks = ((listsize - 1) / (BUCKET_THREAD_N * BUCKET_BAND)) + 1; checkCudaErrors(hipMalloc((void**)&d_prefixoffsets, blocks * BUCKET_BLOCK_MEMORY * sizeof(int))); } initHistogram1024(); } //////////////////////////////////////////////////////////////////////////////// // Uninitialize the bucketsort algorithm //////////////////////////////////////////////////////////////////////////////// void finish_bucketsort() { gloop::Statistics::Scope<gloop::Statistics::Type::DataInit> scope; free(pivotPoints); free(h_offsets); free(historesult); { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(hipFree(d_prefixoffsets)); checkCudaErrors(hipFree(d_indice)); checkCudaErrors(hipFree(d_offsets)); checkCudaErrors(hipFree(l_pivotpoints)); checkCudaErrors(hipFree(l_offsets)); } closeHistogram1024(); } //////////////////////////////////////////////////////////////////////////////// // Given the input array of floats and the min and max of the distribution, // sort the elements into float4 aligned buckets of roughly equal size //////////////////////////////////////////////////////////////////////////////// void bucketSort(Context* ctx, float* d_input, float* d_output, int listsize, int* sizes, int* nullElements, float minimum, float maximum, unsigned int* origOffsets) { gloop::Statistics::Scope<gloop::Statistics::Type::DataInit> scope; //////////////////////////////////////////////////////////////////////////// // First pass - Create 1024 bin histogram //////////////////////////////////////////////////////////////////////////// { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(hipMemset((void*)d_offsets, 0, histosize * sizeof(int))); } histogram1024GPU(ctx, h_offsets, d_input, minimum, maximum, listsize); for (int i = 0; i < histosize; i++) historesult[i] = (float)h_offsets[i]; /////////////////////////////////////////////////////////////////////////// // Calculate pivot points (CPU algorithm) /////////////////////////////////////////////////////////////////////////// calcPivotPoints(historesult, histosize, listsize, DIVISIONS, minimum, maximum, pivotPoints, (maximum - minimum) / (float)histosize); /////////////////////////////////////////////////////////////////////////// // Count the bucket sizes in new divisions /////////////////////////////////////////////////////////////////////////// { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(hipMemcpy(l_pivotpoints, pivotPoints, (DIVISIONS) * sizeof(int), hipMemcpyHostToDevice)); checkCudaErrors(hipMemset((void*)d_offsets, 0, DIVISIONS * sizeof(int))); checkCudaErrors(hipBindTexture(0, texPivot, l_pivotpoints, DIVISIONS * sizeof(int))); } // Setup block and grid dim3 threads(BUCKET_THREAD_N, 1); int blocks = ((listsize - 1) / (threads.x * BUCKET_BAND)) + 1; dim3 grid(blocks, 1); { // Find the new indice for all elements gloop::Statistics::Scope<gloop::Statistics::Type::Kernel> scope; bucketcountGPU(ctx, grid, threads, d_input, d_indice, d_prefixoffsets, listsize); /////////////////////////////////////////////////////////////////////////// // Prefix scan offsets and align each division to float4 (required by // mergesort) /////////////////////////////////////////////////////////////////////////// #ifdef BUCKET_WG_SIZE_0 threads.x = BUCKET_WG_SIZE_0; #else threads.x = 128; #endif grid.x = DIVISIONS / threads.x; bucketprefixoffsetGPU(ctx, grid, threads, d_prefixoffsets, d_offsets, blocks); hipDeviceSynchronize(); } { // copy the sizes from device to host gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; hipMemcpy(h_offsets, d_offsets, DIVISIONS * sizeof(int), hipMemcpyDeviceToHost); } origOffsets[0] = 0; for (int i = 0; i < DIVISIONS; i++) { origOffsets[i + 1] = h_offsets[i] + origOffsets[i]; if ((h_offsets[i] % 4) != 0) { nullElements[i] = (h_offsets[i] & ~3) + 4 - h_offsets[i]; } else nullElements[i] = 0; } for (int i = 0; i < DIVISIONS; i++) sizes[i] = (h_offsets[i] + nullElements[i]) / 4; for (int i = 0; i < DIVISIONS; i++) { if ((h_offsets[i] % 4) != 0) h_offsets[i] = (h_offsets[i] & ~3) + 4; } for (int i = 1; i < DIVISIONS; i++) h_offsets[i] = h_offsets[i - 1] + h_offsets[i]; for (int i = DIVISIONS - 1; i > 0; i--) h_offsets[i] = h_offsets[i - 1]; h_offsets[0] = 0; /////////////////////////////////////////////////////////////////////////// // Finally, sort the lot /////////////////////////////////////////////////////////////////////////// { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; hipMemcpy(l_offsets, h_offsets, (DIVISIONS) * sizeof(int), hipMemcpyHostToDevice); hipMemset(d_output, 0x0, (listsize + (DIVISIONS * 4)) * sizeof(float)); } threads.x = BUCKET_THREAD_N; blocks = ((listsize - 1) / (threads.x * BUCKET_BAND)) + 1; grid.x = blocks; { gloop::Statistics::Scope<gloop::Statistics::Type::Kernel> scope; bucketsortGPU(ctx, grid, threads, d_input, d_indice, d_output, listsize, d_prefixoffsets, l_offsets); } } //////////////////////////////////////////////////////////////////////////////// // Given a histogram of the list, figure out suitable pivotpoints that divide // the list into approximately listsize/divisions elements each //////////////////////////////////////////////////////////////////////////////// void calcPivotPoints(float* histogram, int histosize, int listsize, int divisions, float min, float max, float* pivotPoints, float histo_width) { float elemsPerSlice = listsize / (float)divisions; float startsAt = min; float endsAt = min + histo_width; float we_need = elemsPerSlice; int p_idx = 0; for (int i = 0; i < histosize; i++) { if (i == histosize - 1) { if (!(p_idx < divisions)) { pivotPoints[p_idx++] = startsAt + (we_need / histogram[i]) * histo_width; } break; } while (histogram[i] > we_need) { if (!(p_idx < divisions)) { printf("i=%d, p_idx = %d, divisions = %d\n", i, p_idx, divisions); exit(0); } pivotPoints[p_idx++] = startsAt + (we_need / histogram[i]) * histo_width; startsAt += (we_need / histogram[i]) * histo_width; histogram[i] -= we_need; we_need = elemsPerSlice; } // grab what we can from what remains of it we_need -= histogram[i]; startsAt = endsAt; endsAt += histo_width; } while (p_idx < divisions) { pivotPoints[p_idx] = pivotPoints[p_idx - 1]; p_idx++; } }
473125bfd51ad2fb2ad2d449bb40e753f996bc48.cu
#ifdef _WIN32 #define WINDOWS_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #endif //////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////// #include "bucketsort.cuh" #include "helper_cuda.h" #include "histogram1024.cuh" #include <GL/glew.h> #include <GL/glut.h> #include <cuda_gl_interop.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gloop/gloop.h> #include <gloop/statistics.h> //////////////////////////////////////////////////////////////////////////////// // Forward declarations //////////////////////////////////////////////////////////////////////////////// void calcPivotPoints(float* histogram, int histosize, int listsize, int divisions, float min, float max, float* pivotPoints, float histo_width); //////////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////////// const int histosize = 1024; unsigned int* h_offsets = NULL; unsigned int* d_offsets = NULL; int* d_indice = NULL; float* pivotPoints = NULL; float* historesult = NULL; float* l_pivotpoints = NULL; unsigned int* d_prefixoffsets = NULL; unsigned int* l_offsets = NULL; //////////////////////////////////////////////////////////////////////////////// // Initialize the bucketsort algorithm //////////////////////////////////////////////////////////////////////////////// void init_bucketsort(int listsize) { gloop::Statistics::Scope<gloop::Statistics::Type::DataInit> scope; h_offsets = (unsigned int*)malloc(histosize * sizeof(int)); pivotPoints = (float*)malloc(DIVISIONS * sizeof(float)); historesult = (float*)malloc(histosize * sizeof(float)); { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(cudaMalloc((void**)&d_offsets, histosize * sizeof(unsigned int))); checkCudaErrors(cudaMalloc((void**)&l_pivotpoints, DIVISIONS * sizeof(float))); checkCudaErrors(cudaMalloc((void**)&l_offsets, DIVISIONS * sizeof(int))); checkCudaErrors(cudaMalloc((void**)&d_indice, listsize * sizeof(int))); int blocks = ((listsize - 1) / (BUCKET_THREAD_N * BUCKET_BAND)) + 1; checkCudaErrors(cudaMalloc((void**)&d_prefixoffsets, blocks * BUCKET_BLOCK_MEMORY * sizeof(int))); } initHistogram1024(); } //////////////////////////////////////////////////////////////////////////////// // Uninitialize the bucketsort algorithm //////////////////////////////////////////////////////////////////////////////// void finish_bucketsort() { gloop::Statistics::Scope<gloop::Statistics::Type::DataInit> scope; free(pivotPoints); free(h_offsets); free(historesult); { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(cudaFree(d_prefixoffsets)); checkCudaErrors(cudaFree(d_indice)); checkCudaErrors(cudaFree(d_offsets)); checkCudaErrors(cudaFree(l_pivotpoints)); checkCudaErrors(cudaFree(l_offsets)); } closeHistogram1024(); } //////////////////////////////////////////////////////////////////////////////// // Given the input array of floats and the min and max of the distribution, // sort the elements into float4 aligned buckets of roughly equal size //////////////////////////////////////////////////////////////////////////////// void bucketSort(Context* ctx, float* d_input, float* d_output, int listsize, int* sizes, int* nullElements, float minimum, float maximum, unsigned int* origOffsets) { gloop::Statistics::Scope<gloop::Statistics::Type::DataInit> scope; //////////////////////////////////////////////////////////////////////////// // First pass - Create 1024 bin histogram //////////////////////////////////////////////////////////////////////////// { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(cudaMemset((void*)d_offsets, 0, histosize * sizeof(int))); } histogram1024GPU(ctx, h_offsets, d_input, minimum, maximum, listsize); for (int i = 0; i < histosize; i++) historesult[i] = (float)h_offsets[i]; /////////////////////////////////////////////////////////////////////////// // Calculate pivot points (CPU algorithm) /////////////////////////////////////////////////////////////////////////// calcPivotPoints(historesult, histosize, listsize, DIVISIONS, minimum, maximum, pivotPoints, (maximum - minimum) / (float)histosize); /////////////////////////////////////////////////////////////////////////// // Count the bucket sizes in new divisions /////////////////////////////////////////////////////////////////////////// { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; checkCudaErrors(cudaMemcpy(l_pivotpoints, pivotPoints, (DIVISIONS) * sizeof(int), cudaMemcpyHostToDevice)); checkCudaErrors(cudaMemset((void*)d_offsets, 0, DIVISIONS * sizeof(int))); checkCudaErrors(cudaBindTexture(0, texPivot, l_pivotpoints, DIVISIONS * sizeof(int))); } // Setup block and grid dim3 threads(BUCKET_THREAD_N, 1); int blocks = ((listsize - 1) / (threads.x * BUCKET_BAND)) + 1; dim3 grid(blocks, 1); { // Find the new indice for all elements gloop::Statistics::Scope<gloop::Statistics::Type::Kernel> scope; bucketcountGPU(ctx, grid, threads, d_input, d_indice, d_prefixoffsets, listsize); /////////////////////////////////////////////////////////////////////////// // Prefix scan offsets and align each division to float4 (required by // mergesort) /////////////////////////////////////////////////////////////////////////// #ifdef BUCKET_WG_SIZE_0 threads.x = BUCKET_WG_SIZE_0; #else threads.x = 128; #endif grid.x = DIVISIONS / threads.x; bucketprefixoffsetGPU(ctx, grid, threads, d_prefixoffsets, d_offsets, blocks); cudaThreadSynchronize(); } { // copy the sizes from device to host gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; cudaMemcpy(h_offsets, d_offsets, DIVISIONS * sizeof(int), cudaMemcpyDeviceToHost); } origOffsets[0] = 0; for (int i = 0; i < DIVISIONS; i++) { origOffsets[i + 1] = h_offsets[i] + origOffsets[i]; if ((h_offsets[i] % 4) != 0) { nullElements[i] = (h_offsets[i] & ~3) + 4 - h_offsets[i]; } else nullElements[i] = 0; } for (int i = 0; i < DIVISIONS; i++) sizes[i] = (h_offsets[i] + nullElements[i]) / 4; for (int i = 0; i < DIVISIONS; i++) { if ((h_offsets[i] % 4) != 0) h_offsets[i] = (h_offsets[i] & ~3) + 4; } for (int i = 1; i < DIVISIONS; i++) h_offsets[i] = h_offsets[i - 1] + h_offsets[i]; for (int i = DIVISIONS - 1; i > 0; i--) h_offsets[i] = h_offsets[i - 1]; h_offsets[0] = 0; /////////////////////////////////////////////////////////////////////////// // Finally, sort the lot /////////////////////////////////////////////////////////////////////////// { gloop::Statistics::Scope<gloop::Statistics::Type::Copy> scope; cudaMemcpy(l_offsets, h_offsets, (DIVISIONS) * sizeof(int), cudaMemcpyHostToDevice); cudaMemset(d_output, 0x0, (listsize + (DIVISIONS * 4)) * sizeof(float)); } threads.x = BUCKET_THREAD_N; blocks = ((listsize - 1) / (threads.x * BUCKET_BAND)) + 1; grid.x = blocks; { gloop::Statistics::Scope<gloop::Statistics::Type::Kernel> scope; bucketsortGPU(ctx, grid, threads, d_input, d_indice, d_output, listsize, d_prefixoffsets, l_offsets); } } //////////////////////////////////////////////////////////////////////////////// // Given a histogram of the list, figure out suitable pivotpoints that divide // the list into approximately listsize/divisions elements each //////////////////////////////////////////////////////////////////////////////// void calcPivotPoints(float* histogram, int histosize, int listsize, int divisions, float min, float max, float* pivotPoints, float histo_width) { float elemsPerSlice = listsize / (float)divisions; float startsAt = min; float endsAt = min + histo_width; float we_need = elemsPerSlice; int p_idx = 0; for (int i = 0; i < histosize; i++) { if (i == histosize - 1) { if (!(p_idx < divisions)) { pivotPoints[p_idx++] = startsAt + (we_need / histogram[i]) * histo_width; } break; } while (histogram[i] > we_need) { if (!(p_idx < divisions)) { printf("i=%d, p_idx = %d, divisions = %d\n", i, p_idx, divisions); exit(0); } pivotPoints[p_idx++] = startsAt + (we_need / histogram[i]) * histo_width; startsAt += (we_need / histogram[i]) * histo_width; histogram[i] -= we_need; we_need = elemsPerSlice; } // grab what we can from what remains of it we_need -= histogram[i]; startsAt = endsAt; endsAt += histo_width; } while (p_idx < divisions) { pivotPoints[p_idx] = pivotPoints[p_idx - 1]; p_idx++; } }
678548d29ee8b273c18a0643f51aef7638736977.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <cmath> #include <vector> #include "caffe/layers/sigmoid_layer.hpp" namespace caffe { template <typename Dtype> __global__ void SigmoidForward(const int n, const Dtype* in, Dtype* out) { CUDA_KERNEL_LOOP(index, n) { out[index] = 1. / (1. + exp(-in[index])); } } template <typename Dtype> void SigmoidLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); const int count = bottom[0]->count(); // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( SigmoidForward<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, count, bottom_data, top_data); CUDA_POST_KERNEL_CHECK; // << " count: " << count << " bottom_data: " // << (unsigned long)bottom_data // << " top_data: " << (unsigned long)top_data // << " blocks: " << CAFFE_GET_BLOCKS(count) // << " threads: " << CAFFE_CUDA_NUM_THREADS; } template <typename Dtype> __global__ void SigmoidBackward(const int n, const Dtype* in_diff, const Dtype* out_data, Dtype* out_diff) { CUDA_KERNEL_LOOP(index, n) { const Dtype sigmoid_x = out_data[index]; out_diff[index] = in_diff[index] * sigmoid_x * (1 - sigmoid_x); } } template <typename Dtype> void SigmoidLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0]) { const Dtype* top_data = top[0]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int count = bottom[0]->count(); // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( SigmoidBackward<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, count, top_diff, top_data, bottom_diff); CUDA_POST_KERNEL_CHECK; } } INSTANTIATE_LAYER_GPU_FUNCS(SigmoidLayer); } // namespace caffe
678548d29ee8b273c18a0643f51aef7638736977.cu
#include <cmath> #include <vector> #include "caffe/layers/sigmoid_layer.hpp" namespace caffe { template <typename Dtype> __global__ void SigmoidForward(const int n, const Dtype* in, Dtype* out) { CUDA_KERNEL_LOOP(index, n) { out[index] = 1. / (1. + exp(-in[index])); } } template <typename Dtype> void SigmoidLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); const int count = bottom[0]->count(); // NOLINT_NEXT_LINE(whitespace/operators) SigmoidForward<Dtype><<<CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS>>>( count, bottom_data, top_data); CUDA_POST_KERNEL_CHECK; // << " count: " << count << " bottom_data: " // << (unsigned long)bottom_data // << " top_data: " << (unsigned long)top_data // << " blocks: " << CAFFE_GET_BLOCKS(count) // << " threads: " << CAFFE_CUDA_NUM_THREADS; } template <typename Dtype> __global__ void SigmoidBackward(const int n, const Dtype* in_diff, const Dtype* out_data, Dtype* out_diff) { CUDA_KERNEL_LOOP(index, n) { const Dtype sigmoid_x = out_data[index]; out_diff[index] = in_diff[index] * sigmoid_x * (1 - sigmoid_x); } } template <typename Dtype> void SigmoidLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0]) { const Dtype* top_data = top[0]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int count = bottom[0]->count(); // NOLINT_NEXT_LINE(whitespace/operators) SigmoidBackward<Dtype><<<CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS>>>( count, top_diff, top_data, bottom_diff); CUDA_POST_KERNEL_CHECK; } } INSTANTIATE_LAYER_GPU_FUNCS(SigmoidLayer); } // namespace caffe
bde8ea594e6250e3559fb5eb80384d58f6dd39f1.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "vf2gpu.h" #include "utils.cuh" #include "mesh.cuh" #include "threadIdx.cuh" #include "inverseInterpolation.cuh" #include <cstdio> #include <algorithm> template <typename T> __device__ T line_integral(const vf2gpu_hdr_t& h, const T X0[], const T X1[], const T A0[], const T A1[]) { T dX[3] = {X1[0] - X0[0], X1[1] - X0[1], X1[2] - X0[2]}; T A[3] = {A0[0] + A1[0], A0[1] + A1[1], A0[2] + A1[2]}; for (int i=0; i<3; i++) if (dX[i] > h.lengths[i]/2) dX[i] -= h.lengths[i]; else if (dX[i] < -h.lengths[i]/2) dX[i] += h.lengths[i]; return 0.5 * inner_product(A, dX); } template <typename T, int gauge> __device__ inline void magnetic_potential(const vf2gpu_hdr_t& h, T X[3], T A[3]) { // if (h.B[1]>0) { // yz gauge if (gauge == VF2GPU_GAUGE_YZ) { A[0] = -h.Kx; A[1] = X[0] * h.B[2]; A[2] = -X[0] * h.B[1]; } else { // xz gauge A[0] = -X[1] * h.B[2] - h.Kx; A[1] = 0; A[2] = X[1] * h.B[0]; } } template <typename T, int meshtype, int gauge> __device__ inline bool get_face_values( const vf2gpu_hdr_t& h, int fid, T X[][3], T A[][3], T rho[], T phi[], const T *rho_phi_) { const int nnodes = meshtype == VF2GPU_MESH_TET ? 3 : 4; int nidxs[nnodes][3], nids[nnodes]; bool valid; if (meshtype == VF2GPU_MESH_TET) valid = fid2nodes3D_tet(h, fid, nidxs); else if (meshtype == VF2GPU_MESH_HEX) valid = fid2nodes3D_hex(h, fid, nidxs); else valid = fid2nodes2D(h, fid, nidxs); if (valid) { for (int i=0; i<nnodes; i++) { if (meshtype == VF2GPU_MESH_QUAD) { nids[i] = nidx2nid2D(h, nidxs[i]); nidx2pos2D(h, nidxs[i], X[i]); } else { nids[i] = nidx2nid3D(h, nidxs[i]); nidx2pos3D(h, nidxs[i], X[i]); } rho[i] = rho_phi_[nids[i]*2]; phi[i] = rho_phi_[nids[i]*2+1]; magnetic_potential<T, gauge>(h, X[i], A[i]); } } return valid; } template <typename T> __device__ inline int contour_chirality( const vf2gpu_hdr_t &h, int nnodes, // nnodes <= 4 const T phi[], const T X[][3], const T A[][3], T delta[]) { T phase_jump = 0; for (int i=0; i<nnodes; i++) { int j = (i+1) % nnodes; delta[i] = phi[j] - phi[i]; T li = line_integral(h, X[i], X[j], A[i], A[j]), qp = 0; // TODO delta[i] = mod2pi1(delta[i] - li + qp); phase_jump -= delta[i]; } if (fabs(phase_jump)<0.5) return 0; // not punctured else return sgn(phase_jump); } // for space-time vfaces template <typename T> __device__ inline int contour_chirality_spt( const vf2gpu_hdr_t &h, const vf2gpu_hdr_t &h1, const T phi[4], const T X[4][3], const T A[4][3], T delta[]) { T li[4] = { // FIXME: varying B line_integral(h, X[0], X[1], A[0], A[1]), 0, line_integral(h, X[1], X[0], A[2], A[3]), 0}; T qp[4] = {0, 0, 0, 0}; // FIXME T phase_jump = 0; for (int i=0; i<4; i++) { int j = (i+1) % 4; delta[i] = phi[j] - phi[i]; delta[i] = mod2pi1(delta[i] - li[i] + qp[i]); phase_jump -= delta[i]; } if (fabs(phase_jump)<0.5) return 0; // not punctured else return sgn(phase_jump); } template <typename T> __device__ inline void gauge_transform( int nnodes, const T rho[], const T delta[], T phi[], T re[], T im[]) { re[0] = rho[0] * cos(phi[0]); im[0] = rho[0] * sin(phi[0]); for (int i=1; i<nnodes; i++) { phi[i] = phi[i-1] + delta[i-1]; re[i] = rho[i] * cos(phi[i]); im[i] = rho[i] * sin(phi[i]); } } template <typename T, int meshtype, int gauge> __device__ inline int extract_face( const vf2gpu_hdr_t& h, int fid, unsigned int *pfcount, vf2gpu_pf_t *pflist, const T *rho_phi_) { const int nnodes = meshtype == VF2GPU_MESH_TET ? 3 : 4; T X[nnodes][3], A[nnodes][3], rho[nnodes], phi[nnodes], re[nnodes], im[nnodes]; T delta[nnodes]; bool valid = get_face_values<T, meshtype, gauge>(h, fid, X, A, rho, phi, rho_phi_); if (!valid) return 0; // compute phase shift int chirality = contour_chirality(h, nnodes, phi, X, A, delta); if (chirality == 0) return 0; // gauge transformation gauge_transform(nnodes, rho, delta, phi, re, im); // find puncture point vf2gpu_pf_t pf; pf.fid = fid; pf.chirality = chirality; find_zero<T, meshtype>(re, im, X, pf.pos, T(1)); unsigned int idx = atomicInc(pfcount, 0xffffffff); pflist[idx] = pf; return chirality; } template <typename T> __global__ static void compute_rho_phi_kernel( const vf2gpu_hdr_t *h, T *re_im, T *rho_phi) { int idx = getGlobalIdx_3D_1D(); if (idx>=h->count) return; T r, i; r = re_im[idx*2]; i = re_im[idx*2+1]; rho_phi[idx*2] = sqrt(r*r + i*i); rho_phi[idx*2+1] = atan2(i, r); } template <typename T> __global__ static void copy_phi_kernel( // copy phi to another array const vf2gpu_hdr_t *h, T *rho_phi, T *phi) { int idx = getGlobalIdx_3D_1D(); if (idx>=h->count) return; phi[idx] = rho_phi[idx*2+1]; } template <typename T, int meshtype, int gauge> __global__ static void extract_faces_kernel( const vf2gpu_hdr_t* h, unsigned int *pfcount, const unsigned int pflimit, vf2gpu_pf_t *pflist, const T *rho_phi) { int nfacetypes; if (meshtype == VF2GPU_MESH_TET) nfacetypes = 12; else if (meshtype == VF2GPU_MESH_HEX) nfacetypes = 3; else nfacetypes = 1; int fid = getGlobalIdx_3D_1D(); if (fid>=h->count*nfacetypes) return; #if 0 // use global memory extract_face<T, meshtype, gauge>(*h, fid, pfcount, pflist, rho, phi); #else // use shared memory extern __shared__ char smem[]; unsigned int *spfcount = (unsigned int*)smem; vf2gpu_pf_t *spflist= (vf2gpu_pf_t*)(smem + sizeof(int)); if (threadIdx.x == 0) *spfcount = 0; __syncthreads(); extract_face<T, meshtype, gauge>(*h, fid, spfcount, spflist, rho_phi); __syncthreads(); if (threadIdx.x == 0 && (*spfcount)>0) { unsigned int idx = atomicAdd(pfcount, *spfcount); // printf("idx=%d, count=%d\n", idx, *spfcount); if (idx + *spfcount < pflimit) memcpy(pflist + idx, spflist, (*spfcount) * sizeof(vf2gpu_pf_t)); } #endif } //////////////////////////////// extern "C" { void vf2gpu_set_data_insitu( vf2gpu_ctx_t* c, const vf2gpu_hdr_t &h, float *d_re_im, float *d_tmp1, float *d_tmp2) { if (c->d_h == NULL) hipMalloc((void**)&c->d_h, sizeof(vf2gpu_hdr_t)); memcpy(&c->h, &h, sizeof(vf2gpu_hdr_t)); hipMemcpy(c->d_h, &c->h, sizeof(vf2gpu_hdr_t), hipMemcpyHostToDevice); c->d_re_im = d_re_im; c->d_rho_phi = d_tmp1; c->d_pfcount = (unsigned int*)d_tmp2; c->d_pflist = (vf2gpu_pf_t*)(d_tmp2 + 1); } void vf2gpu_compute_rho_phi(vf2gpu_ctx_t* c) { const int count = c->h.count; const int maxGridDim = 1024; // 32768; const int blockSize = 256; const int nBlocks = idivup(count, blockSize); dim3 gridSize; if (nBlocks >= maxGridDim) gridSize = dim3(idivup(nBlocks, maxGridDim), maxGridDim); else gridSize = dim3(nBlocks); // fprintf(stderr, "count=%d\n", c->h.count); hipLaunchKernelGGL(( compute_rho_phi_kernel<float>), dim3(gridSize), dim3(blockSize), 0, 0, c->d_h, c->d_re_im, c->d_rho_phi); checkLastCudaError("[vf2gpu] compute rho and phi"); } void vf2gpu_copy_phi(vf2gpu_ctx_t* c) { const int count = c->h.count; const int maxGridDim = 1024; // 32768; const int blockSize = 256; const int nBlocks = idivup(count, blockSize); dim3 gridSize; if (nBlocks >= maxGridDim) gridSize = dim3(idivup(nBlocks, maxGridDim), maxGridDim); else gridSize = dim3(nBlocks); // copy_phi_kernel<float><<<gridSize, blockSize>>>(c->d_h, c->d_re_im, c->d_rho_phi); checkLastCudaError("[vf2gpu] copy phi"); } void vf2gpu_extract_faces(vf2gpu_ctx_t* c) { int nfacetypes; if (c->meshtype == VF2GPU_MESH_TET) nfacetypes = 12; else if (c->meshtype == VF2GPU_MESH_HEX) nfacetypes = 3; else nfacetypes = 1; const int threadCount = c->h.count * nfacetypes; const int maxGridDim = 1024; // 32768; const int blockSize = 256; const int nBlocks = idivup(threadCount, blockSize); dim3 gridSize; if (nBlocks >= maxGridDim) gridSize = dim3(idivup(nBlocks, maxGridDim), maxGridDim); else gridSize = dim3(nBlocks); const int sharedSize = blockSize * sizeof(vf2gpu_pf_t) + sizeof(unsigned int); // enough shared memory for every block const unsigned int pflimit = c->h.count / sizeof(vf2gpu_pf_t); const int gauge = c->h.B[1]>0 ? VF2GPU_GAUGE_YZ : VF2GPU_GAUGE_XZ; vf2gpu_compute_rho_phi(c); hipMemset(c->d_pfcount, 0, sizeof(unsigned int)); if (c->meshtype == VF2GPU_MESH_HEX) { if (gauge == VF2GPU_GAUGE_YZ) hipLaunchKernelGGL(( extract_faces_kernel<float, VF2GPU_MESH_HEX, VF2GPU_GAUGE_YZ>), dim3(gridSize), dim3(blockSize), sharedSize, 0, c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); else hipLaunchKernelGGL(( extract_faces_kernel<float, VF2GPU_MESH_HEX, VF2GPU_GAUGE_XZ>), dim3(gridSize), dim3(blockSize), sharedSize, 0, c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); } else if (c->meshtype == VF2GPU_MESH_TET) { if (gauge == VF2GPU_GAUGE_YZ) hipLaunchKernelGGL(( extract_faces_kernel<float, VF2GPU_MESH_TET, VF2GPU_GAUGE_YZ>), dim3(gridSize), dim3(blockSize), sharedSize, 0, c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); else hipLaunchKernelGGL(( extract_faces_kernel<float, VF2GPU_MESH_TET, VF2GPU_GAUGE_XZ>), dim3(gridSize), dim3(blockSize), sharedSize, 0, c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); } else if (c->meshtype == VF2GPU_MESH_QUAD) { if (gauge == VF2GPU_GAUGE_YZ) hipLaunchKernelGGL(( extract_faces_kernel<float, VF2GPU_MESH_QUAD, VF2GPU_GAUGE_YZ>), dim3(gridSize), dim3(blockSize), sharedSize, 0, c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); else hipLaunchKernelGGL(( extract_faces_kernel<float, VF2GPU_MESH_QUAD, VF2GPU_GAUGE_XZ>), dim3(gridSize), dim3(blockSize), sharedSize, 0, c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); } hipMemcpy((void*)&c->pfcount, c->d_pfcount, sizeof(unsigned int), hipMemcpyDeviceToHost); printf("pfcount=%d\n", c->pfcount); // if (c->pfcount>0) // hipMemcpy(c->pflist, c->d_pflist, sizeof(vf2gpu_pf_t)*c->pfcount, hipMemcpyDeviceToHost); checkLastCudaError("[vf2gpu] extract faces"); } int vf2gpu_write_binary(vf2gpu_ctx_t* c, const char *filename) { int pfcount; hipMemcpy(&pfcount, c->d_pfcount, sizeof(unsigned int), hipMemcpyDeviceToHost); const int pflimit = c->h.count / sizeof(vf2gpu_pf_t); if (pfcount == 0 || pfcount>pflimit) return 0; vf2gpu_pf_t *pflist = (vf2gpu_pf_t*)malloc(sizeof(vf2gpu_pf_t) * pfcount); hipMemcpy(pflist, c->d_pflist, sizeof(vf2gpu_pf_t)*pfcount, hipMemcpyDeviceToHost); FILE *fp = fopen(filename, "wb"); fwrite(&pfcount, sizeof(int), 1, fp); fwrite(pflist, sizeof(vf2gpu_pf_t), pfcount, fp); fclose(fp); free(pflist); return pfcount; } int vf2gpu_write_ascii(vf2gpu_ctx_t* c, const char *filename) { int pfcount; hipMemcpy(&pfcount, c->d_pfcount, sizeof(unsigned int), hipMemcpyDeviceToHost); const int pflimit = c->h.count / sizeof(vf2gpu_pf_t); if (pfcount == 0 || pfcount>pflimit) return 0; vf2gpu_pf_t *pflist = (vf2gpu_pf_t*)malloc(sizeof(vf2gpu_pf_t) * pfcount); hipMemcpy(pflist, c->d_pflist, sizeof(vf2gpu_pf_t)*pfcount, hipMemcpyDeviceToHost); FILE *fp = fopen(filename, "w"); fprintf(fp, "%d\n", pfcount); for (int i=0; i<pfcount; i++) fprintf(fp, "%d, %d, %f, %f, %f\n", pflist[i].fid, pflist[i].chirality, pflist[i].pos[0], pflist[i].pos[1], pflist[i].pos[2]); fclose(fp); free(pflist); return pfcount; } } // extern "C"
bde8ea594e6250e3559fb5eb80384d58f6dd39f1.cu
#include "vf2gpu.h" #include "utils.cuh" #include "mesh.cuh" #include "threadIdx.cuh" #include "inverseInterpolation.cuh" #include <cstdio> #include <algorithm> template <typename T> __device__ T line_integral(const vf2gpu_hdr_t& h, const T X0[], const T X1[], const T A0[], const T A1[]) { T dX[3] = {X1[0] - X0[0], X1[1] - X0[1], X1[2] - X0[2]}; T A[3] = {A0[0] + A1[0], A0[1] + A1[1], A0[2] + A1[2]}; for (int i=0; i<3; i++) if (dX[i] > h.lengths[i]/2) dX[i] -= h.lengths[i]; else if (dX[i] < -h.lengths[i]/2) dX[i] += h.lengths[i]; return 0.5 * inner_product(A, dX); } template <typename T, int gauge> __device__ inline void magnetic_potential(const vf2gpu_hdr_t& h, T X[3], T A[3]) { // if (h.B[1]>0) { // yz gauge if (gauge == VF2GPU_GAUGE_YZ) { A[0] = -h.Kx; A[1] = X[0] * h.B[2]; A[2] = -X[0] * h.B[1]; } else { // xz gauge A[0] = -X[1] * h.B[2] - h.Kx; A[1] = 0; A[2] = X[1] * h.B[0]; } } template <typename T, int meshtype, int gauge> __device__ inline bool get_face_values( const vf2gpu_hdr_t& h, int fid, T X[][3], T A[][3], T rho[], T phi[], const T *rho_phi_) { const int nnodes = meshtype == VF2GPU_MESH_TET ? 3 : 4; int nidxs[nnodes][3], nids[nnodes]; bool valid; if (meshtype == VF2GPU_MESH_TET) valid = fid2nodes3D_tet(h, fid, nidxs); else if (meshtype == VF2GPU_MESH_HEX) valid = fid2nodes3D_hex(h, fid, nidxs); else valid = fid2nodes2D(h, fid, nidxs); if (valid) { for (int i=0; i<nnodes; i++) { if (meshtype == VF2GPU_MESH_QUAD) { nids[i] = nidx2nid2D(h, nidxs[i]); nidx2pos2D(h, nidxs[i], X[i]); } else { nids[i] = nidx2nid3D(h, nidxs[i]); nidx2pos3D(h, nidxs[i], X[i]); } rho[i] = rho_phi_[nids[i]*2]; phi[i] = rho_phi_[nids[i]*2+1]; magnetic_potential<T, gauge>(h, X[i], A[i]); } } return valid; } template <typename T> __device__ inline int contour_chirality( const vf2gpu_hdr_t &h, int nnodes, // nnodes <= 4 const T phi[], const T X[][3], const T A[][3], T delta[]) { T phase_jump = 0; for (int i=0; i<nnodes; i++) { int j = (i+1) % nnodes; delta[i] = phi[j] - phi[i]; T li = line_integral(h, X[i], X[j], A[i], A[j]), qp = 0; // TODO delta[i] = mod2pi1(delta[i] - li + qp); phase_jump -= delta[i]; } if (fabs(phase_jump)<0.5) return 0; // not punctured else return sgn(phase_jump); } // for space-time vfaces template <typename T> __device__ inline int contour_chirality_spt( const vf2gpu_hdr_t &h, const vf2gpu_hdr_t &h1, const T phi[4], const T X[4][3], const T A[4][3], T delta[]) { T li[4] = { // FIXME: varying B line_integral(h, X[0], X[1], A[0], A[1]), 0, line_integral(h, X[1], X[0], A[2], A[3]), 0}; T qp[4] = {0, 0, 0, 0}; // FIXME T phase_jump = 0; for (int i=0; i<4; i++) { int j = (i+1) % 4; delta[i] = phi[j] - phi[i]; delta[i] = mod2pi1(delta[i] - li[i] + qp[i]); phase_jump -= delta[i]; } if (fabs(phase_jump)<0.5) return 0; // not punctured else return sgn(phase_jump); } template <typename T> __device__ inline void gauge_transform( int nnodes, const T rho[], const T delta[], T phi[], T re[], T im[]) { re[0] = rho[0] * cos(phi[0]); im[0] = rho[0] * sin(phi[0]); for (int i=1; i<nnodes; i++) { phi[i] = phi[i-1] + delta[i-1]; re[i] = rho[i] * cos(phi[i]); im[i] = rho[i] * sin(phi[i]); } } template <typename T, int meshtype, int gauge> __device__ inline int extract_face( const vf2gpu_hdr_t& h, int fid, unsigned int *pfcount, vf2gpu_pf_t *pflist, const T *rho_phi_) { const int nnodes = meshtype == VF2GPU_MESH_TET ? 3 : 4; T X[nnodes][3], A[nnodes][3], rho[nnodes], phi[nnodes], re[nnodes], im[nnodes]; T delta[nnodes]; bool valid = get_face_values<T, meshtype, gauge>(h, fid, X, A, rho, phi, rho_phi_); if (!valid) return 0; // compute phase shift int chirality = contour_chirality(h, nnodes, phi, X, A, delta); if (chirality == 0) return 0; // gauge transformation gauge_transform(nnodes, rho, delta, phi, re, im); // find puncture point vf2gpu_pf_t pf; pf.fid = fid; pf.chirality = chirality; find_zero<T, meshtype>(re, im, X, pf.pos, T(1)); unsigned int idx = atomicInc(pfcount, 0xffffffff); pflist[idx] = pf; return chirality; } template <typename T> __global__ static void compute_rho_phi_kernel( const vf2gpu_hdr_t *h, T *re_im, T *rho_phi) { int idx = getGlobalIdx_3D_1D(); if (idx>=h->count) return; T r, i; r = re_im[idx*2]; i = re_im[idx*2+1]; rho_phi[idx*2] = sqrt(r*r + i*i); rho_phi[idx*2+1] = atan2(i, r); } template <typename T> __global__ static void copy_phi_kernel( // copy phi to another array const vf2gpu_hdr_t *h, T *rho_phi, T *phi) { int idx = getGlobalIdx_3D_1D(); if (idx>=h->count) return; phi[idx] = rho_phi[idx*2+1]; } template <typename T, int meshtype, int gauge> __global__ static void extract_faces_kernel( const vf2gpu_hdr_t* h, unsigned int *pfcount, const unsigned int pflimit, vf2gpu_pf_t *pflist, const T *rho_phi) { int nfacetypes; if (meshtype == VF2GPU_MESH_TET) nfacetypes = 12; else if (meshtype == VF2GPU_MESH_HEX) nfacetypes = 3; else nfacetypes = 1; int fid = getGlobalIdx_3D_1D(); if (fid>=h->count*nfacetypes) return; #if 0 // use global memory extract_face<T, meshtype, gauge>(*h, fid, pfcount, pflist, rho, phi); #else // use shared memory extern __shared__ char smem[]; unsigned int *spfcount = (unsigned int*)smem; vf2gpu_pf_t *spflist= (vf2gpu_pf_t*)(smem + sizeof(int)); if (threadIdx.x == 0) *spfcount = 0; __syncthreads(); extract_face<T, meshtype, gauge>(*h, fid, spfcount, spflist, rho_phi); __syncthreads(); if (threadIdx.x == 0 && (*spfcount)>0) { unsigned int idx = atomicAdd(pfcount, *spfcount); // printf("idx=%d, count=%d\n", idx, *spfcount); if (idx + *spfcount < pflimit) memcpy(pflist + idx, spflist, (*spfcount) * sizeof(vf2gpu_pf_t)); } #endif } //////////////////////////////// extern "C" { void vf2gpu_set_data_insitu( vf2gpu_ctx_t* c, const vf2gpu_hdr_t &h, float *d_re_im, float *d_tmp1, float *d_tmp2) { if (c->d_h == NULL) cudaMalloc((void**)&c->d_h, sizeof(vf2gpu_hdr_t)); memcpy(&c->h, &h, sizeof(vf2gpu_hdr_t)); cudaMemcpy(c->d_h, &c->h, sizeof(vf2gpu_hdr_t), cudaMemcpyHostToDevice); c->d_re_im = d_re_im; c->d_rho_phi = d_tmp1; c->d_pfcount = (unsigned int*)d_tmp2; c->d_pflist = (vf2gpu_pf_t*)(d_tmp2 + 1); } void vf2gpu_compute_rho_phi(vf2gpu_ctx_t* c) { const int count = c->h.count; const int maxGridDim = 1024; // 32768; const int blockSize = 256; const int nBlocks = idivup(count, blockSize); dim3 gridSize; if (nBlocks >= maxGridDim) gridSize = dim3(idivup(nBlocks, maxGridDim), maxGridDim); else gridSize = dim3(nBlocks); // fprintf(stderr, "count=%d\n", c->h.count); compute_rho_phi_kernel<float><<<gridSize, blockSize>>>(c->d_h, c->d_re_im, c->d_rho_phi); checkLastCudaError("[vf2gpu] compute rho and phi"); } void vf2gpu_copy_phi(vf2gpu_ctx_t* c) { const int count = c->h.count; const int maxGridDim = 1024; // 32768; const int blockSize = 256; const int nBlocks = idivup(count, blockSize); dim3 gridSize; if (nBlocks >= maxGridDim) gridSize = dim3(idivup(nBlocks, maxGridDim), maxGridDim); else gridSize = dim3(nBlocks); // copy_phi_kernel<float><<<gridSize, blockSize>>>(c->d_h, c->d_re_im, c->d_rho_phi); checkLastCudaError("[vf2gpu] copy phi"); } void vf2gpu_extract_faces(vf2gpu_ctx_t* c) { int nfacetypes; if (c->meshtype == VF2GPU_MESH_TET) nfacetypes = 12; else if (c->meshtype == VF2GPU_MESH_HEX) nfacetypes = 3; else nfacetypes = 1; const int threadCount = c->h.count * nfacetypes; const int maxGridDim = 1024; // 32768; const int blockSize = 256; const int nBlocks = idivup(threadCount, blockSize); dim3 gridSize; if (nBlocks >= maxGridDim) gridSize = dim3(idivup(nBlocks, maxGridDim), maxGridDim); else gridSize = dim3(nBlocks); const int sharedSize = blockSize * sizeof(vf2gpu_pf_t) + sizeof(unsigned int); // enough shared memory for every block const unsigned int pflimit = c->h.count / sizeof(vf2gpu_pf_t); const int gauge = c->h.B[1]>0 ? VF2GPU_GAUGE_YZ : VF2GPU_GAUGE_XZ; vf2gpu_compute_rho_phi(c); cudaMemset(c->d_pfcount, 0, sizeof(unsigned int)); if (c->meshtype == VF2GPU_MESH_HEX) { if (gauge == VF2GPU_GAUGE_YZ) extract_faces_kernel<float, VF2GPU_MESH_HEX, VF2GPU_GAUGE_YZ><<<gridSize, blockSize, sharedSize>>> (c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); else extract_faces_kernel<float, VF2GPU_MESH_HEX, VF2GPU_GAUGE_XZ><<<gridSize, blockSize, sharedSize>>> (c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); } else if (c->meshtype == VF2GPU_MESH_TET) { if (gauge == VF2GPU_GAUGE_YZ) extract_faces_kernel<float, VF2GPU_MESH_TET, VF2GPU_GAUGE_YZ><<<gridSize, blockSize, sharedSize>>> (c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); else extract_faces_kernel<float, VF2GPU_MESH_TET, VF2GPU_GAUGE_XZ><<<gridSize, blockSize, sharedSize>>> (c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); } else if (c->meshtype == VF2GPU_MESH_QUAD) { if (gauge == VF2GPU_GAUGE_YZ) extract_faces_kernel<float, VF2GPU_MESH_QUAD, VF2GPU_GAUGE_YZ><<<gridSize, blockSize, sharedSize>>> (c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); else extract_faces_kernel<float, VF2GPU_MESH_QUAD, VF2GPU_GAUGE_XZ><<<gridSize, blockSize, sharedSize>>> (c->d_h, c->d_pfcount, pflimit, c->d_pflist, c->d_rho_phi); } cudaMemcpy((void*)&c->pfcount, c->d_pfcount, sizeof(unsigned int), cudaMemcpyDeviceToHost); printf("pfcount=%d\n", c->pfcount); // if (c->pfcount>0) // cudaMemcpy(c->pflist, c->d_pflist, sizeof(vf2gpu_pf_t)*c->pfcount, cudaMemcpyDeviceToHost); checkLastCudaError("[vf2gpu] extract faces"); } int vf2gpu_write_binary(vf2gpu_ctx_t* c, const char *filename) { int pfcount; cudaMemcpy(&pfcount, c->d_pfcount, sizeof(unsigned int), cudaMemcpyDeviceToHost); const int pflimit = c->h.count / sizeof(vf2gpu_pf_t); if (pfcount == 0 || pfcount>pflimit) return 0; vf2gpu_pf_t *pflist = (vf2gpu_pf_t*)malloc(sizeof(vf2gpu_pf_t) * pfcount); cudaMemcpy(pflist, c->d_pflist, sizeof(vf2gpu_pf_t)*pfcount, cudaMemcpyDeviceToHost); FILE *fp = fopen(filename, "wb"); fwrite(&pfcount, sizeof(int), 1, fp); fwrite(pflist, sizeof(vf2gpu_pf_t), pfcount, fp); fclose(fp); free(pflist); return pfcount; } int vf2gpu_write_ascii(vf2gpu_ctx_t* c, const char *filename) { int pfcount; cudaMemcpy(&pfcount, c->d_pfcount, sizeof(unsigned int), cudaMemcpyDeviceToHost); const int pflimit = c->h.count / sizeof(vf2gpu_pf_t); if (pfcount == 0 || pfcount>pflimit) return 0; vf2gpu_pf_t *pflist = (vf2gpu_pf_t*)malloc(sizeof(vf2gpu_pf_t) * pfcount); cudaMemcpy(pflist, c->d_pflist, sizeof(vf2gpu_pf_t)*pfcount, cudaMemcpyDeviceToHost); FILE *fp = fopen(filename, "w"); fprintf(fp, "%d\n", pfcount); for (int i=0; i<pfcount; i++) fprintf(fp, "%d, %d, %f, %f, %f\n", pflist[i].fid, pflist[i].chirality, pflist[i].pos[0], pflist[i].pos[1], pflist[i].pos[2]); fclose(fp); free(pflist); return pfcount; } } // extern "C"
7de06cf061320722ff9d605e39ddbba9d339191f.hip
// !!! This is a file automatically generated by hipify!!! #include <hip/hip_runtime.h> #include<iostream> using namespace std; #include <device_launch_parameters.h> int main(void) { //struct containing info such as name, threads/block, etc. hipDeviceProp_t devProp; int count; //pass addr of var, get method populates hipGetDeviceCount(&count); for (int i = 0; i < count; i++) { hipGetDeviceProperties(&devProp, i); cout << "Name: " << devProp.name << endl; cout << "Clock rate: " << devProp.clockRate << endl; cout << "Total global memory: " << devProp.totalGlobalMem << endl; printf("Max thread dimensions: (%d, %d, %d)\n", devProp.maxThreadsDim[0], devProp.maxThreadsDim[1], devProp.maxThreadsDim[2]); } //Check for GPUs capable of double-precision floating-point math, only available on those w computer capability >= 1.3 //Fill block of mem w particular struct that is threshold, then use hipChooseDevice to find one with best criteria //Lower overhead, instead of iterating through all in for loop int deviceID; hipGetDevice(&deviceID); //copy obj for first 0 iterations and allocate mem memset(&devProp, 0, sizeof(hipDeviceProp_t)); devProp.major = 1; devProp.minor = 3; hipChooseDevice(&deviceID, &devProp); cout << "Device ID with closest capability: " << deviceID << endl; //host comms w this device now hipSetDevice(deviceID); }
7de06cf061320722ff9d605e39ddbba9d339191f.cu
#include <cuda_runtime.h> #include<iostream> using namespace std; #include <device_launch_parameters.h> int main(void) { //struct containing info such as name, threads/block, etc. cudaDeviceProp devProp; int count; //pass addr of var, get method populates cudaGetDeviceCount(&count); for (int i = 0; i < count; i++) { cudaGetDeviceProperties(&devProp, i); cout << "Name: " << devProp.name << endl; cout << "Clock rate: " << devProp.clockRate << endl; cout << "Total global memory: " << devProp.totalGlobalMem << endl; printf("Max thread dimensions: (%d, %d, %d)\n", devProp.maxThreadsDim[0], devProp.maxThreadsDim[1], devProp.maxThreadsDim[2]); } //Check for GPUs capable of double-precision floating-point math, only available on those w computer capability >= 1.3 //Fill block of mem w particular struct that is threshold, then use cudaChooseDevice to find one with best criteria //Lower overhead, instead of iterating through all in for loop int deviceID; cudaGetDevice(&deviceID); //copy obj for first 0 iterations and allocate mem memset(&devProp, 0, sizeof(cudaDeviceProp)); devProp.major = 1; devProp.minor = 3; cudaChooseDevice(&deviceID, &devProp); cout << "Device ID with closest capability: " << deviceID << endl; //host comms w this device now cudaSetDevice(deviceID); }
4b5b2705324744b202ea3f0e0513b309640c3b97.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <ATen/ATen.h> #include <ATen/NativeFunctions.h> #include <ATen/LegacyTHFunctionsCUDA.h> #include <ATen/native/UnaryOps.h> #include <ATen/hip/HIPContext.h> #include <ATen/hip/HIPApplyUtils.cuh> #include <ATen/native/hip/LaunchUtils.h> #include <ATen/AccumulateType.h> #include <ATen/hip/HIPGraphsUtils.cuh> #include <THH/THHReduceApplyUtils.cuh> #include <THH/THHTensorMathReduce.cuh> #include <THH/THHNumerics.cuh> #include <hiprand/hiprand.h> #include <hiprand/hiprand_kernel.h> #include <hiprand/hiprand_kernel.h> namespace at { namespace native { namespace { #define MAX_NUM_BLOCKS 64 // Normalizes the L1 norm of every row to 1; used by multinomial template <typename scalar_t> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_1(1024) #endif __global__ void renormRowsL1(scalar_t* dist, long rows, long cols) { extern __shared__ unsigned char my_smem[]; scalar_t *smem = reinterpret_cast<scalar_t *>(my_smem); scalar_t zero = static_cast<scalar_t>(0); scalar_t val; for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { scalar_t sum = static_cast<scalar_t>(0); for (int64_t col = threadIdx.x; col < cols; col += blockDim.x) { val = dist[row * cols + col]; CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::lt(val, zero)); // ! < 0 for NaN handling sum = sum + val; } sum = reduceBlock(smem, blockDim.x, sum, ReduceAdd<scalar_t>(), zero); if (threadIdx.x == 0) { CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::lt(val, zero)); // ! < 0 for NaN handling smem[0] = sum; } __syncthreads(); sum = smem[0]; if (sum > zero) { for (int64_t col = threadIdx.x; col < cols; col += blockDim.x) { dist[row * cols + col] = dist[row * cols + col] / sum; } } } } void renormRows(Tensor& t) { TORCH_CHECK(t.dim() == 2); int64_t rows = t.size(0); int64_t cols = t.size(1); auto props = at::cuda::getCurrentDeviceProperties(); CUDA_KERNEL_ASSERT(props != NULL); int numSM = props->multiProcessorCount; int maxThreads = props->maxThreadsPerBlock; dim3 grid(rows < numSM * 4 ? rows : numSM * 4); dim3 block(cols < maxThreads ? cols : maxThreads); AT_DISPATCH_FLOATING_TYPES_AND_HALF(t.scalar_type(), "renormRows_cuda", [&] { hipLaunchKernelGGL(( renormRowsL1<scalar_t>) , dim3(grid), dim3(block), block.x * sizeof(scalar_t), at::hip::getCurrentHIPStreamMasqueradingAsCUDA(), t.data_ptr<scalar_t>(), rows, cols); }); } template <typename scalar_t> __device__ int binarySearchForMultinomial(scalar_t* cumdist, scalar_t* dist, int size, scalar_t val) { int start = 0; int end = size; // cumdist[size - 1] = 0 => all zero prob dist CUDA_KERNEL_ASSERT(cumdist[size - 1] > static_cast<scalar_t>(0)); while (end - start > 0) { int mid = start + (end - start) / 2; scalar_t midVal = cumdist[mid]; if (midVal < val) { start = mid + 1; } else { end = mid; } } if (start == size) { // No probability mass or precision problems; just return the // first non-zero element by setting start to size-1 here, // the code below will move it to the last non-zero probability // this actually can happen when the random number is 1 // (github pytorch issue #4858). start = size - 1; } while(start >= 1 && dist[start] == 0) start--; return start; } template <typename scalar_t> __global__ void sampleMultinomialWithReplacement(PhiloxCudaState philox_args, int totalSamples, int64_t* dest, int64_t distributions, int categories, scalar_t* normDistPrefixSum, scalar_t* normDist) { // At the moment, each warp computes one sample value in the binary // search due to divergence. It seems possible to compute multiple // values and limit divergence though later on. auto seeds = at::cuda::philox::unpack(philox_args); // global index formula for 2D grid of 1D blocks int idx = blockIdx.y * gridDim.x * blockDim.x + blockIdx.x * blockDim.x + threadIdx.x; hiprandStatePhilox4_32_10_t state; hiprand_init(std::get<0>(seeds), idx, std::get<1>(seeds), &state); // The block determines the distribution for which we generate a point for (int64_t curDist = blockIdx.y; curDist < distributions; curDist += gridDim.y) { for (int sample = blockIdx.x*blockDim.x + threadIdx.x; sample < totalSamples; sample += blockDim.x*gridDim.x) { //we are losing 3 out of 4 generated numbers but it's ok //this kernel is not very efficient anyway auto rand = hiprand_uniform4(&state); scalar_t r = static_cast<scalar_t>(rand.x); // Find the bucket that a uniform sample lies in int choice = binarySearchForMultinomial<scalar_t>( normDistPrefixSum + curDist * categories, normDist + curDist * categories, categories, r); dest[curDist * totalSamples + sample] = choice; } } } template <typename scalar_t, typename accscalar_t> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_1(1024) #endif __global__ void sampleMultinomialOnce(int64_t* dest, int64_t distributions, int categories, scalar_t* sampled, scalar_t* dist, int stride_dist, // dist->stride(0) int stride_categories // dist->stride(1) ) { extern __shared__ unsigned char my_smem[]; __shared__ bool found; // Shared Memory hold blockdim.x T for holding the cumulative sum, // blockDim.x AccT for normalizing the probabilities, scalar_t *smem = reinterpret_cast<scalar_t *>(my_smem); accscalar_t *asmem = reinterpret_cast<accscalar_t *>(&my_smem[blockDim.x * sizeof(scalar_t)]); accscalar_t accZero = static_cast<accscalar_t>(0); scalar_t zero = static_cast<scalar_t>(0); for (int64_t curDist = blockIdx.x; curDist < distributions; curDist += gridDim.x) { // Each block handles one distribution // First pass, find the total sum of the distribution accscalar_t sum = accZero; scalar_t val; for (int cat = threadIdx.x; cat < categories; cat += blockDim.x) { val = dist[curDist * stride_dist + cat * stride_categories]; CUDA_KERNEL_ASSERT(val >= zero); CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::isinf(val)); CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::isnan(val)); sum = sum + static_cast<accscalar_t>(val); } // threadIdx.x == 0 has the sum value from this sum = reduceBlock(asmem, blockDim.x, sum, ReduceAdd<accscalar_t>(), accZero); // Broadcast sum and sample value if (threadIdx.x == 0) { // Make sure the sum of our distribution didn't overflow CUDA_KERNEL_ASSERT(!THCNumerics<accscalar_t>::isinf(sum)); CUDA_KERNEL_ASSERT(sum > accZero); asmem[0] = sum; smem[0] = sampled[curDist]; } __syncthreads(); sum = asmem[0]; scalar_t sample = smem[0]; __syncthreads(); if (sum == accZero) { // Choose the first element if (threadIdx.x == 0) { dest[curDist] = 0; } continue; } int chunks = (categories + (int)blockDim.x - 1) / blockDim.x; scalar_t prevHighProb = zero; found = false; for (int chunk = 0; chunk < chunks && !found; ++chunk) { // All threads in bounds load a value int cat = chunk * blockDim.x + threadIdx.x; accscalar_t a_dist_val = cat < categories ? static_cast<accscalar_t>(dist[curDist * stride_dist + cat * stride_categories]) / sum : accZero; scalar_t dist_val = static_cast<scalar_t>(a_dist_val); smem[threadIdx.x] = dist_val; __syncthreads(); // Perform an inclusive prefix sum of the shared memory contents for (int offset = 1; offset < blockDim.x; offset *= 2) { scalar_t val = zero; if (threadIdx.x >= offset) { val = smem[threadIdx.x - offset] + smem[threadIdx.x]; } __syncthreads(); if (threadIdx.x >= offset) { smem[threadIdx.x] = val; } __syncthreads(); } // Each thread will check to see if the sample falls in its // bucket scalar_t curBucket = smem[threadIdx.x] + prevHighProb; scalar_t prevBucket = threadIdx.x == 0 ? prevHighProb : smem[threadIdx.x - 1] + prevHighProb; bool inBucket = (cat < categories) && (!(sample >= curBucket) && (sample >= prevBucket) && (dist_val > zero)); if (inBucket) { // We're done; we have the sample // Torch indices are 1-based dest[curDist] = cat; found = true; } // Store the previous scan's high value for future use prevHighProb = prevHighProb + smem[blockDim.x - 1]; __syncthreads(); } if (threadIdx.x == 0 && !found) { // This should address a rare bug where we don't select a valid index. This likely occurs when // due to floating point arithmetic rounding errors, our cumulative sum does not add up to 1, but // and our uniform sample is greater than this value. In this case we likely have unitialized memory // in dest[curDist]. So basically we will loop through the distribution and pick the largest index // where the distribution is non-zero. This is obviously terribly inefficient, but due to the // rarity in which this occurs, this should not be an issue. for (int cat = categories - 1; cat >= 0; --cat) { if (dist[curDist * stride_dist + cat * stride_categories] > zero) { dest[curDist] = cat; break; } } } } } void multinomial_kernel_impl(Tensor& result, const Tensor& self, const int64_t n_sample, const bool with_replacement, c10::optional<Generator> generator) { auto gen = get_generator_or_default<CUDAGeneratorImpl>(generator, cuda::detail::getDefaultCUDAGenerator()); int inputSize = self.dim(); int64_t numDist = inputSize == 1 ? 1 : self.size(0); int numCategories = inputSize == 1 ? self.size(0) : self.size(1); // Restructure data for 2d auto self_v = inputSize == 1 ? self.view({numDist, numCategories}) : self; result.resize_({numDist, n_sample}); AT_DISPATCH_FLOATING_TYPES_AND_HALF(self_v.scalar_type(), "multinomial_kernel_cuda", [&] { using accscalar_t = at::acc_type<scalar_t, true>; auto props = at::cuda::getCurrentDeviceProperties(); CUDA_KERNEL_ASSERT(props != NULL); int numSM = props->multiProcessorCount; int maxThreads = props->maxThreadsPerBlock; int maxShared = props->sharedMemPerBlock; int requiredShared = (numCategories < maxThreads ? numCategories : maxThreads) * (sizeof(scalar_t) + sizeof(accscalar_t)); if (n_sample == 1 && maxShared >= requiredShared) { // Optimized allocation-free implementation // To exploit greater parallelism for the sampling, generate the // Uniform random samples in a separate kernel launch, into // temporarily allocated memory. The device RNG is thread-limited Tensor sampled = native::empty_cuda({numDist, n_sample}, optTypeMetaToScalarType(self_v.options().dtype_opt()), self_v.options().layout_opt(), self_v.options().device_opt(), self_v.options().pinned_memory_opt()); at::native::uniform_(sampled, 0.0, 1.0, generator); dim3 block(numCategories < maxThreads ? numCategories : maxThreads); dim3 grid(numDist < numSM * 4 ? numDist : numSM * 4); hipLaunchKernelGGL(( sampleMultinomialOnce<scalar_t, accscalar_t>) , dim3(grid), dim3(block), requiredShared, at::hip::getCurrentHIPStreamMasqueradingAsCUDA(), result.data_ptr<int64_t>(), numDist, numCategories, sampled.data_ptr<scalar_t>(), self_v.data_ptr<scalar_t>(), self_v.stride(0), self_v.stride(1) ); } else { // Generic, slow implementation with memory allocations // For sampling without replacement, we modify the distribution // for subsequent samples in this space Tensor origDist = native::empty_like(self_v, LEGACY_CONTIGUOUS_MEMORY_FORMAT); origDist.copy_(self_v); Tensor normDist = native::empty_like(self_v, LEGACY_CONTIGUOUS_MEMORY_FORMAT); Tensor prefixSum = native::empty_like(self_v, LEGACY_CONTIGUOUS_MEMORY_FORMAT); // Renorm along rows normDist.copy_(origDist); renormRows(normDist); // Prefix sum along rows at::_cumsum_out(prefixSum, normDist, 1); PhiloxCudaState rng_engine_inputs; if (with_replacement) { // Binary search is warp divergent (so effectively we're running // with just a single thread), but for better utilization, // we need each block to have at least 4 warps. dim3 block(128); // Each block will generate a sample from one // distribution concurrently. int grid_y=std::min<int>(numDist, at::cuda::getCurrentDeviceProperties()->maxGridSize[1]); dim3 grid((n_sample-1)/block.x+1, grid_y); { // See Note [Acquire lock when using random generators] std::lock_guard<std::mutex> lock(gen->mutex_); // each thread generates a single sample for (numdist/numblocks.y) distributions, however, since we have to use // hiprand_uniform4 (See Note [Register spilling in hiprand call for CUDA < 10]), // offset is 4 times that. auto offset = ((numDist-1)/grid.y+1)*4; rng_engine_inputs = gen->philox_cuda_state(offset); } // Sample with replacement hipLaunchKernelGGL(( sampleMultinomialWithReplacement) , dim3(grid), dim3(block), 0, at::hip::getCurrentHIPStreamMasqueradingAsCUDA(), rng_engine_inputs, n_sample, result.data_ptr<int64_t>(), numDist, numCategories, prefixSum.data_ptr<scalar_t>(), normDist.data_ptr<scalar_t>()); } } }); AT_CUDA_CHECK(hipGetLastError()); if (inputSize == 1) { result.resize_({n_sample}); } } } REGISTER_DISPATCH(multinomial_stub, &multinomial_kernel_impl); }}
4b5b2705324744b202ea3f0e0513b309640c3b97.cu
#include <ATen/ATen.h> #include <ATen/NativeFunctions.h> #include <ATen/LegacyTHFunctionsCUDA.h> #include <ATen/native/UnaryOps.h> #include <ATen/cuda/CUDAContext.h> #include <ATen/cuda/CUDAApplyUtils.cuh> #include <ATen/native/cuda/LaunchUtils.h> #include <ATen/AccumulateType.h> #include <ATen/cuda/CUDAGraphsUtils.cuh> #include <THC/THCReduceApplyUtils.cuh> #include <THC/THCTensorMathReduce.cuh> #include <THC/THCNumerics.cuh> #include <curand.h> #include <curand_kernel.h> #include <curand_philox4x32_x.h> namespace at { namespace native { namespace { #define MAX_NUM_BLOCKS 200 // Normalizes the L1 norm of every row to 1; used by multinomial template <typename scalar_t> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_1(1024) #endif __global__ void renormRowsL1(scalar_t* dist, long rows, long cols) { extern __shared__ unsigned char my_smem[]; scalar_t *smem = reinterpret_cast<scalar_t *>(my_smem); scalar_t zero = static_cast<scalar_t>(0); scalar_t val; for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { scalar_t sum = static_cast<scalar_t>(0); for (int64_t col = threadIdx.x; col < cols; col += blockDim.x) { val = dist[row * cols + col]; CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::lt(val, zero)); // ! < 0 for NaN handling sum = sum + val; } sum = reduceBlock(smem, blockDim.x, sum, ReduceAdd<scalar_t>(), zero); if (threadIdx.x == 0) { CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::lt(val, zero)); // ! < 0 for NaN handling smem[0] = sum; } __syncthreads(); sum = smem[0]; if (sum > zero) { for (int64_t col = threadIdx.x; col < cols; col += blockDim.x) { dist[row * cols + col] = dist[row * cols + col] / sum; } } } } void renormRows(Tensor& t) { TORCH_CHECK(t.dim() == 2); int64_t rows = t.size(0); int64_t cols = t.size(1); auto props = at::cuda::getCurrentDeviceProperties(); CUDA_KERNEL_ASSERT(props != NULL); int numSM = props->multiProcessorCount; int maxThreads = props->maxThreadsPerBlock; dim3 grid(rows < numSM * 4 ? rows : numSM * 4); dim3 block(cols < maxThreads ? cols : maxThreads); AT_DISPATCH_FLOATING_TYPES_AND_HALF(t.scalar_type(), "renormRows_cuda", [&] { renormRowsL1<scalar_t> <<<grid, block, block.x * sizeof(scalar_t), at::cuda::getCurrentCUDAStream()>>>(t.data_ptr<scalar_t>(), rows, cols); }); } template <typename scalar_t> __device__ int binarySearchForMultinomial(scalar_t* cumdist, scalar_t* dist, int size, scalar_t val) { int start = 0; int end = size; // cumdist[size - 1] = 0 => all zero prob dist CUDA_KERNEL_ASSERT(cumdist[size - 1] > static_cast<scalar_t>(0)); while (end - start > 0) { int mid = start + (end - start) / 2; scalar_t midVal = cumdist[mid]; if (midVal < val) { start = mid + 1; } else { end = mid; } } if (start == size) { // No probability mass or precision problems; just return the // first non-zero element by setting start to size-1 here, // the code below will move it to the last non-zero probability // this actually can happen when the random number is 1 // (github pytorch issue #4858). start = size - 1; } while(start >= 1 && dist[start] == 0) start--; return start; } template <typename scalar_t> __global__ void sampleMultinomialWithReplacement(PhiloxCudaState philox_args, int totalSamples, int64_t* dest, int64_t distributions, int categories, scalar_t* normDistPrefixSum, scalar_t* normDist) { // At the moment, each warp computes one sample value in the binary // search due to divergence. It seems possible to compute multiple // values and limit divergence though later on. auto seeds = at::cuda::philox::unpack(philox_args); // global index formula for 2D grid of 1D blocks int idx = blockIdx.y * gridDim.x * blockDim.x + blockIdx.x * blockDim.x + threadIdx.x; curandStatePhilox4_32_10_t state; curand_init(std::get<0>(seeds), idx, std::get<1>(seeds), &state); // The block determines the distribution for which we generate a point for (int64_t curDist = blockIdx.y; curDist < distributions; curDist += gridDim.y) { for (int sample = blockIdx.x*blockDim.x + threadIdx.x; sample < totalSamples; sample += blockDim.x*gridDim.x) { //we are losing 3 out of 4 generated numbers but it's ok //this kernel is not very efficient anyway auto rand = curand_uniform4(&state); scalar_t r = static_cast<scalar_t>(rand.x); // Find the bucket that a uniform sample lies in int choice = binarySearchForMultinomial<scalar_t>( normDistPrefixSum + curDist * categories, normDist + curDist * categories, categories, r); dest[curDist * totalSamples + sample] = choice; } } } template <typename scalar_t, typename accscalar_t> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_1(1024) #endif __global__ void sampleMultinomialOnce(int64_t* dest, int64_t distributions, int categories, scalar_t* sampled, scalar_t* dist, int stride_dist, // dist->stride(0) int stride_categories // dist->stride(1) ) { extern __shared__ unsigned char my_smem[]; __shared__ bool found; // Shared Memory hold blockdim.x T for holding the cumulative sum, // blockDim.x AccT for normalizing the probabilities, scalar_t *smem = reinterpret_cast<scalar_t *>(my_smem); accscalar_t *asmem = reinterpret_cast<accscalar_t *>(&my_smem[blockDim.x * sizeof(scalar_t)]); accscalar_t accZero = static_cast<accscalar_t>(0); scalar_t zero = static_cast<scalar_t>(0); for (int64_t curDist = blockIdx.x; curDist < distributions; curDist += gridDim.x) { // Each block handles one distribution // First pass, find the total sum of the distribution accscalar_t sum = accZero; scalar_t val; for (int cat = threadIdx.x; cat < categories; cat += blockDim.x) { val = dist[curDist * stride_dist + cat * stride_categories]; CUDA_KERNEL_ASSERT(val >= zero); CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::isinf(val)); CUDA_KERNEL_ASSERT(!THCNumerics<scalar_t>::isnan(val)); sum = sum + static_cast<accscalar_t>(val); } // threadIdx.x == 0 has the sum value from this sum = reduceBlock(asmem, blockDim.x, sum, ReduceAdd<accscalar_t>(), accZero); // Broadcast sum and sample value if (threadIdx.x == 0) { // Make sure the sum of our distribution didn't overflow CUDA_KERNEL_ASSERT(!THCNumerics<accscalar_t>::isinf(sum)); CUDA_KERNEL_ASSERT(sum > accZero); asmem[0] = sum; smem[0] = sampled[curDist]; } __syncthreads(); sum = asmem[0]; scalar_t sample = smem[0]; __syncthreads(); if (sum == accZero) { // Choose the first element if (threadIdx.x == 0) { dest[curDist] = 0; } continue; } int chunks = (categories + (int)blockDim.x - 1) / blockDim.x; scalar_t prevHighProb = zero; found = false; for (int chunk = 0; chunk < chunks && !found; ++chunk) { // All threads in bounds load a value int cat = chunk * blockDim.x + threadIdx.x; accscalar_t a_dist_val = cat < categories ? static_cast<accscalar_t>(dist[curDist * stride_dist + cat * stride_categories]) / sum : accZero; scalar_t dist_val = static_cast<scalar_t>(a_dist_val); smem[threadIdx.x] = dist_val; __syncthreads(); // Perform an inclusive prefix sum of the shared memory contents for (int offset = 1; offset < blockDim.x; offset *= 2) { scalar_t val = zero; if (threadIdx.x >= offset) { val = smem[threadIdx.x - offset] + smem[threadIdx.x]; } __syncthreads(); if (threadIdx.x >= offset) { smem[threadIdx.x] = val; } __syncthreads(); } // Each thread will check to see if the sample falls in its // bucket scalar_t curBucket = smem[threadIdx.x] + prevHighProb; scalar_t prevBucket = threadIdx.x == 0 ? prevHighProb : smem[threadIdx.x - 1] + prevHighProb; bool inBucket = (cat < categories) && (!(sample >= curBucket) && (sample >= prevBucket) && (dist_val > zero)); if (inBucket) { // We're done; we have the sample // Torch indices are 1-based dest[curDist] = cat; found = true; } // Store the previous scan's high value for future use prevHighProb = prevHighProb + smem[blockDim.x - 1]; __syncthreads(); } if (threadIdx.x == 0 && !found) { // This should address a rare bug where we don't select a valid index. This likely occurs when // due to floating point arithmetic rounding errors, our cumulative sum does not add up to 1, but // and our uniform sample is greater than this value. In this case we likely have unitialized memory // in dest[curDist]. So basically we will loop through the distribution and pick the largest index // where the distribution is non-zero. This is obviously terribly inefficient, but due to the // rarity in which this occurs, this should not be an issue. for (int cat = categories - 1; cat >= 0; --cat) { if (dist[curDist * stride_dist + cat * stride_categories] > zero) { dest[curDist] = cat; break; } } } } } void multinomial_kernel_impl(Tensor& result, const Tensor& self, const int64_t n_sample, const bool with_replacement, c10::optional<Generator> generator) { auto gen = get_generator_or_default<CUDAGeneratorImpl>(generator, cuda::detail::getDefaultCUDAGenerator()); int inputSize = self.dim(); int64_t numDist = inputSize == 1 ? 1 : self.size(0); int numCategories = inputSize == 1 ? self.size(0) : self.size(1); // Restructure data for 2d auto self_v = inputSize == 1 ? self.view({numDist, numCategories}) : self; result.resize_({numDist, n_sample}); AT_DISPATCH_FLOATING_TYPES_AND_HALF(self_v.scalar_type(), "multinomial_kernel_cuda", [&] { using accscalar_t = at::acc_type<scalar_t, true>; auto props = at::cuda::getCurrentDeviceProperties(); CUDA_KERNEL_ASSERT(props != NULL); int numSM = props->multiProcessorCount; int maxThreads = props->maxThreadsPerBlock; int maxShared = props->sharedMemPerBlock; int requiredShared = (numCategories < maxThreads ? numCategories : maxThreads) * (sizeof(scalar_t) + sizeof(accscalar_t)); if (n_sample == 1 && maxShared >= requiredShared) { // Optimized allocation-free implementation // To exploit greater parallelism for the sampling, generate the // Uniform random samples in a separate kernel launch, into // temporarily allocated memory. The device RNG is thread-limited Tensor sampled = native::empty_cuda({numDist, n_sample}, optTypeMetaToScalarType(self_v.options().dtype_opt()), self_v.options().layout_opt(), self_v.options().device_opt(), self_v.options().pinned_memory_opt()); at::native::uniform_(sampled, 0.0, 1.0, generator); dim3 block(numCategories < maxThreads ? numCategories : maxThreads); dim3 grid(numDist < numSM * 4 ? numDist : numSM * 4); sampleMultinomialOnce<scalar_t, accscalar_t> <<<grid, block, requiredShared, at::cuda::getCurrentCUDAStream()>>>( result.data_ptr<int64_t>(), numDist, numCategories, sampled.data_ptr<scalar_t>(), self_v.data_ptr<scalar_t>(), self_v.stride(0), self_v.stride(1) ); } else { // Generic, slow implementation with memory allocations // For sampling without replacement, we modify the distribution // for subsequent samples in this space Tensor origDist = native::empty_like(self_v, LEGACY_CONTIGUOUS_MEMORY_FORMAT); origDist.copy_(self_v); Tensor normDist = native::empty_like(self_v, LEGACY_CONTIGUOUS_MEMORY_FORMAT); Tensor prefixSum = native::empty_like(self_v, LEGACY_CONTIGUOUS_MEMORY_FORMAT); // Renorm along rows normDist.copy_(origDist); renormRows(normDist); // Prefix sum along rows at::_cumsum_out(prefixSum, normDist, 1); PhiloxCudaState rng_engine_inputs; if (with_replacement) { // Binary search is warp divergent (so effectively we're running // with just a single thread), but for better utilization, // we need each block to have at least 4 warps. dim3 block(128); // Each block will generate a sample from one // distribution concurrently. int grid_y=std::min<int>(numDist, at::cuda::getCurrentDeviceProperties()->maxGridSize[1]); dim3 grid((n_sample-1)/block.x+1, grid_y); { // See Note [Acquire lock when using random generators] std::lock_guard<std::mutex> lock(gen->mutex_); // each thread generates a single sample for (numdist/numblocks.y) distributions, however, since we have to use // curand_uniform4 (See Note [Register spilling in curand call for CUDA < 10]), // offset is 4 times that. auto offset = ((numDist-1)/grid.y+1)*4; rng_engine_inputs = gen->philox_cuda_state(offset); } // Sample with replacement sampleMultinomialWithReplacement <<<grid, block, 0, at::cuda::getCurrentCUDAStream()>>>( rng_engine_inputs, n_sample, result.data_ptr<int64_t>(), numDist, numCategories, prefixSum.data_ptr<scalar_t>(), normDist.data_ptr<scalar_t>()); } } }); AT_CUDA_CHECK(cudaGetLastError()); if (inputSize == 1) { result.resize_({n_sample}); } } } REGISTER_DISPATCH(multinomial_stub, &multinomial_kernel_impl); }}
6ebaf44a4043f9e6922acc2f5153e159080d04d5.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #ifndef THC_GENERIC_FILE #define THC_GENERIC_FILE "THHUNN/generic/VolumetricAdaptiveAveragePooling.hip" #else #include <THHUNN/common.h> // 5d tensor B x D x T x H x W void THNN_(VolumetricAdaptiveAveragePooling_updateOutput)( THCState *state, THCTensor *input, THCTensor *output, int osizeT, int osizeW, int osizeH) { THCUNN_assertSameGPU(state, 2, input, output); THCUNN_argCheck(state, !input->is_empty() && (input->dim() == 4 || input->dim() == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); scalar_t *output_data; scalar_t *input_data; int64_t sizeD, isizeT, isizeH, isizeW; int64_t istrideD, istrideT, istrideH, istrideW; int64_t totalZ; if (input->dim() == 4) { sizeD = input->size(0); isizeT = input->size(1); isizeH = input->size(2); isizeW = input->size(3); istrideD = input->stride(0); istrideT = input->stride(1); istrideH = input->stride(2); istrideW = input->stride(3); THCTensor_(resize4d)(state, output, sizeD, osizeT, osizeH, osizeW); totalZ = sizeD * osizeT; } else { input = THCTensor_(newContiguous)(state, input); int64_t sizeB = input->size(0); sizeD = input->size(1); isizeT = input->size(2); isizeH = input->size(3); isizeW = input->size(4); istrideD = input->stride(1); istrideT = input->stride(2); istrideH = input->stride(3); istrideW = input->stride(4); THCTensor_(resize5d)(state, output, sizeB, sizeD, osizeT, osizeH, osizeW); totalZ = sizeB * sizeD * osizeT; } input_data = THCTensor_(data)(state, input); output_data = THCTensor_(data)(state, output); int64_t offsetZ = 0; dim3 threads(32, 8); // each H*W plane is processed by blocksH thread blocks int blocksH = max((int)(16L / totalZ), 1); while (totalZ > 0) { dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); hipLaunchKernelGGL(( cunn_VolumetricAdaptiveAveragePooling_updateOutput_kernel) , dim3(blocks), dim3(threads), 0, THCState_getCurrentStream(state), input_data, output_data, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW, offsetZ ); totalZ -= 65535; offsetZ += 65535; THCudaCheck(hipGetLastError()); } if (input->dim() == 5) { // clean THCTensor_(free)(state, input); } } void THNN_(VolumetricAdaptiveAveragePooling_updateGradInput)( THCState *state, THCTensor *input, THCTensor *gradOutput, THCTensor *gradInput) { THCUNN_assertSameGPU(state, 3, input, gradOutput, gradInput); gradOutput = THCTensor_(newContiguous)(state, gradOutput); THCTensor_(resizeAs)(state, gradInput, input); THCTensor_(zero)(state, gradInput); scalar_t *gradInput_data; scalar_t *gradOutput_data; int64_t sizeD, isizeT, isizeH, isizeW; int64_t osizeT, osizeH, osizeW; int64_t totalZ; if (input->dim() == 4) { sizeD = input->size(0); isizeT = input->size(1); isizeH = input->size(2); isizeW = input->size(3); osizeT = gradOutput->size(1); osizeH = gradOutput->size(2); osizeW = gradOutput->size(3); } else { sizeD = input->size(1); isizeT = input->size(2); isizeH = input->size(3); isizeW = input->size(4); osizeT = gradOutput->size(2); osizeH = gradOutput->size(3); osizeW = gradOutput->size(4); } // somehow nonatomic is passing all test for volumetric case. bool atomic = false; //(isizeW%osizeW != 0) || (isizeH%osizeH != 0) || (isizeT%osizeT != 0); if (input->dim() == 4) { totalZ = atomic ? sizeD * osizeT : sizeD * isizeT; } else { int sizeB = input->size(0); totalZ = atomic ? sizeB * sizeD * osizeT : sizeB * sizeD * isizeT; } gradInput_data = THCTensor_(data)(state, gradInput); gradOutput_data = THCTensor_(data)(state, gradOutput); int64_t offsetZ = 0; dim3 threads(32, 8); // each H*W plane is processed by blocksH thread blocks int blocksH = max((int)(16L / totalZ), 1); while (totalZ > 0) { dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); if (atomic) { hipLaunchKernelGGL(( cunn_atomic_VolumetricAdaptiveAveragePooling_updateGradInput_kernel) , dim3(blocks), dim3(threads), 0, THCState_getCurrentStream(state), gradInput_data, gradOutput_data, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, offsetZ ); } else { hipLaunchKernelGGL(( cunn_VolumetricAdaptiveAveragePooling_updateGradInput_kernel) , dim3(blocks), dim3(threads), 0, THCState_getCurrentStream(state), gradInput_data, gradOutput_data, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, offsetZ ); } totalZ -= 65535; offsetZ += 65535; THCudaCheck(hipGetLastError()); } // clean THCTensor_(free)(state, gradOutput); } #endif
6ebaf44a4043f9e6922acc2f5153e159080d04d5.cu
#ifndef THC_GENERIC_FILE #define THC_GENERIC_FILE "THCUNN/generic/VolumetricAdaptiveAveragePooling.cu" #else #include <THCUNN/common.h> // 5d tensor B x D x T x H x W void THNN_(VolumetricAdaptiveAveragePooling_updateOutput)( THCState *state, THCTensor *input, THCTensor *output, int osizeT, int osizeW, int osizeH) { THCUNN_assertSameGPU(state, 2, input, output); THCUNN_argCheck(state, !input->is_empty() && (input->dim() == 4 || input->dim() == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); scalar_t *output_data; scalar_t *input_data; int64_t sizeD, isizeT, isizeH, isizeW; int64_t istrideD, istrideT, istrideH, istrideW; int64_t totalZ; if (input->dim() == 4) { sizeD = input->size(0); isizeT = input->size(1); isizeH = input->size(2); isizeW = input->size(3); istrideD = input->stride(0); istrideT = input->stride(1); istrideH = input->stride(2); istrideW = input->stride(3); THCTensor_(resize4d)(state, output, sizeD, osizeT, osizeH, osizeW); totalZ = sizeD * osizeT; } else { input = THCTensor_(newContiguous)(state, input); int64_t sizeB = input->size(0); sizeD = input->size(1); isizeT = input->size(2); isizeH = input->size(3); isizeW = input->size(4); istrideD = input->stride(1); istrideT = input->stride(2); istrideH = input->stride(3); istrideW = input->stride(4); THCTensor_(resize5d)(state, output, sizeB, sizeD, osizeT, osizeH, osizeW); totalZ = sizeB * sizeD * osizeT; } input_data = THCTensor_(data)(state, input); output_data = THCTensor_(data)(state, output); int64_t offsetZ = 0; dim3 threads(32, 8); // each H*W plane is processed by blocksH thread blocks int blocksH = max((int)(16L / totalZ), 1); while (totalZ > 0) { dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); cunn_VolumetricAdaptiveAveragePooling_updateOutput_kernel <<<blocks, threads, 0, THCState_getCurrentStream(state)>>>( input_data, output_data, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW, offsetZ ); totalZ -= 65535; offsetZ += 65535; THCudaCheck(cudaGetLastError()); } if (input->dim() == 5) { // clean THCTensor_(free)(state, input); } } void THNN_(VolumetricAdaptiveAveragePooling_updateGradInput)( THCState *state, THCTensor *input, THCTensor *gradOutput, THCTensor *gradInput) { THCUNN_assertSameGPU(state, 3, input, gradOutput, gradInput); gradOutput = THCTensor_(newContiguous)(state, gradOutput); THCTensor_(resizeAs)(state, gradInput, input); THCTensor_(zero)(state, gradInput); scalar_t *gradInput_data; scalar_t *gradOutput_data; int64_t sizeD, isizeT, isizeH, isizeW; int64_t osizeT, osizeH, osizeW; int64_t totalZ; if (input->dim() == 4) { sizeD = input->size(0); isizeT = input->size(1); isizeH = input->size(2); isizeW = input->size(3); osizeT = gradOutput->size(1); osizeH = gradOutput->size(2); osizeW = gradOutput->size(3); } else { sizeD = input->size(1); isizeT = input->size(2); isizeH = input->size(3); isizeW = input->size(4); osizeT = gradOutput->size(2); osizeH = gradOutput->size(3); osizeW = gradOutput->size(4); } // somehow nonatomic is passing all test for volumetric case. bool atomic = false; //(isizeW%osizeW != 0) || (isizeH%osizeH != 0) || (isizeT%osizeT != 0); if (input->dim() == 4) { totalZ = atomic ? sizeD * osizeT : sizeD * isizeT; } else { int sizeB = input->size(0); totalZ = atomic ? sizeB * sizeD * osizeT : sizeB * sizeD * isizeT; } gradInput_data = THCTensor_(data)(state, gradInput); gradOutput_data = THCTensor_(data)(state, gradOutput); int64_t offsetZ = 0; dim3 threads(32, 8); // each H*W plane is processed by blocksH thread blocks int blocksH = max((int)(16L / totalZ), 1); while (totalZ > 0) { dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); if (atomic) { cunn_atomic_VolumetricAdaptiveAveragePooling_updateGradInput_kernel <<<blocks, threads, 0, THCState_getCurrentStream(state)>>>( gradInput_data, gradOutput_data, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, offsetZ ); } else { cunn_VolumetricAdaptiveAveragePooling_updateGradInput_kernel <<<blocks, threads, 0, THCState_getCurrentStream(state)>>>( gradInput_data, gradOutput_data, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, offsetZ ); } totalZ -= 65535; offsetZ += 65535; THCudaCheck(cudaGetLastError()); } // clean THCTensor_(free)(state, gradOutput); } #endif
bc3555c1266eb6443a495024279b4066b11685b0.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include<iostream> #include<cstdio> #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<cuda_runtime.h> // http://www.programmerfish.com/how-to-write-a-custom-cuda-kernel-with-opencv-as-host-library/#.V6I5d9_I70o using std::cout; using std::endl; static inline void _safe_cuda_call(hipError_t err, const char* msg, const char* file_name, const int line_number) { if(err!=hipSuccess) { fprintf(stderr,"%s\n\nFile: %s\n\nLine Number: %d\n\nReason: %s\n",msg,file_name,line_number,hipGetErrorString(err)); std::cin.get(); exit(EXIT_FAILURE); } } #define SAFE_CALL(call,msg) _safe_cuda_call((call),(msg),__FILE__,__LINE__) __global__ void bgr_to_gray_kernel( unsigned char* input, unsigned char* output, int width, int height, int colorWidthStep, int grayWidthStep) { //2D Index of current thread const int xIndex = blockIdx.x * blockDim.x + threadIdx.x; const int yIndex = blockIdx.y * blockDim.y + threadIdx.y; //Only valid threads perform memory I/O if((xIndex<width) && (yIndex<height)) { //Location of colored pixel in input const int color_tid = yIndex * colorWidthStep + (3 * xIndex); //Location of gray pixel in output const int gray_tid = yIndex * grayWidthStep + xIndex; const unsigned char blue = input[color_tid]; const unsigned char green = input[color_tid + 1]; const unsigned char red = input[color_tid + 2]; const float gray = red * 0.3f + green * 0.59f + blue * 0.11f; output[gray_tid] = static_cast<unsigned char>(gray); } } void convert_to_gray(const cv::Mat& input, cv::Mat& output) { //Calculate total number of bytes of input and output image const int colorBytes = input.step * input.rows; const int grayBytes = output.step * output.rows; unsigned char *d_input, *d_output; //Allocate device memory SAFE_CALL(hipMalloc<unsigned char>(&d_input,colorBytes),"CUDA Malloc Failed"); SAFE_CALL(hipMalloc<unsigned char>(&d_output,grayBytes),"CUDA Malloc Failed"); //Copy data from OpenCV input image to device memory SAFE_CALL(hipMemcpy(d_input,input.ptr(),colorBytes,hipMemcpyHostToDevice),"CUDA Memcpy Host To Device Failed"); //Specify a reasonable block size const dim3 block(16,16); //Calculate grid size to cover the whole image const dim3 grid((input.cols + block.x - 1)/block.x, (input.rows + block.y - 1)/block.y); //Launch the color conversion kernel hipLaunchKernelGGL(( bgr_to_gray_kernel), dim3(grid),dim3(block), 0, 0, d_input,d_output,input.cols,input.rows,input.step,output.step); //Synchronize to check for any kernel launch errors SAFE_CALL(hipDeviceSynchronize(),"Kernel Launch Failed"); //Copy back data from destination device meory to OpenCV output image SAFE_CALL(hipMemcpy(output.ptr(),d_output,grayBytes,hipMemcpyDeviceToHost),"CUDA Memcpy Host To Device Failed"); //Free the device memory SAFE_CALL(hipFree(d_input),"CUDA Free Failed"); SAFE_CALL(hipFree(d_output),"CUDA Free Failed"); } int main() { std::string imagePath = "image.jpg"; //Read input image from the disk cv::Mat input = cv::imread(imagePath,CV_LOAD_IMAGE_COLOR); if(input.empty()) { std::cout<<"Image Not Found!"<<std::endl; std::cin.get(); return -1; } //Create output image cv::Mat output(input.rows,input.cols,CV_8UC1); //Call the wrapper function convert_to_gray(input,output); //Show the input and output cv::imshow("Input",input); cv::imshow("Output",output); //Wait for key press cv::waitKey(); return 0; }
bc3555c1266eb6443a495024279b4066b11685b0.cu
#include<iostream> #include<cstdio> #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<cuda_runtime.h> // http://www.programmerfish.com/how-to-write-a-custom-cuda-kernel-with-opencv-as-host-library/#.V6I5d9_I70o using std::cout; using std::endl; static inline void _safe_cuda_call(cudaError err, const char* msg, const char* file_name, const int line_number) { if(err!=cudaSuccess) { fprintf(stderr,"%s\n\nFile: %s\n\nLine Number: %d\n\nReason: %s\n",msg,file_name,line_number,cudaGetErrorString(err)); std::cin.get(); exit(EXIT_FAILURE); } } #define SAFE_CALL(call,msg) _safe_cuda_call((call),(msg),__FILE__,__LINE__) __global__ void bgr_to_gray_kernel( unsigned char* input, unsigned char* output, int width, int height, int colorWidthStep, int grayWidthStep) { //2D Index of current thread const int xIndex = blockIdx.x * blockDim.x + threadIdx.x; const int yIndex = blockIdx.y * blockDim.y + threadIdx.y; //Only valid threads perform memory I/O if((xIndex<width) && (yIndex<height)) { //Location of colored pixel in input const int color_tid = yIndex * colorWidthStep + (3 * xIndex); //Location of gray pixel in output const int gray_tid = yIndex * grayWidthStep + xIndex; const unsigned char blue = input[color_tid]; const unsigned char green = input[color_tid + 1]; const unsigned char red = input[color_tid + 2]; const float gray = red * 0.3f + green * 0.59f + blue * 0.11f; output[gray_tid] = static_cast<unsigned char>(gray); } } void convert_to_gray(const cv::Mat& input, cv::Mat& output) { //Calculate total number of bytes of input and output image const int colorBytes = input.step * input.rows; const int grayBytes = output.step * output.rows; unsigned char *d_input, *d_output; //Allocate device memory SAFE_CALL(cudaMalloc<unsigned char>(&d_input,colorBytes),"CUDA Malloc Failed"); SAFE_CALL(cudaMalloc<unsigned char>(&d_output,grayBytes),"CUDA Malloc Failed"); //Copy data from OpenCV input image to device memory SAFE_CALL(cudaMemcpy(d_input,input.ptr(),colorBytes,cudaMemcpyHostToDevice),"CUDA Memcpy Host To Device Failed"); //Specify a reasonable block size const dim3 block(16,16); //Calculate grid size to cover the whole image const dim3 grid((input.cols + block.x - 1)/block.x, (input.rows + block.y - 1)/block.y); //Launch the color conversion kernel bgr_to_gray_kernel<<<grid,block>>>(d_input,d_output,input.cols,input.rows,input.step,output.step); //Synchronize to check for any kernel launch errors SAFE_CALL(cudaDeviceSynchronize(),"Kernel Launch Failed"); //Copy back data from destination device meory to OpenCV output image SAFE_CALL(cudaMemcpy(output.ptr(),d_output,grayBytes,cudaMemcpyDeviceToHost),"CUDA Memcpy Host To Device Failed"); //Free the device memory SAFE_CALL(cudaFree(d_input),"CUDA Free Failed"); SAFE_CALL(cudaFree(d_output),"CUDA Free Failed"); } int main() { std::string imagePath = "image.jpg"; //Read input image from the disk cv::Mat input = cv::imread(imagePath,CV_LOAD_IMAGE_COLOR); if(input.empty()) { std::cout<<"Image Not Found!"<<std::endl; std::cin.get(); return -1; } //Create output image cv::Mat output(input.rows,input.cols,CV_8UC1); //Call the wrapper function convert_to_gray(input,output); //Show the input and output cv::imshow("Input",input); cv::imshow("Output",output); //Wait for key press cv::waitKey(); return 0; }
ab0aba0cae6947f2082772b38835872190da9def.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <iostream> #include <ctime> #include "FreeImage.h" #pragma commet(lib,"FreeImage.lib") #pragma warning(disable : 4096) //#define MAX_NUMBER 32768 // 32 * 1024 //#define MAX_NUMBER 65536 // 64 * 1024 //#define MAX_NUMBER 131072 // 128 * 1024 #define MAX_NUMBER (1024 * 1024 * 16) // 128 * 1024 #define TEST_NUMBER 512 typedef unsigned int cuda_int; typedef unsigned int cpu_int; const int device = 0; // Matebook 14MX250 int deviceNum; int maxBlockNumX; int maxBlockNumY; int maxBlockNumZ; int maxThdPerBlock; hipDeviceProp_t deviceProp; void printChangePhase() { std::cout << std::endl << "-------------------------------------------" << std::endl << std::endl; } hipError_t cudaEnvInit() { hipError_t cudaStatus; int value; /* cuda */ cudaStatus = hipGetDeviceCount(&deviceNum); cudaStatus = hipGetDeviceProperties(&deviceProp, 0); cudaStatus = hipSetDevice(device); if (cudaStatus != hipSuccess) { std::cout << "hipSetDevice failed!" << std::endl; return cudaStatus; } /* GPU */ cudaStatus = hipDeviceGetAttribute(&value, hipDeviceAttributeMaxBlockDimX, device);\ maxBlockNumX = value; cudaStatus = hipDeviceGetAttribute(&value, hipDeviceAttributeMaxBlockDimY, device); maxBlockNumY = value; cudaStatus = hipDeviceGetAttribute(&value, hipDeviceAttributeMaxBlockDimZ, device); maxBlockNumZ = value; /* GPUmemory */ maxThdPerBlock = deviceProp.maxThreadsPerBlock; return hipSuccess; } void cudaShowDevInfo() { std::cout << "CUDA device number: " << deviceNum << std::endl; std::cout << "CUDA device name: " << deviceProp.name << std::endl; std::cout << "CUDA device is " << (deviceProp.integrated == 1 ? "integrated" : "discreted") << std::endl; std::cout << "Multiprocessor number: " << deviceProp.multiProcessorCount << std::endl; std::cout << "register number of each Multiprocessor: " << deviceProp.regsPerMultiprocessor << std::endl; std::cout << "Global L1 cache supported: " << (deviceProp.globalL1CacheSupported == 1 ? "Yes" : "No") << std::endl; std::cout << "Local L1 cache supported: " << (deviceProp.localL1CacheSupported == 1 ? "Yes" : "No") << std::endl; std::cout << "L2 cache size: " << deviceProp.l2CacheSize << std::endl; std::cout << "warp size: " << deviceProp.warpSize << std::endl; std::cout << "Max threads dimension: " << deviceProp.maxThreadsDim << std::endl; std::cout << "Max threads per block: " << deviceProp.maxThreadsPerBlock << std::endl; std::cout << "Max threads per multiprocessor: " << deviceProp.maxThreadsPerMultiProcessor << std::endl; std::cout << "registers per block: " << deviceProp.regsPerBlock << std::endl; std::cout << "Global memory available on device: " << (double)deviceProp.totalGlobalMem / 1024 / 1024 << "MB" << std::endl; std::cout << "Max X blocks: " << maxBlockNumX << std::endl; std::cout << "Max Y blocks: " << maxBlockNumY << std::endl; std::cout << "Max Z blocks: " << maxBlockNumZ << std::endl; std::cout << "Max threads per block: " << maxThdPerBlock << std::endl; std::cout << "Clock rate: " << (double)deviceProp.clockRate / 1024 / 1024 << " GHz" << std::endl; printChangePhase(); } /*********************************************************************************************** * GPU vs CPU kernel * ***********************************************************************************************/ cuda_int *dev_a = NULL; cuda_int *dev_b = NULL; cuda_int *dev_c = NULL; cpu_int a[MAX_NUMBER]; cpu_int b[MAX_NUMBER]; cpu_int c[MAX_NUMBER]; __global__ void kernel(cuda_int *C, const cuda_int *A, const cuda_int *B) { int i = blockIdx.x * blockDim.x + threadIdx.x; C[i] = (A[i] + B[i]) * (A[i] - B[i]); C[i] = 2 * (C[i] + i) / i; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; } void GPUvsCPU() { std::cout << "GPU vs CPU: " << std::endl; hipMalloc((void **)&dev_a, MAX_NUMBER * sizeof(int)); hipMalloc((void **)&dev_b, MAX_NUMBER * sizeof(int)); hipMalloc((void **)&dev_c, MAX_NUMBER * sizeof(int)); /* CPUGPU */ hipMemcpy(dev_a, a, sizeof(cpu_int) * MAX_NUMBER, hipMemcpyHostToDevice); hipMemcpy(dev_b, b, sizeof(cpu_int) * MAX_NUMBER, hipMemcpyHostToDevice); /* GPU */ int usedBlockNum = maxBlockNumZ; int usedThdPerBlock = maxThdPerBlock; int iter_lenth = usedBlockNum * usedThdPerBlock; // thread // thread int iter_times = (MAX_NUMBER % iter_lenth == 0 ? MAX_NUMBER / iter_lenth : (MAX_NUMBER + iter_lenth) / iter_lenth); std::cout << "iter_lenth: " << iter_lenth << std::endl; std::cout << "iter_times: " << iter_times << std::endl; clock_t start_t, end_t; /* GPUCPU */ start_t = clock(); for (int i = 0; i < iter_times; i++) { /* GPU */ hipLaunchKernelGGL(( kernel), dim3(usedBlockNum), dim3(usedThdPerBlock), 0, 0, dev_c + iter_lenth * i, dev_a + iter_lenth * i, dev_b + iter_lenth * i); // kernel<<<blockNum, threadsPerBlock>>> (Param1, Param2, Param3, ...) // blockMX250block1024thread // blockSM // blockwarpwarp32thead hipDeviceSynchronize(); if (i == iter_times - 1) { int copy_len = (MAX_NUMBER % iter_lenth == 0 ? iter_lenth : MAX_NUMBER % iter_lenth); hipMemcpy(c + iter_lenth * i, dev_c + iter_lenth * i, sizeof(cpu_int) * copy_len, hipMemcpyDeviceToHost); } else hipMemcpy(c + iter_lenth * i, dev_c + iter_lenth * i, sizeof(cpu_int) * iter_lenth, hipMemcpyDeviceToHost); } end_t = clock(); std::cout << "GPU used time: " << (double)(end_t - start_t) * 1000 / CLOCKS_PER_SEC << "ms" << std::endl; /* CPUGPU */ start_t = clock(); for (int i = 1; i < MAX_NUMBER; i++) { c[i] = (a[i] + b[i]) * (a[i] - b[i]); c[i] = 2 * (c[i] + i) / i; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; } end_t = clock(); std::cout << "CPU used time: " << (double)(end_t - start_t) * 1000 / CLOCKS_PER_SEC << "ms" << std::endl; for (int i = 0; i < 100; i++) std::cout << c[i] << ' '; std::cout << std::endl; hipFree(dev_a); hipFree(dev_b); hipFree(dev_c); printChangePhase(); } /*********************************************************************************************** * test 1D kernel * ***********************************************************************************************/ cpu_int block1D[MAX_NUMBER]; cpu_int warp1D[MAX_NUMBER]; cpu_int localthread1D[MAX_NUMBER]; cpu_int globalthread1D[MAX_NUMBER]; cuda_int *dev_block1D; cuda_int *dev_warp1D; cuda_int *dev_localthread1D; cuda_int *dev_globalthread1D; __global__ void kernelInfo1D(cuda_int *blockId, cuda_int *warpId, cuda_int *localThreadId, cuda_int *globalThreadId) { int thread_x = blockIdx.x * blockDim.x + threadIdx.x; blockId[thread_x] = blockIdx.x; warpId[thread_x] = threadIdx.x / warpSize; localThreadId[thread_x] = threadIdx.x; globalThreadId[thread_x] = thread_x; } void test1DKernel() { std::cout << "1D kernel info: " << std::endl; hipMalloc((void **)&dev_block1D, TEST_NUMBER * sizeof(int)); hipMalloc((void **)&dev_warp1D, TEST_NUMBER * sizeof(int)); hipMalloc((void **)&dev_localthread1D, TEST_NUMBER * sizeof(int)); hipMalloc((void **)&dev_globalthread1D, TEST_NUMBER * sizeof(int)); hipLaunchKernelGGL(( kernelInfo1D), dim3(8), dim3(64), 0, 0, dev_block1D, dev_warp1D, dev_localthread1D, dev_globalthread1D); hipMemcpy(block1D, dev_block1D, sizeof(cpu_int) * TEST_NUMBER, hipMemcpyDeviceToHost); hipMemcpy(warp1D, dev_warp1D, sizeof(cpu_int) * TEST_NUMBER, hipMemcpyDeviceToHost); hipMemcpy(localthread1D, dev_localthread1D, sizeof(cpu_int) * TEST_NUMBER, hipMemcpyDeviceToHost); hipMemcpy(globalthread1D, dev_globalthread1D, sizeof(cpu_int) * TEST_NUMBER, hipMemcpyDeviceToHost); for (int i = 0; i < TEST_NUMBER; i++) { std::cout << "blockId:\t" << block1D[i] << "\twarpId:\t" << warp1D[i] \ << "\tlocalthreadId:\t" << localthread1D[i] << "\tglobalthreaId:\t" << globalthread1D[i] << std::endl; } hipFree(dev_block1D); hipFree(dev_warp1D); hipFree(dev_localthread1D); hipFree(dev_globalthread1D); printChangePhase(); } /*********************************************************************************************** * test 2D kernel * ***********************************************************************************************/ struct BlockPosition { int x; int y; }; typedef struct BlockPosition cuda_pos; typedef struct BlockPosition cpu_pos; cpu_pos block2D[MAX_NUMBER / 2]; cpu_int localthread2D[MAX_NUMBER / 2]; cpu_int globalthread2D[MAX_NUMBER / 2]; cuda_pos *dev_block2D = NULL; cuda_int *dev_localthread2D = NULL; cuda_int *dev_globalthread2D = NULL; __global__ void kernelInfo2D(cuda_pos *threadInfo, cuda_int *localThreadId, cuda_int *globalThreadId) { int idx = blockIdx.x * blockDim.x + threadIdx.x; int idy = blockIdx.y * blockDim.y + threadIdx.y; int thread_idx = gridDim.x * blockDim.x * blockDim.y * blockIdx.y + blockDim.x * blockDim.y * blockIdx.x \ + blockDim.x * threadIdx.y + threadIdx.x; threadInfo[thread_idx].x = blockIdx.x; threadInfo[thread_idx].y = blockIdx.y; localThreadId[thread_idx] = threadIdx.y * blockDim.x + threadIdx.x; globalThreadId[thread_idx] = thread_idx; } void test2DKernel() { std::cout << "2D kernel info: " << std::endl; hipMalloc((void **)&dev_block2D, TEST_NUMBER * sizeof(cuda_pos) / 2); hipMalloc((void **)&dev_localthread2D, TEST_NUMBER * sizeof(cuda_int) / 2); hipMalloc((void **)&dev_globalthread2D, TEST_NUMBER * sizeof(cuda_int) / 2); dim3 threads_rect(32, 2); // blockblock32x2thread dim3 blocks_rect(2, 2); // gridgrid2x2block hipLaunchKernelGGL(( kernelInfo2D), dim3(blocks_rect), dim3(threads_rect), 0, 0, dev_block2D, dev_localthread2D, dev_globalthread2D); hipMemcpy(block2D, dev_block2D, TEST_NUMBER * sizeof(cuda_pos) / 2, hipMemcpyDeviceToHost); hipMemcpy(localthread2D, dev_localthread2D, TEST_NUMBER * sizeof(cuda_int) / 2, hipMemcpyDeviceToHost); hipMemcpy(globalthread2D, dev_globalthread2D, TEST_NUMBER * sizeof(cuda_int) / 2, hipMemcpyDeviceToHost); for (int i = 0; i < TEST_NUMBER / 2; i++) { std::cout << "block_x:\t" << block2D[i].x << "\tblock_y:\t" << block2D[i].y \ << "\tlocalthreadId:\t" << localthread2D[i] << "\tglobalthreaId:\t" << globalthread2D[i] << std::endl; } hipFree(dev_block2D); hipFree(dev_localthread2D); hipFree(dev_globalthread2D); printChangePhase();; } /*********************************************************************************************** * FreeImage * ***********************************************************************************************/ void loadImage(const char *filename, int *width, int *height, unsigned int **buffer) { FREE_IMAGE_FORMAT format = FreeImage_GetFileType(filename, 0); FIBITMAP *image = FreeImage_Load(format, filename); FIBITMAP *temp = image; image = FreeImage_ConvertTo32Bits(temp); *width = FreeImage_GetWidth(image); *height = FreeImage_GetHeight(image); *buffer = (unsigned int *)malloc(sizeof(unsigned int) * (*width) * (*height)); if (!*buffer) std::cout << "malloc image buffer failed" << std::endl; else std::cout << "malloc image buffer success" << std::endl; memcpy(*buffer, FreeImage_GetBits(image), (*width) * (*height) * sizeof(unsigned int)); FreeImage_Unload(image); } void saveImage(const char *filename, unsigned int *buffer, int width, int height) { FREE_IMAGE_FORMAT format = FreeImage_GetFIFFromFilename(filename); FIBITMAP *image = FreeImage_ConvertFromRawBits((BYTE*)buffer, width, height, width * 4, 32, 0xFF000000, 0x00FF0000, 0x0000FF00); FreeImage_Save(format, image, filename); } /*********************************************************************************************** * image processing kernel * ***********************************************************************************************/ unsigned int *imageBuf; unsigned int *outBuf; cuda_int *dev_image; cuda_int *dev_out; __global__ void kernelImageProcessing(cuda_int *image, cuda_int *out) { unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x; unsigned int idy = blockIdx.y * blockDim.y + threadIdx.y; // unsigned int thread_idx = (blockDim.x * blockDim.y) * (blockIdx.y * gridDim.x + blockIdx.y) + blockDim.x * threadIdx.y + threadIdx.x; unsigned int thread_idx = gridDim.x * blockDim.x * idy + idx; unsigned int data = image[thread_idx]; data ^= 0x00FFFFFF; int red, green, blue; red = (data & 0x00FF0000) >> 16; green = (data & 0x0000FF00) >> 8; blue = (data & 0x000000FF) >> 0; int dif1, dif2, dif3; dif1 = red > green ? red - green : green - red; dif2 = red > blue ? red - blue : blue - red; dif3 = blue > green ? blue - green : green - blue; if (dif1 < 0x25 && dif2 < 0x25 && dif3 < 0x25) data = 0xFF000000; out[thread_idx] = data; } void processImage(const char *filename) { int width, height; loadImage(filename, &width, &height, &imageBuf); outBuf = (unsigned int *)malloc(sizeof(unsigned int) * width * height); std::cout << filename << " processing: " << std::endl; hipMalloc((void **)&dev_image, width * height * sizeof(cuda_int)); hipMalloc((void **)&dev_out, width * height * sizeof(cuda_int)); hipMemcpy(dev_image, imageBuf, sizeof(cpu_int) * width * height, hipMemcpyHostToDevice); int block_x, block_y, thread_x, thread_y; block_x = width % 32 ? width / 32 + 1 : width / 32; block_y = height % 32 ? height / 32 + 1 : height / 32; dim3 threads_rect(1, 1); // blockblock32x32thread dim3 blocks_rect(width, height); // grid hipLaunchKernelGGL(( kernelImageProcessing), dim3(blocks_rect), dim3(threads_rect), 0, 0, dev_image, dev_out); hipMemcpy(outBuf, dev_out, sizeof(cpu_int) * width * height, hipMemcpyDeviceToHost); saveImage("kaito.png", outBuf, width, height); } int main() { for (int i = 0; i < MAX_NUMBER; i++) { a[i] = 2; b[i] = 1; } clock_t start_t, end_t; cudaEnvInit(); // CUDA cudaShowDevInfo(); GPUvsCPU(); // test1DKernel(); // test2DKernel(); processImage("hyperbeast01.png"); system("pause"); return 0; }
ab0aba0cae6947f2082772b38835872190da9def.cu
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <iostream> #include <ctime> #include "FreeImage.h" #pragma commet(lib,"FreeImage.lib") #pragma warning(disable : 4096) //#define MAX_NUMBER 32768 // 32 * 1024 //#define MAX_NUMBER 65536 // 64 * 1024 //#define MAX_NUMBER 131072 // 128 * 1024 #define MAX_NUMBER (1024 * 1024 * 16) // 128 * 1024 #define TEST_NUMBER 512 typedef unsigned int cuda_int; typedef unsigned int cpu_int; const int device = 0; // 在Matebook 14上只有一个MX250 int deviceNum; int maxBlockNumX; int maxBlockNumY; int maxBlockNumZ; int maxThdPerBlock; cudaDeviceProp deviceProp; void printChangePhase() { std::cout << std::endl << "-------------------------------------------" << std::endl << std::endl; } cudaError_t cudaEnvInit() { cudaError_t cudaStatus; int value; /* 在硬件平台上选择一个支持cuda的设备 */ cudaStatus = cudaGetDeviceCount(&deviceNum); cudaStatus = cudaGetDeviceProperties(&deviceProp, 0); cudaStatus = cudaSetDevice(device); if (cudaStatus != cudaSuccess) { std::cout << "cudaSetDevice failed!" << std::endl; return cudaStatus; } /* 记录GPU的硬件参数 */ cudaStatus = cudaDeviceGetAttribute(&value, cudaDevAttrMaxBlockDimX, device);\ maxBlockNumX = value; cudaStatus = cudaDeviceGetAttribute(&value, cudaDevAttrMaxBlockDimY, device); maxBlockNumY = value; cudaStatus = cudaDeviceGetAttribute(&value, cudaDevAttrMaxBlockDimZ, device); maxBlockNumZ = value; /* 在GPU端分配memory */ maxThdPerBlock = deviceProp.maxThreadsPerBlock; return cudaSuccess; } void cudaShowDevInfo() { std::cout << "CUDA device number: " << deviceNum << std::endl; std::cout << "CUDA device name: " << deviceProp.name << std::endl; std::cout << "CUDA device is " << (deviceProp.integrated == 1 ? "integrated" : "discreted") << std::endl; std::cout << "Multiprocessor number: " << deviceProp.multiProcessorCount << std::endl; std::cout << "register number of each Multiprocessor: " << deviceProp.regsPerMultiprocessor << std::endl; std::cout << "Global L1 cache supported: " << (deviceProp.globalL1CacheSupported == 1 ? "Yes" : "No") << std::endl; std::cout << "Local L1 cache supported: " << (deviceProp.localL1CacheSupported == 1 ? "Yes" : "No") << std::endl; std::cout << "L2 cache size: " << deviceProp.l2CacheSize << std::endl; std::cout << "warp size: " << deviceProp.warpSize << std::endl; std::cout << "Max threads dimension: " << deviceProp.maxThreadsDim << std::endl; std::cout << "Max threads per block: " << deviceProp.maxThreadsPerBlock << std::endl; std::cout << "Max threads per multiprocessor: " << deviceProp.maxThreadsPerMultiProcessor << std::endl; std::cout << "registers per block: " << deviceProp.regsPerBlock << std::endl; std::cout << "Global memory available on device: " << (double)deviceProp.totalGlobalMem / 1024 / 1024 << "MB" << std::endl; std::cout << "Max X blocks: " << maxBlockNumX << std::endl; std::cout << "Max Y blocks: " << maxBlockNumY << std::endl; std::cout << "Max Z blocks: " << maxBlockNumZ << std::endl; std::cout << "Max threads per block: " << maxThdPerBlock << std::endl; std::cout << "Clock rate: " << (double)deviceProp.clockRate / 1024 / 1024 << " GHz" << std::endl; printChangePhase(); } /*********************************************************************************************** * GPU vs CPU kernel * ***********************************************************************************************/ cuda_int *dev_a = NULL; cuda_int *dev_b = NULL; cuda_int *dev_c = NULL; cpu_int a[MAX_NUMBER]; cpu_int b[MAX_NUMBER]; cpu_int c[MAX_NUMBER]; __global__ void kernel(cuda_int *C, const cuda_int *A, const cuda_int *B) { int i = blockIdx.x * blockDim.x + threadIdx.x; C[i] = (A[i] + B[i]) * (A[i] - B[i]); C[i] = 2 * (C[i] + i) / i; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; C[i] = C[i] * C[i]; C[i] = C[i] + A[i] + B[i]; C[i] = C[i] / A[i]; C[i] = C[i] / B[i]; } void GPUvsCPU() { std::cout << "GPU vs CPU: " << std::endl; cudaMalloc((void **)&dev_a, MAX_NUMBER * sizeof(int)); cudaMalloc((void **)&dev_b, MAX_NUMBER * sizeof(int)); cudaMalloc((void **)&dev_c, MAX_NUMBER * sizeof(int)); /* 把我们需要进行计算的数据从CPU端搬运到GPU端 */ cudaMemcpy(dev_a, a, sizeof(cpu_int) * MAX_NUMBER, cudaMemcpyHostToDevice); cudaMemcpy(dev_b, b, sizeof(cpu_int) * MAX_NUMBER, cudaMemcpyHostToDevice); /* 根据GPU的硬件参数,确定线程空间(维度) */ int usedBlockNum = maxBlockNumZ; int usedThdPerBlock = maxThdPerBlock; int iter_lenth = usedBlockNum * usedThdPerBlock; // 软件层面,能同时处理多少个thread // 要完成所有的thread,需要多少次迭代 int iter_times = (MAX_NUMBER % iter_lenth == 0 ? MAX_NUMBER / iter_lenth : (MAX_NUMBER + iter_lenth) / iter_lenth); std::cout << "iter_lenth: " << iter_lenth << std::endl; std::cout << "iter_times: " << iter_times << std::endl; clock_t start_t, end_t; /* 调用GPU来计算,并把计算完的数据搬运回CPU端 */ start_t = clock(); for (int i = 0; i < iter_times; i++) { /* 调用GPU计算 */ kernel<<<usedBlockNum, usedThdPerBlock>>>(dev_c + iter_lenth * i, dev_a + iter_lenth * i, dev_b + iter_lenth * i); // kernel<<<blockNum, threadsPerBlock>>> (Param1, Param2, Param3, ...) // block中(MX250),每个block最多可包含1024个thread // 软件上的block抽象是在硬件上SM上调度的基本单元 // 一个block中包含多个warp,每个warp有32个thead cudaDeviceSynchronize(); if (i == iter_times - 1) { int copy_len = (MAX_NUMBER % iter_lenth == 0 ? iter_lenth : MAX_NUMBER % iter_lenth); cudaMemcpy(c + iter_lenth * i, dev_c + iter_lenth * i, sizeof(cpu_int) * copy_len, cudaMemcpyDeviceToHost); } else cudaMemcpy(c + iter_lenth * i, dev_c + iter_lenth * i, sizeof(cpu_int) * iter_lenth, cudaMemcpyDeviceToHost); } end_t = clock(); std::cout << "GPU used time: " << (double)(end_t - start_t) * 1000 / CLOCKS_PER_SEC << "ms" << std::endl; /* 使用CPU来计算相同的程序量,记录时间,和GPU性能进行对比 */ start_t = clock(); for (int i = 1; i < MAX_NUMBER; i++) { c[i] = (a[i] + b[i]) * (a[i] - b[i]); c[i] = 2 * (c[i] + i) / i; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; c[i] = c[i] * c[i]; c[i] = c[i] + a[i] + b[i]; c[i] = c[i] / a[i]; c[i] = c[i] / a[i]; } end_t = clock(); std::cout << "CPU used time: " << (double)(end_t - start_t) * 1000 / CLOCKS_PER_SEC << "ms" << std::endl; for (int i = 0; i < 100; i++) std::cout << c[i] << ' '; std::cout << std::endl; cudaFree(dev_a); cudaFree(dev_b); cudaFree(dev_c); printChangePhase(); } /*********************************************************************************************** * test 1D kernel * ***********************************************************************************************/ cpu_int block1D[MAX_NUMBER]; cpu_int warp1D[MAX_NUMBER]; cpu_int localthread1D[MAX_NUMBER]; cpu_int globalthread1D[MAX_NUMBER]; cuda_int *dev_block1D; cuda_int *dev_warp1D; cuda_int *dev_localthread1D; cuda_int *dev_globalthread1D; __global__ void kernelInfo1D(cuda_int *blockId, cuda_int *warpId, cuda_int *localThreadId, cuda_int *globalThreadId) { int thread_x = blockIdx.x * blockDim.x + threadIdx.x; blockId[thread_x] = blockIdx.x; warpId[thread_x] = threadIdx.x / warpSize; localThreadId[thread_x] = threadIdx.x; globalThreadId[thread_x] = thread_x; } void test1DKernel() { std::cout << "1D kernel info: " << std::endl; cudaMalloc((void **)&dev_block1D, TEST_NUMBER * sizeof(int)); cudaMalloc((void **)&dev_warp1D, TEST_NUMBER * sizeof(int)); cudaMalloc((void **)&dev_localthread1D, TEST_NUMBER * sizeof(int)); cudaMalloc((void **)&dev_globalthread1D, TEST_NUMBER * sizeof(int)); kernelInfo1D<<<8, 64>>>(dev_block1D, dev_warp1D, dev_localthread1D, dev_globalthread1D); cudaMemcpy(block1D, dev_block1D, sizeof(cpu_int) * TEST_NUMBER, cudaMemcpyDeviceToHost); cudaMemcpy(warp1D, dev_warp1D, sizeof(cpu_int) * TEST_NUMBER, cudaMemcpyDeviceToHost); cudaMemcpy(localthread1D, dev_localthread1D, sizeof(cpu_int) * TEST_NUMBER, cudaMemcpyDeviceToHost); cudaMemcpy(globalthread1D, dev_globalthread1D, sizeof(cpu_int) * TEST_NUMBER, cudaMemcpyDeviceToHost); for (int i = 0; i < TEST_NUMBER; i++) { std::cout << "blockId:\t" << block1D[i] << "\twarpId:\t" << warp1D[i] \ << "\tlocalthreadId:\t" << localthread1D[i] << "\tglobalthreaId:\t" << globalthread1D[i] << std::endl; } cudaFree(dev_block1D); cudaFree(dev_warp1D); cudaFree(dev_localthread1D); cudaFree(dev_globalthread1D); printChangePhase(); } /*********************************************************************************************** * test 2D kernel * ***********************************************************************************************/ struct BlockPosition { int x; int y; }; typedef struct BlockPosition cuda_pos; typedef struct BlockPosition cpu_pos; cpu_pos block2D[MAX_NUMBER / 2]; cpu_int localthread2D[MAX_NUMBER / 2]; cpu_int globalthread2D[MAX_NUMBER / 2]; cuda_pos *dev_block2D = NULL; cuda_int *dev_localthread2D = NULL; cuda_int *dev_globalthread2D = NULL; __global__ void kernelInfo2D(cuda_pos *threadInfo, cuda_int *localThreadId, cuda_int *globalThreadId) { int idx = blockIdx.x * blockDim.x + threadIdx.x; int idy = blockIdx.y * blockDim.y + threadIdx.y; int thread_idx = gridDim.x * blockDim.x * blockDim.y * blockIdx.y + blockDim.x * blockDim.y * blockIdx.x \ + blockDim.x * threadIdx.y + threadIdx.x; threadInfo[thread_idx].x = blockIdx.x; threadInfo[thread_idx].y = blockIdx.y; localThreadId[thread_idx] = threadIdx.y * blockDim.x + threadIdx.x; globalThreadId[thread_idx] = thread_idx; } void test2DKernel() { std::cout << "2D kernel info: " << std::endl; cudaMalloc((void **)&dev_block2D, TEST_NUMBER * sizeof(cuda_pos) / 2); cudaMalloc((void **)&dev_localthread2D, TEST_NUMBER * sizeof(cuda_int) / 2); cudaMalloc((void **)&dev_globalthread2D, TEST_NUMBER * sizeof(cuda_int) / 2); dim3 threads_rect(32, 2); // block的维度,每个block有32x2个thread dim3 blocks_rect(2, 2); // grid的维度,每个grid有2x2个block kernelInfo2D<<<blocks_rect, threads_rect>>>(dev_block2D, dev_localthread2D, dev_globalthread2D); cudaMemcpy(block2D, dev_block2D, TEST_NUMBER * sizeof(cuda_pos) / 2, cudaMemcpyDeviceToHost); cudaMemcpy(localthread2D, dev_localthread2D, TEST_NUMBER * sizeof(cuda_int) / 2, cudaMemcpyDeviceToHost); cudaMemcpy(globalthread2D, dev_globalthread2D, TEST_NUMBER * sizeof(cuda_int) / 2, cudaMemcpyDeviceToHost); for (int i = 0; i < TEST_NUMBER / 2; i++) { std::cout << "block_x:\t" << block2D[i].x << "\tblock_y:\t" << block2D[i].y \ << "\tlocalthreadId:\t" << localthread2D[i] << "\tglobalthreaId:\t" << globalthread2D[i] << std::endl; } cudaFree(dev_block2D); cudaFree(dev_localthread2D); cudaFree(dev_globalthread2D); printChangePhase();; } /*********************************************************************************************** * FreeImage * ***********************************************************************************************/ void loadImage(const char *filename, int *width, int *height, unsigned int **buffer) { FREE_IMAGE_FORMAT format = FreeImage_GetFileType(filename, 0); FIBITMAP *image = FreeImage_Load(format, filename); FIBITMAP *temp = image; image = FreeImage_ConvertTo32Bits(temp); *width = FreeImage_GetWidth(image); *height = FreeImage_GetHeight(image); *buffer = (unsigned int *)malloc(sizeof(unsigned int) * (*width) * (*height)); if (!*buffer) std::cout << "malloc image buffer failed" << std::endl; else std::cout << "malloc image buffer success" << std::endl; memcpy(*buffer, FreeImage_GetBits(image), (*width) * (*height) * sizeof(unsigned int)); FreeImage_Unload(image); } void saveImage(const char *filename, unsigned int *buffer, int width, int height) { FREE_IMAGE_FORMAT format = FreeImage_GetFIFFromFilename(filename); FIBITMAP *image = FreeImage_ConvertFromRawBits((BYTE*)buffer, width, height, width * 4, 32, 0xFF000000, 0x00FF0000, 0x0000FF00); FreeImage_Save(format, image, filename); } /*********************************************************************************************** * image processing kernel * ***********************************************************************************************/ unsigned int *imageBuf; unsigned int *outBuf; cuda_int *dev_image; cuda_int *dev_out; __global__ void kernelImageProcessing(cuda_int *image, cuda_int *out) { unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x; unsigned int idy = blockIdx.y * blockDim.y + threadIdx.y; // unsigned int thread_idx = (blockDim.x * blockDim.y) * (blockIdx.y * gridDim.x + blockIdx.y) + blockDim.x * threadIdx.y + threadIdx.x; unsigned int thread_idx = gridDim.x * blockDim.x * idy + idx; unsigned int data = image[thread_idx]; data ^= 0x00FFFFFF; int red, green, blue; red = (data & 0x00FF0000) >> 16; green = (data & 0x0000FF00) >> 8; blue = (data & 0x000000FF) >> 0; int dif1, dif2, dif3; dif1 = red > green ? red - green : green - red; dif2 = red > blue ? red - blue : blue - red; dif3 = blue > green ? blue - green : green - blue; if (dif1 < 0x25 && dif2 < 0x25 && dif3 < 0x25) data = 0xFF000000; out[thread_idx] = data; } void processImage(const char *filename) { int width, height; loadImage(filename, &width, &height, &imageBuf); outBuf = (unsigned int *)malloc(sizeof(unsigned int) * width * height); std::cout << filename << " processing: " << std::endl; cudaMalloc((void **)&dev_image, width * height * sizeof(cuda_int)); cudaMalloc((void **)&dev_out, width * height * sizeof(cuda_int)); cudaMemcpy(dev_image, imageBuf, sizeof(cpu_int) * width * height, cudaMemcpyHostToDevice); int block_x, block_y, thread_x, thread_y; block_x = width % 32 ? width / 32 + 1 : width / 32; block_y = height % 32 ? height / 32 + 1 : height / 32; dim3 threads_rect(1, 1); // block的维度,每个block有32x32个thread dim3 blocks_rect(width, height); // grid的维度 kernelImageProcessing<<<blocks_rect, threads_rect>>>(dev_image, dev_out); cudaMemcpy(outBuf, dev_out, sizeof(cpu_int) * width * height, cudaMemcpyDeviceToHost); saveImage("kaito.png", outBuf, width, height); } int main() { for (int i = 0; i < MAX_NUMBER; i++) { a[i] = 2; b[i] = 1; } clock_t start_t, end_t; cudaEnvInit(); // CUDA硬件使用环境初始化 cudaShowDevInfo(); GPUvsCPU(); // test1DKernel(); // test2DKernel(); processImage("hyperbeast01.png"); system("pause"); return 0; }
7a797b9bf0175942717453a9f705aa8f426f0211.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void matrixAddKernel2(float* ans, float* M, float* N, int size) { int row = blockIdx.y*blockDim.y + threadIdx.y; if(row < size) { for(int i = 0; i < size; ++i) ans[row*size + i] = M[row*size + i] + N[row*size + i]; } }
7a797b9bf0175942717453a9f705aa8f426f0211.cu
#include "includes.h" __global__ void matrixAddKernel2(float* ans, float* M, float* N, int size) { int row = blockIdx.y*blockDim.y + threadIdx.y; if(row < size) { for(int i = 0; i < size; ++i) ans[row*size + i] = M[row*size + i] + N[row*size + i]; } }
4b7c7ff9b0443891f06915c45ad7bbd2e442ccc0.hip
// !!! This is a file automatically generated by hipify!!! #include <vector> #include <iostream> #include <fstream> #include <iomanip> #include <cstdlib> #include <cassert> using namespace std; /* //#define CUDA #ifdef CUDA //#include "deviceGPU.h" #include<rocblas.h> #else #include "deviceCPU.h" typedef ComputingDevice::DeviceCPU dev; #endif */ #include "matrix.h" using namespace YAMATH; void loadMatrix(MatrixCpu &inM, char* filename, bool inTransposed = false) { cout << "loading [" << filename << "] ... " << endl; ifstream f(filename); inM.Load(f, inTransposed); f.close(); } void saveMatrix(MatrixCpu &inM, char* filename) { cout << "saving [" << filename << "] ... " << endl; ofstream f(filename); inM.Save(f); f.close(); } void msgG(char * inMsg, const MatrixGpu &inM) { MatrixCpu x = inM; if(x.getX()*x.getY() > 400) { cout << "GPU: " << inMsg << ":" << endl; cout << x.getX() << " x " << x.getY() << endl; cout << "[ " << (x.getData()[0]) << " ... " << (x.getData()[x.getX()*x.getY()-1]) << " ]" << endl; cout << endl; } else if(x.getX()*x.getY() == 1) { cout << "GPU: " << inMsg << ":" << x.getData()[0] << flush; } else { cout << "GPU: " << inMsg << ":" << endl; x.Save(cout); cout << endl; } } void msgC(char * inMsg, const MatrixCpu &inM) { cout << "CPU: " << inMsg << ":" << endl; const MatrixCpu &x = inM; if(x.getX()*x.getY() > 100) { cout << x.getX() << " x " << x.getY() << endl; cout << "[ " << (x.getDataConst()[0]) << " ... " << (x.getDataConst()[x.getX()*x.getY()-1]) << " ]" << endl; } else { x.Save(cout); } cout << endl; } void ms(char * inMsg, const MatrixGpu &inM) { msgG(inMsg, inM); } void testGpu(int x, int y) { typedef MatrixGpu M; typedef MatrixCpu MC; cout << "GPU -----------" << endl; MC ac(x, y); for(int i = 0; i < ac.getX()*ac.getY(); ++i) { ac.getData()[i] = float(i); } M a = ac; msgG("a - init", a); //a = 11.0f; //msgG("a=11.0f", a); M b = a.AbsSum(); msgG("b=a.AbsSum()", b); MC cc(y, 3); for(int i = 0; i < cc.getX()*cc.getY(); ++i) { cc.getData()[i] = 0.0f; } cc.getData()[0] = 1.0f; cc.getData()[y+1] = 1.0f; cc.getData()[2*y+2] = 1.0f; M c = cc; msgG("c", c); M d = a*c; msgG("d=a*c", d); } void testCpu(int x, int y) { typedef MatrixCpu M; cout << "CPU -----------" << endl; M a(x, y); msgC("a - init", a); //a = 11.0f; for(int i = 0; i < a.getX()*a.getY(); ++i) { a.getData()[i] = 11; } msgC("a=11.0f", a); M b(1,1); float sum = 0.0f; for(int i = 0; i < a.getX()*a.getY(); ++i) { sum += a.getData()[i]; } b.getData()[0] = sum; msgC("sum=a.AbsSum()", b); } //const float x1[] = {1.0f, 0.0f, 0.0f}; //const float t1[] = {1.0f, 0.0f}; // //const float x2[] = {1.0f, 0.0f, 1.0f}; //const float t2[] = {1.0f, 0.0f}; // //const float x3[] = {1.0f, 1.0f, 0.0f}; //const float t3[] = {1.0f, 0.0f}; // //const float x4[] = {1.0f, 1.0f, 1.0f}; //const float t4[] = {0.0f, 1.0f}; int main(int argc, char** argv) { if(argc != 4) { cout << "Too few params!" << endl; cout << argv[0] << " input-vector-file weights-file output-file" << endl; exit(1); } hipblasStatus_t stat; hipblasHandle_t handle; stat = hipblasCreate(&handle); if (stat != HIPBLAS_STATUS_SUCCESS) { printf ("CUBLAS initialization failed\n"); return EXIT_FAILURE; } typedef MatrixGpu Mat; MatrixCpu *xCpu = new MatrixCpu(); MatrixCpu *wCpu = new MatrixCpu(); loadMatrix(*xCpu, argv[1]); Mat x = *xCpu; ms("x", x); loadMatrix(*wCpu, argv[2]); Mat w = *wCpu; ms("w", w); delete xCpu; delete wCpu; Mat y; y = Mult(x, w); // matrixwise - y.shape = (dataA.x, weights.y) == (dataB.x, dataB.y) ms("y=x*w", y); MatrixCpu res = y; msgC("res=", res); saveMatrix(res, argv[3]); //res.Save(cout); cout << "done" << endl; return 0; }
4b7c7ff9b0443891f06915c45ad7bbd2e442ccc0.cu
#include <vector> #include <iostream> #include <fstream> #include <iomanip> #include <cstdlib> #include <cassert> using namespace std; /* //#define CUDA #ifdef CUDA //#include "deviceGPU.h" #include<cublas_v2.h> #else #include "deviceCPU.h" typedef ComputingDevice::DeviceCPU dev; #endif */ #include "matrix.h" using namespace YAMATH; void loadMatrix(MatrixCpu &inM, char* filename, bool inTransposed = false) { cout << "loading [" << filename << "] ... " << endl; ifstream f(filename); inM.Load(f, inTransposed); f.close(); } void saveMatrix(MatrixCpu &inM, char* filename) { cout << "saving [" << filename << "] ... " << endl; ofstream f(filename); inM.Save(f); f.close(); } void msgG(char * inMsg, const MatrixGpu &inM) { MatrixCpu x = inM; if(x.getX()*x.getY() > 400) { cout << "GPU: " << inMsg << ":" << endl; cout << x.getX() << " x " << x.getY() << endl; cout << "[ " << (x.getData()[0]) << " ... " << (x.getData()[x.getX()*x.getY()-1]) << " ]" << endl; cout << endl; } else if(x.getX()*x.getY() == 1) { cout << "GPU: " << inMsg << ":" << x.getData()[0] << flush; } else { cout << "GPU: " << inMsg << ":" << endl; x.Save(cout); cout << endl; } } void msgC(char * inMsg, const MatrixCpu &inM) { cout << "CPU: " << inMsg << ":" << endl; const MatrixCpu &x = inM; if(x.getX()*x.getY() > 100) { cout << x.getX() << " x " << x.getY() << endl; cout << "[ " << (x.getDataConst()[0]) << " ... " << (x.getDataConst()[x.getX()*x.getY()-1]) << " ]" << endl; } else { x.Save(cout); } cout << endl; } void ms(char * inMsg, const MatrixGpu &inM) { msgG(inMsg, inM); } void testGpu(int x, int y) { typedef MatrixGpu M; typedef MatrixCpu MC; cout << "GPU -----------" << endl; MC ac(x, y); for(int i = 0; i < ac.getX()*ac.getY(); ++i) { ac.getData()[i] = float(i); } M a = ac; msgG("a - init", a); //a = 11.0f; //msgG("a=11.0f", a); M b = a.AbsSum(); msgG("b=a.AbsSum()", b); MC cc(y, 3); for(int i = 0; i < cc.getX()*cc.getY(); ++i) { cc.getData()[i] = 0.0f; } cc.getData()[0] = 1.0f; cc.getData()[y+1] = 1.0f; cc.getData()[2*y+2] = 1.0f; M c = cc; msgG("c", c); M d = a*c; msgG("d=a*c", d); } void testCpu(int x, int y) { typedef MatrixCpu M; cout << "CPU -----------" << endl; M a(x, y); msgC("a - init", a); //a = 11.0f; for(int i = 0; i < a.getX()*a.getY(); ++i) { a.getData()[i] = 11; } msgC("a=11.0f", a); M b(1,1); float sum = 0.0f; for(int i = 0; i < a.getX()*a.getY(); ++i) { sum += a.getData()[i]; } b.getData()[0] = sum; msgC("sum=a.AbsSum()", b); } //const float x1[] = {1.0f, 0.0f, 0.0f}; //const float t1[] = {1.0f, 0.0f}; // //const float x2[] = {1.0f, 0.0f, 1.0f}; //const float t2[] = {1.0f, 0.0f}; // //const float x3[] = {1.0f, 1.0f, 0.0f}; //const float t3[] = {1.0f, 0.0f}; // //const float x4[] = {1.0f, 1.0f, 1.0f}; //const float t4[] = {0.0f, 1.0f}; int main(int argc, char** argv) { if(argc != 4) { cout << "Too few params!" << endl; cout << argv[0] << " input-vector-file weights-file output-file" << endl; exit(1); } cublasStatus_t stat; cublasHandle_t handle; stat = cublasCreate(&handle); if (stat != CUBLAS_STATUS_SUCCESS) { printf ("CUBLAS initialization failed\n"); return EXIT_FAILURE; } typedef MatrixGpu Mat; MatrixCpu *xCpu = new MatrixCpu(); MatrixCpu *wCpu = new MatrixCpu(); loadMatrix(*xCpu, argv[1]); Mat x = *xCpu; ms("x", x); loadMatrix(*wCpu, argv[2]); Mat w = *wCpu; ms("w", w); delete xCpu; delete wCpu; Mat y; y = Mult(x, w); // matrixwise - y.shape = (dataA.x, weights.y) == (dataB.x, dataB.y) ms("y=x*w", y); MatrixCpu res = y; msgC("res=", res); saveMatrix(res, argv[3]); //res.Save(cout); cout << "done" << endl; return 0; }
b79b9e435d205da62e7cdd0839c8a2ff54357d16.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- // // Reference: // https://github.com/open-mmlab/OpenPCDet/blob/master/pcdet/ops/iou3d_nms/src/iou3d_nms_kernel.cu // // Reference: // https://github.com/open-mmlab/mmdetection3d/blob/master/mmdet3d/ops/iou3d/src/iou3d_kernel.cu // 3D IoU Calculation and Rotated NMS(modified from 2D NMS written by others) // Written by Shaoshuai Shi // All Rights Reserved 2019-2020. #include <thrust/device_vector.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/sequence.h> #include <thrust/sort.h> #include "open3d/ml/Helper.h" #include "open3d/ml/contrib/IoUImpl.h" #include "open3d/ml/contrib/Nms.h" #include "open3d/utility/Helper.h" namespace open3d { namespace ml { namespace contrib { template <typename T> static void SortIndices(T *values, int64_t *sort_indices, int64_t n, bool descending = false) { // Cast to thrust device pointer. thrust::device_ptr<T> values_dptr = thrust::device_pointer_cast(values); thrust::device_ptr<int64_t> sort_indices_dptr = thrust::device_pointer_cast(sort_indices); // Fill sort_indices with 0, 1, ..., n-1. thrust::sequence(sort_indices_dptr, sort_indices_dptr + n, 0); // Sort values and sort_indices together. if (descending) { thrust::stable_sort_by_key(values_dptr, values_dptr + n, sort_indices_dptr, thrust::greater<T>()); } else { thrust::stable_sort_by_key(values_dptr, values_dptr + n, sort_indices_dptr); } } __global__ void NmsKernel(const float *boxes, const int64_t *sort_indices, uint64_t *mask, const int n, const double nms_overlap_thresh, const int num_block_cols) { // Row-wise block index. const int block_row_idx = blockIdx.y; // Column-wise block index. const int block_col_idx = blockIdx.x; // Local block row size. const int row_size = fminf(n - block_row_idx * NMS_BLOCK_SIZE, NMS_BLOCK_SIZE); // Local block col size. const int col_size = fminf(n - block_col_idx * NMS_BLOCK_SIZE, NMS_BLOCK_SIZE); // Fill local block_boxes by fetching the global box memory. // block_boxes = boxes[NBS*block_col_idx : NBS*block_col_idx+col_size, :]. // // TODO: It is also possible to load the comparison target to the shared // memory as well. __shared__ float block_boxes[NMS_BLOCK_SIZE * 5]; if (threadIdx.x < col_size) { float *dst = block_boxes + threadIdx.x * 5; const int src_idx = NMS_BLOCK_SIZE * block_col_idx + threadIdx.x; const float *src = boxes + sort_indices[src_idx] * 5; dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; } __syncthreads(); // Comparing src and dst. In one block, the following src and dst indices // are compared: // - src: BS * block_row_idx : BS * block_row_idx + row_size // - dst: BS * block_col_idx : BS * block_col_idx + col_size // // With all blocks, all src and dst indices are compared. // // Result: // mask[i, j] is a 64-bit integer where mask[i, j][k] (k counted from right) // is 1 iff box[i] overlaps with box[BS*j+k]. if (threadIdx.x < row_size) { // src_idx indices the global memory. const int src_idx = NMS_BLOCK_SIZE * block_row_idx + threadIdx.x; // dst_idx indices the shared memory. int dst_idx = block_row_idx == block_col_idx ? threadIdx.x + 1 : 0; uint64_t t = 0; while (dst_idx < col_size) { if (IoUBev2DWithMinAndMax(boxes + sort_indices[src_idx] * 5, block_boxes + dst_idx * 5) > nms_overlap_thresh) { t |= 1ULL << dst_idx; } dst_idx++; } mask[src_idx * num_block_cols + block_col_idx] = t; } } std::vector<int64_t> NmsCUDAKernel(const float *boxes, const float *scores, int n, double nms_overlap_thresh) { if (n == 0) { return {}; } // Cololum-wise number of blocks. const int num_block_cols = utility::DivUp(n, NMS_BLOCK_SIZE); // Compute sort indices. float *scores_copy = nullptr; OPEN3D_CUDA_CHECK(hipMalloc((void **)&scores_copy, n * sizeof(float))); OPEN3D_CUDA_CHECK(hipMemcpy(scores_copy, scores, n * sizeof(float), hipMemcpyDeviceToDevice)); int64_t *sort_indices = nullptr; OPEN3D_CUDA_CHECK(hipMalloc((void **)&sort_indices, n * sizeof(int64_t))); SortIndices(scores_copy, sort_indices, n, true); OPEN3D_CUDA_CHECK(hipFree(scores_copy)); // Allocate masks on device. uint64_t *mask_ptr = nullptr; OPEN3D_CUDA_CHECK(hipMalloc((void **)&mask_ptr, n * num_block_cols * sizeof(uint64_t))); // Launch kernel. dim3 blocks(utility::DivUp(n, NMS_BLOCK_SIZE), utility::DivUp(n, NMS_BLOCK_SIZE)); dim3 threads(NMS_BLOCK_SIZE); hipLaunchKernelGGL(( NmsKernel), dim3(blocks), dim3(threads), 0, 0, boxes, sort_indices, mask_ptr, n, nms_overlap_thresh, num_block_cols); // Copy cuda masks to cpu. std::vector<uint64_t> mask_vec(n * num_block_cols); uint64_t *mask = mask_vec.data(); OPEN3D_CUDA_CHECK(hipMemcpy(mask_vec.data(), mask_ptr, n * num_block_cols * sizeof(uint64_t), hipMemcpyDeviceToHost)); OPEN3D_CUDA_CHECK(hipFree(mask_ptr)); // Copy sort_indices to cpu. std::vector<int64_t> sort_indices_cpu(n); OPEN3D_CUDA_CHECK(hipMemcpy(sort_indices_cpu.data(), sort_indices, n * sizeof(int64_t), hipMemcpyDeviceToHost)); // Write to keep_indices in CPU. // remv_cpu has n bits in total. If the bit is 1, the corresponding // box will be removed. // TODO: This part can be implemented in CUDA. We use the original author's // implementation here. std::vector<uint64_t> remv_cpu(num_block_cols, 0); std::vector<int64_t> keep_indices; for (int i = 0; i < n; i++) { int block_col_idx = i / NMS_BLOCK_SIZE; int inner_block_col_idx = i % NMS_BLOCK_SIZE; // threadIdx.x // Querying the i-th bit in remv_cpu, counted from the right. // - remv_cpu[block_col_idx]: the block bitmap containing the query // - 1ULL << inner_block_col_idx: the one-hot bitmap to extract i if (!(remv_cpu[block_col_idx] & (1ULL << inner_block_col_idx))) { // Keep the i-th box. keep_indices.push_back(sort_indices_cpu[i]); // Any box that overlaps with the i-th box will be removed. uint64_t *p = mask + i * num_block_cols; for (int j = block_col_idx; j < num_block_cols; j++) { remv_cpu[j] |= p[j]; } } } OPEN3D_CUDA_CHECK(hipFree(sort_indices)); return keep_indices; } } // namespace contrib } // namespace ml } // namespace open3d
b79b9e435d205da62e7cdd0839c8a2ff54357d16.cu
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- // // Reference: // https://github.com/open-mmlab/OpenPCDet/blob/master/pcdet/ops/iou3d_nms/src/iou3d_nms_kernel.cu // // Reference: // https://github.com/open-mmlab/mmdetection3d/blob/master/mmdet3d/ops/iou3d/src/iou3d_kernel.cu // 3D IoU Calculation and Rotated NMS(modified from 2D NMS written by others) // Written by Shaoshuai Shi // All Rights Reserved 2019-2020. #include <thrust/device_vector.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/sequence.h> #include <thrust/sort.h> #include "open3d/ml/Helper.h" #include "open3d/ml/contrib/IoUImpl.h" #include "open3d/ml/contrib/Nms.h" #include "open3d/utility/Helper.h" namespace open3d { namespace ml { namespace contrib { template <typename T> static void SortIndices(T *values, int64_t *sort_indices, int64_t n, bool descending = false) { // Cast to thrust device pointer. thrust::device_ptr<T> values_dptr = thrust::device_pointer_cast(values); thrust::device_ptr<int64_t> sort_indices_dptr = thrust::device_pointer_cast(sort_indices); // Fill sort_indices with 0, 1, ..., n-1. thrust::sequence(sort_indices_dptr, sort_indices_dptr + n, 0); // Sort values and sort_indices together. if (descending) { thrust::stable_sort_by_key(values_dptr, values_dptr + n, sort_indices_dptr, thrust::greater<T>()); } else { thrust::stable_sort_by_key(values_dptr, values_dptr + n, sort_indices_dptr); } } __global__ void NmsKernel(const float *boxes, const int64_t *sort_indices, uint64_t *mask, const int n, const double nms_overlap_thresh, const int num_block_cols) { // Row-wise block index. const int block_row_idx = blockIdx.y; // Column-wise block index. const int block_col_idx = blockIdx.x; // Local block row size. const int row_size = fminf(n - block_row_idx * NMS_BLOCK_SIZE, NMS_BLOCK_SIZE); // Local block col size. const int col_size = fminf(n - block_col_idx * NMS_BLOCK_SIZE, NMS_BLOCK_SIZE); // Fill local block_boxes by fetching the global box memory. // block_boxes = boxes[NBS*block_col_idx : NBS*block_col_idx+col_size, :]. // // TODO: It is also possible to load the comparison target to the shared // memory as well. __shared__ float block_boxes[NMS_BLOCK_SIZE * 5]; if (threadIdx.x < col_size) { float *dst = block_boxes + threadIdx.x * 5; const int src_idx = NMS_BLOCK_SIZE * block_col_idx + threadIdx.x; const float *src = boxes + sort_indices[src_idx] * 5; dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; } __syncthreads(); // Comparing src and dst. In one block, the following src and dst indices // are compared: // - src: BS * block_row_idx : BS * block_row_idx + row_size // - dst: BS * block_col_idx : BS * block_col_idx + col_size // // With all blocks, all src and dst indices are compared. // // Result: // mask[i, j] is a 64-bit integer where mask[i, j][k] (k counted from right) // is 1 iff box[i] overlaps with box[BS*j+k]. if (threadIdx.x < row_size) { // src_idx indices the global memory. const int src_idx = NMS_BLOCK_SIZE * block_row_idx + threadIdx.x; // dst_idx indices the shared memory. int dst_idx = block_row_idx == block_col_idx ? threadIdx.x + 1 : 0; uint64_t t = 0; while (dst_idx < col_size) { if (IoUBev2DWithMinAndMax(boxes + sort_indices[src_idx] * 5, block_boxes + dst_idx * 5) > nms_overlap_thresh) { t |= 1ULL << dst_idx; } dst_idx++; } mask[src_idx * num_block_cols + block_col_idx] = t; } } std::vector<int64_t> NmsCUDAKernel(const float *boxes, const float *scores, int n, double nms_overlap_thresh) { if (n == 0) { return {}; } // Cololum-wise number of blocks. const int num_block_cols = utility::DivUp(n, NMS_BLOCK_SIZE); // Compute sort indices. float *scores_copy = nullptr; OPEN3D_CUDA_CHECK(cudaMalloc((void **)&scores_copy, n * sizeof(float))); OPEN3D_CUDA_CHECK(cudaMemcpy(scores_copy, scores, n * sizeof(float), cudaMemcpyDeviceToDevice)); int64_t *sort_indices = nullptr; OPEN3D_CUDA_CHECK(cudaMalloc((void **)&sort_indices, n * sizeof(int64_t))); SortIndices(scores_copy, sort_indices, n, true); OPEN3D_CUDA_CHECK(cudaFree(scores_copy)); // Allocate masks on device. uint64_t *mask_ptr = nullptr; OPEN3D_CUDA_CHECK(cudaMalloc((void **)&mask_ptr, n * num_block_cols * sizeof(uint64_t))); // Launch kernel. dim3 blocks(utility::DivUp(n, NMS_BLOCK_SIZE), utility::DivUp(n, NMS_BLOCK_SIZE)); dim3 threads(NMS_BLOCK_SIZE); NmsKernel<<<blocks, threads>>>(boxes, sort_indices, mask_ptr, n, nms_overlap_thresh, num_block_cols); // Copy cuda masks to cpu. std::vector<uint64_t> mask_vec(n * num_block_cols); uint64_t *mask = mask_vec.data(); OPEN3D_CUDA_CHECK(cudaMemcpy(mask_vec.data(), mask_ptr, n * num_block_cols * sizeof(uint64_t), cudaMemcpyDeviceToHost)); OPEN3D_CUDA_CHECK(cudaFree(mask_ptr)); // Copy sort_indices to cpu. std::vector<int64_t> sort_indices_cpu(n); OPEN3D_CUDA_CHECK(cudaMemcpy(sort_indices_cpu.data(), sort_indices, n * sizeof(int64_t), cudaMemcpyDeviceToHost)); // Write to keep_indices in CPU. // remv_cpu has n bits in total. If the bit is 1, the corresponding // box will be removed. // TODO: This part can be implemented in CUDA. We use the original author's // implementation here. std::vector<uint64_t> remv_cpu(num_block_cols, 0); std::vector<int64_t> keep_indices; for (int i = 0; i < n; i++) { int block_col_idx = i / NMS_BLOCK_SIZE; int inner_block_col_idx = i % NMS_BLOCK_SIZE; // threadIdx.x // Querying the i-th bit in remv_cpu, counted from the right. // - remv_cpu[block_col_idx]: the block bitmap containing the query // - 1ULL << inner_block_col_idx: the one-hot bitmap to extract i if (!(remv_cpu[block_col_idx] & (1ULL << inner_block_col_idx))) { // Keep the i-th box. keep_indices.push_back(sort_indices_cpu[i]); // Any box that overlaps with the i-th box will be removed. uint64_t *p = mask + i * num_block_cols; for (int j = block_col_idx; j < num_block_cols; j++) { remv_cpu[j] |= p[j]; } } } OPEN3D_CUDA_CHECK(cudaFree(sort_indices)); return keep_indices; } } // namespace contrib } // namespace ml } // namespace open3d
514788fd3d10f9049dcb7bcb107f590efbe3edfc.hip
// !!! This is a file automatically generated by hipify!!! #include <iostream> #include <hip/hip_runtime.h> #include <chrono> #define SIZE 1000 void checkCudaError(hipError_t msg, int x) { if (msg != hipSuccess) { fprintf(stderr, "line: %d %s\n", x, hipGetErrorString(msg)); exit(1); } return; } int main() { float *s, *dev_s; int i; std::chrono::time_point<std::chrono::system_clock> start, end; double time; s = (float *)malloc(sizeof(float)*SIZE); for (i = 0; i < SIZE; i++) { s[i] = i; } checkCudaError(hipMalloc((void**)&dev_s, sizeof(float)*SIZE), __LINE__); start = std::chrono::system_clock::now(); checkCudaError(hipMemcpy(dev_s, s, sizeof(float)*SIZE, hipMemcpyHostToDevice), __LINE__); checkCudaError(hipDeviceSynchronize(), __LINE__); end = std::chrono::system_clock::now(); time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(); free(s); checkCudaError(hipFree(dev_s), __LINE__); std::cout << time << "usec." << std::endl; return 0; }
514788fd3d10f9049dcb7bcb107f590efbe3edfc.cu
#include <iostream> #include <cuda.h> #include <chrono> #define SIZE 1000 void checkCudaError(cudaError_t msg, int x) { if (msg != cudaSuccess) { fprintf(stderr, "line: %d %s\n", x, cudaGetErrorString(msg)); exit(1); } return; } int main() { float *s, *dev_s; int i; std::chrono::time_point<std::chrono::system_clock> start, end; double time; s = (float *)malloc(sizeof(float)*SIZE); for (i = 0; i < SIZE; i++) { s[i] = i; } checkCudaError(cudaMalloc((void**)&dev_s, sizeof(float)*SIZE), __LINE__); start = std::chrono::system_clock::now(); checkCudaError(cudaMemcpy(dev_s, s, sizeof(float)*SIZE, cudaMemcpyHostToDevice), __LINE__); checkCudaError(cudaThreadSynchronize(), __LINE__); end = std::chrono::system_clock::now(); time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(); free(s); checkCudaError(cudaFree(dev_s), __LINE__); std::cout << time << "usec." << std::endl; return 0; }
26b5658b0e5ce66138a9731f25af27071d734454.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // ------------------------------------------------------------------ // Project: Mask R-CNN // File: ROIAlignLayer // Adopted from roi_pooling_layer.cu (written by Ross Grischik) // Author: Jasjeet Dhaliwal // ------------------------------------------------------------------ #include <cfloat> #include <iostream> #include <string> #include <utility> #include <vector> #include <algorithm> #include <stdlib.h> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/proto/caffe.pb.h" using std::max; using std::min; using std::floor; using std::ceil; using std::fabs; using std::cout; namespace caffe { template <typename Dtype> __global__ void ROIAlignForward(const int nthreads, const Dtype* bottom_data, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const Dtype* bottom_rois, Dtype* top_data, int* argmax_idx, Dtype* argmax_mult) { CUDA_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int c = (index / pooled_width / pooled_height) % channels; int n = index / pooled_width / pooled_height / channels; int argmax_index = index * 4; bottom_rois += n * 5; int roi_batch_ind = bottom_rois[0]; Dtype roi_start_w = bottom_rois[1] * spatial_scale; Dtype roi_start_h = bottom_rois[2] * spatial_scale; Dtype roi_end_w = bottom_rois[3] * spatial_scale; Dtype roi_end_h = bottom_rois[4] * spatial_scale; //Util Values Dtype zero = 0.0, one = 1.0; // Force malformed ROIs to be 1x1 Dtype roi_width = max(roi_end_w - roi_start_w + 1.0, one); Dtype roi_height = max(roi_end_h - roi_start_h + 1.0, one); Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height); Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width); Dtype hstart = static_cast<Dtype>(ph) * bin_size_h; Dtype wstart = static_cast<Dtype>(pw) * bin_size_w; Dtype hend = static_cast<Dtype>(ph + 1) * bin_size_h; Dtype wend = static_cast<Dtype>(pw + 1) * bin_size_w; // Add roi offsets and clip to input boundaries hstart = min(max(hstart + roi_start_h, zero), static_cast<Dtype>(height) ); hend = min(max(hend + roi_start_h, zero), static_cast<Dtype>(height)); wstart = min(max(wstart + roi_start_w, zero), static_cast<Dtype>(width)); wend = min(max(wend + roi_start_w, zero), static_cast<Dtype>(width)); bool is_empty = (hend <= hstart) || (wend <= wstart); // Define an empty pooling region to be zero Dtype maxvalue = is_empty ? 0 : -FLT_MAX; int maxidx[4]; Dtype maxmult[4]; //int bottom_offset = (roi_batch_ind * channels + c) * height * width ; //bottom_data += (roi_batch_ind * channels + c) * height * width; /* Normalization function - normalizes values between -1 and 1. a = -1, b = 1 y = f(x) = [[(b - a) (x - roi_start_h)] / [roi_end_h - roi_start_h]] + a x = f^{-1}(y) = [[(f(x) - a)(roi_end_h - roi_end_h)] / (b - a)] + roi_start_h Normalized coordinates of 4 regularly sampled points in the ROI: sn_1 = (-0.5,-0.5) sn_2 = (-0.5,0.5) sn_3 = (0.5,-0.5) sn_4 = (0.5,0.5) // Debugging purposes Dtype x_pos = (((0.5 + 1)*(roi_end_w - roi_start_w))/2.0) + roi_start_w; Dtype x_neg = (((-0.5 + 1)*(roi_end_w - roi_start_w))/2.0) + roi_start_w; Dtype y_pos = (((0.5 + 1)*(roi_end_h - roi_start_h))/2.0) + roi_start_h; Dtype y_neg = (((-0.5 + 1)*(roi_end_h - roi_start_h))/2.0) + roi_start_h; Dtype samples[2] = {x_neg, y_neg, x_neg, y_pos, x_pos, y_neg, x_pos, y_pos}; */ Dtype samples_n[8] = {-0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5}; //Holds interpolated values for each sample point Dtype bisampled[4]; int counter = 0; Dtype x_smp_n = -2.0, y_smp_n = -2.0, h_idx_n = -2.0, w_idx_n = -2.0; //Bilinearly Interpolate 4 sampled values for (int smp = 0; smp < sizeof(samples_n)/sizeof(*samples_n) ; smp+=2) { x_smp_n = samples_n[smp]; y_smp_n = samples_n[smp+1]; bisampled[smp/2] = 0.0; int b_index[4] = {-1, -1 , -1, -1}; // -1,-1,-1,-1}; //int b_index_curr[4] = {-1,-1,-1,-1}; Dtype multiplier[4] = {Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX)}; //Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX)}; counter = 0; //ceil(hstart) //floor(hend) for (int h_idx = ceil(hstart); h_idx <= floor(hend) && h_idx <= height && h_idx >= 0 ; ++h_idx) { for (int w_idx =ceil(wstart); w_idx <= floor(wend) && w_idx <= width && w_idx >= 0; ++w_idx) { if (counter < 4) { b_index[counter] = ((((roi_batch_ind * channels) + c) * height) + h_idx) * width + w_idx; // b_index_curr[counter]= h_idx*width + w_idx; //Normalize width and height to lie between -1 and 1 h_idx_n = static_cast<Dtype>( (static_cast<Dtype>(2)*(static_cast<Dtype>(h_idx) - roi_start_h) / (roi_end_h - roi_start_h)) - 1); w_idx_n = static_cast<Dtype>((static_cast<Dtype>(2)*(static_cast<Dtype>(w_idx) - roi_start_w) / (roi_end_w - roi_start_w)) - 1); h_idx_n = min(max(h_idx_n, static_cast<Dtype>(-1.0)),one); w_idx_n = min(max(w_idx_n, static_cast<Dtype>(-1.0)),one); multiplier[counter]= max(zero ,static_cast<Dtype>(1 - fabs(x_smp_n - w_idx_n))) * max(zero,static_cast<Dtype>(1 - fabs(y_smp_n - h_idx_n))); //bisampled[smp/2] += multiplier[counter]; bisampled[smp/2] += bottom_data[ b_index[counter]] * multiplier[counter]; ++counter; } else { goto stop; } } //w }//h stop: if (bisampled[smp/2] > maxvalue) { maxvalue = bisampled[smp/2]; //Using two loops to comply with c++ convention for (int i=0; i<4;++i) { maxidx[i] = b_index[i]; maxmult[i] = multiplier[i]; } } } //smp //Store value in the top blob top_data[index] = maxvalue; for (int i = 0; i<4; ++i, ++argmax_index) { argmax_idx[argmax_index] = maxidx[i]; argmax_mult[argmax_index] = maxmult[i]; } } } template <typename Dtype> void ROIAlignLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); const Dtype* bottom_rois = bottom[1]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); int* argmax_idx = max_pts_.mutable_gpu_data(); Dtype* argmax_mult = max_mult_.mutable_gpu_data(); int count = top[0]->count(); LOG(INFO) << "Doing forward now"; // NOLINT_NEXT_LINE(whitespace/operators) //Change CAFFE_CUDA_NUM_THREADS to 64 hipLaunchKernelGGL(( ROIAlignForward<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(32), 0, 0, count, bottom_data, spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, bottom_rois, top_data, argmax_idx, argmax_mult); LOG(INFO) << "Done forward "; CUDA_POST_KERNEL_CHECK; } template <typename Dtype> __global__ void ROIAlignBackward(const int nthreads, const Dtype* top_diff, const int* argmax_idx, const Dtype* argmax_mult, const int num_rois, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, Dtype* bottom_diff, const Dtype* bottom_rois) { CUDA_KERNEL_LOOP(index, nthreads) { // (n, c, h, w) coords in bottom data int w = index % width; int h = (index / width) % height; int c = (index / width / height) % channels; int n = index / width / height / channels; Dtype gradient = 0.0; // Accumulate gradient over all ROIs that pooled this element for (int roi_n = 0; roi_n < num_rois; ++roi_n) { //const Dtype* offset_bottom_rois = bottom_rois + roi_n * 5; //int roi_batch_ind = offset_bottom_rois[0]; // Skip if ROI's batch index doesn't match n // if (n != roi_batch_ind) { // continue; // } const Dtype* offset_bottom_rois = bottom_rois + roi_n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Skip if ROI's batch index doesn't match n if (n != roi_batch_ind) { continue; } int roi_start_w = ceil(offset_bottom_rois[1] * spatial_scale); int roi_start_h = ceil(offset_bottom_rois[2] * spatial_scale); int roi_end_w = floor(offset_bottom_rois[3] * spatial_scale); int roi_end_h = floor(offset_bottom_rois[4] * spatial_scale); // Skip if ROI doesn't include (h, w) const bool in_roi = (w >= roi_start_w && w <= roi_end_w && h >= roi_start_h && h <= roi_end_h); if (!in_roi) { continue; } int offset = (roi_n * channels + c) * pooled_height * pooled_width; int argmax_offset = offset * 4; const Dtype* offset_top_diff = top_diff + offset; const int* offset_argmax_idx = argmax_idx + argmax_offset; const Dtype* offset_argmax_mult = argmax_mult + argmax_offset; // Util Vals Dtype multiplier = 0.0; for (int ph = 0; ph < pooled_height; ++ph) { for (int pw = 0; pw < pooled_width; ++pw) { for (int k = 0; k < 4; ++k) { if (offset_argmax_idx[((ph * pooled_width + pw) * 4) + k] == index ) { multiplier = offset_argmax_mult[( (ph * pooled_width + pw) * 4) + k]; gradient += offset_top_diff[ph * pooled_width + pw] * multiplier; } } }//pw }//ph }//rois bottom_diff[index] = gradient; } } template <typename Dtype> void ROIAlignLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } const Dtype* bottom_rois = bottom[1]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int count = bottom[0]->count(); caffe_gpu_set(count, Dtype(0.), bottom_diff); const int* argmax_idx = max_pts_.gpu_data(); const Dtype* argmax_mult = max_mult_.gpu_data(); // NOLINT_NEXT_LINE(whitespace/operators) // CAFFE_CUDA_NUM_THREADS replaced with 64 LOG(INFO) << "Doing backward "; hipLaunchKernelGGL(( ROIAlignBackward<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(16), 0, 0, count, top_diff, argmax_idx, argmax_mult, top[0]->num(), spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, bottom_diff, bottom_rois); LOG(INFO) << "Done backward"; CUDA_POST_KERNEL_CHECK; } INSTANTIATE_LAYER_GPU_FUNCS(ROIAlignLayer); } // namespace caffe
26b5658b0e5ce66138a9731f25af27071d734454.cu
// ------------------------------------------------------------------ // Project: Mask R-CNN // File: ROIAlignLayer // Adopted from roi_pooling_layer.cu (written by Ross Grischik) // Author: Jasjeet Dhaliwal // ------------------------------------------------------------------ #include <cfloat> #include <iostream> #include <string> #include <utility> #include <vector> #include <algorithm> #include <stdlib.h> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/proto/caffe.pb.h" using std::max; using std::min; using std::floor; using std::ceil; using std::fabs; using std::cout; namespace caffe { template <typename Dtype> __global__ void ROIAlignForward(const int nthreads, const Dtype* bottom_data, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const Dtype* bottom_rois, Dtype* top_data, int* argmax_idx, Dtype* argmax_mult) { CUDA_KERNEL_LOOP(index, nthreads) { // (n, c, ph, pw) is an element in the pooled output int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int c = (index / pooled_width / pooled_height) % channels; int n = index / pooled_width / pooled_height / channels; int argmax_index = index * 4; bottom_rois += n * 5; int roi_batch_ind = bottom_rois[0]; Dtype roi_start_w = bottom_rois[1] * spatial_scale; Dtype roi_start_h = bottom_rois[2] * spatial_scale; Dtype roi_end_w = bottom_rois[3] * spatial_scale; Dtype roi_end_h = bottom_rois[4] * spatial_scale; //Util Values Dtype zero = 0.0, one = 1.0; // Force malformed ROIs to be 1x1 Dtype roi_width = max(roi_end_w - roi_start_w + 1.0, one); Dtype roi_height = max(roi_end_h - roi_start_h + 1.0, one); Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height); Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width); Dtype hstart = static_cast<Dtype>(ph) * bin_size_h; Dtype wstart = static_cast<Dtype>(pw) * bin_size_w; Dtype hend = static_cast<Dtype>(ph + 1) * bin_size_h; Dtype wend = static_cast<Dtype>(pw + 1) * bin_size_w; // Add roi offsets and clip to input boundaries hstart = min(max(hstart + roi_start_h, zero), static_cast<Dtype>(height) ); hend = min(max(hend + roi_start_h, zero), static_cast<Dtype>(height)); wstart = min(max(wstart + roi_start_w, zero), static_cast<Dtype>(width)); wend = min(max(wend + roi_start_w, zero), static_cast<Dtype>(width)); bool is_empty = (hend <= hstart) || (wend <= wstart); // Define an empty pooling region to be zero Dtype maxvalue = is_empty ? 0 : -FLT_MAX; int maxidx[4]; Dtype maxmult[4]; //int bottom_offset = (roi_batch_ind * channels + c) * height * width ; //bottom_data += (roi_batch_ind * channels + c) * height * width; /* Normalization function - normalizes values between -1 and 1. a = -1, b = 1 y = f(x) = [[(b - a) (x - roi_start_h)] / [roi_end_h - roi_start_h]] + a x = f^{-1}(y) = [[(f(x) - a)(roi_end_h - roi_end_h)] / (b - a)] + roi_start_h Normalized coordinates of 4 regularly sampled points in the ROI: sn_1 = (-0.5,-0.5) sn_2 = (-0.5,0.5) sn_3 = (0.5,-0.5) sn_4 = (0.5,0.5) // Debugging purposes Dtype x_pos = (((0.5 + 1)*(roi_end_w - roi_start_w))/2.0) + roi_start_w; Dtype x_neg = (((-0.5 + 1)*(roi_end_w - roi_start_w))/2.0) + roi_start_w; Dtype y_pos = (((0.5 + 1)*(roi_end_h - roi_start_h))/2.0) + roi_start_h; Dtype y_neg = (((-0.5 + 1)*(roi_end_h - roi_start_h))/2.0) + roi_start_h; Dtype samples[2] = {x_neg, y_neg, x_neg, y_pos, x_pos, y_neg, x_pos, y_pos}; */ Dtype samples_n[8] = {-0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5}; //Holds interpolated values for each sample point Dtype bisampled[4]; int counter = 0; Dtype x_smp_n = -2.0, y_smp_n = -2.0, h_idx_n = -2.0, w_idx_n = -2.0; //Bilinearly Interpolate 4 sampled values for (int smp = 0; smp < sizeof(samples_n)/sizeof(*samples_n) ; smp+=2) { x_smp_n = samples_n[smp]; y_smp_n = samples_n[smp+1]; bisampled[smp/2] = 0.0; int b_index[4] = {-1, -1 , -1, -1}; // -1,-1,-1,-1}; //int b_index_curr[4] = {-1,-1,-1,-1}; Dtype multiplier[4] = {Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX)}; //Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX), Dtype(-FLT_MAX)}; counter = 0; //ceil(hstart) //floor(hend) for (int h_idx = ceil(hstart); h_idx <= floor(hend) && h_idx <= height && h_idx >= 0 ; ++h_idx) { for (int w_idx =ceil(wstart); w_idx <= floor(wend) && w_idx <= width && w_idx >= 0; ++w_idx) { if (counter < 4) { b_index[counter] = ((((roi_batch_ind * channels) + c) * height) + h_idx) * width + w_idx; // b_index_curr[counter]= h_idx*width + w_idx; //Normalize width and height to lie between -1 and 1 h_idx_n = static_cast<Dtype>( (static_cast<Dtype>(2)*(static_cast<Dtype>(h_idx) - roi_start_h) / (roi_end_h - roi_start_h)) - 1); w_idx_n = static_cast<Dtype>((static_cast<Dtype>(2)*(static_cast<Dtype>(w_idx) - roi_start_w) / (roi_end_w - roi_start_w)) - 1); h_idx_n = min(max(h_idx_n, static_cast<Dtype>(-1.0)),one); w_idx_n = min(max(w_idx_n, static_cast<Dtype>(-1.0)),one); multiplier[counter]= max(zero ,static_cast<Dtype>(1 - fabs(x_smp_n - w_idx_n))) * max(zero,static_cast<Dtype>(1 - fabs(y_smp_n - h_idx_n))); //bisampled[smp/2] += multiplier[counter]; bisampled[smp/2] += bottom_data[ b_index[counter]] * multiplier[counter]; ++counter; } else { goto stop; } } //w }//h stop: if (bisampled[smp/2] > maxvalue) { maxvalue = bisampled[smp/2]; //Using two loops to comply with c++ convention for (int i=0; i<4;++i) { maxidx[i] = b_index[i]; maxmult[i] = multiplier[i]; } } } //smp //Store value in the top blob top_data[index] = maxvalue; for (int i = 0; i<4; ++i, ++argmax_index) { argmax_idx[argmax_index] = maxidx[i]; argmax_mult[argmax_index] = maxmult[i]; } } } template <typename Dtype> void ROIAlignLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); const Dtype* bottom_rois = bottom[1]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); int* argmax_idx = max_pts_.mutable_gpu_data(); Dtype* argmax_mult = max_mult_.mutable_gpu_data(); int count = top[0]->count(); LOG(INFO) << "Doing forward now"; // NOLINT_NEXT_LINE(whitespace/operators) //Change CAFFE_CUDA_NUM_THREADS to 64 ROIAlignForward<Dtype><<<CAFFE_GET_BLOCKS(count), 32>>>( count, bottom_data, spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, bottom_rois, top_data, argmax_idx, argmax_mult); LOG(INFO) << "Done forward "; CUDA_POST_KERNEL_CHECK; } template <typename Dtype> __global__ void ROIAlignBackward(const int nthreads, const Dtype* top_diff, const int* argmax_idx, const Dtype* argmax_mult, const int num_rois, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, Dtype* bottom_diff, const Dtype* bottom_rois) { CUDA_KERNEL_LOOP(index, nthreads) { // (n, c, h, w) coords in bottom data int w = index % width; int h = (index / width) % height; int c = (index / width / height) % channels; int n = index / width / height / channels; Dtype gradient = 0.0; // Accumulate gradient over all ROIs that pooled this element for (int roi_n = 0; roi_n < num_rois; ++roi_n) { //const Dtype* offset_bottom_rois = bottom_rois + roi_n * 5; //int roi_batch_ind = offset_bottom_rois[0]; // Skip if ROI's batch index doesn't match n // if (n != roi_batch_ind) { // continue; // } const Dtype* offset_bottom_rois = bottom_rois + roi_n * 5; int roi_batch_ind = offset_bottom_rois[0]; // Skip if ROI's batch index doesn't match n if (n != roi_batch_ind) { continue; } int roi_start_w = ceil(offset_bottom_rois[1] * spatial_scale); int roi_start_h = ceil(offset_bottom_rois[2] * spatial_scale); int roi_end_w = floor(offset_bottom_rois[3] * spatial_scale); int roi_end_h = floor(offset_bottom_rois[4] * spatial_scale); // Skip if ROI doesn't include (h, w) const bool in_roi = (w >= roi_start_w && w <= roi_end_w && h >= roi_start_h && h <= roi_end_h); if (!in_roi) { continue; } int offset = (roi_n * channels + c) * pooled_height * pooled_width; int argmax_offset = offset * 4; const Dtype* offset_top_diff = top_diff + offset; const int* offset_argmax_idx = argmax_idx + argmax_offset; const Dtype* offset_argmax_mult = argmax_mult + argmax_offset; // Util Vals Dtype multiplier = 0.0; for (int ph = 0; ph < pooled_height; ++ph) { for (int pw = 0; pw < pooled_width; ++pw) { for (int k = 0; k < 4; ++k) { if (offset_argmax_idx[((ph * pooled_width + pw) * 4) + k] == index ) { multiplier = offset_argmax_mult[( (ph * pooled_width + pw) * 4) + k]; gradient += offset_top_diff[ph * pooled_width + pw] * multiplier; } } }//pw }//ph }//rois bottom_diff[index] = gradient; } } template <typename Dtype> void ROIAlignLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } const Dtype* bottom_rois = bottom[1]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int count = bottom[0]->count(); caffe_gpu_set(count, Dtype(0.), bottom_diff); const int* argmax_idx = max_pts_.gpu_data(); const Dtype* argmax_mult = max_mult_.gpu_data(); // NOLINT_NEXT_LINE(whitespace/operators) // CAFFE_CUDA_NUM_THREADS replaced with 64 LOG(INFO) << "Doing backward "; ROIAlignBackward<Dtype><<<CAFFE_GET_BLOCKS(count), 16>>>( count, top_diff, argmax_idx, argmax_mult, top[0]->num(), spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, bottom_diff, bottom_rois); LOG(INFO) << "Done backward"; CUDA_POST_KERNEL_CHECK; } INSTANTIATE_LAYER_GPU_FUNCS(ROIAlignLayer); } // namespace caffe
d76afaf9b9ca59206e86e0d34443320ec1851e4b.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Copyright (C) 2016 Gernot Riegler // Institute for Computer Graphics and Vision (ICG) // Graz University of Technology (TU GRAZ) // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by the ICG, TU GRAZ. // 4. Neither the name of the ICG, TU GRAZ nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE PROVIDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "utils.h" #include "common.h" __global__ void icgThreshold3Forward(float* out, const float* in1, const float* in2, const float* in3, int length, float threshold) { CUDA_KERNEL_LOOP(idx, length) { out[idx] = in3[idx] <= threshold ? in2[idx] : in1[idx]; } } static int icgcunn_IcgThreshold3_updateOutput(lua_State *L) { THCState* state = getCutorchState(L); THCudaTensor* input1 = (THCudaTensor*)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor* input2 = (THCudaTensor*)luaT_checkudata(L, 3, "torch.CudaTensor"); THCudaTensor* input3 = (THCudaTensor*)luaT_checkudata(L, 4, "torch.CudaTensor"); float threshold = luaT_getfieldchecknumber(L, 1, "threshold"); THCudaTensor* output = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "output", "torch.CudaTensor"); long nelem = THCudaTensor_nElement(state, input1); luaL_argcheck(L, nelem == THCudaTensor_nElement(state, input2), 2, "cuf, input1 should have same number of elements as input2"); luaL_argcheck(L, nelem == THCudaTensor_nElement(state, input3), 2, "cuf, input1 should have same number of elements as input3"); THCudaTensor_resizeAs(state, output, input1); input1 = THCudaTensor_newContiguous(state, input1); input2 = THCudaTensor_newContiguous(state, input2); input3 = THCudaTensor_newContiguous(state, input3); float* out = THCudaTensor_data(state, output); float* in1 = THCudaTensor_data(state, input1); float* in2 = THCudaTensor_data(state, input2); float* in3 = THCudaTensor_data(state, input3); hipLaunchKernelGGL(( icgThreshold3Forward), dim3(GET_BLOCKS(nelem)), dim3(CUDA_NUM_THREADS), 0, THCState_getCurrentStream(state), out, in1, in2, in3, nelem, threshold); THCudaTensor_free(state, input1); THCudaTensor_free(state, input2); THCudaTensor_free(state, input3); THCudaCheck(hipGetLastError()); return 1; } __global__ void icgThreshold3Backward(float* grad_in1, float* grad_in2, const float* grad_out, const float* in3, int length, float threshold) { CUDA_KERNEL_LOOP(idx, length) { grad_in1[idx] = in3[idx] <= threshold ? 0 : grad_out[idx]; grad_in2[idx] = in3[idx] <= threshold ? grad_out[idx] : 0; } } static int icgcunn_IcgThreshold3_updateGradInput(lua_State *L) { THCState* state = getCutorchState(L); THCudaTensor* input1 = (THCudaTensor*)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor* input2 = (THCudaTensor*)luaT_checkudata(L, 3, "torch.CudaTensor"); THCudaTensor* input3 = (THCudaTensor*)luaT_checkudata(L, 4, "torch.CudaTensor"); THCudaTensor* grad_input1 = (THCudaTensor*)luaT_checkudata(L, 5, "torch.CudaTensor"); THCudaTensor* grad_input2 = (THCudaTensor*)luaT_checkudata(L, 6, "torch.CudaTensor"); THCudaTensor* grad_output = (THCudaTensor*)luaT_checkudata(L, 7, "torch.CudaTensor"); float threshold = luaT_getfieldchecknumber(L, 1, "threshold"); THAssert(THCudaTensor_checkGPU(state, 4, input2, grad_output, grad_input1, input1)); long nelem = THCudaTensor_nElement(state, input1); THCudaTensor_resizeAs(state, grad_input1, input1); THCudaTensor_resizeAs(state, grad_input2, input2); float* grad_out = THCudaTensor_data(state, grad_output); float* grad_in1 = THCudaTensor_data(state, grad_input1); float* grad_in2 = THCudaTensor_data(state, grad_input2); float* in3 = THCudaTensor_data(state, input3); hipLaunchKernelGGL(( icgThreshold3Backward), dim3(GET_BLOCKS(nelem)), dim3(CUDA_NUM_THREADS), 0, THCState_getCurrentStream(state), grad_in1, grad_in2, grad_out, in3, nelem, threshold); THCudaCheck(hipGetLastError()); return 1; } static const struct luaL_Reg icgcunn_IcgThreshold3__ [] = { {"IcgThreshold3_updateOutput", icgcunn_IcgThreshold3_updateOutput}, {"IcgThreshold3_updateGradInput", icgcunn_IcgThreshold3_updateGradInput}, {NULL, NULL} }; void icgcunn_IcgThreshold3_init(lua_State *L) { luaT_pushmetatable(L, "torch.CudaTensor"); luaT_registeratname(L, icgcunn_IcgThreshold3__, "icgnn"); lua_pop(L,1); }
d76afaf9b9ca59206e86e0d34443320ec1851e4b.cu
// Copyright (C) 2016 Gernot Riegler // Institute for Computer Graphics and Vision (ICG) // Graz University of Technology (TU GRAZ) // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by the ICG, TU GRAZ. // 4. Neither the name of the ICG, TU GRAZ nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE PROVIDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "utils.h" #include "common.h" __global__ void icgThreshold3Forward(float* out, const float* in1, const float* in2, const float* in3, int length, float threshold) { CUDA_KERNEL_LOOP(idx, length) { out[idx] = in3[idx] <= threshold ? in2[idx] : in1[idx]; } } static int icgcunn_IcgThreshold3_updateOutput(lua_State *L) { THCState* state = getCutorchState(L); THCudaTensor* input1 = (THCudaTensor*)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor* input2 = (THCudaTensor*)luaT_checkudata(L, 3, "torch.CudaTensor"); THCudaTensor* input3 = (THCudaTensor*)luaT_checkudata(L, 4, "torch.CudaTensor"); float threshold = luaT_getfieldchecknumber(L, 1, "threshold"); THCudaTensor* output = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "output", "torch.CudaTensor"); long nelem = THCudaTensor_nElement(state, input1); luaL_argcheck(L, nelem == THCudaTensor_nElement(state, input2), 2, "cuf, input1 should have same number of elements as input2"); luaL_argcheck(L, nelem == THCudaTensor_nElement(state, input3), 2, "cuf, input1 should have same number of elements as input3"); THCudaTensor_resizeAs(state, output, input1); input1 = THCudaTensor_newContiguous(state, input1); input2 = THCudaTensor_newContiguous(state, input2); input3 = THCudaTensor_newContiguous(state, input3); float* out = THCudaTensor_data(state, output); float* in1 = THCudaTensor_data(state, input1); float* in2 = THCudaTensor_data(state, input2); float* in3 = THCudaTensor_data(state, input3); icgThreshold3Forward<<<GET_BLOCKS(nelem), CUDA_NUM_THREADS, 0, THCState_getCurrentStream(state)>>>( out, in1, in2, in3, nelem, threshold); THCudaTensor_free(state, input1); THCudaTensor_free(state, input2); THCudaTensor_free(state, input3); THCudaCheck(cudaGetLastError()); return 1; } __global__ void icgThreshold3Backward(float* grad_in1, float* grad_in2, const float* grad_out, const float* in3, int length, float threshold) { CUDA_KERNEL_LOOP(idx, length) { grad_in1[idx] = in3[idx] <= threshold ? 0 : grad_out[idx]; grad_in2[idx] = in3[idx] <= threshold ? grad_out[idx] : 0; } } static int icgcunn_IcgThreshold3_updateGradInput(lua_State *L) { THCState* state = getCutorchState(L); THCudaTensor* input1 = (THCudaTensor*)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor* input2 = (THCudaTensor*)luaT_checkudata(L, 3, "torch.CudaTensor"); THCudaTensor* input3 = (THCudaTensor*)luaT_checkudata(L, 4, "torch.CudaTensor"); THCudaTensor* grad_input1 = (THCudaTensor*)luaT_checkudata(L, 5, "torch.CudaTensor"); THCudaTensor* grad_input2 = (THCudaTensor*)luaT_checkudata(L, 6, "torch.CudaTensor"); THCudaTensor* grad_output = (THCudaTensor*)luaT_checkudata(L, 7, "torch.CudaTensor"); float threshold = luaT_getfieldchecknumber(L, 1, "threshold"); THAssert(THCudaTensor_checkGPU(state, 4, input2, grad_output, grad_input1, input1)); long nelem = THCudaTensor_nElement(state, input1); THCudaTensor_resizeAs(state, grad_input1, input1); THCudaTensor_resizeAs(state, grad_input2, input2); float* grad_out = THCudaTensor_data(state, grad_output); float* grad_in1 = THCudaTensor_data(state, grad_input1); float* grad_in2 = THCudaTensor_data(state, grad_input2); float* in3 = THCudaTensor_data(state, input3); icgThreshold3Backward<<<GET_BLOCKS(nelem), CUDA_NUM_THREADS, 0, THCState_getCurrentStream(state)>>>( grad_in1, grad_in2, grad_out, in3, nelem, threshold); THCudaCheck(cudaGetLastError()); return 1; } static const struct luaL_Reg icgcunn_IcgThreshold3__ [] = { {"IcgThreshold3_updateOutput", icgcunn_IcgThreshold3_updateOutput}, {"IcgThreshold3_updateGradInput", icgcunn_IcgThreshold3_updateGradInput}, {NULL, NULL} }; void icgcunn_IcgThreshold3_init(lua_State *L) { luaT_pushmetatable(L, "torch.CudaTensor"); luaT_registeratname(L, icgcunn_IcgThreshold3__, "icgnn"); lua_pop(L,1); }
8734b72fdaa296d709caf5f2d0b38b7a9a743cee.hip
// !!! This is a file automatically generated by hipify!!! /* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cugraph/experimental/detail/graph_utils.cuh> #include <cugraph/experimental/graph_functions.hpp> #include <cugraph/utilities/error.hpp> #include <cugraph/utilities/shuffle_comm.cuh> #include <rmm/thrust_rmm_allocator.h> #include <thrust/functional.h> #include <thrust/transform_reduce.h> #include <cstdint> namespace cugraph { namespace experimental { namespace { template <typename vertex_t, typename edge_t, typename weight_t, bool store_transposed, bool multi_gpu> std::enable_if_t< multi_gpu, std::tuple< cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>, rmm::device_uvector<vertex_t>>> create_graph_from_edgelist_impl( raft::handle_t const& handle, std::optional<std::tuple<vertex_t const*, vertex_t>> optional_local_vertex_span, rmm::device_uvector<vertex_t>&& edgelist_rows, rmm::device_uvector<vertex_t>&& edgelist_cols, rmm::device_uvector<weight_t>&& edgelist_weights, graph_properties_t graph_properties, bool renumber) { CUGRAPH_EXPECTS(renumber, "renumber should be true if multi_gpu is true."); auto& comm = handle.get_comms(); auto const comm_size = comm.get_size(); auto const comm_rank = comm.get_rank(); auto& row_comm = handle.get_subcomm(cugraph::partition_2d::key_naming_t().row_name()); auto const row_comm_size = row_comm.get_size(); auto& col_comm = handle.get_subcomm(cugraph::partition_2d::key_naming_t().col_name()); auto const col_comm_size = col_comm.get_size(); auto local_partition_id_op = [comm_size, key_func = cugraph::experimental::detail::compute_partition_id_from_edge_t<vertex_t>{ comm_size, row_comm_size, col_comm_size}] __device__(auto pair) { return key_func(thrust::get<0>(pair), thrust::get<1>(pair)) / comm_size; // global partition id to local partition id }; auto pair_first = store_transposed ? thrust::make_zip_iterator(thrust::make_tuple(edgelist_cols.begin(), edgelist_rows.begin())) : thrust::make_zip_iterator(thrust::make_tuple(edgelist_rows.begin(), edgelist_cols.begin())); auto edge_counts = graph_properties.is_weighted ? cugraph::experimental::groupby_and_count(pair_first, pair_first + edgelist_rows.size(), edgelist_weights.begin(), local_partition_id_op, col_comm_size, handle.get_stream()) : cugraph::experimental::groupby_and_count(pair_first, pair_first + edgelist_rows.size(), local_partition_id_op, col_comm_size, handle.get_stream()); std::vector<size_t> h_edge_counts(edge_counts.size()); raft::update_host( h_edge_counts.data(), edge_counts.data(), edge_counts.size(), handle.get_stream()); handle.get_stream_view().synchronize(); std::vector<size_t> h_displacements(h_edge_counts.size(), size_t{0}); std::partial_sum(h_edge_counts.begin(), h_edge_counts.end() - 1, h_displacements.begin() + 1); // 3. renumber rmm::device_uvector<vertex_t> renumber_map_labels(0, handle.get_stream()); cugraph::experimental::partition_t<vertex_t> partition{}; vertex_t number_of_vertices{}; edge_t number_of_edges{}; { std::vector<vertex_t*> major_ptrs(h_edge_counts.size()); std::vector<vertex_t*> minor_ptrs(major_ptrs.size()); std::vector<edge_t> counts(major_ptrs.size()); for (size_t i = 0; i < h_edge_counts.size(); ++i) { major_ptrs[i] = (store_transposed ? edgelist_cols.begin() : edgelist_rows.begin()) + h_displacements[i]; minor_ptrs[i] = (store_transposed ? edgelist_rows.begin() : edgelist_cols.begin()) + h_displacements[i]; counts[i] = static_cast<edge_t>(h_edge_counts[i]); } std::tie(renumber_map_labels, partition, number_of_vertices, number_of_edges) = cugraph::experimental::renumber_edgelist<vertex_t, edge_t, multi_gpu>( handle, optional_local_vertex_span, major_ptrs, minor_ptrs, counts); } // 4. create a graph std::vector<cugraph::experimental::edgelist_t<vertex_t, edge_t, weight_t>> edgelists( h_edge_counts.size()); for (size_t i = 0; i < h_edge_counts.size(); ++i) { edgelists[i] = cugraph::experimental::edgelist_t<vertex_t, edge_t, weight_t>{ edgelist_rows.data() + h_displacements[i], edgelist_cols.data() + h_displacements[i], graph_properties.is_weighted ? edgelist_weights.data() + h_displacements[i] : static_cast<weight_t*>(nullptr), static_cast<edge_t>(h_edge_counts[i])}; } return std::make_tuple( cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>( handle, edgelists, partition, number_of_vertices, number_of_edges, graph_properties, true), std::move(renumber_map_labels)); } template <typename vertex_t, typename edge_t, typename weight_t, bool store_transposed, bool multi_gpu> std::enable_if_t< !multi_gpu, std::tuple< cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>, rmm::device_uvector<vertex_t>>> create_graph_from_edgelist_impl( raft::handle_t const& handle, std::optional<std::tuple<vertex_t const*, vertex_t>> optional_vertex_span, rmm::device_uvector<vertex_t>&& edgelist_rows, rmm::device_uvector<vertex_t>&& edgelist_cols, rmm::device_uvector<weight_t>&& edgelist_weights, graph_properties_t graph_properties, bool renumber) { auto renumber_map_labels = renumber ? cugraph::experimental::renumber_edgelist<vertex_t, edge_t, multi_gpu>( handle, optional_vertex_span, store_transposed ? edgelist_cols.data() : edgelist_rows.data(), store_transposed ? edgelist_rows.data() : edgelist_cols.data(), static_cast<edge_t>(edgelist_rows.size())) : rmm::device_uvector<vertex_t>(0, handle.get_stream()); vertex_t num_vertices{}; if (renumber) { num_vertices = static_cast<vertex_t>(renumber_map_labels.size()); } else { if (optional_vertex_span) { num_vertices = std::get<1>(*optional_vertex_span); } else { auto edge_first = thrust::make_zip_iterator(thrust::make_tuple(edgelist_rows.begin(), edgelist_cols.begin())); num_vertices = thrust::transform_reduce( rmm::exec_policy(handle.get_stream())->on(handle.get_stream()), edge_first, edge_first + edgelist_rows.size(), [] __device__(auto e) { return ::max(thrust::get<0>(e), thrust::get<1>(e)); }, vertex_t{0}, thrust::maximum<vertex_t>()) + 1; } } return std::make_tuple( cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>( handle, cugraph::experimental::edgelist_t<vertex_t, edge_t, weight_t>{ edgelist_rows.data(), edgelist_cols.data(), graph_properties.is_weighted ? edgelist_weights.data() : static_cast<weight_t*>(nullptr), static_cast<edge_t>(edgelist_rows.size())}, num_vertices, graph_properties, renumber ? true : false), std::move(renumber_map_labels)); } } // namespace template <typename vertex_t, typename edge_t, typename weight_t, bool store_transposed, bool multi_gpu> std::tuple<cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>, rmm::device_uvector<vertex_t>> create_graph_from_edgelist( raft::handle_t const& handle, std::optional<std::tuple<vertex_t const*, vertex_t>> optional_vertex_span, rmm::device_uvector<vertex_t>&& edgelist_rows, rmm::device_uvector<vertex_t>&& edgelist_cols, rmm::device_uvector<weight_t>&& edgelist_weights, graph_properties_t graph_properties, bool renumber) { return create_graph_from_edgelist_impl<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>( handle, optional_vertex_span, std::move(edgelist_rows), std::move(edgelist_cols), std::move(edgelist_weights), graph_properties, renumber); } // explicit instantiations template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, false, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, false, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, true, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, true, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, false, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, false, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, true, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, true, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); } // namespace experimental } // namespace cugraph
8734b72fdaa296d709caf5f2d0b38b7a9a743cee.cu
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cugraph/experimental/detail/graph_utils.cuh> #include <cugraph/experimental/graph_functions.hpp> #include <cugraph/utilities/error.hpp> #include <cugraph/utilities/shuffle_comm.cuh> #include <rmm/thrust_rmm_allocator.h> #include <thrust/functional.h> #include <thrust/transform_reduce.h> #include <cstdint> namespace cugraph { namespace experimental { namespace { template <typename vertex_t, typename edge_t, typename weight_t, bool store_transposed, bool multi_gpu> std::enable_if_t< multi_gpu, std::tuple< cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>, rmm::device_uvector<vertex_t>>> create_graph_from_edgelist_impl( raft::handle_t const& handle, std::optional<std::tuple<vertex_t const*, vertex_t>> optional_local_vertex_span, rmm::device_uvector<vertex_t>&& edgelist_rows, rmm::device_uvector<vertex_t>&& edgelist_cols, rmm::device_uvector<weight_t>&& edgelist_weights, graph_properties_t graph_properties, bool renumber) { CUGRAPH_EXPECTS(renumber, "renumber should be true if multi_gpu is true."); auto& comm = handle.get_comms(); auto const comm_size = comm.get_size(); auto const comm_rank = comm.get_rank(); auto& row_comm = handle.get_subcomm(cugraph::partition_2d::key_naming_t().row_name()); auto const row_comm_size = row_comm.get_size(); auto& col_comm = handle.get_subcomm(cugraph::partition_2d::key_naming_t().col_name()); auto const col_comm_size = col_comm.get_size(); auto local_partition_id_op = [comm_size, key_func = cugraph::experimental::detail::compute_partition_id_from_edge_t<vertex_t>{ comm_size, row_comm_size, col_comm_size}] __device__(auto pair) { return key_func(thrust::get<0>(pair), thrust::get<1>(pair)) / comm_size; // global partition id to local partition id }; auto pair_first = store_transposed ? thrust::make_zip_iterator(thrust::make_tuple(edgelist_cols.begin(), edgelist_rows.begin())) : thrust::make_zip_iterator(thrust::make_tuple(edgelist_rows.begin(), edgelist_cols.begin())); auto edge_counts = graph_properties.is_weighted ? cugraph::experimental::groupby_and_count(pair_first, pair_first + edgelist_rows.size(), edgelist_weights.begin(), local_partition_id_op, col_comm_size, handle.get_stream()) : cugraph::experimental::groupby_and_count(pair_first, pair_first + edgelist_rows.size(), local_partition_id_op, col_comm_size, handle.get_stream()); std::vector<size_t> h_edge_counts(edge_counts.size()); raft::update_host( h_edge_counts.data(), edge_counts.data(), edge_counts.size(), handle.get_stream()); handle.get_stream_view().synchronize(); std::vector<size_t> h_displacements(h_edge_counts.size(), size_t{0}); std::partial_sum(h_edge_counts.begin(), h_edge_counts.end() - 1, h_displacements.begin() + 1); // 3. renumber rmm::device_uvector<vertex_t> renumber_map_labels(0, handle.get_stream()); cugraph::experimental::partition_t<vertex_t> partition{}; vertex_t number_of_vertices{}; edge_t number_of_edges{}; { std::vector<vertex_t*> major_ptrs(h_edge_counts.size()); std::vector<vertex_t*> minor_ptrs(major_ptrs.size()); std::vector<edge_t> counts(major_ptrs.size()); for (size_t i = 0; i < h_edge_counts.size(); ++i) { major_ptrs[i] = (store_transposed ? edgelist_cols.begin() : edgelist_rows.begin()) + h_displacements[i]; minor_ptrs[i] = (store_transposed ? edgelist_rows.begin() : edgelist_cols.begin()) + h_displacements[i]; counts[i] = static_cast<edge_t>(h_edge_counts[i]); } std::tie(renumber_map_labels, partition, number_of_vertices, number_of_edges) = cugraph::experimental::renumber_edgelist<vertex_t, edge_t, multi_gpu>( handle, optional_local_vertex_span, major_ptrs, minor_ptrs, counts); } // 4. create a graph std::vector<cugraph::experimental::edgelist_t<vertex_t, edge_t, weight_t>> edgelists( h_edge_counts.size()); for (size_t i = 0; i < h_edge_counts.size(); ++i) { edgelists[i] = cugraph::experimental::edgelist_t<vertex_t, edge_t, weight_t>{ edgelist_rows.data() + h_displacements[i], edgelist_cols.data() + h_displacements[i], graph_properties.is_weighted ? edgelist_weights.data() + h_displacements[i] : static_cast<weight_t*>(nullptr), static_cast<edge_t>(h_edge_counts[i])}; } return std::make_tuple( cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>( handle, edgelists, partition, number_of_vertices, number_of_edges, graph_properties, true), std::move(renumber_map_labels)); } template <typename vertex_t, typename edge_t, typename weight_t, bool store_transposed, bool multi_gpu> std::enable_if_t< !multi_gpu, std::tuple< cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>, rmm::device_uvector<vertex_t>>> create_graph_from_edgelist_impl( raft::handle_t const& handle, std::optional<std::tuple<vertex_t const*, vertex_t>> optional_vertex_span, rmm::device_uvector<vertex_t>&& edgelist_rows, rmm::device_uvector<vertex_t>&& edgelist_cols, rmm::device_uvector<weight_t>&& edgelist_weights, graph_properties_t graph_properties, bool renumber) { auto renumber_map_labels = renumber ? cugraph::experimental::renumber_edgelist<vertex_t, edge_t, multi_gpu>( handle, optional_vertex_span, store_transposed ? edgelist_cols.data() : edgelist_rows.data(), store_transposed ? edgelist_rows.data() : edgelist_cols.data(), static_cast<edge_t>(edgelist_rows.size())) : rmm::device_uvector<vertex_t>(0, handle.get_stream()); vertex_t num_vertices{}; if (renumber) { num_vertices = static_cast<vertex_t>(renumber_map_labels.size()); } else { if (optional_vertex_span) { num_vertices = std::get<1>(*optional_vertex_span); } else { auto edge_first = thrust::make_zip_iterator(thrust::make_tuple(edgelist_rows.begin(), edgelist_cols.begin())); num_vertices = thrust::transform_reduce( rmm::exec_policy(handle.get_stream())->on(handle.get_stream()), edge_first, edge_first + edgelist_rows.size(), [] __device__(auto e) { return std::max(thrust::get<0>(e), thrust::get<1>(e)); }, vertex_t{0}, thrust::maximum<vertex_t>()) + 1; } } return std::make_tuple( cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>( handle, cugraph::experimental::edgelist_t<vertex_t, edge_t, weight_t>{ edgelist_rows.data(), edgelist_cols.data(), graph_properties.is_weighted ? edgelist_weights.data() : static_cast<weight_t*>(nullptr), static_cast<edge_t>(edgelist_rows.size())}, num_vertices, graph_properties, renumber ? true : false), std::move(renumber_map_labels)); } } // namespace template <typename vertex_t, typename edge_t, typename weight_t, bool store_transposed, bool multi_gpu> std::tuple<cugraph::experimental::graph_t<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>, rmm::device_uvector<vertex_t>> create_graph_from_edgelist( raft::handle_t const& handle, std::optional<std::tuple<vertex_t const*, vertex_t>> optional_vertex_span, rmm::device_uvector<vertex_t>&& edgelist_rows, rmm::device_uvector<vertex_t>&& edgelist_cols, rmm::device_uvector<weight_t>&& edgelist_weights, graph_properties_t graph_properties, bool renumber) { return create_graph_from_edgelist_impl<vertex_t, edge_t, weight_t, store_transposed, multi_gpu>( handle, optional_vertex_span, std::move(edgelist_rows), std::move(edgelist_cols), std::move(edgelist_weights), graph_properties, renumber); } // explicit instantiations template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, float, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, float, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int32_t, double, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int32_t, double, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, float, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, float, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, false, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, false, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, true, false>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int32_t, int64_t, double, true, true>, rmm::device_uvector<int32_t>> create_graph_from_edgelist<int32_t, int64_t, double, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int32_t const*, int32_t>> optional_vertex_span, rmm::device_uvector<int32_t>&& edgelist_rows, rmm::device_uvector<int32_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, false, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, false, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, true, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, float, true, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, float, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<float>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, false, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, false, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, false, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, false, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, true, false>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, true, false>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); template std::tuple<cugraph::experimental::graph_t<int64_t, int64_t, double, true, true>, rmm::device_uvector<int64_t>> create_graph_from_edgelist<int64_t, int64_t, double, true, true>( raft::handle_t const& handle, std::optional<std::tuple<int64_t const*, int64_t>> optional_vertex_span, rmm::device_uvector<int64_t>&& edgelist_rows, rmm::device_uvector<int64_t>&& edgelist_cols, rmm::device_uvector<double>&& edgelist_weights, graph_properties_t graph_properties, bool renumber); } // namespace experimental } // namespace cugraph
049e3758897d235d2b8c49b47f4da15fd337c34e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> #include <stdlib.h> #include "kmeans.h" static inline int nextPowerOfTwo(int n) { n--; n = n >> 1 | n; n = n >> 2 | n; n = n >> 4 | n; n = n >> 8 | n; n = n >> 16 | n; // n = n >> 32 | n; // For 64-bit ints return ++n; } /*----< euclid_dist_2() >----------------------------------------------------*/ /* square of Euclid distance between two multi-dimensional points */ __host__ __device__ inline static float euclid_dist_2(int numCoords, int numObjs, int numClusters, float *objects, // [numCoords][numObjs] float *clusters, // [numCoords][numClusters] int objectId, int clusterId) { int i; float ans=0.0; for (i = 0; i < numCoords; i++) { ans += (objects[numObjs * i + objectId] - clusters[numClusters * i + clusterId]) * (objects[numObjs * i + objectId] - clusters[numClusters * i + clusterId]); } return(ans); } /*----< find_nearest_cluster() >---------------------------------------------*/ __global__ static void find_nearest_cluster(int numCoords, int numObjs, int numClusters, float *objects, // [numCoords][numObjs] float *deviceClusters, // [numCoords][numClusters] int *membership, // [numObjs] int *intermediates) { extern __shared__ char sharedMemory[]; // The type chosen for membershipChanged must be large enough to support // reductions! There are blockDim.x elements, one for each thread in the // block. See numThreadsPerClusterBlock in cuda_kmeans(). unsigned char *membershipChanged = (unsigned char *)sharedMemory; #if BLOCK_SHARED_MEM_OPTIMIZATION float *clusters = (float *)(sharedMemory + blockDim.x); #else float *clusters = deviceClusters; #endif membershipChanged[threadIdx.x] = 0; #if BLOCK_SHARED_MEM_OPTIMIZATION // BEWARE: We can overrun our shared memory here if there are too many // clusters or too many coordinates! For reference, a Tesla C1060 has 16 // KiB of shared memory per block, and a GeForce GTX 480 has 48 KiB of // shared memory per block. for (int i = threadIdx.x; i < numClusters; i += blockDim.x) { for (int j = 0; j < numCoords; j++) { clusters[numClusters * j + i] = deviceClusters[numClusters * j + i]; } } __syncthreads(); #endif int objectId = blockDim.x * blockIdx.x + threadIdx.x; if (objectId < numObjs) { int index, i; float dist, min_dist; /* find the cluster id that has min distance to object */ index = 0; min_dist = euclid_dist_2(numCoords, numObjs, numClusters, objects, clusters, objectId, 0); for (i=1; i<numClusters; i++) { dist = euclid_dist_2(numCoords, numObjs, numClusters, objects, clusters, objectId, i); /* no need square root */ if (dist < min_dist) { /* find the min and its array index */ min_dist = dist; index = i; } } if (membership[objectId] != index) { membershipChanged[threadIdx.x] = 1; } /* assign the membership to object objectId */ membership[objectId] = index; __syncthreads(); // For membershipChanged[] // blockDim.x *must* be a power of two! for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) { if (threadIdx.x < s) { membershipChanged[threadIdx.x] += membershipChanged[threadIdx.x + s]; } __syncthreads(); } if (threadIdx.x == 0) { intermediates[blockIdx.x] = membershipChanged[0]; } } } __global__ static void compute_delta(int *deviceIntermediates, int numIntermediates, // The actual number of intermediates int numIntermediates2) // The next power of two { // The number of elements in this array should be equal to // numIntermediates2, the number of threads launched. It *must* be a power // of two! extern __shared__ unsigned int intermediates[]; // Copy global intermediate values into shared memory. intermediates[threadIdx.x] = (threadIdx.x < numIntermediates) ? deviceIntermediates[threadIdx.x] : 0; __syncthreads(); // numIntermediates2 *must* be a power of two! for (unsigned int s = numIntermediates2 / 2; s > 0; s >>= 1) { if (threadIdx.x < s) { intermediates[threadIdx.x] += intermediates[threadIdx.x + s]; } __syncthreads(); } if (threadIdx.x == 0) { deviceIntermediates[0] = intermediates[0]; } } /*----< cuda_kmeans() >-------------------------------------------------------*/ // // ---------------------------------------- // DATA LAYOUT // // objects [numObjs][numCoords] // clusters [numClusters][numCoords] // dimObjects [numCoords][numObjs] // dimClusters [numCoords][numClusters] // newClusters [numCoords][numClusters] // deviceObjects [numCoords][numObjs] // deviceClusters [numCoords][numClusters] // ---------------------------------------- // /* return an array of cluster centers of size [numClusters][numCoords] */ float** cuda_kmeans(float **objects, /* in: [numObjs][numCoords] */ int numCoords, /* no. features */ int numObjs, /* no. objects */ int numClusters, /* no. clusters */ float threshold, /* % objects change membership */ int *membership, /* out: [numObjs] */ int *loop_iterations) { int i, j, index, loop=0; int *newClusterSize; /* [numClusters]: no. objects assigned in each new cluster */ float delta; /* % of objects change their clusters */ float **dimObjects; float **clusters; /* out: [numClusters][numCoords] */ float **dimClusters; float **newClusters; /* [numCoords][numClusters] */ float *deviceObjects; float *deviceClusters; int *deviceMembership; int *deviceIntermediates; // Copy objects given in [numObjs][numCoords] layout to new // [numCoords][numObjs] layout malloc2D(dimObjects, numCoords, numObjs, float); for (i = 0; i < numCoords; i++) { for (j = 0; j < numObjs; j++) { dimObjects[i][j] = objects[j][i]; } } /* pick first numClusters elements of objects[] as initial cluster centers*/ malloc2D(dimClusters, numCoords, numClusters, float); for (i = 0; i < numCoords; i++) { for (j = 0; j < numClusters; j++) { dimClusters[i][j] = dimObjects[i][j]; } } /* initialize membership[] */ for (i=0; i<numObjs; i++) membership[i] = -1; /* need to initialize newClusterSize and newClusters[0] to all 0 */ newClusterSize = (int*) calloc(numClusters, sizeof(int)); assert(newClusterSize != NULL); malloc2D(newClusters, numCoords, numClusters, float); memset(newClusters[0], 0, numCoords * numClusters * sizeof(float)); // To support reduction, numThreadsPerClusterBlock *must* be a power of // two, and it *must* be no larger than the number of bits that will // fit into an unsigned char, the type used to keep track of membership // changes in the kernel. const unsigned int numThreadsPerClusterBlock = 128; const unsigned int numClusterBlocks = (numObjs + numThreadsPerClusterBlock - 1) / numThreadsPerClusterBlock; #if BLOCK_SHARED_MEM_OPTIMIZATION const unsigned int clusterBlockSharedDataSize = numThreadsPerClusterBlock * sizeof(unsigned char) + numClusters * numCoords * sizeof(float); hipDeviceProp_t deviceProp; int deviceNum; hipGetDevice(&deviceNum); hipGetDeviceProperties(&deviceProp, deviceNum); if (clusterBlockSharedDataSize > deviceProp.sharedMemPerBlock) { err("WARNING: Your CUDA hardware has insufficient block shared memory. " "You need to recompile with BLOCK_SHARED_MEM_OPTIMIZATION=0. " "See the README for details.\n"); } #else const unsigned int clusterBlockSharedDataSize = numThreadsPerClusterBlock * sizeof(unsigned char); #endif const unsigned int numReductionThreads = nextPowerOfTwo(numClusterBlocks); const unsigned int reductionBlockSharedDataSize = numReductionThreads * sizeof(unsigned int); checkCuda(hipMalloc(&deviceObjects, numObjs*numCoords*sizeof(float))); checkCuda(hipMalloc(&deviceClusters, numClusters*numCoords*sizeof(float))); checkCuda(hipMalloc(&deviceMembership, numObjs*sizeof(int))); checkCuda(hipMalloc(&deviceIntermediates, numReductionThreads*sizeof(unsigned int))); checkCuda(hipMemcpy(deviceObjects, dimObjects[0], numObjs*numCoords*sizeof(float), hipMemcpyHostToDevice)); checkCuda(hipMemcpy(deviceMembership, membership, numObjs*sizeof(int), hipMemcpyHostToDevice)); do { checkCuda(hipMemcpy(deviceClusters, dimClusters[0], numClusters*numCoords*sizeof(float), hipMemcpyHostToDevice)); hipLaunchKernelGGL(( find_nearest_cluster) , dim3(numClusterBlocks), dim3(numThreadsPerClusterBlock), clusterBlockSharedDataSize , 0, numCoords, numObjs, numClusters, deviceObjects, deviceClusters, deviceMembership, deviceIntermediates); hipDeviceSynchronize(); checkLastCudaError(); hipLaunchKernelGGL(( compute_delta) , dim3(1), dim3(numReductionThreads), reductionBlockSharedDataSize , 0, deviceIntermediates, numClusterBlocks, numReductionThreads); hipDeviceSynchronize(); checkLastCudaError(); int d; checkCuda(hipMemcpy(&d, deviceIntermediates, sizeof(int), hipMemcpyDeviceToHost)); delta = (float)d; checkCuda(hipMemcpy(membership, deviceMembership, numObjs*sizeof(int), hipMemcpyDeviceToHost)); for (i=0; i<numObjs; i++) { /* find the array index of nestest cluster center */ index = membership[i]; /* update new cluster centers : sum of objects located within */ newClusterSize[index]++; for (j=0; j<numCoords; j++) newClusters[j][index] += objects[i][j]; } // TODO: Flip the nesting order // TODO: Change layout of newClusters to [numClusters][numCoords] /* average the sum and replace old cluster centers with newClusters */ for (i=0; i<numClusters; i++) { for (j=0; j<numCoords; j++) { if (newClusterSize[i] > 0) dimClusters[j][i] = newClusters[j][i] / newClusterSize[i]; newClusters[j][i] = 0.0; /* set back to 0 */ } newClusterSize[i] = 0; /* set back to 0 */ } delta /= numObjs; } while (delta > threshold && loop++ < 500); *loop_iterations = loop + 1; /* allocate a 2D space for returning variable clusters[] (coordinates of cluster centers) */ malloc2D(clusters, numClusters, numCoords, float); for (i = 0; i < numClusters; i++) { for (j = 0; j < numCoords; j++) { clusters[i][j] = dimClusters[j][i]; } } checkCuda(hipFree(deviceObjects)); checkCuda(hipFree(deviceClusters)); checkCuda(hipFree(deviceMembership)); checkCuda(hipFree(deviceIntermediates)); free(dimObjects[0]); free(dimObjects); free(dimClusters[0]); free(dimClusters); free(newClusters[0]); free(newClusters); free(newClusterSize); return clusters; }
049e3758897d235d2b8c49b47f4da15fd337c34e.cu
#include <stdio.h> #include <stdlib.h> #include "kmeans.h" static inline int nextPowerOfTwo(int n) { n--; n = n >> 1 | n; n = n >> 2 | n; n = n >> 4 | n; n = n >> 8 | n; n = n >> 16 | n; // n = n >> 32 | n; // For 64-bit ints return ++n; } /*----< euclid_dist_2() >----------------------------------------------------*/ /* square of Euclid distance between two multi-dimensional points */ __host__ __device__ inline static float euclid_dist_2(int numCoords, int numObjs, int numClusters, float *objects, // [numCoords][numObjs] float *clusters, // [numCoords][numClusters] int objectId, int clusterId) { int i; float ans=0.0; for (i = 0; i < numCoords; i++) { ans += (objects[numObjs * i + objectId] - clusters[numClusters * i + clusterId]) * (objects[numObjs * i + objectId] - clusters[numClusters * i + clusterId]); } return(ans); } /*----< find_nearest_cluster() >---------------------------------------------*/ __global__ static void find_nearest_cluster(int numCoords, int numObjs, int numClusters, float *objects, // [numCoords][numObjs] float *deviceClusters, // [numCoords][numClusters] int *membership, // [numObjs] int *intermediates) { extern __shared__ char sharedMemory[]; // The type chosen for membershipChanged must be large enough to support // reductions! There are blockDim.x elements, one for each thread in the // block. See numThreadsPerClusterBlock in cuda_kmeans(). unsigned char *membershipChanged = (unsigned char *)sharedMemory; #if BLOCK_SHARED_MEM_OPTIMIZATION float *clusters = (float *)(sharedMemory + blockDim.x); #else float *clusters = deviceClusters; #endif membershipChanged[threadIdx.x] = 0; #if BLOCK_SHARED_MEM_OPTIMIZATION // BEWARE: We can overrun our shared memory here if there are too many // clusters or too many coordinates! For reference, a Tesla C1060 has 16 // KiB of shared memory per block, and a GeForce GTX 480 has 48 KiB of // shared memory per block. for (int i = threadIdx.x; i < numClusters; i += blockDim.x) { for (int j = 0; j < numCoords; j++) { clusters[numClusters * j + i] = deviceClusters[numClusters * j + i]; } } __syncthreads(); #endif int objectId = blockDim.x * blockIdx.x + threadIdx.x; if (objectId < numObjs) { int index, i; float dist, min_dist; /* find the cluster id that has min distance to object */ index = 0; min_dist = euclid_dist_2(numCoords, numObjs, numClusters, objects, clusters, objectId, 0); for (i=1; i<numClusters; i++) { dist = euclid_dist_2(numCoords, numObjs, numClusters, objects, clusters, objectId, i); /* no need square root */ if (dist < min_dist) { /* find the min and its array index */ min_dist = dist; index = i; } } if (membership[objectId] != index) { membershipChanged[threadIdx.x] = 1; } /* assign the membership to object objectId */ membership[objectId] = index; __syncthreads(); // For membershipChanged[] // blockDim.x *must* be a power of two! for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) { if (threadIdx.x < s) { membershipChanged[threadIdx.x] += membershipChanged[threadIdx.x + s]; } __syncthreads(); } if (threadIdx.x == 0) { intermediates[blockIdx.x] = membershipChanged[0]; } } } __global__ static void compute_delta(int *deviceIntermediates, int numIntermediates, // The actual number of intermediates int numIntermediates2) // The next power of two { // The number of elements in this array should be equal to // numIntermediates2, the number of threads launched. It *must* be a power // of two! extern __shared__ unsigned int intermediates[]; // Copy global intermediate values into shared memory. intermediates[threadIdx.x] = (threadIdx.x < numIntermediates) ? deviceIntermediates[threadIdx.x] : 0; __syncthreads(); // numIntermediates2 *must* be a power of two! for (unsigned int s = numIntermediates2 / 2; s > 0; s >>= 1) { if (threadIdx.x < s) { intermediates[threadIdx.x] += intermediates[threadIdx.x + s]; } __syncthreads(); } if (threadIdx.x == 0) { deviceIntermediates[0] = intermediates[0]; } } /*----< cuda_kmeans() >-------------------------------------------------------*/ // // ---------------------------------------- // DATA LAYOUT // // objects [numObjs][numCoords] // clusters [numClusters][numCoords] // dimObjects [numCoords][numObjs] // dimClusters [numCoords][numClusters] // newClusters [numCoords][numClusters] // deviceObjects [numCoords][numObjs] // deviceClusters [numCoords][numClusters] // ---------------------------------------- // /* return an array of cluster centers of size [numClusters][numCoords] */ float** cuda_kmeans(float **objects, /* in: [numObjs][numCoords] */ int numCoords, /* no. features */ int numObjs, /* no. objects */ int numClusters, /* no. clusters */ float threshold, /* % objects change membership */ int *membership, /* out: [numObjs] */ int *loop_iterations) { int i, j, index, loop=0; int *newClusterSize; /* [numClusters]: no. objects assigned in each new cluster */ float delta; /* % of objects change their clusters */ float **dimObjects; float **clusters; /* out: [numClusters][numCoords] */ float **dimClusters; float **newClusters; /* [numCoords][numClusters] */ float *deviceObjects; float *deviceClusters; int *deviceMembership; int *deviceIntermediates; // Copy objects given in [numObjs][numCoords] layout to new // [numCoords][numObjs] layout malloc2D(dimObjects, numCoords, numObjs, float); for (i = 0; i < numCoords; i++) { for (j = 0; j < numObjs; j++) { dimObjects[i][j] = objects[j][i]; } } /* pick first numClusters elements of objects[] as initial cluster centers*/ malloc2D(dimClusters, numCoords, numClusters, float); for (i = 0; i < numCoords; i++) { for (j = 0; j < numClusters; j++) { dimClusters[i][j] = dimObjects[i][j]; } } /* initialize membership[] */ for (i=0; i<numObjs; i++) membership[i] = -1; /* need to initialize newClusterSize and newClusters[0] to all 0 */ newClusterSize = (int*) calloc(numClusters, sizeof(int)); assert(newClusterSize != NULL); malloc2D(newClusters, numCoords, numClusters, float); memset(newClusters[0], 0, numCoords * numClusters * sizeof(float)); // To support reduction, numThreadsPerClusterBlock *must* be a power of // two, and it *must* be no larger than the number of bits that will // fit into an unsigned char, the type used to keep track of membership // changes in the kernel. const unsigned int numThreadsPerClusterBlock = 128; const unsigned int numClusterBlocks = (numObjs + numThreadsPerClusterBlock - 1) / numThreadsPerClusterBlock; #if BLOCK_SHARED_MEM_OPTIMIZATION const unsigned int clusterBlockSharedDataSize = numThreadsPerClusterBlock * sizeof(unsigned char) + numClusters * numCoords * sizeof(float); cudaDeviceProp deviceProp; int deviceNum; cudaGetDevice(&deviceNum); cudaGetDeviceProperties(&deviceProp, deviceNum); if (clusterBlockSharedDataSize > deviceProp.sharedMemPerBlock) { err("WARNING: Your CUDA hardware has insufficient block shared memory. " "You need to recompile with BLOCK_SHARED_MEM_OPTIMIZATION=0. " "See the README for details.\n"); } #else const unsigned int clusterBlockSharedDataSize = numThreadsPerClusterBlock * sizeof(unsigned char); #endif const unsigned int numReductionThreads = nextPowerOfTwo(numClusterBlocks); const unsigned int reductionBlockSharedDataSize = numReductionThreads * sizeof(unsigned int); checkCuda(cudaMalloc(&deviceObjects, numObjs*numCoords*sizeof(float))); checkCuda(cudaMalloc(&deviceClusters, numClusters*numCoords*sizeof(float))); checkCuda(cudaMalloc(&deviceMembership, numObjs*sizeof(int))); checkCuda(cudaMalloc(&deviceIntermediates, numReductionThreads*sizeof(unsigned int))); checkCuda(cudaMemcpy(deviceObjects, dimObjects[0], numObjs*numCoords*sizeof(float), cudaMemcpyHostToDevice)); checkCuda(cudaMemcpy(deviceMembership, membership, numObjs*sizeof(int), cudaMemcpyHostToDevice)); do { checkCuda(cudaMemcpy(deviceClusters, dimClusters[0], numClusters*numCoords*sizeof(float), cudaMemcpyHostToDevice)); find_nearest_cluster <<< numClusterBlocks, numThreadsPerClusterBlock, clusterBlockSharedDataSize >>> (numCoords, numObjs, numClusters, deviceObjects, deviceClusters, deviceMembership, deviceIntermediates); cudaDeviceSynchronize(); checkLastCudaError(); compute_delta <<< 1, numReductionThreads, reductionBlockSharedDataSize >>> (deviceIntermediates, numClusterBlocks, numReductionThreads); cudaDeviceSynchronize(); checkLastCudaError(); int d; checkCuda(cudaMemcpy(&d, deviceIntermediates, sizeof(int), cudaMemcpyDeviceToHost)); delta = (float)d; checkCuda(cudaMemcpy(membership, deviceMembership, numObjs*sizeof(int), cudaMemcpyDeviceToHost)); for (i=0; i<numObjs; i++) { /* find the array index of nestest cluster center */ index = membership[i]; /* update new cluster centers : sum of objects located within */ newClusterSize[index]++; for (j=0; j<numCoords; j++) newClusters[j][index] += objects[i][j]; } // TODO: Flip the nesting order // TODO: Change layout of newClusters to [numClusters][numCoords] /* average the sum and replace old cluster centers with newClusters */ for (i=0; i<numClusters; i++) { for (j=0; j<numCoords; j++) { if (newClusterSize[i] > 0) dimClusters[j][i] = newClusters[j][i] / newClusterSize[i]; newClusters[j][i] = 0.0; /* set back to 0 */ } newClusterSize[i] = 0; /* set back to 0 */ } delta /= numObjs; } while (delta > threshold && loop++ < 500); *loop_iterations = loop + 1; /* allocate a 2D space for returning variable clusters[] (coordinates of cluster centers) */ malloc2D(clusters, numClusters, numCoords, float); for (i = 0; i < numClusters; i++) { for (j = 0; j < numCoords; j++) { clusters[i][j] = dimClusters[j][i]; } } checkCuda(cudaFree(deviceObjects)); checkCuda(cudaFree(deviceClusters)); checkCuda(cudaFree(deviceMembership)); checkCuda(cudaFree(deviceIntermediates)); free(dimObjects[0]); free(dimObjects); free(dimClusters[0]); free(dimClusters); free(newClusters[0]); free(newClusters); free(newClusterSize); return clusters; }
1dc0eddd49ffb3805055977c6f938e274a273b7c.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <hip/hip_runtime.h> // Initialize host vectors void init(int *a, int *b, int n) { for (int i=0; i < n; ++i) { a[i] = i; b[i] = n-i; } } // Check result correctness void check(int *c, int n) { int i = 0; while (i < n && c[i] == n) { ++i; } if (i == n) printf("Ok\n"); else printf("Non ok\n"); } // Cuda kernel __global__ void add(int *a, int *b, int *c, int n) { //@TODO@ : complete kernel code int i = threadIdx.x + blockDim.x * blockIdx.x; if(i < n) { c[i]=a[i]+b[i]; } } int main(int argc, char **argv) { if(argc<2) {printf("Give the vector size as first parameter\n");;exit(2);} int n = atoi(argv[1]); int b = atoi(argv[2]); int t = atoi(argv[3]); printf("Vector size is %d\n",n); // host pointers int *host_a, *host_b, *host_c; // Device pointers int *dev_a, *dev_b, *dev_c; // Allocations on host //@TODO@ : host_a= (int *) malloc(sizeof(int)*n); host_b= (int *) malloc(sizeof(int)*n); host_c= (int *) malloc(sizeof(int)*n); // Initialize vectors init(host_a,host_b,n); // Allocations on device //@TODO@ : hipMalloc(&dev_a, sizeof(int) *n); hipMalloc(&dev_b, sizeof(int) *n); hipMalloc(&dev_c, sizeof(int) *n); // Copy from host to device //@TODO@ : complete here hipMemcpy(dev_a, host_a, sizeof(int)*n,hipMemcpyHostToDevice); hipMemcpy(dev_b, host_b, sizeof(int)*n,hipMemcpyHostToDevice); // Invoke kernel //@TODO@ : complete here hipLaunchKernelGGL(( add), dim3(b), dim3(t), 0, 0, dev_a, dev_b, dev_c, n ); // Copy result from device to host //@TODO@ : complete here hipMemcpy(host_c, dev_c, sizeof(int)*n, hipMemcpyDeviceToHost); // Check result check(host_c,n); // Free device memory hipFree(dev_a); hipFree(dev_b); hipFree(dev_c); // Free host memory free(host_a); free(host_b); free(host_c); return 0; }
1dc0eddd49ffb3805055977c6f938e274a273b7c.cu
#include <stdio.h> #include <cuda.h> // Initialize host vectors void init(int *a, int *b, int n) { for (int i=0; i < n; ++i) { a[i] = i; b[i] = n-i; } } // Check result correctness void check(int *c, int n) { int i = 0; while (i < n && c[i] == n) { ++i; } if (i == n) printf("Ok\n"); else printf("Non ok\n"); } // Cuda kernel __global__ void add(int *a, int *b, int *c, int n) { //@TODO@ : complete kernel code int i = threadIdx.x + blockDim.x * blockIdx.x; if(i < n) { c[i]=a[i]+b[i]; } } int main(int argc, char **argv) { if(argc<2) {printf("Give the vector size as first parameter\n");;exit(2);} int n = atoi(argv[1]); int b = atoi(argv[2]); int t = atoi(argv[3]); printf("Vector size is %d\n",n); // host pointers int *host_a, *host_b, *host_c; // Device pointers int *dev_a, *dev_b, *dev_c; // Allocations on host //@TODO@ : host_a= (int *) malloc(sizeof(int)*n); host_b= (int *) malloc(sizeof(int)*n); host_c= (int *) malloc(sizeof(int)*n); // Initialize vectors init(host_a,host_b,n); // Allocations on device //@TODO@ : cudaMalloc(&dev_a, sizeof(int) *n); cudaMalloc(&dev_b, sizeof(int) *n); cudaMalloc(&dev_c, sizeof(int) *n); // Copy from host to device //@TODO@ : complete here cudaMemcpy(dev_a, host_a, sizeof(int)*n,cudaMemcpyHostToDevice); cudaMemcpy(dev_b, host_b, sizeof(int)*n,cudaMemcpyHostToDevice); // Invoke kernel //@TODO@ : complete here add<<<b, t>>>(dev_a, dev_b, dev_c, n ); // Copy result from device to host //@TODO@ : complete here cudaMemcpy(host_c, dev_c, sizeof(int)*n, cudaMemcpyDeviceToHost); // Check result check(host_c,n); // Free device memory cudaFree(dev_a); cudaFree(dev_b); cudaFree(dev_c); // Free host memory free(host_a); free(host_b); free(host_c); return 0; }
eace2c5f932803d0847fc1ab9c99504e383afb2e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; __global__ void insert(int *a, int t){ int i = blockIdx.x*blockDim.x+threadIdx.x; int cont = 0; while(cont <= i*10000){ cont++; } if(i < t){ for(int k = 0; k < t-1; k++){ if(a[k] > a[k+1]){ int aux = a[k]; a[k] = a[k+1]; a[k+1] = aux; } } } } void imp(int *a, int n){ for(int i = 0; i < n; i++){ cout << a[i]<<endl; } cout<<endl<<endl; } void cuda(int *a, int n){ int *array; hipMalloc((void**)&array, n * sizeof(int)); hipMemcpy(array,a,n * sizeof(int),hipMemcpyHostToDevice); hipLaunchKernelGGL(( insert), dim3(1024),dim3(1), 0, 0, array,n); hipMemcpy(a,array,n * sizeof(int),hipMemcpyDeviceToHost); hipFree(array); } int main(){ int n; cin >> n; int a[n]; int *vec; vec = (int*)malloc(n*sizeof(int)); for(int i = 0; i < n; i++){ cin >> a[i]; vec[i] = a[i]; } cuda(vec,n); imp(vec,n); free(vec); return 0; }
eace2c5f932803d0847fc1ab9c99504e383afb2e.cu
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; __global__ void insert(int *a, int t){ int i = blockIdx.x*blockDim.x+threadIdx.x; int cont = 0; while(cont <= i*10000){ cont++; } if(i < t){ for(int k = 0; k < t-1; k++){ if(a[k] > a[k+1]){ int aux = a[k]; a[k] = a[k+1]; a[k+1] = aux; } } } } void imp(int *a, int n){ for(int i = 0; i < n; i++){ cout << a[i]<<endl; } cout<<endl<<endl; } void cuda(int *a, int n){ int *array; cudaMalloc((void**)&array, n * sizeof(int)); cudaMemcpy(array,a,n * sizeof(int),cudaMemcpyHostToDevice); insert<<<1024,1>>>(array,n); cudaMemcpy(a,array,n * sizeof(int),cudaMemcpyDeviceToHost); cudaFree(array); } int main(){ int n; cin >> n; int a[n]; int *vec; vec = (int*)malloc(n*sizeof(int)); for(int i = 0; i < n; i++){ cin >> a[i]; vec[i] = a[i]; } cuda(vec,n); imp(vec,n); free(vec); return 0; }
86413b812f652c13170ed7a8ecbd489452bde42a.hip
// !!! This is a file automatically generated by hipify!!! #include <stdbool.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <hiprand/hiprand_kernel.h> #include <stdlib.h> #include <hip/hip_runtime.h> #include <sys/time.h> #include "histogram_privatized_kernel.cu" #include<chrono> #include<iostream> using namespace std; using namespace std::chrono; int blocks_[20][2] = {{8,8},{16,16},{24,24},{32,32},{1,64},{1,128},{1,192},{1,256},{1,320},{1,384},{1,448},{1,512},{1,576},{1,640},{1,704},{1,768},{1,832},{1,896},{1,960},{1,1024}}; int matrices_[7][2] = {{240,240},{496,496},{784,784},{1016,1016},{1232,1232},{1680,1680},{2024,2024}}; int main(int argc, char **argv) { hipSetDevice(0); char* p;int matrix_len=strtol(argv[1], &p, 10); for(int matrix_looper=0;matrix_looper<matrix_len;matrix_looper++){ for(int block_looper=0;block_looper<20;block_looper++){ int XSIZE=matrices_[matrix_looper][0],YSIZE=matrices_[matrix_looper][1],BLOCKX=blocks_[block_looper][0],BLOCKY=blocks_[block_looper][1]; unsigned char *input = NULL; hipMalloc(&input, XSIZE*YSIZE); unsigned int *bins = NULL; hipMalloc(&bins, XSIZE*YSIZE); unsigned int num_elements = 1; unsigned int num_bins = 1; int iXSIZE= XSIZE; int iYSIZE= YSIZE; while(iXSIZE%BLOCKX!=0) { iXSIZE++; } while(iYSIZE%BLOCKY!=0) { iYSIZE++; } dim3 gridBlock(iXSIZE/BLOCKX, iYSIZE/BLOCKY); dim3 threadBlock(BLOCKX, BLOCKY); hipFree(0);hipLaunchKernelGGL(( histogram_privatized_kernel), dim3(gridBlock),dim3(threadBlock), 0, 0, input,bins,num_elements,num_bins); hipDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) {hipLaunchKernelGGL(( histogram_privatized_kernel), dim3(gridBlock),dim3(threadBlock), 0, 0, input,bins,num_elements,num_bins); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) {hipLaunchKernelGGL(( histogram_privatized_kernel), dim3(gridBlock),dim3(threadBlock), 0, 0, input,bins,num_elements,num_bins); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
86413b812f652c13170ed7a8ecbd489452bde42a.cu
#include <stdbool.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <curand_kernel.h> #include <stdlib.h> #include <cuda.h> #include <sys/time.h> #include "histogram_privatized_kernel.cu" #include<chrono> #include<iostream> using namespace std; using namespace std::chrono; int blocks_[20][2] = {{8,8},{16,16},{24,24},{32,32},{1,64},{1,128},{1,192},{1,256},{1,320},{1,384},{1,448},{1,512},{1,576},{1,640},{1,704},{1,768},{1,832},{1,896},{1,960},{1,1024}}; int matrices_[7][2] = {{240,240},{496,496},{784,784},{1016,1016},{1232,1232},{1680,1680},{2024,2024}}; int main(int argc, char **argv) { cudaSetDevice(0); char* p;int matrix_len=strtol(argv[1], &p, 10); for(int matrix_looper=0;matrix_looper<matrix_len;matrix_looper++){ for(int block_looper=0;block_looper<20;block_looper++){ int XSIZE=matrices_[matrix_looper][0],YSIZE=matrices_[matrix_looper][1],BLOCKX=blocks_[block_looper][0],BLOCKY=blocks_[block_looper][1]; unsigned char *input = NULL; cudaMalloc(&input, XSIZE*YSIZE); unsigned int *bins = NULL; cudaMalloc(&bins, XSIZE*YSIZE); unsigned int num_elements = 1; unsigned int num_bins = 1; int iXSIZE= XSIZE; int iYSIZE= YSIZE; while(iXSIZE%BLOCKX!=0) { iXSIZE++; } while(iYSIZE%BLOCKY!=0) { iYSIZE++; } dim3 gridBlock(iXSIZE/BLOCKX, iYSIZE/BLOCKY); dim3 threadBlock(BLOCKX, BLOCKY); cudaFree(0); histogram_privatized_kernel<<<gridBlock,threadBlock>>>(input,bins,num_elements,num_bins); cudaDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) { histogram_privatized_kernel<<<gridBlock,threadBlock>>>(input,bins,num_elements,num_bins); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) { histogram_privatized_kernel<<<gridBlock,threadBlock>>>(input,bins,num_elements,num_bins); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
e9bc07d77a9b3b378104f89059af43d6b6cb454b.hip
// !!! This is a file automatically generated by hipify!!! // teststring.cpp : // /* * Copyright 1993-2009 NVIDIA Corporation. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property and * proprietary rights in and to this software and related documentation and * any modifications thereto. Any use, reproduction, disclosure, or distribution * of this software and related documentation without an express license * agreement from NVIDIA Corporation is strictly prohibited. * */ /* #include <stdio.h> #include <stdlib.h> #include <cutil_inline.h> */ #include "test.hip" // This example shows how to use the clock function to measure the performance of // a kernel accurately. // // Blocks are executed in parallel and out of order. Since there's no synchronization // mechanism between blocks, we measure the clock once for each block. The clock // samples are written to device memory. #define NUM_BLOCKS 64 #define NUM_THREADS 256 // It's interesting to change the number of blocks and the number of threads to // understand how to keep the hardware busy. // // Here are some numbers I get on my G80: // blocks - clocks // 1 - 3096 // 8 - 3232 // 16 - 3364 // 32 - 4615 // 64 - 9981 // // With less than 16 blocks some of the multiprocessors of the device are idle. With // more than 16 you are using all the multiprocessors, but there's only one block per // multiprocessor and that doesn't allow you to hide the latency of the memory. With // more than 32 the speed scales linearly. int main(int argc, char** argv) { callCuda(); system("pause"); // use command-line specified CUDA device, otherwise use device with highest Gflops/s /* if ( cutCheckCmdLineFlag(argc, (const char **)argv, "device")) cutilDeviceInit(argc, argv); else hipSetDevice( cutGetMaxGflopsDeviceId() ); float * dinput = NULL; float * doutput = NULL; clock_t * dtimer = NULL; clock_t timer[NUM_BLOCKS * 2]; float input[NUM_THREADS * 2]; for (int i = 0; i < NUM_THREADS * 2; i++) { input[i] = (float)i; } cutilSafeCall(hipMalloc((void**)&dinput, sizeof(float) * NUM_THREADS * 2)); cutilSafeCall(hipMalloc((void**)&doutput, sizeof(float) * NUM_BLOCKS)); cutilSafeCall(hipMalloc((void**)&dtimer, sizeof(clock_t) * NUM_BLOCKS * 2)); cutilSafeCall(hipMemcpy(dinput, input, sizeof(float) * NUM_THREADS * 2, hipMemcpyHostToDevice)); timedReduction<<<NUM_BLOCKS, NUM_THREADS, sizeof(float) * 2 * NUM_THREADS>>>(dinput, doutput, dtimer); //cutilSafeCall(hipMemcpy(output, doutput, sizeof(float) * NUM_BLOCKS, hipMemcpyDeviceToHost)); cutilSafeCall(hipMemcpy(timer, dtimer, sizeof(clock_t) * NUM_BLOCKS * 2, hipMemcpyDeviceToHost)); cutilSafeCall(hipFree(dinput)); cutilSafeCall(hipFree(doutput)); cutilSafeCall(hipFree(dtimer)); // This test always passes. printf( "Test PASSED\n"); // Compute the difference between the last block end and the first block start. clock_t minStart = timer[0]; clock_t maxEnd = timer[NUM_BLOCKS]; for (int i = 1; i < NUM_BLOCKS; i++) { minStart = timer[i] < minStart ? timer[i] : minStart; maxEnd = timer[NUM_BLOCKS+i] > maxEnd ? timer[NUM_BLOCKS+i] : maxEnd; } printf("time = %d\n", maxEnd - minStart); hipDeviceReset(); cutilExit(argc, argv);*/ }
e9bc07d77a9b3b378104f89059af43d6b6cb454b.cu
// teststring.cpp : 定义控制台应用程序的入口点。 // /* * Copyright 1993-2009 NVIDIA Corporation. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property and * proprietary rights in and to this software and related documentation and * any modifications thereto. Any use, reproduction, disclosure, or distribution * of this software and related documentation without an express license * agreement from NVIDIA Corporation is strictly prohibited. * */ /* #include <stdio.h> #include <stdlib.h> #include <cutil_inline.h> */ #include "test.cu" // This example shows how to use the clock function to measure the performance of // a kernel accurately. // // Blocks are executed in parallel and out of order. Since there's no synchronization // mechanism between blocks, we measure the clock once for each block. The clock // samples are written to device memory. #define NUM_BLOCKS 64 #define NUM_THREADS 256 // It's interesting to change the number of blocks and the number of threads to // understand how to keep the hardware busy. // // Here are some numbers I get on my G80: // blocks - clocks // 1 - 3096 // 8 - 3232 // 16 - 3364 // 32 - 4615 // 64 - 9981 // // With less than 16 blocks some of the multiprocessors of the device are idle. With // more than 16 you are using all the multiprocessors, but there's only one block per // multiprocessor and that doesn't allow you to hide the latency of the memory. With // more than 32 the speed scales linearly. int main(int argc, char** argv) { callCuda(); system("pause"); // use command-line specified CUDA device, otherwise use device with highest Gflops/s /* if ( cutCheckCmdLineFlag(argc, (const char **)argv, "device")) cutilDeviceInit(argc, argv); else cudaSetDevice( cutGetMaxGflopsDeviceId() ); float * dinput = NULL; float * doutput = NULL; clock_t * dtimer = NULL; clock_t timer[NUM_BLOCKS * 2]; float input[NUM_THREADS * 2]; for (int i = 0; i < NUM_THREADS * 2; i++) { input[i] = (float)i; } cutilSafeCall(cudaMalloc((void**)&dinput, sizeof(float) * NUM_THREADS * 2)); cutilSafeCall(cudaMalloc((void**)&doutput, sizeof(float) * NUM_BLOCKS)); cutilSafeCall(cudaMalloc((void**)&dtimer, sizeof(clock_t) * NUM_BLOCKS * 2)); cutilSafeCall(cudaMemcpy(dinput, input, sizeof(float) * NUM_THREADS * 2, cudaMemcpyHostToDevice)); timedReduction<<<NUM_BLOCKS, NUM_THREADS, sizeof(float) * 2 * NUM_THREADS>>>(dinput, doutput, dtimer); //cutilSafeCall(cudaMemcpy(output, doutput, sizeof(float) * NUM_BLOCKS, cudaMemcpyDeviceToHost)); cutilSafeCall(cudaMemcpy(timer, dtimer, sizeof(clock_t) * NUM_BLOCKS * 2, cudaMemcpyDeviceToHost)); cutilSafeCall(cudaFree(dinput)); cutilSafeCall(cudaFree(doutput)); cutilSafeCall(cudaFree(dtimer)); // This test always passes. printf( "Test PASSED\n"); // Compute the difference between the last block end and the first block start. clock_t minStart = timer[0]; clock_t maxEnd = timer[NUM_BLOCKS]; for (int i = 1; i < NUM_BLOCKS; i++) { minStart = timer[i] < minStart ? timer[i] : minStart; maxEnd = timer[NUM_BLOCKS+i] > maxEnd ? timer[NUM_BLOCKS+i] : maxEnd; } printf("time = %d\n", maxEnd - minStart); cudaThreadExit(); cutilExit(argc, argv);*/ }
b0a0c1e4ca00023a42ec777f31a5ecc948c3af79.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <iostream> __global__ void mult_mat_vec_kernel(float* d_A, float* d_B, float* d_C, int n) { int idx = threadIdx.x + blockDim.x * blockIdx.x; if (idx < n) { int idx1 = idx * n; float sum = 0.0; for (int i = 0; i < n; ++i) { sum += d_A[idx1 + i] * d_B[i]; } d_C[idx] = sum; } } void mult_mat_vec(float* h_A, float* h_B, float* h_C, int n) { float *d_A, *d_B, *d_C; int size_mat = n * n * sizeof(float); hipMalloc((void **) &d_A, size_mat); hipMemcpy(d_A, h_A, size_mat, hipMemcpyHostToDevice); int size_vec = n * sizeof(float); hipMalloc((void **) &d_B, size_vec); hipMemcpy(d_B, h_B, size_vec, hipMemcpyHostToDevice); hipMalloc((void **) &d_C, size_vec); dim3 dimGrid(ceil(n/16.0), 1, 1); dim3 dimBlock(16, 1, 1); hipLaunchKernelGGL(( mult_mat_vec_kernel), dim3(dimGrid), dim3(dimBlock), 0, 0, d_A, d_B, d_C, n); hipMemcpy(h_C, d_C, size_vec, hipMemcpyDeviceToHost); hipFree(d_A); hipFree(d_B); hipFree(d_B); } void print_vec(float* m, int n) { for (int j = 0; j < n; ++j) { std::cout << m[j] << " "; } std::cout << "\n"; } void print_mat(float* m, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { std::cout << m[i*n + j] << " "; } std::cout << "\n"; } } int main() { int n = 4; float *h_A = new float[n*n]; float *h_B = new float[n]; float *h_C = new float[n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { h_A[i*n + j] = i; } } for (int i = 0; i < n; ++i) { h_B[i] = i; } mult_mat_vec(h_A, h_B, h_C, n); print_mat(h_A, n); std::cout << "\n"; print_vec(h_B, n); std::cout << "\n"; print_vec(h_C, n); delete[] h_A; delete[] h_B; delete[] h_C; return 0; }
b0a0c1e4ca00023a42ec777f31a5ecc948c3af79.cu
#include <iostream> __global__ void mult_mat_vec_kernel(float* d_A, float* d_B, float* d_C, int n) { int idx = threadIdx.x + blockDim.x * blockIdx.x; if (idx < n) { int idx1 = idx * n; float sum = 0.0; for (int i = 0; i < n; ++i) { sum += d_A[idx1 + i] * d_B[i]; } d_C[idx] = sum; } } void mult_mat_vec(float* h_A, float* h_B, float* h_C, int n) { float *d_A, *d_B, *d_C; int size_mat = n * n * sizeof(float); cudaMalloc((void **) &d_A, size_mat); cudaMemcpy(d_A, h_A, size_mat, cudaMemcpyHostToDevice); int size_vec = n * sizeof(float); cudaMalloc((void **) &d_B, size_vec); cudaMemcpy(d_B, h_B, size_vec, cudaMemcpyHostToDevice); cudaMalloc((void **) &d_C, size_vec); dim3 dimGrid(ceil(n/16.0), 1, 1); dim3 dimBlock(16, 1, 1); mult_mat_vec_kernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C, n); cudaMemcpy(h_C, d_C, size_vec, cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_B); cudaFree(d_B); } void print_vec(float* m, int n) { for (int j = 0; j < n; ++j) { std::cout << m[j] << " "; } std::cout << "\n"; } void print_mat(float* m, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { std::cout << m[i*n + j] << " "; } std::cout << "\n"; } } int main() { int n = 4; float *h_A = new float[n*n]; float *h_B = new float[n]; float *h_C = new float[n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { h_A[i*n + j] = i; } } for (int i = 0; i < n; ++i) { h_B[i] = i; } mult_mat_vec(h_A, h_B, h_C, n); print_mat(h_A, n); std::cout << "\n"; print_vec(h_B, n); std::cout << "\n"; print_vec(h_C, n); delete[] h_A; delete[] h_B; delete[] h_C; return 0; }
37b1394315d646177cd3dcd1b9287c498fa152b6.hip
// !!! This is a file automatically generated by hipify!!! #pragma once #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <iostream> #include "include/tensor/tensor.hpp" #include "include/tensor/tensor_span.hpp" #include "include/cuda/kernels/pointwise/multiply.cuh" #include "include/tensor/tensor_random.hpp" #include "include/cuda/tensor/cuda_funcs.cuh" #include "include/cublas/cublas_funcs.cuh" #include "include/tensor/debug/print.hpp" #include "rocblas.h" #include "cublas_api.h" #include "include/ai/lstm/lstm.hpp" #include <fstream> #include <unordered_map> #include <set> #include <iostream> int main() { std::fstream input_data; input_data.open("C:/Users/1019l/Desktop/pbw/PaperbackWriter/tests/data.txt"); std::set<char> unique_buffer = { std::istreambuf_iterator<char>(input_data), std::istreambuf_iterator<char>() }; std::unordered_map<char, std::size_t> data_map; for (std::set<char>::iterator index = unique_buffer.begin(); index != unique_buffer.end(); ++index) { data_map.insert({ *index,std::distance(unique_buffer.begin(),index) }); } std::cout << "UNIQUE CHARACTERS: " << data_map.size() << std::endl; int unique_chars = data_map.size(); char vals[89]; for (auto elem : data_map) { vals[elem.second] = elem.first; } std::vector<int> positions; char ch; std::fstream fin("C:/Users/1019l/Desktop/pbw/PaperbackWriter/tests/data.txt", std::fstream::in); while (fin >> std::noskipws >> ch) { positions.push_back(data_map.at(ch)); } lstm network; size_t counter = 0; size_t epoch = 0; while (true) { if ((counter + 101 > positions.size())) { counter = 0; epoch++; } for (int i = 1; i < 101; i++) { float * input = new float[89]; std::fill(&input[0], input + 89, 0); input[positions.at(counter + i - 1)] = 1; network.forward(input, i); } for (int k = 100; k > 0; k--) { float * target = new float[89]; std::fill(&target[0], target + 89, 0); target[positions.at(counter + k)] = 1; network.backward(target, k); } network.clip(); network.updateweights(); network.updatebiases(); network.copy_states(); network.reset_delta_next(); counter += 100; if ((counter % 10000) == 0) { std::cout << "----------------------------" << std::endl; std::cout << "EPOCH: " << epoch << std::endl; std::cout << "ITERATION: " << counter << std::endl; std::cout << "----------------------------" << std::endl; network.sample(1000, vals); } } std::cin.get(); return 0; }
37b1394315d646177cd3dcd1b9287c498fa152b6.cu
#pragma once #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <iostream> #include "include/tensor/tensor.hpp" #include "include/tensor/tensor_span.hpp" #include "include/cuda/kernels/pointwise/multiply.cuh" #include "include/tensor/tensor_random.hpp" #include "include/cuda/tensor/cuda_funcs.cuh" #include "include/cublas/cublas_funcs.cuh" #include "include/tensor/debug/print.hpp" #include "cublas_v2.h" #include "cublas_api.h" #include "include/ai/lstm/lstm.hpp" #include <fstream> #include <unordered_map> #include <set> #include <iostream> int main() { std::fstream input_data; input_data.open("C:/Users/1019l/Desktop/pbw/PaperbackWriter/tests/data.txt"); std::set<char> unique_buffer = { std::istreambuf_iterator<char>(input_data), std::istreambuf_iterator<char>() }; std::unordered_map<char, std::size_t> data_map; for (std::set<char>::iterator index = unique_buffer.begin(); index != unique_buffer.end(); ++index) { data_map.insert({ *index,std::distance(unique_buffer.begin(),index) }); } std::cout << "UNIQUE CHARACTERS: " << data_map.size() << std::endl; int unique_chars = data_map.size(); char vals[89]; for (auto elem : data_map) { vals[elem.second] = elem.first; } std::vector<int> positions; char ch; std::fstream fin("C:/Users/1019l/Desktop/pbw/PaperbackWriter/tests/data.txt", std::fstream::in); while (fin >> std::noskipws >> ch) { positions.push_back(data_map.at(ch)); } lstm network; size_t counter = 0; size_t epoch = 0; while (true) { if ((counter + 101 > positions.size())) { counter = 0; epoch++; } for (int i = 1; i < 101; i++) { float * input = new float[89]; std::fill(&input[0], input + 89, 0); input[positions.at(counter + i - 1)] = 1; network.forward(input, i); } for (int k = 100; k > 0; k--) { float * target = new float[89]; std::fill(&target[0], target + 89, 0); target[positions.at(counter + k)] = 1; network.backward(target, k); } network.clip(); network.updateweights(); network.updatebiases(); network.copy_states(); network.reset_delta_next(); counter += 100; if ((counter % 10000) == 0) { std::cout << "----------------------------" << std::endl; std::cout << "EPOCH: " << epoch << std::endl; std::cout << "ITERATION: " << counter << std::endl; std::cout << "----------------------------" << std::endl; network.sample(1000, vals); } } std::cin.get(); return 0; }
81508cf9743f8a64d567adce39a2072534c05625.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include "Header.h" #define NUM_THREADS_IN_BLOCK 1000 hipError_t pointsOrgenaizeCuda(Cluster* clusters, Point *points, const int n, const int k, bool *flag); hipError_t Error(Point* dev_points, Cluster* dev_clusters, bool* dev_flags); __device__ double distanceCuda(double x1, double y1, double x2, double y2) { return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); } __global__ void organizePointsKernel(Cluster *clusters, Point *points, bool *flags, const int k, const int n) { double min = DBL_MAX; int minIdx; int i = blockIdx.x; int j = threadIdx.x; int idx = NUM_THREADS_IN_BLOCK * i + j; if (idx < n) { for (int l = 0; l < k; l++) { double tempDistance = distanceCuda(points[idx].x, points[idx].y, clusters[l].centerX, clusters[l].centerY); if (tempDistance < min) { minIdx = l; min = tempDistance; } } if (points[idx].myCluster != minIdx) flags[idx] = true; points[idx].myCluster = minIdx; } } int cudaOrganizePoints(Cluster* clusters, Point* points, int n, int k, bool *flag) { *flag = false; // Add vectors in parallel. hipError_t cudaStatus = pointsOrgenaizeCuda(clusters,points, n, k, flag); if (cudaStatus != hipSuccess) { fprintf(stderr, "addWithCuda failed!"); return 1; } // hipDeviceReset must be called before exiting in order for profiling and // tracing tools such as Nsight and Visual Profiler to show complete traces. cudaStatus = hipDeviceReset(); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipDeviceReset failed!"); return 1; } return 0; } // Helper function for using CUDA to add vectors in parallel. hipError_t pointsOrgenaizeCuda(Cluster* clusters, Point *points, const int n, const int k, bool *flag) { Cluster *dev_clusters = 0; Point *dev_points = 0; hipError_t cudaStatus; int numOfBlocks; if(n % NUM_THREADS_IN_BLOCK == 0) numOfBlocks = n / NUM_THREADS_IN_BLOCK; else numOfBlocks = n / NUM_THREADS_IN_BLOCK + 1; bool* dev_flags; bool* flags = (bool*)malloc(n * sizeof(bool)); for (int i = 0; i < n; i++) { flags[i] = false; } // Choose which GPU to run on, change this on a multi-GPU system. cudaStatus = hipSetDevice(0); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipSetDevice failed! Do you have a CUDA-capable GPU installed?"); //goto Error; Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = hipMalloc((void**)&dev_points, n * sizeof(Point)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = hipMalloc((void**)&dev_clusters, k * sizeof(Cluster)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = hipMalloc((void**)&dev_flags, n * sizeof(bool)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy input vectors from host memory to GPU buffers. cudaStatus = hipMemcpy(dev_flags, flags, n * sizeof(bool), hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy input vectors from host memory to GPU buffers. cudaStatus = hipMemcpy(dev_points, points, n * sizeof(Point), hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy input vectors from host memory to GPU buffers. cudaStatus = hipMemcpy(dev_clusters, clusters, k * sizeof(Cluster), hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Launch a kernel on the GPU with one thread for each element. hipLaunchKernelGGL(( organizePointsKernel) , dim3(numOfBlocks), dim3(NUM_THREADS_IN_BLOCK) , 0, 0, dev_clusters, dev_points, dev_flags, k,n); // Check for any errors launching the kernel cudaStatus = hipGetLastError(); if (cudaStatus != hipSuccess) { fprintf(stderr, "addKernel launch failed: %s\n", hipGetErrorString(cudaStatus)); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // hipDeviceSynchronize waits for the kernel to finish, and returns // any errors encountered during the launch. cudaStatus = hipDeviceSynchronize(); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy output vector from GPU buffer to host memory. cudaStatus = hipMemcpy(points, dev_points, n * sizeof(Point), hipMemcpyDeviceToHost); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy output vector from GPU buffer to host memory. cudaStatus = hipMemcpy(clusters, dev_clusters, k * sizeof(Cluster), hipMemcpyDeviceToHost); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy output vector from GPU buffer to host memory. cudaStatus = hipMemcpy(flags, dev_flags, n * sizeof(bool), hipMemcpyDeviceToHost); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } for (int i = 0; i < n; i++) { if (flags[i] == true) { *flag = true; break; } } return Error(dev_points, dev_clusters, dev_flags); } hipError_t Error(Point* dev_points, Cluster* dev_clusters, bool* dev_flags) { hipError_t cudaStatus; cudaStatus = hipFree(dev_points); if (cudaStatus != hipSuccess) fprintf(stderr, "hipFree failed!"); cudaStatus = hipFree(dev_clusters); if (cudaStatus != hipSuccess) fprintf(stderr, "hipFree failed!"); cudaStatus = hipFree(dev_flags); if (cudaStatus != hipSuccess) fprintf(stderr, "hipFree failed!"); return cudaStatus; }
81508cf9743f8a64d567adce39a2072534c05625.cu
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include "Header.h" #define NUM_THREADS_IN_BLOCK 1000 cudaError_t pointsOrgenaizeCuda(Cluster* clusters, Point *points, const int n, const int k, bool *flag); cudaError_t Error(Point* dev_points, Cluster* dev_clusters, bool* dev_flags); __device__ double distanceCuda(double x1, double y1, double x2, double y2) { return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); } __global__ void organizePointsKernel(Cluster *clusters, Point *points, bool *flags, const int k, const int n) { double min = DBL_MAX; int minIdx; int i = blockIdx.x; int j = threadIdx.x; int idx = NUM_THREADS_IN_BLOCK * i + j; if (idx < n) { for (int l = 0; l < k; l++) { double tempDistance = distanceCuda(points[idx].x, points[idx].y, clusters[l].centerX, clusters[l].centerY); if (tempDistance < min) { minIdx = l; min = tempDistance; } } if (points[idx].myCluster != minIdx) flags[idx] = true; points[idx].myCluster = minIdx; } } int cudaOrganizePoints(Cluster* clusters, Point* points, int n, int k, bool *flag) { *flag = false; // Add vectors in parallel. cudaError_t cudaStatus = pointsOrgenaizeCuda(clusters,points, n, k, flag); if (cudaStatus != cudaSuccess) { fprintf(stderr, "addWithCuda failed!"); return 1; } // cudaDeviceReset must be called before exiting in order for profiling and // tracing tools such as Nsight and Visual Profiler to show complete traces. cudaStatus = cudaDeviceReset(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaDeviceReset failed!"); return 1; } return 0; } // Helper function for using CUDA to add vectors in parallel. cudaError_t pointsOrgenaizeCuda(Cluster* clusters, Point *points, const int n, const int k, bool *flag) { Cluster *dev_clusters = 0; Point *dev_points = 0; cudaError_t cudaStatus; int numOfBlocks; if(n % NUM_THREADS_IN_BLOCK == 0) numOfBlocks = n / NUM_THREADS_IN_BLOCK; else numOfBlocks = n / NUM_THREADS_IN_BLOCK + 1; bool* dev_flags; bool* flags = (bool*)malloc(n * sizeof(bool)); for (int i = 0; i < n; i++) { flags[i] = false; } // Choose which GPU to run on, change this on a multi-GPU system. cudaStatus = cudaSetDevice(0); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?"); //goto Error; Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&dev_points, n * sizeof(Point)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&dev_clusters, k * sizeof(Cluster)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&dev_flags, n * sizeof(bool)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy input vectors from host memory to GPU buffers. cudaStatus = cudaMemcpy(dev_flags, flags, n * sizeof(bool), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy input vectors from host memory to GPU buffers. cudaStatus = cudaMemcpy(dev_points, points, n * sizeof(Point), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy input vectors from host memory to GPU buffers. cudaStatus = cudaMemcpy(dev_clusters, clusters, k * sizeof(Cluster), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Launch a kernel on the GPU with one thread for each element. organizePointsKernel <<<numOfBlocks, NUM_THREADS_IN_BLOCK >>>(dev_clusters, dev_points, dev_flags, k,n); // Check for any errors launching the kernel cudaStatus = cudaGetLastError(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus)); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // cudaDeviceSynchronize waits for the kernel to finish, and returns // any errors encountered during the launch. cudaStatus = cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy output vector from GPU buffer to host memory. cudaStatus = cudaMemcpy(points, dev_points, n * sizeof(Point), cudaMemcpyDeviceToHost); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy output vector from GPU buffer to host memory. cudaStatus = cudaMemcpy(clusters, dev_clusters, k * sizeof(Cluster), cudaMemcpyDeviceToHost); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } // Copy output vector from GPU buffer to host memory. cudaStatus = cudaMemcpy(flags, dev_flags, n * sizeof(bool), cudaMemcpyDeviceToHost); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); Error(dev_points, dev_clusters, dev_flags); return cudaStatus; } for (int i = 0; i < n; i++) { if (flags[i] == true) { *flag = true; break; } } return Error(dev_points, dev_clusters, dev_flags); } cudaError_t Error(Point* dev_points, Cluster* dev_clusters, bool* dev_flags) { cudaError_t cudaStatus; cudaStatus = cudaFree(dev_points); if (cudaStatus != cudaSuccess) fprintf(stderr, "cudaFree failed!"); cudaStatus = cudaFree(dev_clusters); if (cudaStatus != cudaSuccess) fprintf(stderr, "cudaFree failed!"); cudaStatus = cudaFree(dev_flags); if (cudaStatus != cudaSuccess) fprintf(stderr, "cudaFree failed!"); return cudaStatus; }
83d72131fa4498a87bedebe1017d6df8c6da2c91.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // -------------------------------------------------------- // Written by Bharat Singh, 2017. // -------------------------------------------------------- #include <algorithm> #include <cfloat> #include <vector> #include "caffe/layers/psroi_pooling_layer.hpp" #include "caffe/util/gpu_util.cuh" using std::max; using std::min; namespace caffe { template <typename Dtype> __global__ void PSROIPoolingForward( const int nthreads, const Dtype* bottom_data, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const Dtype* bottom_rois, const int output_dim, const int group_size, Dtype* top_data, int* mapping_channel) { CUDA_KERNEL_LOOP(index, nthreads) { // The output is in order (n, ctop, ph, pw) int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int ctop = (index / pooled_width / pooled_height) % output_dim; int n = index / pooled_width / pooled_height / output_dim; // [start, end) interval for spatial sampling bottom_rois += n * 5; int roi_batch_ind = bottom_rois[0]; Dtype roi_start_w = bottom_rois[1] * spatial_scale; Dtype roi_start_h = bottom_rois[2] * spatial_scale; Dtype roi_end_w = bottom_rois[3] * spatial_scale; Dtype roi_end_h = bottom_rois[4] * spatial_scale; Dtype roi_width = roi_end_w - roi_start_w; Dtype roi_height = roi_end_h - roi_start_h; // Compute w and h at bottom Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height); Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width); // bin size is ratio of scaled roi height and 7,14, so it would be around 1,2,3 //ph, pw is the position in the roi //therefore, we need use, bin size and ph to get the position of the 4 feature values int x1, x2, y1, y2; float px, py, pxmax, pymax, pxmin, pymin; pxmax = min(max(roi_start_w + static_cast<Dtype>(pw + 0.75) * bin_size_w, 0.001), width - 1.001); pymax = min(max(roi_start_h + static_cast<Dtype>(ph + 0.75) * bin_size_h, 0.001), height - 1.001); pxmin = min(max(roi_start_w + static_cast<Dtype>(pw + 0.25) * bin_size_w, 0.001), width - 1.001); pymin = min(max(roi_start_h + static_cast<Dtype>(ph + 0.25) * bin_size_h, 0.001), height - 1.001); Dtype out_sum = 0; int gw = pw; int gh = ph; int c = (ctop*group_size + gh)*group_size + gw; bottom_data += (roi_batch_ind * channels + c) * height * width; px = pxmin; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; px = pxmax; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; px = pxmin; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; px = pxmax; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; top_data[index] = out_sum/4; mapping_channel[index] = c; } } template <typename Dtype> void PSROIPoolingLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); const Dtype* bottom_rois = bottom[1]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); int* mapping_channel_ptr = mapping_channel_.mutable_gpu_data(); int count = top[0]->count(); caffe_gpu_set(count, Dtype(0), top_data); caffe_gpu_set(count, -1, mapping_channel_ptr); // NOLINT_NEXT_LINE(whitespace/operators) PSROIPoolingForward<Dtype> << <CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS >> >(count, bottom_data, spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, bottom_rois, output_dim_, group_size_, top_data, mapping_channel_ptr); CUDA_POST_KERNEL_CHECK; } template <typename Dtype> __global__ void PSROIPoolingBackwardAtomic( const int nthreads, const Dtype* top_diff, const int* mapping_channel, const int num_rois, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int output_dim, Dtype* bottom_diff, const Dtype* bottom_rois) { CUDA_KERNEL_LOOP(index, nthreads) { // The output is in order (n, ctop, ph, pw) int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int n = index / pooled_width / pooled_height / output_dim; // [start, end) interval for spatial sampling bottom_rois += n * 5; int roi_batch_ind = bottom_rois[0]; Dtype roi_start_w = bottom_rois[1] * spatial_scale; Dtype roi_start_h = bottom_rois[2] * spatial_scale; Dtype roi_end_w = bottom_rois[3] * spatial_scale; Dtype roi_end_h = bottom_rois[4] * spatial_scale; Dtype roi_width = roi_end_w - roi_start_w; Dtype roi_height = roi_end_h - roi_start_h; // Compute w and h at bottom Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height); Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width); int x1, x2, y1, y2 ; float pxmin, pymin, pxmax, pymax, py, px; pxmax = min(max(roi_start_w + static_cast<Dtype>(pw + 0.75) * bin_size_w, 0.001), width - 1.001); pymax = min(max(roi_start_h + static_cast<Dtype>(ph + 0.75) * bin_size_h, 0.001), height - 1.001); pxmin = min(max(roi_start_w + static_cast<Dtype>(pw + 0.25) * bin_size_w, 0.001), width - 1.001); pymin = min(max(roi_start_h + static_cast<Dtype>(ph + 0.25) * bin_size_h, 0.001), height - 1.001); // Compute c at bottom int c = mapping_channel[index]; Dtype* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels + c) * height * width; Dtype diff_val = 0; diff_val = top_diff[index]/4; px = pxmin; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); px = pxmax; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); px = pxmin; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); px = pxmax; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); } } template <typename Dtype> void PSROIPoolingLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } const Dtype* bottom_rois = bottom[1]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int bottom_count = bottom[0]->count(); const int* mapping_channel_ptr = mapping_channel_.gpu_data(); caffe_gpu_set(bottom[1]->count(), Dtype(0), bottom[1]->mutable_gpu_diff()); caffe_gpu_set(bottom_count, Dtype(0), bottom_diff); const int count = top[0]->count(); // NOLINT_NEXT_LINE(whitespace/operators) PSROIPoolingBackwardAtomic<Dtype> << <CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS >> >(count, top_diff, mapping_channel_ptr, top[0]->num(), spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, output_dim_, bottom_diff, bottom_rois); CUDA_POST_KERNEL_CHECK; } INSTANTIATE_LAYER_GPU_FUNCS(PSROIPoolingLayer); } // namespace caffe
83d72131fa4498a87bedebe1017d6df8c6da2c91.cu
// -------------------------------------------------------- // Written by Bharat Singh, 2017. // -------------------------------------------------------- #include <algorithm> #include <cfloat> #include <vector> #include "caffe/layers/psroi_pooling_layer.hpp" #include "caffe/util/gpu_util.cuh" using std::max; using std::min; namespace caffe { template <typename Dtype> __global__ void PSROIPoolingForward( const int nthreads, const Dtype* bottom_data, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const Dtype* bottom_rois, const int output_dim, const int group_size, Dtype* top_data, int* mapping_channel) { CUDA_KERNEL_LOOP(index, nthreads) { // The output is in order (n, ctop, ph, pw) int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int ctop = (index / pooled_width / pooled_height) % output_dim; int n = index / pooled_width / pooled_height / output_dim; // [start, end) interval for spatial sampling bottom_rois += n * 5; int roi_batch_ind = bottom_rois[0]; Dtype roi_start_w = bottom_rois[1] * spatial_scale; Dtype roi_start_h = bottom_rois[2] * spatial_scale; Dtype roi_end_w = bottom_rois[3] * spatial_scale; Dtype roi_end_h = bottom_rois[4] * spatial_scale; Dtype roi_width = roi_end_w - roi_start_w; Dtype roi_height = roi_end_h - roi_start_h; // Compute w and h at bottom Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height); Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width); // bin size is ratio of scaled roi height and 7,14, so it would be around 1,2,3 //ph, pw is the position in the roi //therefore, we need use, bin size and ph to get the position of the 4 feature values int x1, x2, y1, y2; float px, py, pxmax, pymax, pxmin, pymin; pxmax = min(max(roi_start_w + static_cast<Dtype>(pw + 0.75) * bin_size_w, 0.001), width - 1.001); pymax = min(max(roi_start_h + static_cast<Dtype>(ph + 0.75) * bin_size_h, 0.001), height - 1.001); pxmin = min(max(roi_start_w + static_cast<Dtype>(pw + 0.25) * bin_size_w, 0.001), width - 1.001); pymin = min(max(roi_start_h + static_cast<Dtype>(ph + 0.25) * bin_size_h, 0.001), height - 1.001); Dtype out_sum = 0; int gw = pw; int gh = ph; int c = (ctop*group_size + gh)*group_size + gw; bottom_data += (roi_batch_ind * channels + c) * height * width; px = pxmin; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; px = pxmax; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; px = pxmin; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; px = pxmax; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); out_sum += (px-x1)*(py-y1) * bottom_data[int(y2*width + x2)]; out_sum += (px-x1)*(y2-py) * bottom_data[int(y1*width + x2)]; out_sum += (x2-px)*(py-y1) * bottom_data[int(y2*width + x1)]; out_sum += (x2-px)*(y2-py) * bottom_data[int(y1*width + x1)]; top_data[index] = out_sum/4; mapping_channel[index] = c; } } template <typename Dtype> void PSROIPoolingLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); const Dtype* bottom_rois = bottom[1]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); int* mapping_channel_ptr = mapping_channel_.mutable_gpu_data(); int count = top[0]->count(); caffe_gpu_set(count, Dtype(0), top_data); caffe_gpu_set(count, -1, mapping_channel_ptr); // NOLINT_NEXT_LINE(whitespace/operators) PSROIPoolingForward<Dtype> << <CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS >> >(count, bottom_data, spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, bottom_rois, output_dim_, group_size_, top_data, mapping_channel_ptr); CUDA_POST_KERNEL_CHECK; } template <typename Dtype> __global__ void PSROIPoolingBackwardAtomic( const int nthreads, const Dtype* top_diff, const int* mapping_channel, const int num_rois, const Dtype spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width, const int output_dim, Dtype* bottom_diff, const Dtype* bottom_rois) { CUDA_KERNEL_LOOP(index, nthreads) { // The output is in order (n, ctop, ph, pw) int pw = index % pooled_width; int ph = (index / pooled_width) % pooled_height; int n = index / pooled_width / pooled_height / output_dim; // [start, end) interval for spatial sampling bottom_rois += n * 5; int roi_batch_ind = bottom_rois[0]; Dtype roi_start_w = bottom_rois[1] * spatial_scale; Dtype roi_start_h = bottom_rois[2] * spatial_scale; Dtype roi_end_w = bottom_rois[3] * spatial_scale; Dtype roi_end_h = bottom_rois[4] * spatial_scale; Dtype roi_width = roi_end_w - roi_start_w; Dtype roi_height = roi_end_h - roi_start_h; // Compute w and h at bottom Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height); Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width); int x1, x2, y1, y2 ; float pxmin, pymin, pxmax, pymax, py, px; pxmax = min(max(roi_start_w + static_cast<Dtype>(pw + 0.75) * bin_size_w, 0.001), width - 1.001); pymax = min(max(roi_start_h + static_cast<Dtype>(ph + 0.75) * bin_size_h, 0.001), height - 1.001); pxmin = min(max(roi_start_w + static_cast<Dtype>(pw + 0.25) * bin_size_w, 0.001), width - 1.001); pymin = min(max(roi_start_h + static_cast<Dtype>(ph + 0.25) * bin_size_h, 0.001), height - 1.001); // Compute c at bottom int c = mapping_channel[index]; Dtype* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels + c) * height * width; Dtype diff_val = 0; diff_val = top_diff[index]/4; px = pxmin; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); px = pxmax; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); px = pxmin; py = pymax; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); px = pxmax; py = pymin; x1 = floor(px); x2 = ceil(px); y1 = floor(py); y2 = ceil(py); caffe_gpu_atomic_add(diff_val * (px-x1)*(py-y1), offset_bottom_diff + int(y2*width + x2)); caffe_gpu_atomic_add(diff_val * (px-x1)*(y2-py), offset_bottom_diff + int(y1*width + x2)); caffe_gpu_atomic_add(diff_val * (x2-px)*(py-y1), offset_bottom_diff + int(y2*width + x1)); caffe_gpu_atomic_add(diff_val * (x2-px)*(y2-py), offset_bottom_diff + int(y1*width + x1)); } } template <typename Dtype> void PSROIPoolingLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } const Dtype* bottom_rois = bottom[1]->gpu_data(); const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int bottom_count = bottom[0]->count(); const int* mapping_channel_ptr = mapping_channel_.gpu_data(); caffe_gpu_set(bottom[1]->count(), Dtype(0), bottom[1]->mutable_gpu_diff()); caffe_gpu_set(bottom_count, Dtype(0), bottom_diff); const int count = top[0]->count(); // NOLINT_NEXT_LINE(whitespace/operators) PSROIPoolingBackwardAtomic<Dtype> << <CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS >> >(count, top_diff, mapping_channel_ptr, top[0]->num(), spatial_scale_, channels_, height_, width_, pooled_height_, pooled_width_, output_dim_, bottom_diff, bottom_rois); CUDA_POST_KERNEL_CHECK; } INSTANTIATE_LAYER_GPU_FUNCS(PSROIPoolingLayer); } // namespace caffe
6c874c38aa073c42b19b5054863e88e96127f0eb.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <algorithm> #include <cfloat> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> __global__ void SoftmaxLossForwardGPU(const int nthreads, const Dtype* prob_data, const Dtype* label, Dtype* loss, const int num, const int dim, const int spatial_dim, const bool has_ignore_label_, const int ignore_label_, Dtype* counts) { CUDA_KERNEL_LOOP(index, nthreads) { const int n = index / spatial_dim; const int s = index % spatial_dim; //const int label_value = static_cast<int>(label[n * spatial_dim + s]); const int label_value = static_cast<int>(label[(n * spatial_dim + s) * 2 + 1]); if (has_ignore_label_ && label_value == ignore_label_) { loss[index] = 0; counts[index] = 0; } else { loss[index] = -log(max(prob_data[n * dim + label_value * spatial_dim + s], Dtype(FLT_MIN))); counts[index] = 1; } } } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Forward_gpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_); const Dtype* prob_data = prob_.gpu_data(); const Dtype* label = bottom[1]->gpu_data(); const int dim = prob_.count() / outer_num_; const int nthreads = outer_num_ * inner_num_; // Since this memory is not used for anything until it is overwritten // on the backward pass, we use it here to avoid having to allocate new GPU // memory to accumulate intermediate results in the kernel. Dtype* loss_data = bottom[0]->mutable_gpu_diff(); // Similarly, this memory is never used elsewhere, and thus we can use it // to avoid having to allocate additional GPU memory. Dtype* counts = prob_.mutable_gpu_diff(); // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( SoftmaxLossForwardGPU<Dtype>), dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, nthreads, prob_data, label, loss_data, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); Dtype loss; caffe_gpu_asum(nthreads, loss_data, &loss); if (normalize_) { Dtype count; caffe_gpu_asum(nthreads, counts, &count); loss /= (count > 0 ? count : Dtype(1)); } else { loss /= outer_num_; } top[0]->mutable_cpu_data()[0] = loss; if (top.size() == 2) { top[1]->ShareData(prob_); } } template <typename Dtype> __global__ void SoftmaxLossBackwardGPU(const int nthreads, const Dtype* top, const Dtype* label, Dtype* bottom_diff, const int num, const int dim, const int spatial_dim, const bool has_ignore_label_, const int ignore_label_, Dtype* counts) { const int channels = dim / spatial_dim; CUDA_KERNEL_LOOP(index, nthreads) { const int n = index / spatial_dim; const int s = index % spatial_dim; //const int label_value = static_cast<int>(label[n * spatial_dim + s]); const int label_value = static_cast<int>(label[(n * spatial_dim + s) * 2 + 1]); if (has_ignore_label_ && label_value == ignore_label_) { for (int c = 0; c < channels; ++c) { bottom_diff[n * dim + c * spatial_dim + s] = 0; } counts[index] = 0; } else { bottom_diff[n * dim + label_value * spatial_dim + s] -= 1; counts[index] = 1; } } } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const Dtype* prob_data = prob_.gpu_data(); const Dtype* top_data = top[0]->gpu_data(); caffe_gpu_memcpy(prob_.count() * sizeof(Dtype), prob_data, bottom_diff); const Dtype* label = bottom[1]->gpu_data(); const int dim = prob_.count() / outer_num_; const int nthreads = outer_num_ * inner_num_; // Since this memory is never used for anything else, // we use to to avoid allocating new GPU memory. Dtype* counts = prob_.mutable_gpu_diff(); // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( SoftmaxLossBackwardGPU<Dtype>), dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, nthreads, top_data, label, bottom_diff, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); const Dtype loss_weight = top[0]->cpu_diff()[0]; if (normalize_) { Dtype count; caffe_gpu_asum(nthreads, counts, &count); caffe_gpu_scal(prob_.count(), loss_weight / (count > 0 ? count : Dtype(1)), bottom_diff); } else { caffe_gpu_scal(prob_.count(), loss_weight / outer_num_, bottom_diff); } } } INSTANTIATE_LAYER_GPU_FUNCS(SoftmaxWithLossLayer); } // namespace caffe
6c874c38aa073c42b19b5054863e88e96127f0eb.cu
#include <algorithm> #include <cfloat> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> __global__ void SoftmaxLossForwardGPU(const int nthreads, const Dtype* prob_data, const Dtype* label, Dtype* loss, const int num, const int dim, const int spatial_dim, const bool has_ignore_label_, const int ignore_label_, Dtype* counts) { CUDA_KERNEL_LOOP(index, nthreads) { const int n = index / spatial_dim; const int s = index % spatial_dim; //const int label_value = static_cast<int>(label[n * spatial_dim + s]); const int label_value = static_cast<int>(label[(n * spatial_dim + s) * 2 + 1]); if (has_ignore_label_ && label_value == ignore_label_) { loss[index] = 0; counts[index] = 0; } else { loss[index] = -log(max(prob_data[n * dim + label_value * spatial_dim + s], Dtype(FLT_MIN))); counts[index] = 1; } } } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Forward_gpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_); const Dtype* prob_data = prob_.gpu_data(); const Dtype* label = bottom[1]->gpu_data(); const int dim = prob_.count() / outer_num_; const int nthreads = outer_num_ * inner_num_; // Since this memory is not used for anything until it is overwritten // on the backward pass, we use it here to avoid having to allocate new GPU // memory to accumulate intermediate results in the kernel. Dtype* loss_data = bottom[0]->mutable_gpu_diff(); // Similarly, this memory is never used elsewhere, and thus we can use it // to avoid having to allocate additional GPU memory. Dtype* counts = prob_.mutable_gpu_diff(); // NOLINT_NEXT_LINE(whitespace/operators) SoftmaxLossForwardGPU<Dtype><<<CAFFE_GET_BLOCKS(nthreads), CAFFE_CUDA_NUM_THREADS>>>(nthreads, prob_data, label, loss_data, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); Dtype loss; caffe_gpu_asum(nthreads, loss_data, &loss); if (normalize_) { Dtype count; caffe_gpu_asum(nthreads, counts, &count); loss /= (count > 0 ? count : Dtype(1)); } else { loss /= outer_num_; } top[0]->mutable_cpu_data()[0] = loss; if (top.size() == 2) { top[1]->ShareData(prob_); } } template <typename Dtype> __global__ void SoftmaxLossBackwardGPU(const int nthreads, const Dtype* top, const Dtype* label, Dtype* bottom_diff, const int num, const int dim, const int spatial_dim, const bool has_ignore_label_, const int ignore_label_, Dtype* counts) { const int channels = dim / spatial_dim; CUDA_KERNEL_LOOP(index, nthreads) { const int n = index / spatial_dim; const int s = index % spatial_dim; //const int label_value = static_cast<int>(label[n * spatial_dim + s]); const int label_value = static_cast<int>(label[(n * spatial_dim + s) * 2 + 1]); if (has_ignore_label_ && label_value == ignore_label_) { for (int c = 0; c < channels; ++c) { bottom_diff[n * dim + c * spatial_dim + s] = 0; } counts[index] = 0; } else { bottom_diff[n * dim + label_value * spatial_dim + s] -= 1; counts[index] = 1; } } } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const Dtype* prob_data = prob_.gpu_data(); const Dtype* top_data = top[0]->gpu_data(); caffe_gpu_memcpy(prob_.count() * sizeof(Dtype), prob_data, bottom_diff); const Dtype* label = bottom[1]->gpu_data(); const int dim = prob_.count() / outer_num_; const int nthreads = outer_num_ * inner_num_; // Since this memory is never used for anything else, // we use to to avoid allocating new GPU memory. Dtype* counts = prob_.mutable_gpu_diff(); // NOLINT_NEXT_LINE(whitespace/operators) SoftmaxLossBackwardGPU<Dtype><<<CAFFE_GET_BLOCKS(nthreads), CAFFE_CUDA_NUM_THREADS>>>(nthreads, top_data, label, bottom_diff, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); const Dtype loss_weight = top[0]->cpu_diff()[0]; if (normalize_) { Dtype count; caffe_gpu_asum(nthreads, counts, &count); caffe_gpu_scal(prob_.count(), loss_weight / (count > 0 ? count : Dtype(1)), bottom_diff); } else { caffe_gpu_scal(prob_.count(), loss_weight / outer_num_, bottom_diff); } } } INSTANTIATE_LAYER_GPU_FUNCS(SoftmaxWithLossLayer); } // namespace caffe
84a13882b27eed7a07f175dac62cde53bfa8f9f5.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" //note: please do not modify this file manually! // this file has been generated automatically by BOAST version 0.99996 // by: make boast_kernels /* !===================================================================== ! ! S p e c f e m 3 D G l o b e V e r s i o n 7 . 0 ! -------------------------------------------------- ! ! Main historical authors: Dimitri Komatitsch and Jeroen Tromp ! Princeton University, USA ! and CNRS / University of Marseille, France ! (there are currently many more authors!) ! (c) Princeton University and CNRS / University of Marseille, April 2014 ! ! This program is free software; you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation; either version 2 of the License, or ! (at your option) any later version. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License along ! with this program; if not, write to the Free Software Foundation, Inc., ! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ! !===================================================================== */ #ifndef INDEX2 #define INDEX2(isize,i,j) i + isize*j #endif #ifndef INDEX3 #define INDEX3(isize,jsize,i,j,k) i + isize*(j + jsize*k) #endif #ifndef INDEX4 #define INDEX4(isize,jsize,ksize,i,j,k,x) i + isize*(j + jsize*(k + ksize*x)) #endif #ifndef INDEX5 #define INDEX5(isize,jsize,ksize,xsize,i,j,k,x,y) i + isize*(j + jsize*(k + ksize*(x + xsize*y))) #endif #ifndef NDIM #define NDIM 3 #endif #ifndef NGLLX #define NGLLX 5 #endif #ifndef NGLL2 #define NGLL2 25 #endif #ifndef NGLL3 #define NGLL3 125 #endif #ifndef NGLL3_PADDED #define NGLL3_PADDED 128 #endif #ifndef N_SLS #define N_SLS 3 #endif #ifndef IREGION_CRUST_MANTLE #define IREGION_CRUST_MANTLE 1 #endif #ifndef IREGION_INNER_CORE #define IREGION_INNER_CORE 3 #endif #ifndef IFLAG_IN_FICTITIOUS_CUBE #define IFLAG_IN_FICTITIOUS_CUBE 11 #endif #ifndef R_EARTH_KM #define R_EARTH_KM 6371.0f #endif #ifndef COLORING_MIN_NSPEC_INNER_CORE #define COLORING_MIN_NSPEC_INNER_CORE 1000 #endif #ifndef COLORING_MIN_NSPEC_OUTER_CORE #define COLORING_MIN_NSPEC_OUTER_CORE 1000 #endif #ifndef BLOCKSIZE_TRANSFER #define BLOCKSIZE_TRANSFER 256 #endif __global__ void compute_rho_kernel(const int * ibool, const float * accel, const float * b_displ, float * rho_kl, const int NSPEC, const float deltat){ int ispec; int ijk_ispec; int iglob; ispec = blockIdx.x + (blockIdx.y) * (gridDim.x); if (ispec < NSPEC) { ijk_ispec = threadIdx.x + (NGLL3) * (ispec); iglob = ibool[ijk_ispec] - (1); rho_kl[ijk_ispec] = rho_kl[ijk_ispec] + (deltat) * ((accel[0 + (3) * (iglob)]) * (b_displ[0 + (3) * (iglob)]) + (accel[1 + (3) * (iglob)]) * (b_displ[1 + (3) * (iglob)]) + (accel[2 + (3) * (iglob)]) * (b_displ[2 + (3) * (iglob)])); } }
84a13882b27eed7a07f175dac62cde53bfa8f9f5.cu
//note: please do not modify this file manually! // this file has been generated automatically by BOAST version 0.99996 // by: make boast_kernels /* !===================================================================== ! ! S p e c f e m 3 D G l o b e V e r s i o n 7 . 0 ! -------------------------------------------------- ! ! Main historical authors: Dimitri Komatitsch and Jeroen Tromp ! Princeton University, USA ! and CNRS / University of Marseille, France ! (there are currently many more authors!) ! (c) Princeton University and CNRS / University of Marseille, April 2014 ! ! This program is free software; you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation; either version 2 of the License, or ! (at your option) any later version. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License along ! with this program; if not, write to the Free Software Foundation, Inc., ! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ! !===================================================================== */ #ifndef INDEX2 #define INDEX2(isize,i,j) i + isize*j #endif #ifndef INDEX3 #define INDEX3(isize,jsize,i,j,k) i + isize*(j + jsize*k) #endif #ifndef INDEX4 #define INDEX4(isize,jsize,ksize,i,j,k,x) i + isize*(j + jsize*(k + ksize*x)) #endif #ifndef INDEX5 #define INDEX5(isize,jsize,ksize,xsize,i,j,k,x,y) i + isize*(j + jsize*(k + ksize*(x + xsize*y))) #endif #ifndef NDIM #define NDIM 3 #endif #ifndef NGLLX #define NGLLX 5 #endif #ifndef NGLL2 #define NGLL2 25 #endif #ifndef NGLL3 #define NGLL3 125 #endif #ifndef NGLL3_PADDED #define NGLL3_PADDED 128 #endif #ifndef N_SLS #define N_SLS 3 #endif #ifndef IREGION_CRUST_MANTLE #define IREGION_CRUST_MANTLE 1 #endif #ifndef IREGION_INNER_CORE #define IREGION_INNER_CORE 3 #endif #ifndef IFLAG_IN_FICTITIOUS_CUBE #define IFLAG_IN_FICTITIOUS_CUBE 11 #endif #ifndef R_EARTH_KM #define R_EARTH_KM 6371.0f #endif #ifndef COLORING_MIN_NSPEC_INNER_CORE #define COLORING_MIN_NSPEC_INNER_CORE 1000 #endif #ifndef COLORING_MIN_NSPEC_OUTER_CORE #define COLORING_MIN_NSPEC_OUTER_CORE 1000 #endif #ifndef BLOCKSIZE_TRANSFER #define BLOCKSIZE_TRANSFER 256 #endif __global__ void compute_rho_kernel(const int * ibool, const float * accel, const float * b_displ, float * rho_kl, const int NSPEC, const float deltat){ int ispec; int ijk_ispec; int iglob; ispec = blockIdx.x + (blockIdx.y) * (gridDim.x); if (ispec < NSPEC) { ijk_ispec = threadIdx.x + (NGLL3) * (ispec); iglob = ibool[ijk_ispec] - (1); rho_kl[ijk_ispec] = rho_kl[ijk_ispec] + (deltat) * ((accel[0 + (3) * (iglob)]) * (b_displ[0 + (3) * (iglob)]) + (accel[1 + (3) * (iglob)]) * (b_displ[1 + (3) * (iglob)]) + (accel[2 + (3) * (iglob)]) * (b_displ[2 + (3) * (iglob)])); } }
0e4b5da5fd18a629152f5ccab48329514a30b4d9.hip
// !!! This is a file automatically generated by hipify!!! /* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. * */ // Graph analytics features // Author: Alex Fender afender@nvidia.com #include <cugraph.h> #include "graph_utils.cuh" #include "pagerank.cuh" #include "COOtoCSR.cuh" #include "utilities/error_utils.h" #include "bfs.cuh" #include <rmm_utils.h> void gdf_col_delete(gdf_column* col) { if (col) { col->size = 0; if(col->data) { ALLOC_FREE_TRY(col->data, nullptr); } delete col; col->data = nullptr; col = nullptr; } } void gdf_col_release(gdf_column* col) { delete col; } void cpy_column_view(const gdf_column *in, gdf_column *out) { if (in != nullptr && out !=nullptr) { gdf_column_view(out, in->data, in->valid, in->size, in->dtype); } } gdf_error gdf_adj_list_view(gdf_graph *graph, const gdf_column *offsets, const gdf_column *indices, const gdf_column *edge_data) { GDF_REQUIRE( offsets->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( (offsets->dtype == indices->dtype), GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( ((offsets->dtype == GDF_INT32) || (offsets->dtype == GDF_INT64)), GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( (offsets->size > 0), GDF_DATASET_EMPTY ); GDF_REQUIRE( (graph->adjList == nullptr) , GDF_INVALID_API_CALL); graph->adjList = new gdf_adj_list; graph->adjList->offsets = new gdf_column; graph->adjList->indices = new gdf_column; graph->adjList->ownership = 0; cpy_column_view(offsets, graph->adjList->offsets); cpy_column_view(indices, graph->adjList->indices); if (edge_data) { GDF_REQUIRE( indices->size == edge_data->size, GDF_COLUMN_SIZE_MISMATCH ); graph->adjList->edge_data = new gdf_column; cpy_column_view(edge_data, graph->adjList->edge_data); } else { graph->adjList->edge_data = nullptr; } return GDF_SUCCESS; } gdf_error gdf_adj_list::get_vertex_identifiers(gdf_column *identifiers) { GDF_REQUIRE( offsets != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( offsets->data != nullptr , GDF_INVALID_API_CALL); cugraph::sequence<int>((int)offsets->size-1, (int*)identifiers->data); return GDF_SUCCESS; } gdf_error gdf_adj_list::get_source_indices (gdf_column *src_indices) { GDF_REQUIRE( offsets != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( offsets->data != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( src_indices->size == indices->size, GDF_COLUMN_SIZE_MISMATCH ); GDF_REQUIRE( src_indices->dtype == indices->dtype, GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( src_indices->size > 0, GDF_DATASET_EMPTY ); cugraph::offsets_to_indices<int>((int*)offsets->data, offsets->size-1, (int*)src_indices->data); return GDF_SUCCESS; } gdf_error gdf_edge_list_view(gdf_graph *graph, const gdf_column *src_indices, const gdf_column *dest_indices, const gdf_column *edge_data) { GDF_REQUIRE( src_indices->size == dest_indices->size, GDF_COLUMN_SIZE_MISMATCH ); GDF_REQUIRE( src_indices->dtype == dest_indices->dtype, GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( ((src_indices->dtype == GDF_INT32) || (src_indices->dtype == GDF_INT64)), GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( src_indices->size > 0, GDF_DATASET_EMPTY ); GDF_REQUIRE( src_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( dest_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( graph->edgeList == nullptr , GDF_INVALID_API_CALL); graph->edgeList = new gdf_edge_list; graph->edgeList->src_indices = new gdf_column; graph->edgeList->dest_indices = new gdf_column; graph->edgeList->ownership = 0; cpy_column_view(src_indices, graph->edgeList->src_indices); cpy_column_view(dest_indices, graph->edgeList->dest_indices); if (edge_data) { GDF_REQUIRE( src_indices->size == edge_data->size, GDF_COLUMN_SIZE_MISMATCH ); graph->edgeList->edge_data = new gdf_column; cpy_column_view(edge_data, graph->edgeList->edge_data); } else { graph->edgeList->edge_data = nullptr; } return GDF_SUCCESS; } template <typename WT> gdf_error gdf_add_adj_list_impl (gdf_graph *graph) { if (graph->adjList == nullptr) { GDF_REQUIRE( graph->edgeList != nullptr , GDF_INVALID_API_CALL); int nnz = graph->edgeList->src_indices->size, status = 0; graph->adjList = new gdf_adj_list; graph->adjList->offsets = new gdf_column; graph->adjList->indices = new gdf_column; graph->adjList->ownership = 1; if (graph->edgeList->edge_data!= nullptr) { graph->adjList->edge_data = new gdf_column; CSR_Result_Weighted<int,WT> adj_list; status = ConvertCOOtoCSR_weighted((int*)graph->edgeList->src_indices->data, (int*)graph->edgeList->dest_indices->data, (WT*)graph->edgeList->edge_data->data, nnz, adj_list); gdf_column_view(graph->adjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->adjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); gdf_column_view(graph->adjList->edge_data, adj_list.edgeWeights, nullptr, adj_list.nnz, graph->edgeList->edge_data->dtype); } else { CSR_Result<int> adj_list; status = ConvertCOOtoCSR((int*)graph->edgeList->src_indices->data,(int*)graph->edgeList->dest_indices->data, nnz, adj_list); gdf_column_view(graph->adjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->adjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); } if (status !=0) { std::cerr << "Could not generate the adj_list" << std::endl; return GDF_CUDA_ERROR; } } return GDF_SUCCESS; } gdf_error gdf_add_edge_list (gdf_graph *graph) { if (graph->edgeList == nullptr) { GDF_REQUIRE( graph->adjList != nullptr , GDF_INVALID_API_CALL); int *d_src; graph->edgeList = new gdf_edge_list; graph->edgeList->src_indices = new gdf_column; graph->edgeList->dest_indices = new gdf_column; graph->edgeList->ownership = 2; CUDA_TRY(hipMallocManaged ((void**)&d_src, sizeof(int) * graph->adjList->indices->size)); cugraph::offsets_to_indices<int>((int*)graph->adjList->offsets->data, graph->adjList->offsets->size-1, (int*)d_src); gdf_column_view(graph->edgeList->src_indices, d_src, nullptr, graph->adjList->indices->size, graph->adjList->indices->dtype); cpy_column_view(graph->adjList->indices, graph->edgeList->dest_indices); if (graph->adjList->edge_data != nullptr) { graph->edgeList->edge_data = new gdf_column; cpy_column_view(graph->adjList->edge_data, graph->edgeList->edge_data); } } return GDF_SUCCESS; } template <typename WT> gdf_error gdf_add_transpose_impl (gdf_graph *graph) { if (graph->transposedAdjList == nullptr ) { GDF_REQUIRE( graph->edgeList != nullptr , GDF_INVALID_API_CALL); int nnz = graph->edgeList->src_indices->size, status = 0; graph->transposedAdjList = new gdf_adj_list; graph->transposedAdjList->offsets = new gdf_column; graph->transposedAdjList->indices = new gdf_column; graph->transposedAdjList->ownership = 1; if (graph->edgeList->edge_data) { graph->transposedAdjList->edge_data = new gdf_column; CSR_Result_Weighted<int,WT> adj_list; status = ConvertCOOtoCSR_weighted( (int*)graph->edgeList->dest_indices->data, (int*)graph->edgeList->src_indices->data, (WT*)graph->edgeList->edge_data->data, nnz, adj_list); gdf_column_view(graph->transposedAdjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->transposedAdjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); gdf_column_view(graph->transposedAdjList->edge_data, adj_list.edgeWeights, nullptr, adj_list.nnz, graph->edgeList->edge_data->dtype); } else { CSR_Result<int> adj_list; status = ConvertCOOtoCSR((int*)graph->edgeList->dest_indices->data, (int*)graph->edgeList->src_indices->data, nnz, adj_list); gdf_column_view(graph->transposedAdjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->transposedAdjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); } if (status !=0) { std::cerr << "Could not generate the adj_list" << std::endl; return GDF_CUDA_ERROR; } } return GDF_SUCCESS; } template <typename WT> gdf_error gdf_pagerank_impl (gdf_graph *graph, gdf_column *pagerank, float alpha = 0.85, float tolerance = 1e-4, int max_iter = 200, bool has_guess = false) { GDF_REQUIRE( graph->edgeList != nullptr, GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( graph->edgeList->src_indices->size == graph->edgeList->dest_indices->size, GDF_COLUMN_SIZE_MISMATCH ); GDF_REQUIRE( graph->edgeList->src_indices->dtype == graph->edgeList->dest_indices->dtype, GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( graph->edgeList->src_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( graph->edgeList->dest_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( pagerank != nullptr , GDF_INVALID_API_CALL ); GDF_REQUIRE( pagerank->data != nullptr , GDF_INVALID_API_CALL ); GDF_REQUIRE( pagerank->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( pagerank->size > 0 , GDF_INVALID_API_CALL ); int m=pagerank->size, nnz = graph->edgeList->src_indices->size, status = 0; WT *d_pr, *d_val = nullptr, *d_leaf_vector = nullptr; WT res = 1.0; WT *residual = &res; if (graph->transposedAdjList == nullptr) { gdf_add_transpose(graph); } hipStream_t stream{nullptr}; ALLOC_MANAGED_TRY((void**)&d_leaf_vector, sizeof(WT) * m, stream); ALLOC_MANAGED_TRY((void**)&d_val, sizeof(WT) * nnz , stream); ALLOC_MANAGED_TRY((void**)&d_pr, sizeof(WT) * m, stream); cugraph::HT_matrix_csc_coo(m, nnz, (int*)graph->transposedAdjList->offsets->data, (int*)graph->transposedAdjList->indices->data, d_val, d_leaf_vector); if (has_guess) { GDF_REQUIRE( pagerank->data != nullptr, GDF_VALIDITY_UNSUPPORTED ); cugraph::copy<WT>(m, (WT*)pagerank->data, d_pr); } status = cugraph::pagerank<int,WT>( m,nnz, (int*)graph->transposedAdjList->offsets->data, (int*)graph->transposedAdjList->indices->data, d_val, alpha, d_leaf_vector, false, tolerance, max_iter, d_pr, residual); if (status !=0) switch ( status ) { case -1: std::cerr<< "Error : bad parameters in Pagerank"<<std::endl; return GDF_CUDA_ERROR; case 1: std::cerr<< "Warning : Pagerank did not reached the desired tolerance"<<std::endl; return GDF_CUDA_ERROR; default: std::cerr<< "Pagerank failed"<<std::endl; return GDF_CUDA_ERROR; } cugraph::copy<WT>(m, d_pr, (WT*)pagerank->data); ALLOC_FREE_TRY(d_val, stream); ALLOC_FREE_TRY(d_pr, stream); ALLOC_FREE_TRY(d_leaf_vector, stream); return GDF_SUCCESS; } gdf_error gdf_add_adj_list(gdf_graph *graph) { if (graph->adjList != nullptr) return GDF_SUCCESS; GDF_REQUIRE( graph->edgeList != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( graph->adjList == nullptr , GDF_INVALID_API_CALL); if (graph->edgeList->edge_data != nullptr) { switch (graph->edgeList->edge_data->dtype) { case GDF_FLOAT32: return gdf_add_adj_list_impl<float>(graph); case GDF_FLOAT64: return gdf_add_adj_list_impl<double>(graph); default: return GDF_UNSUPPORTED_DTYPE; } } else { return gdf_add_adj_list_impl<float>(graph); } } gdf_error gdf_add_transpose(gdf_graph *graph) { if (graph->edgeList == nullptr) gdf_add_edge_list(graph); if (graph->edgeList->edge_data != nullptr) { switch (graph->edgeList->edge_data->dtype) { case GDF_FLOAT32: return gdf_add_transpose_impl<float>(graph); case GDF_FLOAT64: return gdf_add_transpose_impl<double>(graph); default: return GDF_UNSUPPORTED_DTYPE; } } else { return gdf_add_transpose_impl<float>(graph); } } gdf_error gdf_delete_adj_list(gdf_graph *graph) { if (graph->adjList) { delete graph->adjList; } graph->adjList = nullptr; return GDF_SUCCESS; } gdf_error gdf_delete_edge_list(gdf_graph *graph) { if (graph->edgeList) { delete graph->edgeList; } graph->edgeList = nullptr; return GDF_SUCCESS; } gdf_error gdf_delete_transpose(gdf_graph *graph) { if (graph->transposedAdjList) { delete graph->transposedAdjList; } graph->transposedAdjList = nullptr; return GDF_SUCCESS; } gdf_error gdf_pagerank(gdf_graph *graph, gdf_column *pagerank, float alpha, float tolerance, int max_iter, bool has_guess) { switch (pagerank->dtype) { case GDF_FLOAT32: return gdf_pagerank_impl<float>(graph, pagerank, alpha, tolerance, max_iter, has_guess); case GDF_FLOAT64: return gdf_pagerank_impl<double>(graph, pagerank, alpha, tolerance, max_iter, has_guess); default: return GDF_UNSUPPORTED_DTYPE; } } gdf_error gdf_bfs(gdf_graph *graph, gdf_column *distances, gdf_column *predecessors, int start_node, bool directed) { GDF_REQUIRE(graph->adjList != nullptr, GDF_VALIDITY_UNSUPPORTED); GDF_REQUIRE(graph->adjList->offsets->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); GDF_REQUIRE(graph->adjList->indices->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); GDF_REQUIRE(distances->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); GDF_REQUIRE(predecessors->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); int n = graph->adjList->offsets->size - 1; int e = graph->adjList->indices->size; int* offsets_ptr = (int*)graph->adjList->offsets->data; int* indices_ptr = (int*)graph->adjList->indices->data; int* distances_ptr = (int*)distances->data; int* predecessors_ptr = (int*)predecessors->data; int alpha = 15; int beta = 18; cugraph::Bfs<int> bfs(n, e, offsets_ptr, indices_ptr, directed, alpha, beta); bfs.configure(distances_ptr, predecessors_ptr, nullptr); bfs.traverse(start_node); return GDF_SUCCESS; }
0e4b5da5fd18a629152f5ccab48329514a30b4d9.cu
/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. * */ // Graph analytics features // Author: Alex Fender afender@nvidia.com #include <cugraph.h> #include "graph_utils.cuh" #include "pagerank.cuh" #include "COOtoCSR.cuh" #include "utilities/error_utils.h" #include "bfs.cuh" #include <rmm_utils.h> void gdf_col_delete(gdf_column* col) { if (col) { col->size = 0; if(col->data) { ALLOC_FREE_TRY(col->data, nullptr); } delete col; col->data = nullptr; col = nullptr; } } void gdf_col_release(gdf_column* col) { delete col; } void cpy_column_view(const gdf_column *in, gdf_column *out) { if (in != nullptr && out !=nullptr) { gdf_column_view(out, in->data, in->valid, in->size, in->dtype); } } gdf_error gdf_adj_list_view(gdf_graph *graph, const gdf_column *offsets, const gdf_column *indices, const gdf_column *edge_data) { GDF_REQUIRE( offsets->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( (offsets->dtype == indices->dtype), GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( ((offsets->dtype == GDF_INT32) || (offsets->dtype == GDF_INT64)), GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( (offsets->size > 0), GDF_DATASET_EMPTY ); GDF_REQUIRE( (graph->adjList == nullptr) , GDF_INVALID_API_CALL); graph->adjList = new gdf_adj_list; graph->adjList->offsets = new gdf_column; graph->adjList->indices = new gdf_column; graph->adjList->ownership = 0; cpy_column_view(offsets, graph->adjList->offsets); cpy_column_view(indices, graph->adjList->indices); if (edge_data) { GDF_REQUIRE( indices->size == edge_data->size, GDF_COLUMN_SIZE_MISMATCH ); graph->adjList->edge_data = new gdf_column; cpy_column_view(edge_data, graph->adjList->edge_data); } else { graph->adjList->edge_data = nullptr; } return GDF_SUCCESS; } gdf_error gdf_adj_list::get_vertex_identifiers(gdf_column *identifiers) { GDF_REQUIRE( offsets != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( offsets->data != nullptr , GDF_INVALID_API_CALL); cugraph::sequence<int>((int)offsets->size-1, (int*)identifiers->data); return GDF_SUCCESS; } gdf_error gdf_adj_list::get_source_indices (gdf_column *src_indices) { GDF_REQUIRE( offsets != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( offsets->data != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( src_indices->size == indices->size, GDF_COLUMN_SIZE_MISMATCH ); GDF_REQUIRE( src_indices->dtype == indices->dtype, GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( src_indices->size > 0, GDF_DATASET_EMPTY ); cugraph::offsets_to_indices<int>((int*)offsets->data, offsets->size-1, (int*)src_indices->data); return GDF_SUCCESS; } gdf_error gdf_edge_list_view(gdf_graph *graph, const gdf_column *src_indices, const gdf_column *dest_indices, const gdf_column *edge_data) { GDF_REQUIRE( src_indices->size == dest_indices->size, GDF_COLUMN_SIZE_MISMATCH ); GDF_REQUIRE( src_indices->dtype == dest_indices->dtype, GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( ((src_indices->dtype == GDF_INT32) || (src_indices->dtype == GDF_INT64)), GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( src_indices->size > 0, GDF_DATASET_EMPTY ); GDF_REQUIRE( src_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( dest_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( graph->edgeList == nullptr , GDF_INVALID_API_CALL); graph->edgeList = new gdf_edge_list; graph->edgeList->src_indices = new gdf_column; graph->edgeList->dest_indices = new gdf_column; graph->edgeList->ownership = 0; cpy_column_view(src_indices, graph->edgeList->src_indices); cpy_column_view(dest_indices, graph->edgeList->dest_indices); if (edge_data) { GDF_REQUIRE( src_indices->size == edge_data->size, GDF_COLUMN_SIZE_MISMATCH ); graph->edgeList->edge_data = new gdf_column; cpy_column_view(edge_data, graph->edgeList->edge_data); } else { graph->edgeList->edge_data = nullptr; } return GDF_SUCCESS; } template <typename WT> gdf_error gdf_add_adj_list_impl (gdf_graph *graph) { if (graph->adjList == nullptr) { GDF_REQUIRE( graph->edgeList != nullptr , GDF_INVALID_API_CALL); int nnz = graph->edgeList->src_indices->size, status = 0; graph->adjList = new gdf_adj_list; graph->adjList->offsets = new gdf_column; graph->adjList->indices = new gdf_column; graph->adjList->ownership = 1; if (graph->edgeList->edge_data!= nullptr) { graph->adjList->edge_data = new gdf_column; CSR_Result_Weighted<int,WT> adj_list; status = ConvertCOOtoCSR_weighted((int*)graph->edgeList->src_indices->data, (int*)graph->edgeList->dest_indices->data, (WT*)graph->edgeList->edge_data->data, nnz, adj_list); gdf_column_view(graph->adjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->adjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); gdf_column_view(graph->adjList->edge_data, adj_list.edgeWeights, nullptr, adj_list.nnz, graph->edgeList->edge_data->dtype); } else { CSR_Result<int> adj_list; status = ConvertCOOtoCSR((int*)graph->edgeList->src_indices->data,(int*)graph->edgeList->dest_indices->data, nnz, adj_list); gdf_column_view(graph->adjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->adjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); } if (status !=0) { std::cerr << "Could not generate the adj_list" << std::endl; return GDF_CUDA_ERROR; } } return GDF_SUCCESS; } gdf_error gdf_add_edge_list (gdf_graph *graph) { if (graph->edgeList == nullptr) { GDF_REQUIRE( graph->adjList != nullptr , GDF_INVALID_API_CALL); int *d_src; graph->edgeList = new gdf_edge_list; graph->edgeList->src_indices = new gdf_column; graph->edgeList->dest_indices = new gdf_column; graph->edgeList->ownership = 2; CUDA_TRY(cudaMallocManaged ((void**)&d_src, sizeof(int) * graph->adjList->indices->size)); cugraph::offsets_to_indices<int>((int*)graph->adjList->offsets->data, graph->adjList->offsets->size-1, (int*)d_src); gdf_column_view(graph->edgeList->src_indices, d_src, nullptr, graph->adjList->indices->size, graph->adjList->indices->dtype); cpy_column_view(graph->adjList->indices, graph->edgeList->dest_indices); if (graph->adjList->edge_data != nullptr) { graph->edgeList->edge_data = new gdf_column; cpy_column_view(graph->adjList->edge_data, graph->edgeList->edge_data); } } return GDF_SUCCESS; } template <typename WT> gdf_error gdf_add_transpose_impl (gdf_graph *graph) { if (graph->transposedAdjList == nullptr ) { GDF_REQUIRE( graph->edgeList != nullptr , GDF_INVALID_API_CALL); int nnz = graph->edgeList->src_indices->size, status = 0; graph->transposedAdjList = new gdf_adj_list; graph->transposedAdjList->offsets = new gdf_column; graph->transposedAdjList->indices = new gdf_column; graph->transposedAdjList->ownership = 1; if (graph->edgeList->edge_data) { graph->transposedAdjList->edge_data = new gdf_column; CSR_Result_Weighted<int,WT> adj_list; status = ConvertCOOtoCSR_weighted( (int*)graph->edgeList->dest_indices->data, (int*)graph->edgeList->src_indices->data, (WT*)graph->edgeList->edge_data->data, nnz, adj_list); gdf_column_view(graph->transposedAdjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->transposedAdjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); gdf_column_view(graph->transposedAdjList->edge_data, adj_list.edgeWeights, nullptr, adj_list.nnz, graph->edgeList->edge_data->dtype); } else { CSR_Result<int> adj_list; status = ConvertCOOtoCSR((int*)graph->edgeList->dest_indices->data, (int*)graph->edgeList->src_indices->data, nnz, adj_list); gdf_column_view(graph->transposedAdjList->offsets, adj_list.rowOffsets, nullptr, adj_list.size+1, graph->edgeList->src_indices->dtype); gdf_column_view(graph->transposedAdjList->indices, adj_list.colIndices, nullptr, adj_list.nnz, graph->edgeList->src_indices->dtype); } if (status !=0) { std::cerr << "Could not generate the adj_list" << std::endl; return GDF_CUDA_ERROR; } } return GDF_SUCCESS; } template <typename WT> gdf_error gdf_pagerank_impl (gdf_graph *graph, gdf_column *pagerank, float alpha = 0.85, float tolerance = 1e-4, int max_iter = 200, bool has_guess = false) { GDF_REQUIRE( graph->edgeList != nullptr, GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( graph->edgeList->src_indices->size == graph->edgeList->dest_indices->size, GDF_COLUMN_SIZE_MISMATCH ); GDF_REQUIRE( graph->edgeList->src_indices->dtype == graph->edgeList->dest_indices->dtype, GDF_UNSUPPORTED_DTYPE ); GDF_REQUIRE( graph->edgeList->src_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( graph->edgeList->dest_indices->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( pagerank != nullptr , GDF_INVALID_API_CALL ); GDF_REQUIRE( pagerank->data != nullptr , GDF_INVALID_API_CALL ); GDF_REQUIRE( pagerank->null_count == 0 , GDF_VALIDITY_UNSUPPORTED ); GDF_REQUIRE( pagerank->size > 0 , GDF_INVALID_API_CALL ); int m=pagerank->size, nnz = graph->edgeList->src_indices->size, status = 0; WT *d_pr, *d_val = nullptr, *d_leaf_vector = nullptr; WT res = 1.0; WT *residual = &res; if (graph->transposedAdjList == nullptr) { gdf_add_transpose(graph); } cudaStream_t stream{nullptr}; ALLOC_MANAGED_TRY((void**)&d_leaf_vector, sizeof(WT) * m, stream); ALLOC_MANAGED_TRY((void**)&d_val, sizeof(WT) * nnz , stream); ALLOC_MANAGED_TRY((void**)&d_pr, sizeof(WT) * m, stream); cugraph::HT_matrix_csc_coo(m, nnz, (int*)graph->transposedAdjList->offsets->data, (int*)graph->transposedAdjList->indices->data, d_val, d_leaf_vector); if (has_guess) { GDF_REQUIRE( pagerank->data != nullptr, GDF_VALIDITY_UNSUPPORTED ); cugraph::copy<WT>(m, (WT*)pagerank->data, d_pr); } status = cugraph::pagerank<int,WT>( m,nnz, (int*)graph->transposedAdjList->offsets->data, (int*)graph->transposedAdjList->indices->data, d_val, alpha, d_leaf_vector, false, tolerance, max_iter, d_pr, residual); if (status !=0) switch ( status ) { case -1: std::cerr<< "Error : bad parameters in Pagerank"<<std::endl; return GDF_CUDA_ERROR; case 1: std::cerr<< "Warning : Pagerank did not reached the desired tolerance"<<std::endl; return GDF_CUDA_ERROR; default: std::cerr<< "Pagerank failed"<<std::endl; return GDF_CUDA_ERROR; } cugraph::copy<WT>(m, d_pr, (WT*)pagerank->data); ALLOC_FREE_TRY(d_val, stream); ALLOC_FREE_TRY(d_pr, stream); ALLOC_FREE_TRY(d_leaf_vector, stream); return GDF_SUCCESS; } gdf_error gdf_add_adj_list(gdf_graph *graph) { if (graph->adjList != nullptr) return GDF_SUCCESS; GDF_REQUIRE( graph->edgeList != nullptr , GDF_INVALID_API_CALL); GDF_REQUIRE( graph->adjList == nullptr , GDF_INVALID_API_CALL); if (graph->edgeList->edge_data != nullptr) { switch (graph->edgeList->edge_data->dtype) { case GDF_FLOAT32: return gdf_add_adj_list_impl<float>(graph); case GDF_FLOAT64: return gdf_add_adj_list_impl<double>(graph); default: return GDF_UNSUPPORTED_DTYPE; } } else { return gdf_add_adj_list_impl<float>(graph); } } gdf_error gdf_add_transpose(gdf_graph *graph) { if (graph->edgeList == nullptr) gdf_add_edge_list(graph); if (graph->edgeList->edge_data != nullptr) { switch (graph->edgeList->edge_data->dtype) { case GDF_FLOAT32: return gdf_add_transpose_impl<float>(graph); case GDF_FLOAT64: return gdf_add_transpose_impl<double>(graph); default: return GDF_UNSUPPORTED_DTYPE; } } else { return gdf_add_transpose_impl<float>(graph); } } gdf_error gdf_delete_adj_list(gdf_graph *graph) { if (graph->adjList) { delete graph->adjList; } graph->adjList = nullptr; return GDF_SUCCESS; } gdf_error gdf_delete_edge_list(gdf_graph *graph) { if (graph->edgeList) { delete graph->edgeList; } graph->edgeList = nullptr; return GDF_SUCCESS; } gdf_error gdf_delete_transpose(gdf_graph *graph) { if (graph->transposedAdjList) { delete graph->transposedAdjList; } graph->transposedAdjList = nullptr; return GDF_SUCCESS; } gdf_error gdf_pagerank(gdf_graph *graph, gdf_column *pagerank, float alpha, float tolerance, int max_iter, bool has_guess) { switch (pagerank->dtype) { case GDF_FLOAT32: return gdf_pagerank_impl<float>(graph, pagerank, alpha, tolerance, max_iter, has_guess); case GDF_FLOAT64: return gdf_pagerank_impl<double>(graph, pagerank, alpha, tolerance, max_iter, has_guess); default: return GDF_UNSUPPORTED_DTYPE; } } gdf_error gdf_bfs(gdf_graph *graph, gdf_column *distances, gdf_column *predecessors, int start_node, bool directed) { GDF_REQUIRE(graph->adjList != nullptr, GDF_VALIDITY_UNSUPPORTED); GDF_REQUIRE(graph->adjList->offsets->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); GDF_REQUIRE(graph->adjList->indices->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); GDF_REQUIRE(distances->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); GDF_REQUIRE(predecessors->dtype == GDF_INT32, GDF_UNSUPPORTED_DTYPE); int n = graph->adjList->offsets->size - 1; int e = graph->adjList->indices->size; int* offsets_ptr = (int*)graph->adjList->offsets->data; int* indices_ptr = (int*)graph->adjList->indices->data; int* distances_ptr = (int*)distances->data; int* predecessors_ptr = (int*)predecessors->data; int alpha = 15; int beta = 18; cugraph::Bfs<int> bfs(n, e, offsets_ptr, indices_ptr, directed, alpha, beta); bfs.configure(distances_ptr, predecessors_ptr, nullptr); bfs.traverse(start_node); return GDF_SUCCESS; }
a67a221b6ab6ca159766943db5d4d5570f5cfd9e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include <hip/device_functions.h> #include <hip/hip_runtime.h> #include <sm_30_intrinsics.h> #ifndef __HIPCC__ #define __HIPCC__ #endif // !__HIPCC__ #include <stdio.h> #include <stdlib.h> #include <cmath> #include <float.h> #include <algorithm> #include <iostream> #include <iomanip> #include <hiprand/hiprand.h> #include <ctime> #pragma once #ifdef __INTELLISENSE__ void __syncthreads(); int __shfl_down(double var, unsigned int delta, int width = warpSize); int __shfl_down(int var, unsigned int delta, int width = warpSize); #endif using namespace std; ostream& operator<<(ostream& out, pair<int, double**> mat) { int m = mat.first; double** arr = mat.second; cout << setprecision(5) << fixed << endl; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { cout << arr[i][j] << (j + 1 < m ? ",\t" : "\n"); } } return out; } #define check(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(hipError_t code, const char *file, int line, bool abort = true) { if (code != hipSuccess) { fprintf(stderr, "GPUassert: %s %s %d\n", hipGetErrorString(code), file, line); if (abort) exit(code); } } #define r_check(ans) { curandAssert((ans)); } inline void curandAssert(hiprandStatus_t code, bool abort = true) { if (code != HIPRAND_STATUS_SUCCESS) { if (abort) exit(code); } } //__device__ inline //double __shfl_down(double var, unsigned int srcLane, int width = 32) { // int2 a = *reinterpret_cast<int2*>(&var); // a.x = __shfl_down(a.x, srcLane, width); // a.y = __shfl_down(a.y, srcLane, width); // return *reinterpret_cast<double*>(&a); //} __inline__ __device__ void max_ind_warp(int& max_i, double& max_v ) { #pragma unroll for (int offset = 32 / 2; offset > 0; offset /= 2) { double cand_v = __shfl_down(max_v, offset); int cand_i = __shfl_down(max_i, offset); if (abs(cand_v) > abs(max_v)) { max_v = cand_v; max_i = cand_i; } } } __inline__ __device__ void max_ind_block(int& max_i, double& max_v) { __shared__ double max_vs[32]; __shared__ int max_is[32]; max_ind_warp(max_i, max_v); // printf("Thread %i: %i %f \n", threadIdx.x, max_i, max_v); int lane = threadIdx.x % warpSize; int warpID = threadIdx.x / warpSize; if (lane == 0) { max_vs[warpID] = max_v; max_is[warpID] = max_i; } __syncthreads(); max_v = (threadIdx.x < 32) ? max_vs[lane] : 0.0; max_i = (threadIdx.x < 32) ? max_is[lane] : 0; // printf("Thread %i: %i %f \n", threadIdx.x, max_i, max_v); max_ind_warp(max_i, max_v); // printf("Thread %i: %i %f \n", threadIdx.x, max_i, max_v); } // Allways call with only one block and 1024 threads! __global__ void maxColumn(double ** __restrict__ mat, const int c, const int N, int* __restrict__ P) { int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; int max_i = I; double max_v = 0.0; for (int i = c + I; i < N; i += numThreads) { double cand_v = mat[i][c]; if (abs(cand_v) >= abs(max_v)) { max_v = cand_v; max_i = i; } } max_ind_block(max_i, max_v); if (threadIdx.x == 0) { // printf("%i %f \n", max_i, max_v); double* tmp = mat[max_i]; mat[max_i] = mat[c]; mat[c] = tmp; // printf("max_i %i, P[c] %i, P[max_i] %i \n", max_i, P[c], P[max_i]); int itmp = P[c]; P[c] = P[max_i]; P[max_i] = itmp; } } __global__ void compute_L_column (double ** __restrict__ mat, const int col, const int N) { double diag = mat[col][col]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; for (int i = I + col + 1; i < N; i += numThreads) { mat[i][col] /= diag; } } __global__ void reduce(double ** __restrict__ mat, const int n, const int N) { __shared__ double actv[16]; __shared__ double fact[16]; //int numThreadsX = blockDim.x * gridDim.x; //int numThreadsY = blockDim.y * gridDim.y; int I = threadIdx.x + blockIdx.x * blockDim.x; int J = threadIdx.y + blockIdx.y * blockDim.y; if (I + n + 1 < N && threadIdx.y == 0) { actv[threadIdx.x] = mat[n][I + n + 1]; } if (J + n + 1 < N && threadIdx.x == 0) { fact[threadIdx.y] = mat[J + n + 1][n]; } __syncthreads(); if (I + n + 1 < N && J + n + 1 < N) { mat[J + n + 1][I + n + 1] -= actv[threadIdx.x] * fact[threadIdx.y]; } } __global__ void L_substitution(double ** __restrict__ mat, double* __restrict__ b, const int N) { extern __shared__ double _b[]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; //for (int i = I; i < N; i += numThreads) { // printf("%i %f, ", i, b[i]); // _b[i] = b[i]; //} // on diagonal there are ones which are however not saved for (int j = 0; j < N; j++) { double b_j = _b[j]; for (int i = j + 1 + I; i < N; i += numThreads) { _b[i] -= mat[i][j] * b_j; } } for (int i = I; i < N; i += numThreads) { // printf("%i %f, ",i, _b[i]); b[i] = _b[i]; } } __global__ void U_substitution(double ** __restrict__ mat, double* __restrict__ b, const int N) { extern __shared__ double _b[]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; for (int i = I; i < N; i += numThreads) { _b[i] = b[i]; } for (int j = N - 1; j >= 0; j--) { if ((j % numThreads) == I) { _b[j] /= mat[j][j]; } __syncthreads(); double b_j = _b[j]; for (int i = I; i < j; i += numThreads) { _b[i] -= mat[i][j] * b_j; } } for (int i = I; i < N; i += numThreads) { b[i] = _b[i]; } } // Run with 1 Block 1024 Threads only please! __global__ void permute(double* d_b, const int* P, int const N) { extern __shared__ double _b[]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; //for (int i = I; i < N; i += numThreads) { // printf("%i %f ", i, d_b[i]); //} // printf("\n "); for (int i = I; i < N; i += numThreads) { // printf("I=%i, i=%i, P[i]=%i, %f \n", I, i, P[i], d_b[P[i]]); _b[i] = d_b[P[i]]; } for (int i = I; i < N; i += numThreads) { d_b[i] = _b[i]; } } void LU_decompostion(double** d_mat, const int N, int* &P) { //check(hipMallocManaged(&d_mat, N * sizeof(double*))); //for (int i = 0; i < N; i++) { // // hipMalloc // check(hipMallocManaged(&(d_mat[i]), N * sizeof(double))); //} //for (int i = 0; i < N; i++) { // check(hipMemcpyAsync(&(d_mat[i]), &(mat[i]), N, hipMemcpyHostToDevice)); //} check(hipMallocManaged(&P, N * sizeof(int))); for (int i = 0; i < N; i++) { P[i] = i; } hipDeviceSynchronize(); unsigned int num_threads = min(256, N); unsigned int num_blocks = (N + num_threads - 1) / num_threads; dim3 threadsGrid = dim3(16, 16); for (int i = 0; i < N; i++) { hipLaunchKernelGGL(( maxColumn), dim3(1), dim3(1024), 0, 0, d_mat, i, N, P); hipLaunchKernelGGL(( compute_L_column), dim3(num_blocks), dim3(num_threads), 0, 0, d_mat, i, N); int dim = (N + 16 - 1) / 16; dim3 blockgrid = dim3(dim, dim); hipLaunchKernelGGL(( reduce), dim3(blockgrid), dim3(threadsGrid), 0, 0, d_mat, i, N); //hipDeviceSynchronize(); //auto Mat = make_pair(N, d_mat); //cout << endl << Mat << endl; //for (int i = 0; i < N; i++) { // printf("%i, ", P[i]); //} printf("\n"); } } // deconstructs b during execution // assume d_mat and d_P are device pointer void inline solve_LU(double** d_mat, int* d_P, double* b, const int N) { double* d_b; check(hipMallocManaged(&d_b, N * sizeof(double))); check(hipMemcpy(d_b, b, N * sizeof(double), hipMemcpyDefault)); unsigned int num_threads = min(256, N); unsigned int num_blocks = (N + num_threads - 1) / num_threads; hipLaunchKernelGGL(( permute), dim3(1), dim3(1024), N * sizeof(double), 0, d_b, d_P, N); hipDeviceSynchronize(); hipLaunchKernelGGL(( L_substitution), dim3(num_blocks), dim3(num_threads), N * sizeof(double) , 0, d_mat, d_b, N); hipLaunchKernelGGL(( U_substitution), dim3(num_blocks), dim3(num_threads), N * sizeof(double) , 0, d_mat, d_b, N); hipDeviceSynchronize(); check(hipMemcpy(b, d_b, N * sizeof(double), hipMemcpyDefault)); } void test_maxColumn(double ** __restrict__ mat, const int c, const int N, int* P) { hipLaunchKernelGGL(( maxColumn), dim3(1),dim3(8), 0, 0, mat, c, N, P); hipDeviceSynchronize(); for(int i = 0; i < N; i++){ cout << P[i] << ", "; } } void test_L_column(double ** __restrict__ mat, const int c, const int N) { hipLaunchKernelGGL(( compute_L_column), dim3(1), dim3(8) , 0, 0, mat, c, N); hipDeviceSynchronize(); auto Mat = make_pair(N, mat); cout << endl << Mat << endl; } void test_reduce(double ** __restrict__ d_mat, const int c, const int N) { int* P; check(hipMallocManaged(&P, N * sizeof(int))); for (int i = 0; i < N; i++) { P[i] = i; } test_maxColumn(d_mat, c, N, P); test_L_column(d_mat, c, N); dim3 threadsGrid = dim3(4, 4); int dim = (N + 4 - 1) / 4; dim3 blockgrid = dim3(dim, dim); hipLaunchKernelGGL(( reduce), dim3(blockgrid), dim3(threadsGrid) , 0, 0, d_mat, c, N); hipDeviceSynchronize(); auto Mat = make_pair(N, d_mat); cout << endl << Mat << endl; } void test_LU_decomp(double ** __restrict__ d_mat, int N) { int* P; LU_decompostion(d_mat, N, P); hipDeviceSynchronize(); auto Mat = make_pair(N, d_mat); cout << endl << Mat << endl; double* b = (double*) calloc(sizeof(double), N); for (int i = 0; i < N; i++) { b[i] = i; } hipDeviceSynchronize(); solve_LU(d_mat, P, b, N); hipDeviceSynchronize(); for (int i = 0; i < N; i++) { cout << b[i] << ", "; } } void run_testsuit() { const int N = 5; //double mat_[N][N] = {{ 1,2,3 }, // { 4,4,6 }, // { 1,2,9 }}; double mat_[N][N] = { { 17,24, 1, 8,15 }, { 23, 5, 7,14,16 }, { 4, 6,13,20,22 }, { 10,12,19,21, 3 }, { 11,18,25, 2, 9 } }; double** mat; check(hipMallocManaged(&mat, sizeof(double*) * N)); for (int i = 0; i < N; i++) { check(hipMallocManaged(&(mat[i]), sizeof(double) * N)) // check(hipMemcpy(mat[i], mat_[i], 3, hipMemcpyHostToDevice)); } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mat[i][j] = mat_[i][j]; } } // test_maxColumn(mat, 2, N); // test_L_column(mat, 0, N); // test_reduce(mat, 0, N); // test_LU_decomp(mat, N); } void run_perfomance_test(const int N) { double** mat; check(hipMallocManaged(&mat, sizeof(double*) * N)); hiprandGenerator_t gen; r_check(hiprandCreateGenerator(&gen, HIPRAND_RNG_PSEUDO_DEFAULT)); unsigned long int seed = static_cast<unsigned long int> (time(NULL)); r_check(hiprandSetPseudoRandomGeneratorSeed(gen, seed)); for (int i = 0; i < N; i++) { check(hipMallocManaged(&(mat[i]), sizeof(double) * N)) r_check(hiprandGenerateUniformDouble(gen, mat[i], N)); hipDeviceSynchronize(); } hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); int* P; hipEventRecord(start); LU_decompostion(mat, N, P); hipEventRecord(stop); hipEventSynchronize(stop); float milliseconds = 0; hipEventElapsedTime(&milliseconds, start, stop); cout << "Time " << milliseconds << " for matrix of size " << N << "x" << N << endl; // FREE r_check(hiprandDestroyGenerator(gen)); for (int i = 0; i < N; i++) { check(hipFree(mat[i])); } check(hipFree(mat)); return; } int main() { //run_perfomance_test(100); //run_perfomance_test(300); //run_perfomance_test(900); //run_perfomance_test(900 * 2); //run_perfomance_test(900 * 3); //run_perfomance_test(900 * 4); //run_perfomance_test(900 * 5); //run_perfomance_test(900 * 6); run_perfomance_test(50); run_perfomance_test(50 * 2); run_perfomance_test(50 * 3); run_perfomance_test(50 * 4); run_perfomance_test(50 * 5); run_perfomance_test(50 * 6); run_perfomance_test(50 * 7); run_perfomance_test(50 * 8); run_perfomance_test(50 * 9); run_perfomance_test(50 * 10); check(hipDeviceReset()); }
a67a221b6ab6ca159766943db5d4d5570f5cfd9e.cu
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <device_functions.h> #include <cuda.h> #include <sm_30_intrinsics.h> #ifndef __CUDACC__ #define __CUDACC__ #endif // !__CUDACC__ #include <stdio.h> #include <stdlib.h> #include <cmath> #include <float.h> #include <algorithm> #include <iostream> #include <iomanip> #include <curand.h> #include <ctime> #pragma once #ifdef __INTELLISENSE__ void __syncthreads(); int __shfl_down(double var, unsigned int delta, int width = warpSize); int __shfl_down(int var, unsigned int delta, int width = warpSize); #endif using namespace std; ostream& operator<<(ostream& out, pair<int, double**> mat) { int m = mat.first; double** arr = mat.second; cout << setprecision(5) << fixed << endl; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { cout << arr[i][j] << (j + 1 < m ? ",\t" : "\n"); } } return out; } #define check(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); } } #define r_check(ans) { curandAssert((ans)); } inline void curandAssert(curandStatus_t code, bool abort = true) { if (code != CURAND_STATUS_SUCCESS) { if (abort) exit(code); } } //__device__ inline //double __shfl_down(double var, unsigned int srcLane, int width = 32) { // int2 a = *reinterpret_cast<int2*>(&var); // a.x = __shfl_down(a.x, srcLane, width); // a.y = __shfl_down(a.y, srcLane, width); // return *reinterpret_cast<double*>(&a); //} __inline__ __device__ void max_ind_warp(int& max_i, double& max_v ) { #pragma unroll for (int offset = 32 / 2; offset > 0; offset /= 2) { double cand_v = __shfl_down(max_v, offset); int cand_i = __shfl_down(max_i, offset); if (abs(cand_v) > abs(max_v)) { max_v = cand_v; max_i = cand_i; } } } __inline__ __device__ void max_ind_block(int& max_i, double& max_v) { __shared__ double max_vs[32]; __shared__ int max_is[32]; max_ind_warp(max_i, max_v); // printf("Thread %i: %i %f \n", threadIdx.x, max_i, max_v); int lane = threadIdx.x % warpSize; int warpID = threadIdx.x / warpSize; if (lane == 0) { max_vs[warpID] = max_v; max_is[warpID] = max_i; } __syncthreads(); max_v = (threadIdx.x < 32) ? max_vs[lane] : 0.0; max_i = (threadIdx.x < 32) ? max_is[lane] : 0; // printf("Thread %i: %i %f \n", threadIdx.x, max_i, max_v); max_ind_warp(max_i, max_v); // printf("Thread %i: %i %f \n", threadIdx.x, max_i, max_v); } // Allways call with only one block and 1024 threads! __global__ void maxColumn(double ** __restrict__ mat, const int c, const int N, int* __restrict__ P) { int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; int max_i = I; double max_v = 0.0; for (int i = c + I; i < N; i += numThreads) { double cand_v = mat[i][c]; if (abs(cand_v) >= abs(max_v)) { max_v = cand_v; max_i = i; } } max_ind_block(max_i, max_v); if (threadIdx.x == 0) { // printf("%i %f \n", max_i, max_v); double* tmp = mat[max_i]; mat[max_i] = mat[c]; mat[c] = tmp; // printf("max_i %i, P[c] %i, P[max_i] %i \n", max_i, P[c], P[max_i]); int itmp = P[c]; P[c] = P[max_i]; P[max_i] = itmp; } } __global__ void compute_L_column (double ** __restrict__ mat, const int col, const int N) { double diag = mat[col][col]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; for (int i = I + col + 1; i < N; i += numThreads) { mat[i][col] /= diag; } } __global__ void reduce(double ** __restrict__ mat, const int n, const int N) { __shared__ double actv[16]; __shared__ double fact[16]; //int numThreadsX = blockDim.x * gridDim.x; //int numThreadsY = blockDim.y * gridDim.y; int I = threadIdx.x + blockIdx.x * blockDim.x; int J = threadIdx.y + blockIdx.y * blockDim.y; if (I + n + 1 < N && threadIdx.y == 0) { actv[threadIdx.x] = mat[n][I + n + 1]; } if (J + n + 1 < N && threadIdx.x == 0) { fact[threadIdx.y] = mat[J + n + 1][n]; } __syncthreads(); if (I + n + 1 < N && J + n + 1 < N) { mat[J + n + 1][I + n + 1] -= actv[threadIdx.x] * fact[threadIdx.y]; } } __global__ void L_substitution(double ** __restrict__ mat, double* __restrict__ b, const int N) { extern __shared__ double _b[]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; //for (int i = I; i < N; i += numThreads) { // printf("%i %f, ", i, b[i]); // _b[i] = b[i]; //} // on diagonal there are ones which are however not saved for (int j = 0; j < N; j++) { double b_j = _b[j]; for (int i = j + 1 + I; i < N; i += numThreads) { _b[i] -= mat[i][j] * b_j; } } for (int i = I; i < N; i += numThreads) { // printf("%i %f, ",i, _b[i]); b[i] = _b[i]; } } __global__ void U_substitution(double ** __restrict__ mat, double* __restrict__ b, const int N) { extern __shared__ double _b[]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; for (int i = I; i < N; i += numThreads) { _b[i] = b[i]; } for (int j = N - 1; j >= 0; j--) { if ((j % numThreads) == I) { _b[j] /= mat[j][j]; } __syncthreads(); double b_j = _b[j]; for (int i = I; i < j; i += numThreads) { _b[i] -= mat[i][j] * b_j; } } for (int i = I; i < N; i += numThreads) { b[i] = _b[i]; } } // Run with 1 Block 1024 Threads only please! __global__ void permute(double* d_b, const int* P, int const N) { extern __shared__ double _b[]; int numThreads = blockDim.x * gridDim.x; int I = threadIdx.x + blockIdx.x * blockDim.x; //for (int i = I; i < N; i += numThreads) { // printf("%i %f ", i, d_b[i]); //} // printf("\n "); for (int i = I; i < N; i += numThreads) { // printf("I=%i, i=%i, P[i]=%i, %f \n", I, i, P[i], d_b[P[i]]); _b[i] = d_b[P[i]]; } for (int i = I; i < N; i += numThreads) { d_b[i] = _b[i]; } } void LU_decompostion(double** d_mat, const int N, int* &P) { //check(cudaMallocManaged(&d_mat, N * sizeof(double*))); //for (int i = 0; i < N; i++) { // // cudaMalloc // check(cudaMallocManaged(&(d_mat[i]), N * sizeof(double))); //} //for (int i = 0; i < N; i++) { // check(cudaMemcpyAsync(&(d_mat[i]), &(mat[i]), N, cudaMemcpyHostToDevice)); //} check(cudaMallocManaged(&P, N * sizeof(int))); for (int i = 0; i < N; i++) { P[i] = i; } cudaDeviceSynchronize(); unsigned int num_threads = min(256, N); unsigned int num_blocks = (N + num_threads - 1) / num_threads; dim3 threadsGrid = dim3(16, 16); for (int i = 0; i < N; i++) { maxColumn<<<1, 1024>>>(d_mat, i, N, P); compute_L_column<<<num_blocks, num_threads>>>(d_mat, i, N); int dim = (N + 16 - 1) / 16; dim3 blockgrid = dim3(dim, dim); reduce<<<blockgrid, threadsGrid>>>(d_mat, i, N); //cudaDeviceSynchronize(); //auto Mat = make_pair(N, d_mat); //cout << endl << Mat << endl; //for (int i = 0; i < N; i++) { // printf("%i, ", P[i]); //} printf("\n"); } } // deconstructs b during execution // assume d_mat and d_P are device pointer void inline solve_LU(double** d_mat, int* d_P, double* b, const int N) { double* d_b; check(cudaMallocManaged(&d_b, N * sizeof(double))); check(cudaMemcpy(d_b, b, N * sizeof(double), cudaMemcpyDefault)); unsigned int num_threads = min(256, N); unsigned int num_blocks = (N + num_threads - 1) / num_threads; permute<<<1, 1024, N * sizeof(double)>>>(d_b, d_P, N); cudaDeviceSynchronize(); L_substitution<<<num_blocks, num_threads, N * sizeof(double) >>>(d_mat, d_b, N); U_substitution<<<num_blocks, num_threads, N * sizeof(double) >>>(d_mat, d_b, N); cudaDeviceSynchronize(); check(cudaMemcpy(b, d_b, N * sizeof(double), cudaMemcpyDefault)); } void test_maxColumn(double ** __restrict__ mat, const int c, const int N, int* P) { maxColumn<<<1,8>>>(mat, c, N, P); cudaDeviceSynchronize(); for(int i = 0; i < N; i++){ cout << P[i] << ", "; } } void test_L_column(double ** __restrict__ mat, const int c, const int N) { compute_L_column<<<1, 8 >>>(mat, c, N); cudaDeviceSynchronize(); auto Mat = make_pair(N, mat); cout << endl << Mat << endl; } void test_reduce(double ** __restrict__ d_mat, const int c, const int N) { int* P; check(cudaMallocManaged(&P, N * sizeof(int))); for (int i = 0; i < N; i++) { P[i] = i; } test_maxColumn(d_mat, c, N, P); test_L_column(d_mat, c, N); dim3 threadsGrid = dim3(4, 4); int dim = (N + 4 - 1) / 4; dim3 blockgrid = dim3(dim, dim); reduce<<<blockgrid, threadsGrid >>>(d_mat, c, N); cudaDeviceSynchronize(); auto Mat = make_pair(N, d_mat); cout << endl << Mat << endl; } void test_LU_decomp(double ** __restrict__ d_mat, int N) { int* P; LU_decompostion(d_mat, N, P); cudaDeviceSynchronize(); auto Mat = make_pair(N, d_mat); cout << endl << Mat << endl; double* b = (double*) calloc(sizeof(double), N); for (int i = 0; i < N; i++) { b[i] = i; } cudaDeviceSynchronize(); solve_LU(d_mat, P, b, N); cudaDeviceSynchronize(); for (int i = 0; i < N; i++) { cout << b[i] << ", "; } } void run_testsuit() { const int N = 5; //double mat_[N][N] = {{ 1,2,3 }, // { 4,4,6 }, // { 1,2,9 }}; double mat_[N][N] = { { 17,24, 1, 8,15 }, { 23, 5, 7,14,16 }, { 4, 6,13,20,22 }, { 10,12,19,21, 3 }, { 11,18,25, 2, 9 } }; double** mat; check(cudaMallocManaged(&mat, sizeof(double*) * N)); for (int i = 0; i < N; i++) { check(cudaMallocManaged(&(mat[i]), sizeof(double) * N)) // check(cudaMemcpy(mat[i], mat_[i], 3, cudaMemcpyHostToDevice)); } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mat[i][j] = mat_[i][j]; } } // test_maxColumn(mat, 2, N); // test_L_column(mat, 0, N); // test_reduce(mat, 0, N); // test_LU_decomp(mat, N); } void run_perfomance_test(const int N) { double** mat; check(cudaMallocManaged(&mat, sizeof(double*) * N)); curandGenerator_t gen; r_check(curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT)); unsigned long int seed = static_cast<unsigned long int> (time(NULL)); r_check(curandSetPseudoRandomGeneratorSeed(gen, seed)); for (int i = 0; i < N; i++) { check(cudaMallocManaged(&(mat[i]), sizeof(double) * N)) r_check(curandGenerateUniformDouble(gen, mat[i], N)); cudaDeviceSynchronize(); } cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); int* P; cudaEventRecord(start); LU_decompostion(mat, N, P); cudaEventRecord(stop); cudaEventSynchronize(stop); float milliseconds = 0; cudaEventElapsedTime(&milliseconds, start, stop); cout << "Time " << milliseconds << " for matrix of size " << N << "x" << N << endl; // FREE r_check(curandDestroyGenerator(gen)); for (int i = 0; i < N; i++) { check(cudaFree(mat[i])); } check(cudaFree(mat)); return; } int main() { //run_perfomance_test(100); //run_perfomance_test(300); //run_perfomance_test(900); //run_perfomance_test(900 * 2); //run_perfomance_test(900 * 3); //run_perfomance_test(900 * 4); //run_perfomance_test(900 * 5); //run_perfomance_test(900 * 6); run_perfomance_test(50); run_perfomance_test(50 * 2); run_perfomance_test(50 * 3); run_perfomance_test(50 * 4); run_perfomance_test(50 * 5); run_perfomance_test(50 * 6); run_perfomance_test(50 * 7); run_perfomance_test(50 * 8); run_perfomance_test(50 * 9); run_perfomance_test(50 * 10); check(cudaDeviceReset()); }
2bce2f4d8fe1851a897e68524f3e7d49a21f1971.hip
// !!! This is a file automatically generated by hipify!!! // // Manages control flow of the simulation // Will also manage OpenGL visualization when implemented // #include <hip/hip_runtime.h> #include <device_launch_parameters.h> #include "debug.h" #include "simulation.h" #include "vtkwriter.h" #define BLOCK_SIZE 256 #define SOFTENING 1E-9f #define TIME_STEP 0.01 Simulation::Simulation(const Config& config) : config(config) { // initialize particles pt = new Particles(config.n); } Simulation::~Simulation() { delete pt; } // control loop void Simulation::start() { VTKWriter vtkw; float4* h_pos = new float4[config.n]; for (int i = 0; i < config.frames; i++) { update_particles(); // copy positions to host side gpu_check(hipMemcpy(h_pos, pt->d_pos, sizeof(float4) * config.n, hipMemcpyDeviceToHost)); vtkw.write_pos(h_pos, config.n); } delete[] h_pos; } // advance simulation void Simulation::update_particles() { int grid_size = (config.n + BLOCK_SIZE - 1) / BLOCK_SIZE; hipLaunchKernelGGL(( update_kernel), dim3(grid_size), dim3(BLOCK_SIZE), 0, 0, pt->d_pos, pt->d_vel, pt->d_acc, config.n); gpu_check(hipPeekAtLastError()); // wait for kernels to finish gpu_check(hipDeviceSynchronize()); } // calculates accleration vector from forces __device__ float4 calc_acc(const float4 pos_i, const float4 pos_j, float4 acc) { float3 r = { pos_j.x - pos_i.x, pos_j.y - pos_i.y, pos_j.z - pos_i.z }; // using softening parameter float dist = r.x * r.x + r.y * r.y + r.z * r.z + SOFTENING; float inv_distcb = 1.0f / sqrtf(dist * dist * dist); acc.x += r.x * inv_distcb; acc.y += r.y * inv_distcb; acc.z += r.z * inv_distcb; return acc; } // particle positions per thread tile in extern __shared__ float4 s_pos[BLOCK_SIZE]; // calculates updated acceleration vector __device__ float4 update_acc(const float4* d_pos, const int n) { int id = blockIdx.x * blockDim.x + threadIdx.x; float4 pos = d_pos[id]; float4 acc = {0, 0, 0, 0}; // loops through all particles by tiles int tile = 0; for (int i = 0; i < n; i += BLOCK_SIZE) { // id for thread in this tile int tid = tile * blockDim.x + threadIdx.x; // load particle positions into shared memory s_pos[threadIdx.x] = d_pos[tid]; __syncthreads(); // update current body's accleration with next tile of bodies for (int j = 0; j < blockDim.x; j++) { acc = calc_acc(pos, s_pos[j], acc); } __syncthreads(); tile++; } return acc; } // updates particle properties __global__ void update_kernel(float4* d_pos, float4* d_vel, float4* d_acc, const int n) { int id = blockIdx.x * blockDim.x + threadIdx.x; float4 pos = d_pos[id]; float4 vel = d_vel[id]; float4 acc = d_acc[id]; // using kick-drift-kick leapfrog integrator float t_2 = TIME_STEP / 2; // velocity at mid-point of time step float4 vel_mid = make_float4( vel.x + acc.x * t_2, vel.y + acc.y * t_2, vel.z + acc.z * t_2 ); // update position d_pos[id] = make_float4( pos.x + vel_mid.x * TIME_STEP, pos.y + vel_mid.y * TIME_STEP, pos.z + vel_mid.z * TIME_STEP ); // calculate new accleration acc = update_acc(d_pos, n); // update velocity d_vel[id] = make_float4( vel_mid.x + acc.x * t_2, vel_mid.y + acc.y * t_2, vel_mid.z + acc.z * t_2 ); // update accleration d_acc[id] = acc; }
2bce2f4d8fe1851a897e68524f3e7d49a21f1971.cu
// // Manages control flow of the simulation // Will also manage OpenGL visualization when implemented // #include <cuda_runtime.h> #include <device_launch_parameters.h> #include "debug.h" #include "simulation.h" #include "vtkwriter.h" #define BLOCK_SIZE 256 #define SOFTENING 1E-9f #define TIME_STEP 0.01 Simulation::Simulation(const Config& config) : config(config) { // initialize particles pt = new Particles(config.n); } Simulation::~Simulation() { delete pt; } // control loop void Simulation::start() { VTKWriter vtkw; float4* h_pos = new float4[config.n]; for (int i = 0; i < config.frames; i++) { update_particles(); // copy positions to host side gpu_check(cudaMemcpy(h_pos, pt->d_pos, sizeof(float4) * config.n, cudaMemcpyDeviceToHost)); vtkw.write_pos(h_pos, config.n); } delete[] h_pos; } // advance simulation void Simulation::update_particles() { int grid_size = (config.n + BLOCK_SIZE - 1) / BLOCK_SIZE; update_kernel<<<grid_size, BLOCK_SIZE>>>(pt->d_pos, pt->d_vel, pt->d_acc, config.n); gpu_check(cudaPeekAtLastError()); // wait for kernels to finish gpu_check(cudaDeviceSynchronize()); } // calculates accleration vector from forces __device__ float4 calc_acc(const float4 pos_i, const float4 pos_j, float4 acc) { float3 r = { pos_j.x - pos_i.x, pos_j.y - pos_i.y, pos_j.z - pos_i.z }; // using softening parameter float dist = r.x * r.x + r.y * r.y + r.z * r.z + SOFTENING; float inv_distcb = 1.0f / sqrtf(dist * dist * dist); acc.x += r.x * inv_distcb; acc.y += r.y * inv_distcb; acc.z += r.z * inv_distcb; return acc; } // particle positions per thread tile in extern __shared__ float4 s_pos[BLOCK_SIZE]; // calculates updated acceleration vector __device__ float4 update_acc(const float4* d_pos, const int n) { int id = blockIdx.x * blockDim.x + threadIdx.x; float4 pos = d_pos[id]; float4 acc = {0, 0, 0, 0}; // loops through all particles by tiles int tile = 0; for (int i = 0; i < n; i += BLOCK_SIZE) { // id for thread in this tile int tid = tile * blockDim.x + threadIdx.x; // load particle positions into shared memory s_pos[threadIdx.x] = d_pos[tid]; __syncthreads(); // update current body's accleration with next tile of bodies for (int j = 0; j < blockDim.x; j++) { acc = calc_acc(pos, s_pos[j], acc); } __syncthreads(); tile++; } return acc; } // updates particle properties __global__ void update_kernel(float4* d_pos, float4* d_vel, float4* d_acc, const int n) { int id = blockIdx.x * blockDim.x + threadIdx.x; float4 pos = d_pos[id]; float4 vel = d_vel[id]; float4 acc = d_acc[id]; // using kick-drift-kick leapfrog integrator float t_2 = TIME_STEP / 2; // velocity at mid-point of time step float4 vel_mid = make_float4( vel.x + acc.x * t_2, vel.y + acc.y * t_2, vel.z + acc.z * t_2 ); // update position d_pos[id] = make_float4( pos.x + vel_mid.x * TIME_STEP, pos.y + vel_mid.y * TIME_STEP, pos.z + vel_mid.z * TIME_STEP ); // calculate new accleration acc = update_acc(d_pos, n); // update velocity d_vel[id] = make_float4( vel_mid.x + acc.x * t_2, vel_mid.y + acc.y * t_2, vel_mid.z + acc.z * t_2 ); // update accleration d_acc[id] = acc; }
50a328bd45b7ecffd3e3a929985680e624a6b871.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /********************************************************************************* Implementing Breadth first search on CUDA using algorithm given in HiPC'07 paper "Accelerating Large Graph Algorithms on the GPU using CUDA" Copyright (c) 2008 International Institute of Information Technology - Hyderabad. All rights reserved. Permission to use, copy, modify and distribute this software and its documentation for educational purpose is hereby granted without fee, provided that the above copyright notice and this permission notice appear in all copies of this software and that you do not sell the software. THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,EXPRESS, IMPLIED OR OTHERWISE. The CUDA Kernel for Applying BFS on a loaded Graph. Created By Pawan Harish **********************************************************************************/ #ifndef _KERNEL_H_ #define _KERNEL_H_ __global__ void Kernel( Node* g_graph_nodes, int* g_graph_edges, bool* g_graph_mask, bool* g_updating_graph_mask, bool *g_graph_visited, int* g_cost, int no_of_nodes) { int tid = blockIdx.x*MAX_THREADS_PER_BLOCK + threadIdx.x; if(tid == 0){ g_graph_mask[0]=true; // g_updating_graph_mask[0]=true; } if( tid<no_of_nodes && g_graph_mask[tid]) { g_graph_mask[tid]=false; for(int i=g_graph_nodes[tid].starting; i<(g_graph_nodes[tid].no_of_edges + g_graph_nodes[tid].starting); i++) { int id = g_graph_edges[i]; if(!g_graph_visited[id]) { g_cost[id]=g_cost[tid]+1; g_updating_graph_mask[id]=true; } } } } #endif
50a328bd45b7ecffd3e3a929985680e624a6b871.cu
/********************************************************************************* Implementing Breadth first search on CUDA using algorithm given in HiPC'07 paper "Accelerating Large Graph Algorithms on the GPU using CUDA" Copyright (c) 2008 International Institute of Information Technology - Hyderabad. All rights reserved. Permission to use, copy, modify and distribute this software and its documentation for educational purpose is hereby granted without fee, provided that the above copyright notice and this permission notice appear in all copies of this software and that you do not sell the software. THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,EXPRESS, IMPLIED OR OTHERWISE. The CUDA Kernel for Applying BFS on a loaded Graph. Created By Pawan Harish **********************************************************************************/ #ifndef _KERNEL_H_ #define _KERNEL_H_ __global__ void Kernel( Node* g_graph_nodes, int* g_graph_edges, bool* g_graph_mask, bool* g_updating_graph_mask, bool *g_graph_visited, int* g_cost, int no_of_nodes) { int tid = blockIdx.x*MAX_THREADS_PER_BLOCK + threadIdx.x; if(tid == 0){ g_graph_mask[0]=true; // g_updating_graph_mask[0]=true; } if( tid<no_of_nodes && g_graph_mask[tid]) { g_graph_mask[tid]=false; for(int i=g_graph_nodes[tid].starting; i<(g_graph_nodes[tid].no_of_edges + g_graph_nodes[tid].starting); i++) { int id = g_graph_edges[i]; if(!g_graph_visited[id]) { g_cost[id]=g_cost[tid]+1; g_updating_graph_mask[id]=true; } } } } #endif
d0997f441d8c13a184e6b5a3d5cd7844021575fb.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #define FOUR_STEP_TRANSPOSE_DIM 16 #include "myfft.cu" #include "cufftFunc.cu" #include "fourStepFFT_kernel.cu" // prototype decleration void power_transpose_four_step_exec(hipfftComplex *FFTData, float *powerData, int x, int y); /* * do_four_step_fft */ void do_four_step_fft(hipfftComplex *devFFTData, float *devPowerData, int matrixX, int matrixY){ // FFT along column do_myfft(devFFTData, matrixX, 1); // FFT along row exec_cufft(devFFTData, matrixX, matrixY); // matrix transpose with calculating power spectrum power_transpose_four_step_exec(devFFTData, devPowerData, matrixX, matrixY); } /* * power_transpose_four_step_exec */ void power_transpose_four_step_exec(hipfftComplex *FFTData, float *powerData, int x, int y){ int width; int iter; int i; iter = 1; width = x / FOUR_STEP_TRANSPOSE_DIM; while(width>MAX_GRID){ width /= 2; iter *= 2; } dim3 grid( width, y / FOUR_STEP_TRANSPOSE_DIM, 1); dim3 threads( FOUR_STEP_TRANSPOSE_DIM, FOUR_STEP_TRANSPOSE_DIM, 1); for(i=0; i<iter; i++){ hipLaunchKernelGGL(( power_transpose_four_step), dim3(grid), dim3(threads), 0, 0, &FFTData[width * FOUR_STEP_TRANSPOSE_DIM * i], &powerData[FOUR_STEP_TRANSPOSE_DIM * FOUR_STEP_TRANSPOSE_DIM * width * i], x, y); hipDeviceSynchronize(); } }
d0997f441d8c13a184e6b5a3d5cd7844021575fb.cu
#define FOUR_STEP_TRANSPOSE_DIM 16 #include "myfft.cu" #include "cufftFunc.cu" #include "fourStepFFT_kernel.cu" // prototype decleration void power_transpose_four_step_exec(cufftComplex *FFTData, float *powerData, int x, int y); /* * do_four_step_fft */ void do_four_step_fft(cufftComplex *devFFTData, float *devPowerData, int matrixX, int matrixY){ // FFT along column do_myfft(devFFTData, matrixX, 1); // FFT along row exec_cufft(devFFTData, matrixX, matrixY); // matrix transpose with calculating power spectrum power_transpose_four_step_exec(devFFTData, devPowerData, matrixX, matrixY); } /* * power_transpose_four_step_exec */ void power_transpose_four_step_exec(cufftComplex *FFTData, float *powerData, int x, int y){ int width; int iter; int i; iter = 1; width = x / FOUR_STEP_TRANSPOSE_DIM; while(width>MAX_GRID){ width /= 2; iter *= 2; } dim3 grid( width, y / FOUR_STEP_TRANSPOSE_DIM, 1); dim3 threads( FOUR_STEP_TRANSPOSE_DIM, FOUR_STEP_TRANSPOSE_DIM, 1); for(i=0; i<iter; i++){ power_transpose_four_step<<<grid, threads>>>(&FFTData[width * FOUR_STEP_TRANSPOSE_DIM * i], &powerData[FOUR_STEP_TRANSPOSE_DIM * FOUR_STEP_TRANSPOSE_DIM * width * i], x, y); cudaThreadSynchronize(); } }
9b97f4db828bc80f767bd9375b05563d82921b1b.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void __veccmp(int *a, int *b, int *d) { printf("__veccmp() not defined for CUDA Arch < 300\n"); }
9b97f4db828bc80f767bd9375b05563d82921b1b.cu
#include "includes.h" __global__ void __veccmp(int *a, int *b, int *d) { printf("__veccmp() not defined for CUDA Arch < 300\n"); }
7e848a097add52504bb953854d98983585f9234e.hip
// !!! This is a file automatically generated by hipify!!! #include <iostream> #include <hip/hip_runtime_api.h> // Define and implement the GPU addition function __global__ void add(int *a, int *b, int *c) { *c = *a + *b; } int main() { int a, b, c; // host copies of a, b, c int *d_a, *d_b, *d_c; // device copies of a, b, c int size = sizeof(int); // Allocate space for device copies of a, b, c hipMalloc((void **)&d_a, size); hipMalloc((void **)&d_b, size); hipMalloc((void **)&d_c, size); // Setup input values a = 2; b = 7; // Copy inputs to device hipMemcpy(d_a, &a, size, hipMemcpyHostToDevice); hipMemcpy(d_b, &b, size, hipMemcpyHostToDevice); // Launch add() kernel on GPU hipLaunchKernelGGL(( add), dim3(1),dim3(1), 0, 0, d_a, d_b, d_c); // Copy result back to host hipMemcpy(&c, d_c, size, hipMemcpyDeviceToHost); // Cleanup hipFree(d_a); hipFree(d_b); hipFree(d_c); std::cout << "sum is " << c << std::endl; return 0; }
7e848a097add52504bb953854d98983585f9234e.cu
#include <iostream> #include <cuda_runtime_api.h> // Define and implement the GPU addition function __global__ void add(int *a, int *b, int *c) { *c = *a + *b; } int main() { int a, b, c; // host copies of a, b, c int *d_a, *d_b, *d_c; // device copies of a, b, c int size = sizeof(int); // Allocate space for device copies of a, b, c cudaMalloc((void **)&d_a, size); cudaMalloc((void **)&d_b, size); cudaMalloc((void **)&d_c, size); // Setup input values a = 2; b = 7; // Copy inputs to device cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice); cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice); // Launch add() kernel on GPU add<<<1,1>>>(d_a, d_b, d_c); // Copy result back to host cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost); // Cleanup cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); std::cout << "sum is " << c << std::endl; return 0; }
75239c08b1612e692597b7e759b9177a64657e36.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * @File nbody.cu * * Implementation of the N-Body problem * * Paraleln programovn na GPU (PCG 2020) * Projekt c. 1 (cuda) * Login: xmarci10 */ #include <cmath> #include <cfloat> #include "nbody.h" /** * CUDA kernel to calculate gravitation velocity * @param p - particles * @param tmp_vel - temp array for velocities * @param N - Number of particles * @param dt - Size of the time step */ __global__ void calculate_gravitation_velocity(t_particles p, t_velocities tmp_vel, int N, float dt) { int thread_id = blockDim.x * blockIdx.x + threadIdx.x; if (thread_id < N) { float F, r, dx, dy, dz; float posx, posy, posz; /** * Ressetting the registers for partial results. * note: Using registers reduces the number of accesses to global memory. * Partial results are saved at the end of the calculation. Using * registers also eliminates the need to reset the global memory (tmp_vel) * after each integration step (Instead we just reset the registers). */ float tmpvelx = 0.0f; float tmpvely = 0.0f; float tmpvelz = 0.0f; /** * Loading positions from the global memory into the registers. * note: Pre-reading data from the global memory, reduces the number of * memory accesses and thus signigicantly speeds up the calculation. */ posx = p.pos_x[thread_id]; posy = p.pos_y[thread_id]; posz = p.pos_z[thread_id]; for (int j = 0; j < N; j++) { /** * The calculation of the gravitational force is divided into several * several instructions in order to eliminate data dependencies, and thus * we have increased the ILP. */ F = -G * dt * p.weight[j]; dx = posx - p.pos_x[j]; dy = posy - p.pos_y[j]; dz = posz - p.pos_z[j]; r = sqrt(dx*dx + dy*dy + dz*dz); // see previous comment F /= (r * r * r + FLT_MIN); tmpvelx += (r > COLLISION_DISTANCE) ? F * dx : 0.0f; tmpvely += (r > COLLISION_DISTANCE) ? F * dy : 0.0f; tmpvelz += (r > COLLISION_DISTANCE) ? F * dz : 0.0f; } /** * Write partial results in global memory * note: Only one store to global memory instead of store in each * cycle's iteration */ tmp_vel.x[thread_id] = tmpvelx; tmp_vel.y[thread_id] = tmpvely; tmp_vel.z[thread_id] = tmpvelz; } }// end of calculate_gravitation_velocity //---------------------------------------------------------------------------------------------------------------------- /** * CUDA kernel to calculate collision velocity * @param p - particles * @param tmp_vel - temp array for velocities * @param N - Number of particles * @param dt - Size of the time step */ __global__ void calculate_collision_velocity(t_particles p, t_velocities tmp_vel, int N, float dt) { int thread_id = blockDim.x * blockIdx.x + threadIdx.x; if (thread_id < N) { float r, dx, dy, dz; float posx, posy, posz; float velx, vely, velz; float weight; /** * Ressetting the registers for partial results. * note: Using registers reduces the number of accesses to global memory. * Partial results are saved at the end of the calculation. Using * registers also eliminates the need to reset the global memory (tmp_vel) * after each integration step (Instead we just reset the registers). */ float tmpvelx = 0.0f; float tmpvely = 0.0f; float tmpvelz = 0.0f; /** * Loading positions, velocities and weights from the global memory into the registers. * note: Pre-reading data from the global memory, reduces the number of * memory accesses and thus signigicantly speeds up the calculation. */ posx = p.pos_x[thread_id]; posy = p.pos_y[thread_id]; posz = p.pos_z[thread_id]; velx = p.vel_x[thread_id]; vely = p.vel_y[thread_id]; velz = p.vel_z[thread_id]; weight = p.weight[thread_id]; for (int j = 0; j < N; j++) { /** * Loading the weight of the second particle as it will be used multiple times. * note: It reduces the number of accesses to the global memory. */ float weight_j = p.weight[j]; dx = posx - p.pos_x[j]; dy = posy - p.pos_y[j]; dz = posz - p.pos_z[j]; r = sqrt(dx*dx + dy*dy + dz*dz); if (r < COLLISION_DISTANCE) { /** * Reuseage of the registers of distances. * note: The values are calculated only once and then used several times, see below. */ dx = weight - weight_j; dy = 2 * weight_j; dz = weight + weight_j; tmpvelx += (r > 0.0f) ? ((dx * velx + dy * p.vel_x[j]) / dz) - velx : 0.0f; tmpvely += (r > 0.0f) ? ((dx * vely + dy * p.vel_y[j]) / dz) - vely : 0.0f; tmpvelz += (r > 0.0f) ? ((dx * velz + dy * p.vel_z[j]) / dz) - velz : 0.0f; } } /** * Write partial results in global memory * note: Only one store to global memory instead of store in each * cycle's iteration */ tmp_vel.x[thread_id] += tmpvelx; tmp_vel.y[thread_id] += tmpvely; tmp_vel.z[thread_id] += tmpvelz; } }// end of calculate_collision_velocity //---------------------------------------------------------------------------------------------------------------------- /** * CUDA kernel to update particles * @param p - particles * @param tmp_vel - temp array for velocities * @param N - Number of particles * @param dt - Size of the time step */ __global__ void update_particle(t_particles p, t_velocities tmp_vel, int N, float dt) { int thread_id = blockDim.x * blockIdx.x + threadIdx.x; if (thread_id < N) { p.vel_x[thread_id] += tmp_vel.x[thread_id]; p.pos_x[thread_id] += p.vel_x[thread_id] * dt; p.vel_y[thread_id] += tmp_vel.y[thread_id]; p.pos_y[thread_id] += p.vel_y[thread_id] * dt; p.vel_z[thread_id] += tmp_vel.z[thread_id]; p.pos_z[thread_id] += p.vel_z[thread_id] * dt; } }// end of update_particle //---------------------------------------------------------------------------------------------------------------------- /** * CUDA kernel to update particles * @param p - particles * @param comX - pointer to a center of mass position in X * @param comY - pointer to a center of mass position in Y * @param comZ - pointer to a center of mass position in Z * @param comW - pointer to a center of mass weight * @param lock - pointer to a user-implemented lock * @param N - Number of particles */ __global__ void centerOfMass(t_particles p, float* comX, float* comY, float* comZ, float* comW, int* lock, const int N) { }// end of centerOfMass //---------------------------------------------------------------------------------------------------------------------- /** * CPU implementation of the Center of Mass calculation * @param particles - All particles in the system * @param N - Number of particles */ __host__ float4 centerOfMassCPU(MemDesc& memDesc) { float4 com = {0 ,0, 0, 0}; for(int i = 0; i < memDesc.getDataSize(); i++) { // Calculate the vector on the line connecting points and most recent position of center-of-mass const float dx = memDesc.getPosX(i) - com.x; const float dy = memDesc.getPosY(i) - com.y; const float dz = memDesc.getPosZ(i) - com.z; // Calculate weight ratio only if at least one particle isn't massless const float dw = ((memDesc.getWeight(i) + com.w) > 0.0f) ? ( memDesc.getWeight(i) / (memDesc.getWeight(i) + com.w)) : 0.0f; // Update position and weight of the center-of-mass according to the weight ration and vector com.x += dx * dw; com.y += dy * dw; com.z += dz * dw; com.w += memDesc.getWeight(i); } return com; }// enf of centerOfMassCPU //----------------------------------------------------------------------------------------------------------------------
75239c08b1612e692597b7e759b9177a64657e36.cu
/** * @File nbody.cu * * Implementation of the N-Body problem * * Paralelní programování na GPU (PCG 2020) * Projekt c. 1 (cuda) * Login: xmarci10 */ #include <cmath> #include <cfloat> #include "nbody.h" /** * CUDA kernel to calculate gravitation velocity * @param p - particles * @param tmp_vel - temp array for velocities * @param N - Number of particles * @param dt - Size of the time step */ __global__ void calculate_gravitation_velocity(t_particles p, t_velocities tmp_vel, int N, float dt) { int thread_id = blockDim.x * blockIdx.x + threadIdx.x; if (thread_id < N) { float F, r, dx, dy, dz; float posx, posy, posz; /** * Ressetting the registers for partial results. * note: Using registers reduces the number of accesses to global memory. * Partial results are saved at the end of the calculation. Using * registers also eliminates the need to reset the global memory (tmp_vel) * after each integration step (Instead we just reset the registers). */ float tmpvelx = 0.0f; float tmpvely = 0.0f; float tmpvelz = 0.0f; /** * Loading positions from the global memory into the registers. * note: Pre-reading data from the global memory, reduces the number of * memory accesses and thus signigicantly speeds up the calculation. */ posx = p.pos_x[thread_id]; posy = p.pos_y[thread_id]; posz = p.pos_z[thread_id]; for (int j = 0; j < N; j++) { /** * The calculation of the gravitational force is divided into several * several instructions in order to eliminate data dependencies, and thus * we have increased the ILP. */ F = -G * dt * p.weight[j]; dx = posx - p.pos_x[j]; dy = posy - p.pos_y[j]; dz = posz - p.pos_z[j]; r = sqrt(dx*dx + dy*dy + dz*dz); // see previous comment F /= (r * r * r + FLT_MIN); tmpvelx += (r > COLLISION_DISTANCE) ? F * dx : 0.0f; tmpvely += (r > COLLISION_DISTANCE) ? F * dy : 0.0f; tmpvelz += (r > COLLISION_DISTANCE) ? F * dz : 0.0f; } /** * Write partial results in global memory * note: Only one store to global memory instead of store in each * cycle's iteration */ tmp_vel.x[thread_id] = tmpvelx; tmp_vel.y[thread_id] = tmpvely; tmp_vel.z[thread_id] = tmpvelz; } }// end of calculate_gravitation_velocity //---------------------------------------------------------------------------------------------------------------------- /** * CUDA kernel to calculate collision velocity * @param p - particles * @param tmp_vel - temp array for velocities * @param N - Number of particles * @param dt - Size of the time step */ __global__ void calculate_collision_velocity(t_particles p, t_velocities tmp_vel, int N, float dt) { int thread_id = blockDim.x * blockIdx.x + threadIdx.x; if (thread_id < N) { float r, dx, dy, dz; float posx, posy, posz; float velx, vely, velz; float weight; /** * Ressetting the registers for partial results. * note: Using registers reduces the number of accesses to global memory. * Partial results are saved at the end of the calculation. Using * registers also eliminates the need to reset the global memory (tmp_vel) * after each integration step (Instead we just reset the registers). */ float tmpvelx = 0.0f; float tmpvely = 0.0f; float tmpvelz = 0.0f; /** * Loading positions, velocities and weights from the global memory into the registers. * note: Pre-reading data from the global memory, reduces the number of * memory accesses and thus signigicantly speeds up the calculation. */ posx = p.pos_x[thread_id]; posy = p.pos_y[thread_id]; posz = p.pos_z[thread_id]; velx = p.vel_x[thread_id]; vely = p.vel_y[thread_id]; velz = p.vel_z[thread_id]; weight = p.weight[thread_id]; for (int j = 0; j < N; j++) { /** * Loading the weight of the second particle as it will be used multiple times. * note: It reduces the number of accesses to the global memory. */ float weight_j = p.weight[j]; dx = posx - p.pos_x[j]; dy = posy - p.pos_y[j]; dz = posz - p.pos_z[j]; r = sqrt(dx*dx + dy*dy + dz*dz); if (r < COLLISION_DISTANCE) { /** * Reuseage of the registers of distances. * note: The values are calculated only once and then used several times, see below. */ dx = weight - weight_j; dy = 2 * weight_j; dz = weight + weight_j; tmpvelx += (r > 0.0f) ? ((dx * velx + dy * p.vel_x[j]) / dz) - velx : 0.0f; tmpvely += (r > 0.0f) ? ((dx * vely + dy * p.vel_y[j]) / dz) - vely : 0.0f; tmpvelz += (r > 0.0f) ? ((dx * velz + dy * p.vel_z[j]) / dz) - velz : 0.0f; } } /** * Write partial results in global memory * note: Only one store to global memory instead of store in each * cycle's iteration */ tmp_vel.x[thread_id] += tmpvelx; tmp_vel.y[thread_id] += tmpvely; tmp_vel.z[thread_id] += tmpvelz; } }// end of calculate_collision_velocity //---------------------------------------------------------------------------------------------------------------------- /** * CUDA kernel to update particles * @param p - particles * @param tmp_vel - temp array for velocities * @param N - Number of particles * @param dt - Size of the time step */ __global__ void update_particle(t_particles p, t_velocities tmp_vel, int N, float dt) { int thread_id = blockDim.x * blockIdx.x + threadIdx.x; if (thread_id < N) { p.vel_x[thread_id] += tmp_vel.x[thread_id]; p.pos_x[thread_id] += p.vel_x[thread_id] * dt; p.vel_y[thread_id] += tmp_vel.y[thread_id]; p.pos_y[thread_id] += p.vel_y[thread_id] * dt; p.vel_z[thread_id] += tmp_vel.z[thread_id]; p.pos_z[thread_id] += p.vel_z[thread_id] * dt; } }// end of update_particle //---------------------------------------------------------------------------------------------------------------------- /** * CUDA kernel to update particles * @param p - particles * @param comX - pointer to a center of mass position in X * @param comY - pointer to a center of mass position in Y * @param comZ - pointer to a center of mass position in Z * @param comW - pointer to a center of mass weight * @param lock - pointer to a user-implemented lock * @param N - Number of particles */ __global__ void centerOfMass(t_particles p, float* comX, float* comY, float* comZ, float* comW, int* lock, const int N) { }// end of centerOfMass //---------------------------------------------------------------------------------------------------------------------- /** * CPU implementation of the Center of Mass calculation * @param particles - All particles in the system * @param N - Number of particles */ __host__ float4 centerOfMassCPU(MemDesc& memDesc) { float4 com = {0 ,0, 0, 0}; for(int i = 0; i < memDesc.getDataSize(); i++) { // Calculate the vector on the line connecting points and most recent position of center-of-mass const float dx = memDesc.getPosX(i) - com.x; const float dy = memDesc.getPosY(i) - com.y; const float dz = memDesc.getPosZ(i) - com.z; // Calculate weight ratio only if at least one particle isn't massless const float dw = ((memDesc.getWeight(i) + com.w) > 0.0f) ? ( memDesc.getWeight(i) / (memDesc.getWeight(i) + com.w)) : 0.0f; // Update position and weight of the center-of-mass according to the weight ration and vector com.x += dx * dw; com.y += dy * dw; com.z += dz * dw; com.w += memDesc.getWeight(i); } return com; }// enf of centerOfMassCPU //----------------------------------------------------------------------------------------------------------------------
9d98cc0496dec6904035fa7341affa1ce2c516c7.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Simulate intercalating cells #include <hiprand/hiprand_kernel.h> #include "../include/dtypes.cuh" #include "../include/inits.cuh" #include "../include/links.cuh" #include "../include/solvers.cuh" #include "../include/vtk.cuh" const auto r_max = 1.f; const auto r_min = 0.5f; const auto n_cells = 500u; const auto prots_per_cell = 1; const auto n_time_steps = 250u; const auto dt = 0.2f; __device__ float3 clipped_cubic(float3 Xi, float3 r, float dist, int i, int j) { float3 dF{0}; if (i == j) return dF; if (dist > r_max) return dF; auto F = 2 * (r_min - dist) * (r_max - dist) + powf(r_max - dist, 2); dF = r * F / dist; return dF; } __global__ void update_protrusions( const float3* __restrict__ d_X, hiprandState_t* d_state, Link* d_link) { auto i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= n_cells * prots_per_cell) return; auto r = d_X[d_link[i].a] - d_X[d_link[i].b]; auto dist = norm3df(r.x, r.y, r.z); if ((dist < 1) or (dist > 2)) { d_link[i].a = 0; d_link[i].b = 0; } auto j = static_cast<int>((i + 0.5) / prots_per_cell); auto k = min( static_cast<int>(hiprand_uniform(&d_state[i]) * n_cells), n_cells - 1); if (j == k) return; r = d_X[j] - d_X[k]; dist = norm3df(r.x, r.y, r.z); if ((fabs(r.x / dist) < 0.2) and (1 < dist < 2)) { d_link[i].a = j; d_link[i].b = k; } } int main(int argc, const char* argv[]) { // Prepare initial state Solution<float3, Grid_solver> cells{n_cells}; random_sphere(r_min, cells); Links protrusions{n_cells * prots_per_cell}; auto intercalation = [&protrusions]( const int n, const float3* __restrict__ d_X, float3* d_dX) { return link_forces(protrusions, d_X, d_dX); }; // Integrate cell positions Vtk_output output{"intercalation"}; for (auto time_step = 0; time_step <= n_time_steps; time_step++) { cells.copy_to_host(); protrusions.copy_to_host(); hipLaunchKernelGGL(( update_protrusions), dim3((n_cells * prots_per_cell + 32 - 1) / 32), dim3(32), 0, 0, cells.d_X, protrusions.d_state, protrusions.d_link); cells.take_step<clipped_cubic>(dt, intercalation); output.write_positions(cells); output.write_links(protrusions); } return 0; }
9d98cc0496dec6904035fa7341affa1ce2c516c7.cu
// Simulate intercalating cells #include <curand_kernel.h> #include "../include/dtypes.cuh" #include "../include/inits.cuh" #include "../include/links.cuh" #include "../include/solvers.cuh" #include "../include/vtk.cuh" const auto r_max = 1.f; const auto r_min = 0.5f; const auto n_cells = 500u; const auto prots_per_cell = 1; const auto n_time_steps = 250u; const auto dt = 0.2f; __device__ float3 clipped_cubic(float3 Xi, float3 r, float dist, int i, int j) { float3 dF{0}; if (i == j) return dF; if (dist > r_max) return dF; auto F = 2 * (r_min - dist) * (r_max - dist) + powf(r_max - dist, 2); dF = r * F / dist; return dF; } __global__ void update_protrusions( const float3* __restrict__ d_X, curandState* d_state, Link* d_link) { auto i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= n_cells * prots_per_cell) return; auto r = d_X[d_link[i].a] - d_X[d_link[i].b]; auto dist = norm3df(r.x, r.y, r.z); if ((dist < 1) or (dist > 2)) { d_link[i].a = 0; d_link[i].b = 0; } auto j = static_cast<int>((i + 0.5) / prots_per_cell); auto k = min( static_cast<int>(curand_uniform(&d_state[i]) * n_cells), n_cells - 1); if (j == k) return; r = d_X[j] - d_X[k]; dist = norm3df(r.x, r.y, r.z); if ((fabs(r.x / dist) < 0.2) and (1 < dist < 2)) { d_link[i].a = j; d_link[i].b = k; } } int main(int argc, const char* argv[]) { // Prepare initial state Solution<float3, Grid_solver> cells{n_cells}; random_sphere(r_min, cells); Links protrusions{n_cells * prots_per_cell}; auto intercalation = [&protrusions]( const int n, const float3* __restrict__ d_X, float3* d_dX) { return link_forces(protrusions, d_X, d_dX); }; // Integrate cell positions Vtk_output output{"intercalation"}; for (auto time_step = 0; time_step <= n_time_steps; time_step++) { cells.copy_to_host(); protrusions.copy_to_host(); update_protrusions<<<(n_cells * prots_per_cell + 32 - 1) / 32, 32>>>( cells.d_X, protrusions.d_state, protrusions.d_link); cells.take_step<clipped_cubic>(dt, intercalation); output.write_positions(cells); output.write_links(protrusions); } return 0; }
f199c78dd2f8f0358cd3ef29a2d40ee8e70f3430.hip
// !!! This is a file automatically generated by hipify!!! /*************************************************************************************************** * Copyright (c) 2020, Vijay Thakkar (thakkarv@gatech.edu). **************************************************************************************************/ ////////////////////////////////////////////////////////////////////// // THIS BENCHMARK FILE IS GENERATED AUTOMATICALLY : DO NOT MODIFY // ////////////////////////////////////////////////////////////////////// #include "benchmark/benchmark.h" #include "cuasr/gemm/device/default_srgemm_configuration.h" #include "cuasr/gemm/device/srgemm.h" #include "cuasr/functional.h" #include "harness.h" //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 8 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x32x1_2x4_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<8, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x32x1_2x4_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 16 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x32x1_4x4_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x32x1_4x4_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 16 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x64x1_4x8_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x64x1_4x8_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x32x1_8x4_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x32x1_8x4_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x64x1_8x8_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x64x1_8x8_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 1 x 1 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_64x32x1_8x8_8x4_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_64x32x1_8x8_8x4_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 8 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x16x1_2x2_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<8, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x16x1_2x2_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 8 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x64x8_8x32x1_2x4_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<8, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x64x8_8x32x1_2x4_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 16 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x16x1_4x2_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x16x1_4x2_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 16 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x32x1_4x4_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x32x1_4x4_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 16 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x8_16x64x1_4x8_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x8_16x64x1_4x8_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 1 x 2 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x16x1_4x4_8x4_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x16x1_4x4_8x4_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x32x1_8x4_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x32x1_8x4_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 32 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_32x64x1_8x8_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_32x64x1_8x8_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 1 x 2 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 0) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_64x32x1_8x8_8x4_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_64x32x1_8x8_8x4_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 1 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x32x1_4x4_4x8_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x32x1_4x4_4x8_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 1 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x32x1_8x4_4x8_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x32x1_8x4_4x8_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 1 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x64x1_8x8_4x8_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x64x1_8x8_4x8_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 1 // Threadblock: 128 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x32x1_8x8_8x4_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x32x1_8x8_8x4_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 16 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_8x16x1_2x2_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_8x16x1_2x2_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 16 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_8x32x1_2x4_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_8x32x1_2x4_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x16x1_4x2_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x16x1_4x2_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x32x1_4x4_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x32x1_4x4_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 32 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x64x1_4x8_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x64x1_4x8_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 2 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x16x1_4x4_8x4_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x16x1_4x4_8x4_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x32x1_8x4_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x32x1_8x4_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 64 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x64x1_8x8_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x64x1_8x8_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 2 // Threadblock: 128 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x16x1_8x4_8x4_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x16x1_8x4_8x4_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 2 // Threadblock: 128 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_64x32x1_8x8_8x4_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_64x32x1_8x8_8x4_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 16 x 64 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x16_8x16x1_2x2_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x16_8x16x1_2x2_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 16 x 128 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x16_8x32x1_2x4_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 128, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x16_8x32x1_2x4_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 4 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x8x1_2x2_8x4_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 8, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x8x1_2x2_8x4_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x16x1_4x2_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x16x1_4x2_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 32 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x32x1_4x4_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x32x1_4x4_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 32 x 256 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x256x8_16x64x1_4x8_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 256, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x256x8_16x64x1_4x8_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 4 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x16x1_4x4_8x4_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x16x1_4x4_8x4_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 64 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x32x1_8x4_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x32x1_8x4_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 64 x 256 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_32x64x1_8x8_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 256, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_32x64x1_8x8_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 4 // Threadblock: 128 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 0) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_64x32x1_8x8_8x4_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_64x32x1_8x8_8x4_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_8x16x1_2x2_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_8x16x1_2x2_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_16x16x1_4x2_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_16x16x1_4x2_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x32x1_4x4_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x32x1_4x4_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 2 // Threadblock: 128 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_32x16x1_4x4_8x4_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_32x16x1_4x4_8x4_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 128 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x32x1_8x4_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x32x1_8x4_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 128 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x64x1_8x8_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x64x1_8x8_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 2 // Threadblock: 256 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x32x8_64x16x1_8x4_8x4_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<256, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x32x8_64x16x1_8x4_8x4_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 2 // Threadblock: 256 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x32x1_8x8_8x4_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<256, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x32x1_8x8_8x4_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 32 x 64 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x16_8x16x1_2x2_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x16_8x16x1_2x2_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 32 x 128 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x16_8x32x1_2x4_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x16_8x32x1_2x4_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 64 x 32 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x16_16x8x1_2x2_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 16>; using WarpShape = cutlass::gemm::GemmShape<16, 8, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x16_16x8x1_2x2_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x16x1_4x2_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x16x1_4x2_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 64 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_16x32x1_4x4_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_16x32x1_4x4_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 64 x 256 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_16x64x1_4x8_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 256, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_16x64x1_4x8_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 128 x 32 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x16_32x8x1_4x2_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 16>; using WarpShape = cutlass::gemm::GemmShape<32, 8, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x16_32x8x1_4x2_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 128 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x16x1_4x4_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x16x1_4x4_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 128 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x32x1_8x4_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x32x1_8x4_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 256 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x16x1_8x4_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<256, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); hipDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x16x1_8x4_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif
f199c78dd2f8f0358cd3ef29a2d40ee8e70f3430.cu
/*************************************************************************************************** * Copyright (c) 2020, Vijay Thakkar (thakkarv@gatech.edu). **************************************************************************************************/ ////////////////////////////////////////////////////////////////////// // THIS BENCHMARK FILE IS GENERATED AUTOMATICALLY : DO NOT MODIFY // ////////////////////////////////////////////////////////////////////// #include "benchmark/benchmark.h" #include "cuasr/gemm/device/default_srgemm_configuration.h" #include "cuasr/gemm/device/srgemm.h" #include "cuasr/functional.h" #include "harness.h" //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 8 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x32x1_2x4_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<8, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x32x1_2x4_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 16 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x32x1_4x4_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x32x1_4x4_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 16 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x64x1_4x8_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x64x1_4x8_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x32x1_8x4_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x32x1_8x4_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 1 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x64x1_8x8_4x8_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x64x1_8x8_4x8_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 1 x 1 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_64x32x1_8x8_8x4_1x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_64x32x1_8x8_8x4_1x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 8 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x16x1_2x2_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<8, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x32x8_8x16x1_2x2_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 8 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x64x8_8x32x1_2x4_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<8, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_8x64x8_8x32x1_2x4_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 16 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x16x1_4x2_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_16x16x1_4x2_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 16 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x32x1_4x4_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_16x32x1_4x4_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 16 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x8_16x64x1_4x8_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x8_16x64x1_4x8_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 1 x 2 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x16x1_4x4_8x4_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_32x16x1_4x4_8x4_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x32x1_8x4_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_32x32x1_8x4_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 1 x 2 // Threadblock: 32 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_32x64x1_8x8_4x8_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_32x64x1_8x8_4x8_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 1 x 2 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 0) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_64x32x1_8x8_8x4_1x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_64x32x1_8x8_8x4_1x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 1 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x32x1_4x4_4x8_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x32x1_4x4_4x8_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 1 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x32x1_8x4_4x8_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x32x1_8x4_4x8_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 1 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x64x1_8x8_4x8_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x64x1_8x8_4x8_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 1 // Threadblock: 128 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x32x1_8x8_8x4_2x1(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x32x1_8x8_8x4_2x1) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 16 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_8x16x1_2x2_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x32x8_8x16x1_2x2_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 16 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_8x32x1_2x4_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x8_8x32x1_2x4_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x16x1_4x2_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x16x1_4x2_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x32x1_4x4_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x32x1_4x4_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 32 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x64x1_4x8_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x64x1_4x8_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 2 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x16x1_4x4_8x4_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_32x16x1_4x4_8x4_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x32x1_8x4_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x32x1_8x4_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 2 // Threadblock: 64 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x64x1_8x8_4x8_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x64x1_8x8_4x8_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 2 // Threadblock: 128 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x16x1_8x4_8x4_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_64x16x1_8x4_8x4_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 2 // Threadblock: 128 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_64x32x1_8x8_8x4_2x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_64x32x1_8x8_8x4_2x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 16 x 64 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x16_8x16x1_2x2_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 64, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x64x16_8x16x1_2x2_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 16 x 128 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x16_8x32x1_2x4_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<16, 128, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_16x128x16_8x32x1_2x4_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 4 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x8x1_2x2_8x4_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 8, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_16x8x1_2x2_8x4_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 32 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x16x1_4x2_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x8_16x16x1_4x2_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 32 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x32x1_4x4_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x8_16x32x1_4x4_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 32 x 256 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x256x8_16x64x1_4x8_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 256, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x256x8_16x64x1_4x8_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 4 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x16x1_4x4_8x4_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_32x16x1_4x4_8x4_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 64 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x32x1_8x4_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_32x32x1_8x4_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 2 x 4 // Threadblock: 64 x 256 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_32x64x1_8x8_4x8_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 256, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_32x64x1_8x8_4x8_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 2 x 4 // Threadblock: 128 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 0) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_64x32x1_8x8_8x4_2x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_64x32x1_8x8_8x4_2x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 32 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_8x16x1_2x2_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x32x8_8x16x1_2x2_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 64 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_16x16x1_4x2_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x8_16x16x1_4x2_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x32x1_4x4_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x32x1_4x4_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 2 // Threadblock: 128 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_32x16x1_4x4_8x4_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x8_32x16x1_4x4_8x4_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 128 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x32x1_8x4_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x32x1_8x4_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 2 // Threadblock: 128 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x64x1_8x8_4x8_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x64x1_8x8_4x8_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 2 // Threadblock: 256 x 32 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x32x8_64x16x1_8x4_8x4_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<256, 32, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x32x8_64x16x1_8x4_8x4_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 8 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 2 // Threadblock: 256 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 1) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x32x1_8x8_8x4_4x2(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<256, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x32x1_8x8_8x4_4x2) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 32 x 64 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x16_8x16x1_2x2_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 64, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 16, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x64x16_8x16x1_2x2_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 32 x 128 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x16_8x32x1_2x4_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<32, 128, 16>; using WarpShape = cutlass::gemm::GemmShape<8, 32, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_32x128x16_8x32x1_2x4_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 2 x 2 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 64 x 32 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x16_16x8x1_2x2_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 32, 16>; using WarpShape = cutlass::gemm::GemmShape<16, 8, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x32x16_16x8x1_2x2_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 64 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x16x1_4x2_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x64x8_16x16x1_4x2_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 64 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_16x32x1_4x4_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x128x8_16x32x1_4x4_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 8 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 64 x 256 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_16x64x1_4x8_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<64, 256, 8>; using WarpShape = cutlass::gemm::GemmShape<16, 64, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_64x256x8_16x64x1_4x8_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 2 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 128 x 32 x 16 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x16_32x8x1_4x2_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 32, 16>; using WarpShape = cutlass::gemm::GemmShape<32, 8, 16>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x32x16_32x8x1_4x2_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 4 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 128 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x16x1_4x4_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x64x8_32x16x1_4x4_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 4 x 8 // Warps / Block: 4 x 4 // Threadblock: 128 x 128 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x32x1_8x4_4x8_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<128, 128, 8>; using WarpShape = cutlass::gemm::GemmShape<32, 32, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_128x128x8_32x32x1_8x4_4x8_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif //////////////////////////////////////////////////////////////////////////////// // Elements / Thread: 8 x 4 // Threads / Warp: 8 x 4 // Warps / Block: 4 x 4 // Threadblock: 256 x 64 x 8 #if defined(CUASR_BENCH_LEVEL) and (CUASR_BENCH_LEVEL >= 2) static void BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x16x1_8x4_8x4_4x4(benchmark::State &state) { const auto N = static_cast<int>(state.range(0)); using precision = float; using OpClass = cutlass::arch::OpClassSimt; using SmArch = cutlass::arch::Sm50; using ThreadblockShape = cutlass::gemm::GemmShape<256, 64, 8>; using WarpShape = cutlass::gemm::GemmShape<64, 16, 8>; using InstructionShape = cutlass::gemm::GemmShape<1, 1, 1>; using Config = typename cuasr::gemm::device::DefaultSemiRingConfiguration< // precision, precision, precision, precision, OpClass, // cuasr::maximum<precision>, cuasr::plus<precision>, SmArch>; using AddOp = Config::AdditionOp; using MultOp = Config::MultiplicationOp; using EpilogueOutputOp = Config::EpilogueOutputOp; using Srgemm = cuasr::gemm::device::Srgemm< // AddOp, MultOp, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, cutlass::layout::ColumnMajor, // precision, OpClass, SmArch, // ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, // cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>; // setup bench harness cuasr::bench::device::BenchHarness<Srgemm> bench({ N, N, N }); // benchmark loop for (auto _ : state) { benchmark::DoNotOptimize(bench.run()); cudaDeviceSynchronize(); } double flops_per_itr = 2.0 * N * N * N; state.counters["Flop/s"] = benchmark::Counter(flops_per_itr, benchmark::Counter::kIsIterationInvariantRate); } BENCHMARK(BM_SM50_device_maximum_plus_ssrgemm_nn_n_256x64x8_64x16x1_8x4_8x4_4x4) ->RangeMultiplier(2)->Range(256, 4096); #endif
4973ad87b27a9902184d25edbddfe3f45bd7d856.hip
// !!! This is a file automatically generated by hipify!!! // Miguel Ascanio Gmez // GPU - Prctica 1 #include "imageUtils.hh" #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; unsigned char *readBMP(char *file_name, char header[54], int *w, int *h) { //Se abre el fichero en modo binario para lectura FILE *f = fopen(file_name, "rb"); if (!f) { perror(file_name); exit(1); } // Cabecera archivo imagen //*********************************** //Devuelve cantidad de bytes leidos int n = fread(header, 1, 54, f); //Si no lee 54 bytes es que la imagen de entrada es demasiado pequea if (n != 54) fprintf(stderr, "Entrada muy pequea (%d bytes)\n", n), exit(1); //Si los dos primeros bytes no corresponden con los caracteres BM no es un fichero BMP if (header[0] != 'B' || header[1] != 'M') fprintf(stderr, "No BMP\n"), exit(1); //El tamao de la imagen es el valor de la posicion 2 de la cabecera menos 54 bytes que ocupa esa cabecera int imagesize = *(int*) (header + 2) - 54; //Si la cabecera no tiene el tamao de 54 o el numero de bits por pixel es distinto de 24 la imagen se rechaza if (*(int*) (header + 10) != 54 || *(short*) (header + 28) != 24) fprintf(stderr, "No color 24-bit\n"), exit(1); //Cuando la posicion 30 del header no es 0, es que existe compresion por lo que la imagen no es valida if (*(int*) (header + 30) != 0) fprintf(stderr, "Compresion no suportada\n"), exit(1); //Se recupera la altura y anchura de la cabecera int width = *(int*) (header + 18); int height = *(int*) (header + 22); //************************************** // Lectura de la imagen //************************************* //Se reservan "imagesize+256+width*6" bytes y se devuelve un puntero a estos datos unsigned char *image = (unsigned char*) malloc(imagesize + 256 + width * 6); image += 128 + width * 3; if ((n = fread(image, 1, imagesize + 1, f)) != imagesize) fprintf(stderr, "File size incorrect: %d bytes read insted of %d\n", n, imagesize), exit(1); fclose(f); printf("Image read correctly (width=%i height=%i, imagesize=%i).\n", width, height, imagesize); /* Output variables */ *w = width; *h = height; return (image); } void writeBMP(float *imageFLOAT, char *file_name, char header[54], int width, int height) { FILE *f; int i, n; int imagesize=*(int*)(header+2)-54; unsigned char *image = (unsigned char*)malloc(3*sizeof(unsigned char)*width*height); for (i=0;i<width*height;i++){ image[3*i] = imageFLOAT[i]; //R image[3*i+1] = imageFLOAT[i]; //G image[3*i+2] = imageFLOAT[i]; //B } f=fopen(file_name, "wb"); //Se abre el fichero en modo binario de escritura if (!f){ perror(file_name); exit(1); } n=fwrite(header, 1, 54, f); //Primeramente se escribe la cabecera de la imagen n+=fwrite(image, 1, imagesize, f); //Y despues se escribe el resto de la imagen if (n!=54+imagesize) //Si se han escrito diferente cantidad de bytes que la suma de la cabecera y el tamao de la imagen. Ha habido error fprintf(stderr, "Escritos %d de %d bytes\n", n, imagesize+54); fclose(f); free(image); } float *RGB2BW(unsigned char *imageUCHAR, int width, int height) { int i, j; //float *imageBW = (float *)malloc(sizeof(float)*width*height); float *imageBW; hipError_t e; if((e = hipHostMalloc(&imageBW, sizeof(float)*width*height)) != 0) { cerr << "ERROR, line: " << __LINE__ << " File: " << __FILE__ << " Error: " << hipGetErrorString(e) << endl; exit(-1); } unsigned char R, B, G; for (i=0; i<height; i++) for (j=0; j<width; j++) { R = imageUCHAR[3*(i*width+j)]; G = imageUCHAR[3*(i*width+j)+1]; B = imageUCHAR[3*(i*width+j)+2]; imageBW[i*width+j] = 0.2989 * R + 0.5870 * G + 0.1140 * B; } return(imageBW); }
4973ad87b27a9902184d25edbddfe3f45bd7d856.cu
// Miguel Ascanio Gómez // GPU - Práctica 1 #include "imageUtils.hh" #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; unsigned char *readBMP(char *file_name, char header[54], int *w, int *h) { //Se abre el fichero en modo binario para lectura FILE *f = fopen(file_name, "rb"); if (!f) { perror(file_name); exit(1); } // Cabecera archivo imagen //*********************************** //Devuelve cantidad de bytes leidos int n = fread(header, 1, 54, f); //Si no lee 54 bytes es que la imagen de entrada es demasiado pequeña if (n != 54) fprintf(stderr, "Entrada muy pequeña (%d bytes)\n", n), exit(1); //Si los dos primeros bytes no corresponden con los caracteres BM no es un fichero BMP if (header[0] != 'B' || header[1] != 'M') fprintf(stderr, "No BMP\n"), exit(1); //El tamaño de la imagen es el valor de la posicion 2 de la cabecera menos 54 bytes que ocupa esa cabecera int imagesize = *(int*) (header + 2) - 54; //Si la cabecera no tiene el tamaño de 54 o el numero de bits por pixel es distinto de 24 la imagen se rechaza if (*(int*) (header + 10) != 54 || *(short*) (header + 28) != 24) fprintf(stderr, "No color 24-bit\n"), exit(1); //Cuando la posicion 30 del header no es 0, es que existe compresion por lo que la imagen no es valida if (*(int*) (header + 30) != 0) fprintf(stderr, "Compresion no suportada\n"), exit(1); //Se recupera la altura y anchura de la cabecera int width = *(int*) (header + 18); int height = *(int*) (header + 22); //************************************** // Lectura de la imagen //************************************* //Se reservan "imagesize+256+width*6" bytes y se devuelve un puntero a estos datos unsigned char *image = (unsigned char*) malloc(imagesize + 256 + width * 6); image += 128 + width * 3; if ((n = fread(image, 1, imagesize + 1, f)) != imagesize) fprintf(stderr, "File size incorrect: %d bytes read insted of %d\n", n, imagesize), exit(1); fclose(f); printf("Image read correctly (width=%i height=%i, imagesize=%i).\n", width, height, imagesize); /* Output variables */ *w = width; *h = height; return (image); } void writeBMP(float *imageFLOAT, char *file_name, char header[54], int width, int height) { FILE *f; int i, n; int imagesize=*(int*)(header+2)-54; unsigned char *image = (unsigned char*)malloc(3*sizeof(unsigned char)*width*height); for (i=0;i<width*height;i++){ image[3*i] = imageFLOAT[i]; //R image[3*i+1] = imageFLOAT[i]; //G image[3*i+2] = imageFLOAT[i]; //B } f=fopen(file_name, "wb"); //Se abre el fichero en modo binario de escritura if (!f){ perror(file_name); exit(1); } n=fwrite(header, 1, 54, f); //Primeramente se escribe la cabecera de la imagen n+=fwrite(image, 1, imagesize, f); //Y despues se escribe el resto de la imagen if (n!=54+imagesize) //Si se han escrito diferente cantidad de bytes que la suma de la cabecera y el tamaño de la imagen. Ha habido error fprintf(stderr, "Escritos %d de %d bytes\n", n, imagesize+54); fclose(f); free(image); } float *RGB2BW(unsigned char *imageUCHAR, int width, int height) { int i, j; //float *imageBW = (float *)malloc(sizeof(float)*width*height); float *imageBW; cudaError_t e; if((e = cudaMallocHost(&imageBW, sizeof(float)*width*height)) != 0) { cerr << "ERROR, line: " << __LINE__ << " File: " << __FILE__ << " Error: " << cudaGetErrorString(e) << endl; exit(-1); } unsigned char R, B, G; for (i=0; i<height; i++) for (j=0; j<width; j++) { R = imageUCHAR[3*(i*width+j)]; G = imageUCHAR[3*(i*width+j)+1]; B = imageUCHAR[3*(i*width+j)+2]; imageBW[i*width+j] = 0.2989 * R + 0.5870 * G + 0.1140 * B; } return(imageBW); }
995d2a7ac6403296f50863712db1364bae8133c9.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* -- MAGMA (version 2.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2019 @generated from sparse/blas/zmergecgs.cu, normal z -> d, Wed Jan 2 14:18:53 2019 @author Hartwig Anzt */ #include "magmasparse_internal.h" #define BLOCK_SIZE 512 #define PRECISION_d // These routines merge multiple kernels from dcgs into one. /* -------------------------------------------------------------------------- */ __global__ void magma_dcgs_1_kernel( int num_rows, int num_cols, double beta, double *r, double *q, double *u, double *p ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ double tmp; tmp = r[ i+j*num_rows ] + beta * q[ i+j*num_rows ]; p[ i+j*num_rows ] = tmp + beta * q[ i+j*num_rows ] + beta * beta * p[ i+j*num_rows ]; u[ i+j*num_rows ] = tmp; } } } /** Purpose ------- Mergels multiple operations into one kernel: u = r + beta q p = u + beta*(q + beta*p) Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] beta double scalar @param[in] r magmaDouble_ptr vector @param[in] q magmaDouble_ptr vector @param[in,out] u magmaDouble_ptr vector @param[in,out] p magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_1( magma_int_t num_rows, magma_int_t num_cols, double beta, magmaDouble_ptr r, magmaDouble_ptr q, magmaDouble_ptr u, magmaDouble_ptr p, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); hipLaunchKernelGGL(( magma_dcgs_1_kernel), dim3(Gs), dim3(Bs), 0, queue->cuda_stream() , num_rows, num_cols, beta, r, q, u, p ); return MAGMA_SUCCESS; } __global__ void magma_dcgs_2_kernel( int num_rows, int num_cols, double *r, double *u, double *p ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ double tmp; tmp = r[ i+j*num_rows ]; u[ i+j*num_rows ] = tmp; p[ i+j*num_rows ] = tmp; } } } /** Purpose ------- Mergels multiple operations into one kernel: u = r p = r Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] r magmaDouble_ptr vector @param[in,out] u magmaDouble_ptr vector @param[in,out] p magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_2( magma_int_t num_rows, magma_int_t num_cols, magmaDouble_ptr r, magmaDouble_ptr u, magmaDouble_ptr p, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); hipLaunchKernelGGL(( magma_dcgs_2_kernel), dim3(Gs), dim3(Bs), 0, queue->cuda_stream() , num_rows, num_cols, r, u, p); return MAGMA_SUCCESS; } __global__ void magma_dcgs_3_kernel( int num_rows, int num_cols, double alpha, double *v_hat, double *u, double *q, double *t ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ double uloc, tmp; uloc = u[ i+j*num_rows ]; tmp = uloc - alpha * v_hat[ i+j*num_rows ]; t[ i+j*num_rows ] = tmp + uloc; q[ i+j*num_rows ] = tmp; } } } /** Purpose ------- Mergels multiple operations into one kernel: q = u - alpha v_hat t = u + q Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] alpha double scalar @param[in] v_hat magmaDouble_ptr vector @param[in] u magmaDouble_ptr vector @param[in,out] q magmaDouble_ptr vector @param[in,out] t magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_3( magma_int_t num_rows, magma_int_t num_cols, double alpha, magmaDouble_ptr v_hat, magmaDouble_ptr u, magmaDouble_ptr q, magmaDouble_ptr t, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); hipLaunchKernelGGL(( magma_dcgs_3_kernel), dim3(Gs), dim3(Bs), 0, queue->cuda_stream() , num_rows, num_cols, alpha, v_hat, u, q, t ); return MAGMA_SUCCESS; } __global__ void magma_dcgs_4_kernel( int num_rows, int num_cols, double alpha, double *u_hat, double *t, double *x, double *r ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ x[ i+j*num_rows ] = x[ i+j*num_rows ] + alpha * u_hat[ i+j*num_rows ]; r[ i+j*num_rows ] = r[ i+j*num_rows ] - alpha * t[ i+j*num_rows ]; } } } /** Purpose ------- Mergels multiple operations into one kernel: x = x + alpha u_hat r = r -alpha*A u_hat = r -alpha*t Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] alpha double scalar @param[in] u_hat magmaDouble_ptr vector @param[in] t magmaDouble_ptr vector @param[in,out] x magmaDouble_ptr vector @param[in,out] r magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_4( magma_int_t num_rows, magma_int_t num_cols, double alpha, magmaDouble_ptr u_hat, magmaDouble_ptr t, magmaDouble_ptr x, magmaDouble_ptr r, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); hipLaunchKernelGGL(( magma_dcgs_4_kernel), dim3(Gs), dim3(Bs), 0, queue->cuda_stream() , num_rows, num_cols, alpha, u_hat, t, x, r ); return MAGMA_SUCCESS; }
995d2a7ac6403296f50863712db1364bae8133c9.cu
/* -- MAGMA (version 2.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2019 @generated from sparse/blas/zmergecgs.cu, normal z -> d, Wed Jan 2 14:18:53 2019 @author Hartwig Anzt */ #include "magmasparse_internal.h" #define BLOCK_SIZE 512 #define PRECISION_d // These routines merge multiple kernels from dcgs into one. /* -------------------------------------------------------------------------- */ __global__ void magma_dcgs_1_kernel( int num_rows, int num_cols, double beta, double *r, double *q, double *u, double *p ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ double tmp; tmp = r[ i+j*num_rows ] + beta * q[ i+j*num_rows ]; p[ i+j*num_rows ] = tmp + beta * q[ i+j*num_rows ] + beta * beta * p[ i+j*num_rows ]; u[ i+j*num_rows ] = tmp; } } } /** Purpose ------- Mergels multiple operations into one kernel: u = r + beta q p = u + beta*(q + beta*p) Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] beta double scalar @param[in] r magmaDouble_ptr vector @param[in] q magmaDouble_ptr vector @param[in,out] u magmaDouble_ptr vector @param[in,out] p magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_1( magma_int_t num_rows, magma_int_t num_cols, double beta, magmaDouble_ptr r, magmaDouble_ptr q, magmaDouble_ptr u, magmaDouble_ptr p, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); magma_dcgs_1_kernel<<< Gs, Bs, 0, queue->cuda_stream() >>>( num_rows, num_cols, beta, r, q, u, p ); return MAGMA_SUCCESS; } __global__ void magma_dcgs_2_kernel( int num_rows, int num_cols, double *r, double *u, double *p ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ double tmp; tmp = r[ i+j*num_rows ]; u[ i+j*num_rows ] = tmp; p[ i+j*num_rows ] = tmp; } } } /** Purpose ------- Mergels multiple operations into one kernel: u = r p = r Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] r magmaDouble_ptr vector @param[in,out] u magmaDouble_ptr vector @param[in,out] p magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_2( magma_int_t num_rows, magma_int_t num_cols, magmaDouble_ptr r, magmaDouble_ptr u, magmaDouble_ptr p, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); magma_dcgs_2_kernel<<< Gs, Bs, 0, queue->cuda_stream() >>>( num_rows, num_cols, r, u, p); return MAGMA_SUCCESS; } __global__ void magma_dcgs_3_kernel( int num_rows, int num_cols, double alpha, double *v_hat, double *u, double *q, double *t ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ double uloc, tmp; uloc = u[ i+j*num_rows ]; tmp = uloc - alpha * v_hat[ i+j*num_rows ]; t[ i+j*num_rows ] = tmp + uloc; q[ i+j*num_rows ] = tmp; } } } /** Purpose ------- Mergels multiple operations into one kernel: q = u - alpha v_hat t = u + q Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] alpha double scalar @param[in] v_hat magmaDouble_ptr vector @param[in] u magmaDouble_ptr vector @param[in,out] q magmaDouble_ptr vector @param[in,out] t magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_3( magma_int_t num_rows, magma_int_t num_cols, double alpha, magmaDouble_ptr v_hat, magmaDouble_ptr u, magmaDouble_ptr q, magmaDouble_ptr t, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); magma_dcgs_3_kernel<<< Gs, Bs, 0, queue->cuda_stream() >>>( num_rows, num_cols, alpha, v_hat, u, q, t ); return MAGMA_SUCCESS; } __global__ void magma_dcgs_4_kernel( int num_rows, int num_cols, double alpha, double *u_hat, double *t, double *x, double *r ) { int i = blockIdx.x * blockDim.x + threadIdx.x; if ( i<num_rows ) { for( int j=0; j<num_cols; j++ ){ x[ i+j*num_rows ] = x[ i+j*num_rows ] + alpha * u_hat[ i+j*num_rows ]; r[ i+j*num_rows ] = r[ i+j*num_rows ] - alpha * t[ i+j*num_rows ]; } } } /** Purpose ------- Mergels multiple operations into one kernel: x = x + alpha u_hat r = r -alpha*A u_hat = r -alpha*t Arguments --------- @param[in] num_rows magma_int_t dimension m @param[in] num_cols magma_int_t dimension n @param[in] alpha double scalar @param[in] u_hat magmaDouble_ptr vector @param[in] t magmaDouble_ptr vector @param[in,out] x magmaDouble_ptr vector @param[in,out] r magmaDouble_ptr vector @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_dgegpuk ********************************************************************/ extern "C" magma_int_t magma_dcgs_4( magma_int_t num_rows, magma_int_t num_cols, double alpha, magmaDouble_ptr u_hat, magmaDouble_ptr t, magmaDouble_ptr x, magmaDouble_ptr r, magma_queue_t queue ) { dim3 Bs( BLOCK_SIZE ); dim3 Gs( magma_ceildiv( num_rows, BLOCK_SIZE ) ); magma_dcgs_4_kernel<<< Gs, Bs, 0, queue->cuda_stream() >>>( num_rows, num_cols, alpha, u_hat, t, x, r ); return MAGMA_SUCCESS; }
f235019f9d7898ff7fcee13c43584a037190d6b3.hip
// !!! This is a file automatically generated by hipify!!! #include "improc.h" #define USE_OMP 1 #define NUM_THREADS 8 using namespace cv; using namespace std; // #define NORMAL_ALLOC #define DEBUG /** * Allocate 2D memory on CPU */ #ifdef NORMAL_ALLOC double** memAlloc2D(int rows, int cols) { double **array = new double*[rows]; for (int i = 0; i < rows; ++i) array[i] = new double[cols]; return array; } #else double** memAlloc2D(int rows, int cols) { double **array; array = new double *[rows]; array[0] = new double [rows*cols]; for (int i = 0; i < rows; ++i) array[i] = array[0] + i * cols; return array; } #endif /** * Allocate 2D unified memory */ double** cudaMallocManaged2D(int rows, int cols){ double **array; hipMallocManaged(&array, rows*sizeof(double*)); hipMallocManaged(&array[0], rows*cols*sizeof(double)); for (unsigned i = 1; i < rows; ++i) array[i] = array[0] + i*cols; return array; } /** * Get a 1D Gaussian kernel */ double* get1DGaussianKernel(int rows, double sigma) { Mat gauss = cv::getGaussianKernel(rows, sigma, CV_64F); double *array; hipMallocManaged(&array, rows*sizeof(double)); for (int i=0; i< rows; ++i) { array[i] = gauss.at<double>(i); } return array; } /** * Get a 2D Gaussian kernel */ double** getGaussianKernel(int rows, int cols, double sigmax, double sigmay) { Mat gauss_x = cv::getGaussianKernel(cols, sigmax, CV_64F); Mat gauss_y = cv::getGaussianKernel(rows, sigmay, CV_64F); Mat gauss_2d = gauss_x * gauss_y.t(); // cout << gauss_2d << endl << endl; double **array = cudaMallocManaged2D(rows, cols); for (int i=0; i< rows; ++i) { for (int j = 0; j < cols; j++) { array[i][j] = gauss_2d.at<double>(i,j); } } return array; } /** * Store an image in a 2D array */ double** img2Array(Mat img) { int rows = img.rows; int cols = img.cols; #ifdef DEBUG cout << "Loading image using OpenCV" << endl; #endif double **array = cudaMallocManaged2D(rows, cols); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) array[i][j] = (double)img.at<uchar>(i,j); return array; } /** * Convert a 2D array to a Mat */ Mat array2Img(double **src, int rows, int cols) { Mat dst(rows, cols, CV_8U); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) dst.at<uchar>(i,j) = (uchar)src[i][j]; return dst; } /** * Convolution */ void conv(double **src, int src_rows, int src_cols, double **kernel, int ker_rows, int ker_cols, double **dst) { int offset_x = ker_rows / 2; int offset_y = ker_cols / 2; double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int x = 0; x < src_rows; x++) { for (int y = 0; y < src_cols; y++) { double sum = 0; for (int r = x - offset_x, i = 0; r <= x + offset_x && i < ker_rows; r++, i++) { if (r < 0 || r >= src_rows) continue; for (int c = y - offset_y, j = 0; c <= y + offset_y && j < ker_cols; c++, j++) { if (c < 0 || c >= src_cols) continue; sum += src[r][c] * kernel[i][j]; } } dst[x][y] = sum; } } t2 = omp_get_wtime(); printf("Convolution [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Double threshold */ void doubleThreshold (double **src, int src_rows, int src_cols, double lo, double hi, double **dst){ double t1, t2; /** Compute gradient map, magnitude, and normalize the gradient*/ double gradientX[src_rows][src_cols]; double gradientY[src_rows][src_cols]; double gradientMag[src_rows][src_cols]; int peaks[src_rows][src_cols]; omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 1; i < src_rows - 1; i++) { for (int j = 1; j < src_cols - 1; j++) { gradientX[i][j] = (src[i+1][j] - src[i-1][j]) / 255.0; gradientY[i][j] = (src[i][j+1] - src[i][j-1]) / 255.0; gradientMag[i][j] = sqrt(pow(gradientX[i][j],2) + pow(gradientY[i][j],2)); gradientX[i][j] /= gradientMag[i][j]; gradientY[i][j] /= gradientMag[i][j]; } } t2 = omp_get_wtime(); printf("Compute gradient map [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); /** Find peaks and find strong edges and non-edge pixel*/ t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 1; i < src_rows - 1; i++) { for (int j = 1; j < src_cols - 1; j++) { int forward_x = min(max(0, i + (int)round(gradientX[i][j])), src_rows-2); int forward_y = min(max(0, j + (int)round(gradientY[i][j])), src_cols-2); int backward_x = min(max(0, i - (int)round(gradientX[i][j])), src_rows-2); int backward_y = min(max(0, j - (int)round(gradientY[i][j])), src_cols-2); if (gradientMag[i][j] > gradientMag[forward_x][forward_y] && gradientMag[i][j] >= gradientMag[backward_x][backward_y] || gradientMag[i][j] >= gradientMag[forward_x][forward_y] && gradientMag[i][j] > gradientMag[backward_x][backward_y]) { peaks[i][j] = 1; if (gradientMag[i][j] >= hi) { dst[i][j] = 255; // printf("Strong edge pixel (%d, %d)\n", i, j); } else if (gradientMag[i][j] < lo) dst[i][j] = 0; } } } t2 = omp_get_wtime(); printf("Find strong edge [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); /** Find weak edges*/ t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 1; i < src_rows - 1; i++) { for (int j = 1; j < src_cols - 1; j++) { if (peaks[i][j] != 1 || dst[i][j] > 0) continue; for (int r = -1; r <= 1; r++) { for (int c = -1; c <= 1; c++) { if (dst[i+r][j+c] == 255) { dst[i][j] = 255; // printf("Weak edge pixel (%d, %d)\n", i, j); } } } } } t2 = omp_get_wtime(); printf("Find weak edge [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Distance Transform */ void distTrans(double **src, int src_rows, int src_cols, double **dst) { double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); /** Initialize distance map */ #pragma omp parallel for collapse(2) if (USE_OMP) for (int i = 0; i < src_rows; i++) { for (int j = 0; j < src_cols; j++) { if (src[i][j] > 0) dst[i][j] = 0; else dst[i][j] = (double)INT_MAX; } } t1 = omp_get_wtime(); /** First pass */ for (int k = 0; k <= src_rows + src_cols -2; k++) { int start; int length; int *index_i; if (src_rows < src_cols) { if (k < src_rows) { length = k + 1; start = k; } else if (k < src_cols) { length = src_rows; start = src_rows - 1; } else { length = src_rows + src_cols - k - 1; start = src_rows - 1; } } else { if (k < src_cols) { length = k + 1; start = k; } else if (k < src_rows) { length = src_cols; start = k; } else { length = src_rows + src_cols - k - 1; start = src_rows - 1; } } index_i = new int[length]; for (int r = 0; r < length; r++) index_i[r] = start--; #pragma omp parallel for if (USE_OMP) for (int r = 0; r < length; r++) { int i = index_i[r]; int j = k - i; if (i == 0 && j == 0) continue; else if (i == 0) dst[i][j] = min(dst[i][j], dst[i][j-1] + 1); else if (j == 0) dst[i][j] = min(dst[i][j], dst[i-1][j] + 1); else dst[i][j] = min(dst[i][j], min(dst[i][j-1], dst[i-1][j]) + 1); } delete[] index_i; } /** Second pass */ for (int k = src_rows + src_cols - 2; k >= 0; k--) { int start; int length; int *index_j; if (src_rows < src_cols) { if (k >= src_cols) { length = src_rows + src_cols - k - 1; start = src_cols - 1; } else if (k < src_rows) { length = k + 1; start = k; } else { length = src_rows; start = k; } } else { if (k >= src_rows) { length = src_rows + src_cols - k - 1; start = src_cols - 1; } else if (k < src_cols) { length = k + 1; start = k; } else { length = src_cols; start = src_cols - 1; } } index_j = new int[length]; for (int r = 0; r < length; r++) index_j[r] = start--; #pragma omp parallel for if (USE_OMP) for (int r = 0; r < length; r++) { int j = index_j[r]; int i = k - j; if (i == src_rows - 1 && j == src_cols - 1) continue; else if (i == src_rows - 1) dst[i][j] = min(dst[i][j], dst[i][j+1] + 1); else if (j == src_cols - 1) dst[i][j] = min(dst[i][j], dst[i+1][j] + 1); else dst[i][j] = min(dst[i][j], min(dst[i][j+1], dst[i+1][j]) + 1); } delete[] index_j; } t2 = omp_get_wtime(); printf("DistTrans [%d, %d] : %gms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Dilate the binary image based on its distance map */ void dilate(double **src, int src_rows, int src_cols, int d, double **dst) { double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 0; i < src_rows; i++) { for (int j = 0; j < src_cols; j++) { if (src[i][j] <= d) dst[i][j] = 255; } } t2 = omp_get_wtime(); printf("Dilation [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Non maximum supression */ void nonMaxSupression(double **src, int src_rows, int src_cols, int t_rows, int t_cols, double p, double **dst){ double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); /** Get the max */ double global_max = -1; t1 = omp_get_wtime(); #pragma omp parallel for collapse(2) reduction(max:global_max) if (USE_OMP) for (int x = 0; x < src_rows; x++) { for (int y = 0; y < src_cols; y++) { if (global_max < src[x][y]) global_max = src[x][y]; } } int offset_x = t_rows / 2; int offset_y = t_cols / 2; double threshold = global_max * p; #pragma omp parallel for collapse(2) if (USE_OMP) for (int x = 1; x < src_rows - 1; x++) { for (int y = 1; y < src_cols - 1; y++) { /** Threshold and find local maximum */ if (src[x][y] >= threshold && src[x][y] >= src[x+1][y] && src[x][y] >= src[x-1][y] && src[x][y] >= src[x][y+1] && src[x][y] >= src[x][y-1]) { /** Non maximum supression */ int local_max = -1; int local_sum = 0; for (int r = x - offset_x; r <= x + offset_x; r++) { if (r < 0 || r >= src_rows) continue; for (int c = y - offset_y; c <= y + offset_y; c++) { if (c < 0 || c >= src_cols) continue; if (local_max < src[r][c]) local_max = src[r][c]; local_sum += dst[r][c]; } } if (src[x][y] == local_max && local_sum == 0) { dst[x][y] = src[x][y]; } } } } t2 = omp_get_wtime(); printf("Non maximum supression [%d, %d] : %gms\n", src_rows, src_cols, (t2-t1)*1000); } void drawBox(double **src, int src_rows, int src_cols, int t_rows, int t_cols, Mat &img_rgb){ double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); //omp_set_num_threads(NUM_THREADS); int offset_x = t_rows / 2; int offset_y = t_cols / 2; for (int x = 0; x < src_rows; x++) { for (int y = 0; y < src_cols; y++) { if (src[x][y] == 0) continue; int top = max(x - offset_x, 0); int buttom = min(x + offset_x, src_cols - 1); int left = max(y - offset_y, 0); int right = min(y + offset_y, src_rows - 1); for (int j = left; j <= right; j++) { img_rgb.at<Vec3b>(top, j) = Vec3b(0,0,255); img_rgb.at<Vec3b>(buttom, j) = Vec3b(0,0,255); // img_rgb.at<Vec3b>(top, j)[0] = 255; // img_rgb.at<Vec3b>(top, j)[1] = 0; // img_rgb.at<Vec3b>(top, j)[2] = 0; // img_rgb.at<Vec3b>(buttom, j)[0] = 255; // img_rgb.at<Vec3b>(buttom, j)[0] = 0; // img_rgb.at<Vec3b>(buttom, j)[0] = 0; // cout << img_rgb.at<Vec3b>(buttom, j); } for (int i = top; i <= buttom; i++) { img_rgb.at<Vec3b>(i, left) = Vec3b(0,0,255); img_rgb.at<Vec3b>(i, right) = Vec3b(0,0,255); // img_rgb.at<Vec3b>(i, left)[0] = 255; // img_rgb.at<Vec3b>(i, left)[1] = 0; // img_rgb.at<Vec3b>(i, left)[2] = 0; // img_rgb.at<Vec3b>(i, right)[0] = 255; // img_rgb.at<Vec3b>(i, right)[0] = 0; // img_rgb.at<Vec3b>(i, right)[0] = 0; } } } }
f235019f9d7898ff7fcee13c43584a037190d6b3.cu
#include "improc.h" #define USE_OMP 1 #define NUM_THREADS 8 using namespace cv; using namespace std; // #define NORMAL_ALLOC #define DEBUG /** * Allocate 2D memory on CPU */ #ifdef NORMAL_ALLOC double** memAlloc2D(int rows, int cols) { double **array = new double*[rows]; for (int i = 0; i < rows; ++i) array[i] = new double[cols]; return array; } #else double** memAlloc2D(int rows, int cols) { double **array; array = new double *[rows]; array[0] = new double [rows*cols]; for (int i = 0; i < rows; ++i) array[i] = array[0] + i * cols; return array; } #endif /** * Allocate 2D unified memory */ double** cudaMallocManaged2D(int rows, int cols){ double **array; cudaMallocManaged(&array, rows*sizeof(double*)); cudaMallocManaged(&array[0], rows*cols*sizeof(double)); for (unsigned i = 1; i < rows; ++i) array[i] = array[0] + i*cols; return array; } /** * Get a 1D Gaussian kernel */ double* get1DGaussianKernel(int rows, double sigma) { Mat gauss = cv::getGaussianKernel(rows, sigma, CV_64F); double *array; cudaMallocManaged(&array, rows*sizeof(double)); for (int i=0; i< rows; ++i) { array[i] = gauss.at<double>(i); } return array; } /** * Get a 2D Gaussian kernel */ double** getGaussianKernel(int rows, int cols, double sigmax, double sigmay) { Mat gauss_x = cv::getGaussianKernel(cols, sigmax, CV_64F); Mat gauss_y = cv::getGaussianKernel(rows, sigmay, CV_64F); Mat gauss_2d = gauss_x * gauss_y.t(); // cout << gauss_2d << endl << endl; double **array = cudaMallocManaged2D(rows, cols); for (int i=0; i< rows; ++i) { for (int j = 0; j < cols; j++) { array[i][j] = gauss_2d.at<double>(i,j); } } return array; } /** * Store an image in a 2D array */ double** img2Array(Mat img) { int rows = img.rows; int cols = img.cols; #ifdef DEBUG cout << "Loading image using OpenCV" << endl; #endif double **array = cudaMallocManaged2D(rows, cols); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) array[i][j] = (double)img.at<uchar>(i,j); return array; } /** * Convert a 2D array to a Mat */ Mat array2Img(double **src, int rows, int cols) { Mat dst(rows, cols, CV_8U); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) dst.at<uchar>(i,j) = (uchar)src[i][j]; return dst; } /** * Convolution */ void conv(double **src, int src_rows, int src_cols, double **kernel, int ker_rows, int ker_cols, double **dst) { int offset_x = ker_rows / 2; int offset_y = ker_cols / 2; double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int x = 0; x < src_rows; x++) { for (int y = 0; y < src_cols; y++) { double sum = 0; for (int r = x - offset_x, i = 0; r <= x + offset_x && i < ker_rows; r++, i++) { if (r < 0 || r >= src_rows) continue; for (int c = y - offset_y, j = 0; c <= y + offset_y && j < ker_cols; c++, j++) { if (c < 0 || c >= src_cols) continue; sum += src[r][c] * kernel[i][j]; } } dst[x][y] = sum; } } t2 = omp_get_wtime(); printf("Convolution [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Double threshold */ void doubleThreshold (double **src, int src_rows, int src_cols, double lo, double hi, double **dst){ double t1, t2; /** Compute gradient map, magnitude, and normalize the gradient*/ double gradientX[src_rows][src_cols]; double gradientY[src_rows][src_cols]; double gradientMag[src_rows][src_cols]; int peaks[src_rows][src_cols]; omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 1; i < src_rows - 1; i++) { for (int j = 1; j < src_cols - 1; j++) { gradientX[i][j] = (src[i+1][j] - src[i-1][j]) / 255.0; gradientY[i][j] = (src[i][j+1] - src[i][j-1]) / 255.0; gradientMag[i][j] = sqrt(pow(gradientX[i][j],2) + pow(gradientY[i][j],2)); gradientX[i][j] /= gradientMag[i][j]; gradientY[i][j] /= gradientMag[i][j]; } } t2 = omp_get_wtime(); printf("Compute gradient map [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); /** Find peaks and find strong edges and non-edge pixel*/ t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 1; i < src_rows - 1; i++) { for (int j = 1; j < src_cols - 1; j++) { int forward_x = min(max(0, i + (int)round(gradientX[i][j])), src_rows-2); int forward_y = min(max(0, j + (int)round(gradientY[i][j])), src_cols-2); int backward_x = min(max(0, i - (int)round(gradientX[i][j])), src_rows-2); int backward_y = min(max(0, j - (int)round(gradientY[i][j])), src_cols-2); if (gradientMag[i][j] > gradientMag[forward_x][forward_y] && gradientMag[i][j] >= gradientMag[backward_x][backward_y] || gradientMag[i][j] >= gradientMag[forward_x][forward_y] && gradientMag[i][j] > gradientMag[backward_x][backward_y]) { peaks[i][j] = 1; if (gradientMag[i][j] >= hi) { dst[i][j] = 255; // printf("Strong edge pixel (%d, %d)\n", i, j); } else if (gradientMag[i][j] < lo) dst[i][j] = 0; } } } t2 = omp_get_wtime(); printf("Find strong edge [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); /** Find weak edges*/ t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 1; i < src_rows - 1; i++) { for (int j = 1; j < src_cols - 1; j++) { if (peaks[i][j] != 1 || dst[i][j] > 0) continue; for (int r = -1; r <= 1; r++) { for (int c = -1; c <= 1; c++) { if (dst[i+r][j+c] == 255) { dst[i][j] = 255; // printf("Weak edge pixel (%d, %d)\n", i, j); } } } } } t2 = omp_get_wtime(); printf("Find weak edge [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Distance Transform */ void distTrans(double **src, int src_rows, int src_cols, double **dst) { double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); /** Initialize distance map */ #pragma omp parallel for collapse(2) if (USE_OMP) for (int i = 0; i < src_rows; i++) { for (int j = 0; j < src_cols; j++) { if (src[i][j] > 0) dst[i][j] = 0; else dst[i][j] = (double)INT_MAX; } } t1 = omp_get_wtime(); /** First pass */ for (int k = 0; k <= src_rows + src_cols -2; k++) { int start; int length; int *index_i; if (src_rows < src_cols) { if (k < src_rows) { length = k + 1; start = k; } else if (k < src_cols) { length = src_rows; start = src_rows - 1; } else { length = src_rows + src_cols - k - 1; start = src_rows - 1; } } else { if (k < src_cols) { length = k + 1; start = k; } else if (k < src_rows) { length = src_cols; start = k; } else { length = src_rows + src_cols - k - 1; start = src_rows - 1; } } index_i = new int[length]; for (int r = 0; r < length; r++) index_i[r] = start--; #pragma omp parallel for if (USE_OMP) for (int r = 0; r < length; r++) { int i = index_i[r]; int j = k - i; if (i == 0 && j == 0) continue; else if (i == 0) dst[i][j] = min(dst[i][j], dst[i][j-1] + 1); else if (j == 0) dst[i][j] = min(dst[i][j], dst[i-1][j] + 1); else dst[i][j] = min(dst[i][j], min(dst[i][j-1], dst[i-1][j]) + 1); } delete[] index_i; } /** Second pass */ for (int k = src_rows + src_cols - 2; k >= 0; k--) { int start; int length; int *index_j; if (src_rows < src_cols) { if (k >= src_cols) { length = src_rows + src_cols - k - 1; start = src_cols - 1; } else if (k < src_rows) { length = k + 1; start = k; } else { length = src_rows; start = k; } } else { if (k >= src_rows) { length = src_rows + src_cols - k - 1; start = src_cols - 1; } else if (k < src_cols) { length = k + 1; start = k; } else { length = src_cols; start = src_cols - 1; } } index_j = new int[length]; for (int r = 0; r < length; r++) index_j[r] = start--; #pragma omp parallel for if (USE_OMP) for (int r = 0; r < length; r++) { int j = index_j[r]; int i = k - j; if (i == src_rows - 1 && j == src_cols - 1) continue; else if (i == src_rows - 1) dst[i][j] = min(dst[i][j], dst[i][j+1] + 1); else if (j == src_cols - 1) dst[i][j] = min(dst[i][j], dst[i+1][j] + 1); else dst[i][j] = min(dst[i][j], min(dst[i][j+1], dst[i+1][j]) + 1); } delete[] index_j; } t2 = omp_get_wtime(); printf("DistTrans [%d, %d] : %gms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Dilate the binary image based on its distance map */ void dilate(double **src, int src_rows, int src_cols, int d, double **dst) { double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); t1 = omp_get_wtime(); #pragma omp parallel for if (USE_OMP) for (int i = 0; i < src_rows; i++) { for (int j = 0; j < src_cols; j++) { if (src[i][j] <= d) dst[i][j] = 255; } } t2 = omp_get_wtime(); printf("Dilation [%d, %d] : %f ms\n", src_rows, src_cols, (t2-t1)*1000); } /** * Non maximum supression */ void nonMaxSupression(double **src, int src_rows, int src_cols, int t_rows, int t_cols, double p, double **dst){ double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); omp_set_num_threads(NUM_THREADS); /** Get the max */ double global_max = -1; t1 = omp_get_wtime(); #pragma omp parallel for collapse(2) reduction(max:global_max) if (USE_OMP) for (int x = 0; x < src_rows; x++) { for (int y = 0; y < src_cols; y++) { if (global_max < src[x][y]) global_max = src[x][y]; } } int offset_x = t_rows / 2; int offset_y = t_cols / 2; double threshold = global_max * p; #pragma omp parallel for collapse(2) if (USE_OMP) for (int x = 1; x < src_rows - 1; x++) { for (int y = 1; y < src_cols - 1; y++) { /** Threshold and find local maximum */ if (src[x][y] >= threshold && src[x][y] >= src[x+1][y] && src[x][y] >= src[x-1][y] && src[x][y] >= src[x][y+1] && src[x][y] >= src[x][y-1]) { /** Non maximum supression */ int local_max = -1; int local_sum = 0; for (int r = x - offset_x; r <= x + offset_x; r++) { if (r < 0 || r >= src_rows) continue; for (int c = y - offset_y; c <= y + offset_y; c++) { if (c < 0 || c >= src_cols) continue; if (local_max < src[r][c]) local_max = src[r][c]; local_sum += dst[r][c]; } } if (src[x][y] == local_max && local_sum == 0) { dst[x][y] = src[x][y]; } } } } t2 = omp_get_wtime(); printf("Non maximum supression [%d, %d] : %gms\n", src_rows, src_cols, (t2-t1)*1000); } void drawBox(double **src, int src_rows, int src_cols, int t_rows, int t_cols, Mat &img_rgb){ double t1, t2; double sizeGB = src_rows * src_cols * sizeof(double) / (1024.0 * 1024.0 * 1024.0); //omp_set_num_threads(NUM_THREADS); int offset_x = t_rows / 2; int offset_y = t_cols / 2; for (int x = 0; x < src_rows; x++) { for (int y = 0; y < src_cols; y++) { if (src[x][y] == 0) continue; int top = max(x - offset_x, 0); int buttom = min(x + offset_x, src_cols - 1); int left = max(y - offset_y, 0); int right = min(y + offset_y, src_rows - 1); for (int j = left; j <= right; j++) { img_rgb.at<Vec3b>(top, j) = Vec3b(0,0,255); img_rgb.at<Vec3b>(buttom, j) = Vec3b(0,0,255); // img_rgb.at<Vec3b>(top, j)[0] = 255; // img_rgb.at<Vec3b>(top, j)[1] = 0; // img_rgb.at<Vec3b>(top, j)[2] = 0; // img_rgb.at<Vec3b>(buttom, j)[0] = 255; // img_rgb.at<Vec3b>(buttom, j)[0] = 0; // img_rgb.at<Vec3b>(buttom, j)[0] = 0; // cout << img_rgb.at<Vec3b>(buttom, j); } for (int i = top; i <= buttom; i++) { img_rgb.at<Vec3b>(i, left) = Vec3b(0,0,255); img_rgb.at<Vec3b>(i, right) = Vec3b(0,0,255); // img_rgb.at<Vec3b>(i, left)[0] = 255; // img_rgb.at<Vec3b>(i, left)[1] = 0; // img_rgb.at<Vec3b>(i, left)[2] = 0; // img_rgb.at<Vec3b>(i, right)[0] = 255; // img_rgb.at<Vec3b>(i, right)[0] = 0; // img_rgb.at<Vec3b>(i, right)[0] = 0; } } } }
1b939bcdac6b27676c25c4371ac9c603c7af3a64.hip
// !!! This is a file automatically generated by hipify!!! #include "cuda_error_hadling.h" #include "bfs_gpu.cuh" #include <omp.h> #include <limits> #include <iostream> #include <hip/hip_runtime.h> #include <thrust/device_vector.h> #include <thrust/host_vector.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <hip/hip_runtime.h> #include <sys/time.h> #include <math.h> #include <assert.h> #include <float.h> #include "const.h" using namespace std; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // init levels ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void __global__ init_kernel(int *_levels, int _vertices_count, int _source_vertex) { register const int idx = (blockIdx.x * blockDim.x + threadIdx.x) + blockIdx.y * blockDim.x * gridDim.x; // if (idx < _vertices_count) _levels[idx] = UNVISITED_VERTEX; _levels[_source_vertex] = 1; // - "" } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // main computational algorithm ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void __global__ bfs_kernel_old(int *_levels, long long *_outgoing_ptrs, int *_outgoing_ids, int _vertices_count, long long _edges_count, int *_changes, int _current_level) { register const int src_id = blockIdx.x * blockDim.x + threadIdx.x; if (src_id < _vertices_count) // { if(_levels[src_id] == _current_level) // ( ) { const long long edge_start = _outgoing_ptrs[src_id]; // const int connections_count = _outgoing_ptrs[src_id + 1] - _outgoing_ptrs[src_id]; // for(int edge_pos = 0; edge_pos < connections_count; edge_pos++) // : { int dst_id = _outgoing_ids[edge_start + edge_pos]; // ID if (_levels[dst_id] == UNVISITED_VERTEX) // - { _levels[dst_id] = _current_level + 1; // _changes[0] = 1; } } } } } void __global__ bfs_kernel(int *_frontier_ids, int _frontier_ids_size, int *_levels, long long *_outgoing_ptrs, int *_outgoing_ids, int _vertices_count, long long _edges_count, int *_changes, int _current_level, int threads_per_vertex) { const long long src_id = (blockIdx.x*blockDim.x+threadIdx.x); const int i = src_id / threads_per_vertex; if (i < _frontier_ids_size) // { int idx = _frontier_ids[i]; const int first_edge_ptr = _outgoing_ptrs[idx]; const int connections_count = _outgoing_ptrs[idx + 1] - _outgoing_ptrs[idx]; for (int cur_edge = threadIdx.x % threads_per_vertex; cur_edge < connections_count; cur_edge+=threads_per_vertex) { int dst_id = _outgoing_ids[first_edge_ptr + cur_edge]; if (_levels[dst_id] == UNVISITED_VERTEX) // - { _levels[dst_id] = _current_level + 1; // _changes[0] = 1; } } } } //////////////////////////////// //// Find indices of level ///// //////////////////////////////// void __global__ copy_current_level_frontier(int * _low_ids, int _low_threshold, int * _bunched_ids, int _high_threshold, int * _frontier_ids, long long * _outgoing_ptrs, int * _levels, int _current_level, int _vertices_counts) { register const int idx = threadIdx.x + blockDim.x*blockIdx.x; if (idx < _vertices_counts) { if (_levels[idx] == _current_level) { long long connections = _outgoing_ptrs[idx+1]-_outgoing_ptrs[idx]; if (connections > _high_threshold) { _low_ids[idx] = -1; _bunched_ids[idx] = idx; _frontier_ids[idx] = -1; } else if (connections < _low_threshold){ _low_ids[idx] = idx; _bunched_ids[idx] = -1; _frontier_ids[idx] = -1; } else { _low_ids[idx] = -1; _bunched_ids[idx] = -1; _frontier_ids[idx] = idx; } } else { _low_ids[idx] = -1; _bunched_ids[idx] = -1; _frontier_ids[idx] = -1; } } } struct is_inactive { __host__ __device__ bool operator()(const int x) { return (x == -1); } }; tuple<int, int, int> generate_frontier(int * _low_ids, int _low_threshold, int * _bunched_ids, int _high_threshold, int * _frontier_ids, long long * _outgoing_ptrs, int * _levels, int _current_level, int _vertices_counts) { int blockDim = 1024; int gridDim = (_vertices_counts-1)/blockDim + 1; hipLaunchKernelGGL(( SAFE_KERNEL_CALL((copy_current_level_frontier), dim3(gridDim), dim3(blockDim), 0, 0, _low_ids, _low_threshold, _bunched_ids, _high_threshold, _frontier_ids, _outgoing_ptrs, _levels, _current_level, _vertices_counts))); int *new_end = remove_if(thrust::device, _frontier_ids, _frontier_ids+_vertices_counts,is_inactive()); int frontier_ids_size = new_end - _frontier_ids; new_end = remove_if(thrust::device, _bunched_ids, _bunched_ids+_vertices_counts, is_inactive()); int bunched_ids_size = new_end - _bunched_ids; new_end = remove_if(thrust::device, _low_ids, _low_ids+_vertices_counts, is_inactive()); int low_ids_size = new_end - _low_ids; return make_tuple(frontier_ids_size, bunched_ids_size, low_ids_size); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // single GPU implememntation ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void gpu_bfs_wrapper(long long *_outgoing_ptrs, int *_outgoing_ids, int _vertices_count, long long _edges_count, int _source_vertex, int *_levels, int *_frontier_ids, int *_bunched_ids, int *_low_ids, const vector<hipStream_t>& Stream) { dim3 init_threads(1024); dim3 init_blocks((_vertices_count - 1) / init_threads.x + 1); // call init kernel hipLaunchKernelGGL(( SAFE_KERNEL_CALL((init_kernel) , dim3(init_blocks), dim3(init_threads) , 0, 0, _levels, _vertices_count, _source_vertex))); // device variable to stop iterations, for each source vertex int *changes; SAFE_CALL(hipMallocManaged((void**)&changes, sizeof(int))); // set grid size dim3 compute_threads(1024); dim3 compute_blocks_low(((_vertices_count - 1) / compute_threads.x + 1)/2); dim3 compute_blocks_front; dim3 compute_blocks_bunched(4*((_vertices_count - 1) / compute_threads.x + 1)); int current_level = 1; using namespace thrust; using namespace thrust::placeholders; int low_threshold = 8; // less then 10 edges int high_threshold = 1024; // over 400 edges // compute shortest paths do { changes[0] = 0; std::tuple<int,int,int> ids_sizes = generate_frontier(_low_ids, low_threshold, _bunched_ids, high_threshold, _frontier_ids, _outgoing_ptrs, _levels, current_level, _vertices_count); int frontier_ids_size = std::get<0>(ids_sizes); int bunched_ids_size = std::get<1>(ids_sizes); int low_ids_size = std::get<2>(ids_sizes); //cout << frontier_ids_size << ' ' << bunched_ids_size << ' ' << low_ids_size << "\n"; if (low_ids_size != 0) { hipLaunchKernelGGL(( bfs_kernel) , dim3(compute_blocks_low), dim3(compute_threads), 0, Stream[2] , _low_ids, low_ids_size, _levels, _outgoing_ptrs, _outgoing_ids, _vertices_count, _edges_count, changes, current_level, 1); } if (bunched_ids_size != 0) { hipLaunchKernelGGL(( bfs_kernel) , dim3(compute_blocks_bunched), dim3(compute_threads), 0, Stream[1] , _bunched_ids, bunched_ids_size, _levels, _outgoing_ptrs, _outgoing_ids, _vertices_count, _edges_count, changes, current_level, 1024); } if (low_ids_size != 0 || bunched_ids_size != 0) { compute_blocks_front.x = 24*((_vertices_count - 1) / compute_threads.x + 1); } else { compute_blocks_front.x = 32*((_vertices_count - 1) / compute_threads.x + 1); } hipLaunchKernelGGL(( bfs_kernel) , dim3(compute_blocks_front), dim3(compute_threads), 0, Stream[0] , _frontier_ids, frontier_ids_size, _levels, _outgoing_ptrs, _outgoing_ids, _vertices_count, _edges_count, changes, current_level, 32); hipDeviceSynchronize(); // for ( int i = 0; i < 3; i++ ) { // SAFE_CALL(hipStreamDestroy(Stream[i])); // } current_level++; } while(changes[0] > 0); SAFE_CALL(hipFree(changes)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1b939bcdac6b27676c25c4371ac9c603c7af3a64.cu
#include "cuda_error_hadling.h" #include "bfs_gpu.cuh" #include <omp.h> #include <limits> #include <iostream> #include <cuda_runtime.h> #include <thrust/device_vector.h> #include <thrust/host_vector.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <cuda.h> #include <sys/time.h> #include <math.h> #include <assert.h> #include <float.h> #include "const.h" using namespace std; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // init levels ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void __global__ init_kernel(int *_levels, int _vertices_count, int _source_vertex) { register const int idx = (blockIdx.x * blockDim.x + threadIdx.x) + blockIdx.y * blockDim.x * gridDim.x; // все вершины кроме источника еще не посещены if (idx < _vertices_count) _levels[idx] = UNVISITED_VERTEX; _levels[_source_vertex] = 1; // вершина-источник помещается на первый "уровень" } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // main computational algorithm ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void __global__ bfs_kernel_old(int *_levels, long long *_outgoing_ptrs, int *_outgoing_ids, int _vertices_count, long long _edges_count, int *_changes, int _current_level) { register const int src_id = blockIdx.x * blockDim.x + threadIdx.x; if (src_id < _vertices_count) // для всех графовых вершин выполнить следующее { if(_levels[src_id] == _current_level) // если графовая вершина принадлежит текущему (ранее посещенному уровню) { const long long edge_start = _outgoing_ptrs[src_id]; // получаем положение первого ребра вершины const int connections_count = _outgoing_ptrs[src_id + 1] - _outgoing_ptrs[src_id]; // получаем число смежных ребер вершины for(int edge_pos = 0; edge_pos < connections_count; edge_pos++) // для каждого смежного ребра делаем: { int dst_id = _outgoing_ids[edge_start + edge_pos]; // загружаем ID напарвляющей вершины ребра if (_levels[dst_id] == UNVISITED_VERTEX) // если направляющая вершина - не посещенная { _levels[dst_id] = _current_level + 1; // то помечаем её следующим уровнем _changes[0] = 1; } } } } } void __global__ bfs_kernel(int *_frontier_ids, int _frontier_ids_size, int *_levels, long long *_outgoing_ptrs, int *_outgoing_ids, int _vertices_count, long long _edges_count, int *_changes, int _current_level, int threads_per_vertex) { const long long src_id = (blockIdx.x*blockDim.x+threadIdx.x); const int i = src_id / threads_per_vertex; if (i < _frontier_ids_size) // для всех графовых вершин выполнить следующее { int idx = _frontier_ids[i]; const int first_edge_ptr = _outgoing_ptrs[idx]; const int connections_count = _outgoing_ptrs[idx + 1] - _outgoing_ptrs[idx]; for (int cur_edge = threadIdx.x % threads_per_vertex; cur_edge < connections_count; cur_edge+=threads_per_vertex) { int dst_id = _outgoing_ids[first_edge_ptr + cur_edge]; if (_levels[dst_id] == UNVISITED_VERTEX) // если направляющая вершина - не посещенная { _levels[dst_id] = _current_level + 1; // то помечаем её следующим уровнем _changes[0] = 1; } } } } //////////////////////////////// //// Find indices of level ///// //////////////////////////////// void __global__ copy_current_level_frontier(int * _low_ids, int _low_threshold, int * _bunched_ids, int _high_threshold, int * _frontier_ids, long long * _outgoing_ptrs, int * _levels, int _current_level, int _vertices_counts) { register const int idx = threadIdx.x + blockDim.x*blockIdx.x; if (idx < _vertices_counts) { if (_levels[idx] == _current_level) { long long connections = _outgoing_ptrs[idx+1]-_outgoing_ptrs[idx]; if (connections > _high_threshold) { _low_ids[idx] = -1; _bunched_ids[idx] = idx; _frontier_ids[idx] = -1; } else if (connections < _low_threshold){ _low_ids[idx] = idx; _bunched_ids[idx] = -1; _frontier_ids[idx] = -1; } else { _low_ids[idx] = -1; _bunched_ids[idx] = -1; _frontier_ids[idx] = idx; } } else { _low_ids[idx] = -1; _bunched_ids[idx] = -1; _frontier_ids[idx] = -1; } } } struct is_inactive { __host__ __device__ bool operator()(const int x) { return (x == -1); } }; tuple<int, int, int> generate_frontier(int * _low_ids, int _low_threshold, int * _bunched_ids, int _high_threshold, int * _frontier_ids, long long * _outgoing_ptrs, int * _levels, int _current_level, int _vertices_counts) { int blockDim = 1024; int gridDim = (_vertices_counts-1)/blockDim + 1; SAFE_KERNEL_CALL((copy_current_level_frontier<<<gridDim, blockDim>>> (_low_ids, _low_threshold, _bunched_ids, _high_threshold, _frontier_ids, _outgoing_ptrs, _levels, _current_level, _vertices_counts))); int *new_end = remove_if(thrust::device, _frontier_ids, _frontier_ids+_vertices_counts,is_inactive()); int frontier_ids_size = new_end - _frontier_ids; new_end = remove_if(thrust::device, _bunched_ids, _bunched_ids+_vertices_counts, is_inactive()); int bunched_ids_size = new_end - _bunched_ids; new_end = remove_if(thrust::device, _low_ids, _low_ids+_vertices_counts, is_inactive()); int low_ids_size = new_end - _low_ids; return make_tuple(frontier_ids_size, bunched_ids_size, low_ids_size); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // single GPU implememntation ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void gpu_bfs_wrapper(long long *_outgoing_ptrs, int *_outgoing_ids, int _vertices_count, long long _edges_count, int _source_vertex, int *_levels, int *_frontier_ids, int *_bunched_ids, int *_low_ids, const vector<cudaStream_t>& Stream) { dim3 init_threads(1024); dim3 init_blocks((_vertices_count - 1) / init_threads.x + 1); // call init kernel SAFE_KERNEL_CALL((init_kernel <<< init_blocks, init_threads >>> (_levels, _vertices_count, _source_vertex))); // device variable to stop iterations, for each source vertex int *changes; SAFE_CALL(cudaMallocManaged((void**)&changes, sizeof(int))); // set grid size dim3 compute_threads(1024); dim3 compute_blocks_low(((_vertices_count - 1) / compute_threads.x + 1)/2); dim3 compute_blocks_front; dim3 compute_blocks_bunched(4*((_vertices_count - 1) / compute_threads.x + 1)); int current_level = 1; using namespace thrust; using namespace thrust::placeholders; int low_threshold = 8; // less then 10 edges int high_threshold = 1024; // over 400 edges // compute shortest paths do { changes[0] = 0; std::tuple<int,int,int> ids_sizes = generate_frontier(_low_ids, low_threshold, _bunched_ids, high_threshold, _frontier_ids, _outgoing_ptrs, _levels, current_level, _vertices_count); int frontier_ids_size = std::get<0>(ids_sizes); int bunched_ids_size = std::get<1>(ids_sizes); int low_ids_size = std::get<2>(ids_sizes); //cout << frontier_ids_size << ' ' << bunched_ids_size << ' ' << low_ids_size << "\n"; if (low_ids_size != 0) { bfs_kernel <<< compute_blocks_low, compute_threads, 0, Stream[2] >>> (_low_ids, low_ids_size, _levels, _outgoing_ptrs, _outgoing_ids, _vertices_count, _edges_count, changes, current_level, 1); } if (bunched_ids_size != 0) { bfs_kernel <<< compute_blocks_bunched, compute_threads, 0, Stream[1] >>> (_bunched_ids, bunched_ids_size, _levels, _outgoing_ptrs, _outgoing_ids, _vertices_count, _edges_count, changes, current_level, 1024); } if (low_ids_size != 0 || bunched_ids_size != 0) { compute_blocks_front.x = 24*((_vertices_count - 1) / compute_threads.x + 1); } else { compute_blocks_front.x = 32*((_vertices_count - 1) / compute_threads.x + 1); } bfs_kernel <<< compute_blocks_front, compute_threads, 0, Stream[0] >>> (_frontier_ids, frontier_ids_size, _levels, _outgoing_ptrs, _outgoing_ids, _vertices_count, _edges_count, changes, current_level, 32); cudaDeviceSynchronize(); // for ( int i = 0; i < 3; i++ ) { // SAFE_CALL(cudaStreamDestroy(Stream[i])); // } current_level++; } while(changes[0] > 0); SAFE_CALL(cudaFree(changes)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
316e1a70712c45ca8f9c58f3e820fe6f4a6dd352.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <project_main.h> #define iterations 3600 #define BlockSizeX 26 #define BlockSizeY 26 #define stepsPerKernel 4 #define BlockFinalSizeX (BlockSizeX - 2*stepsPerKernel) #define BlockFinalSizeY (BlockSizeY - 2*stepsPerKernel) #define tPlot 100000 #define lx 1000 #define ly 1000 #define PSx 50 #define PSy 40 #define PSamplitude 0.1f #define PSperiod 3.0f #define obst_x 333 #define obst_y 300 #define obst_r 150 #define leftWall 300 #define rightWall 500 #define btmWall 0 #define topWall 599 #define slitWidth 30 #define uMax 0.1 #define Re 1000 #define nu uMax * 2 * obst_r / Re #define omega 1.0f / (3.0f * nu + 0.5f) #define in 0 #define out (lx-1) #define tx threadIdx.x #define ty threadIdx.y #define bx blockIdx.x #define by blockIdx.y #define bdx blockDim.x #define bdy blockDim.y #define gdx gridDim.x #define gdy gridDim.y #define dir(K) x + y*lx + K*lx*ly #define dirS(K) tx + ty*bdx + K*bdx*bdy #define iceil(n,d) ((n-1)/d)+1 #define cudaCheckErrors(msg) \ do { \ hipError_t __err = hipGetLastError();\ if (__err != hipSuccess) { \ printf("Fatal error %s (%s at %s:%d)\n", msg, hipGetErrorString(__err), __FILE__, __LINE__); \ exit(1); \ } \ } while (0) __device__ float t[9]; //= {4/9, 1/9, 1/9, 1/9, 1/9, 1/36, 1/36, 1/36, 1/36}; __constant__ int cx[9]; __constant__ int cy[9]; __constant__ int opp[9]; __global__ void tiledKernel (float *fIn, float *fOut, char *bbRegion, int iteration) { const int x = bx * (BlockSizeX - 2*stepsPerKernel ) + tx - stepsPerKernel; const int y = by*BlockFinalSizeY + ty - stepsPerKernel; bool onGrid; onGrid = (0 <= x && x < lx && 0 <= y && y < ly); volatile __shared__ float fInS[9 * BlockSizeX * BlockSizeY]; volatile __shared__ float fOutS[9 * BlockSizeX * BlockSizeY]; #pragma unroll for (int k = 0; k < 9; ++k) { fInS[dirS(k)] = (onGrid) ? fIn[dir(k)] : 0.0f; fOutS[dirS(k)] = (onGrid) ? fOut[dir(k)] : 0.0f; } float temp, rho, ux, uy, vert, left, right; bool activeThread = true; #pragma unroll for (int step = 0; step < stepsPerKernel;) { rho = 0.0f; ux = 0.0f; uy = 0.0f; vert = 0.0f; left = 0.0f; right = 0.0f; if (onGrid && activeThread) { // MACROSCOPIC VARIABLES #pragma unroll for (int k = 0; k < 9; ++k) { temp = (onGrid /*x < lx && y < ly*/) ? fInS[dirS(k)] : 0.0f; rho += temp; ux += cx[k] * temp; uy += cy[k] * temp; if (k == 0 || k == 2 || k == 4) { vert += temp; } if (k == 3 || k == 6 || k == 7) { left += temp; } if (k == 1 || k == 5 || k == 8) { right += temp; } } ux /= rho; uy /= rho; vert /= rho; left /= rho; right /= rho; } // MACROSCOPIC (DIRICHLET) BOUNDARY CONDITIONS // Inlet: Poiuseville profile __syncthreads(); if (x == in && 0 < y && y < ly-1) { ux = 4.0f * uMax / ((ly-2.0f)*(ly-2.0f)) * ((y-0.5f)*(ly-2.0f) - (y-0.5f)*(y-0.5f)); uy = 0.0f; rho = 1.0f / (1.0f - ux) * ( vert + 2*left ) ; } // Outlet: constant pressure /* __syncthreads(); if (x == out && 0 < y && y < ly-1) { rho = 1.0f; ux = -1.0f + 1.0f / rho * ( vert + 2*right ) ; uy = 0.0f; } */ // MICROSCOPIC BOUNDARY CONDITIONS: // Inlet: Zou/He B.C. __syncthreads(); if (x == in && 0 < y && y < ly-1) { fInS[dirS(1)] = fInS[dirS(3)] + 2.0f/3.0f * rho * ux; fInS[dirS(5)] = fInS[dirS(7)] + 0.5f*(fInS[dirS(4)]-fInS[dirS(2)]) + 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fInS[dirS(8)] = fInS[dirS(6)] + 0.5f*(fInS[dirS(2)]-fInS[dirS(4)]) - 0.5f*rho*uy + 1.0f/6.0f*rho*ux; } // Outlet: Zou/He BC /* __syncthreads(); if (x == out && 0 < y && y < ly-1) { fInS[dirS(3)] = fInS[dirS(1)] - 2.0f/3.0f * rho * ux; fInS[dirS(7)] = fInS[dirS(5)] + 0.5f*(fInS[dirS(2)]-fInS[dirS(4)]) - 0.5f*rho*uy - 1.0f/6.0f*rho*ux; fInS[dirS(6)] = fInS[dirS(8)] + 0.5f*(fInS[dirS(4)]-fInS[dirS(2)]) + 0.5f*rho*uy - 1.0f/6.0f*rho*ux; } */ // Collision __syncthreads(); if (onGrid && activeThread) { float cu; bool isPS = false; // (x == PSx && y == PSy); if (isPS) { rho = 2.0f + PSamplitude * sin(2*M_PI*iteration/PSperiod); } #pragma unroll for (int k = 0; k < 9; ++k) { cu = 3.0f * (cx[k]*ux + cy[k]*uy); temp = rho * t[k] * ( 1.0f + cu + 0.5*(cu*cu) - 1.5f*(ux*ux + uy*uy)); if (isPS) { fOutS[dirS(k)] = temp; } else { fOutS[dirS(k)] = fInS[dirS(k)] - omega * (fInS[dirS(k)] - temp); } } } // Obstacle (bounce-back) __syncthreads(); if (onGrid && activeThread) { if (bbRegion[x+y*lx] == 1) { #pragma unroll for (int k = 0; k < 9; ++k) { fOutS[dirS(k)] = fInS[dirS(opp[k])]; } } } // increase the border of inactive threads. this is to prevent cross-block talk and allow iteration within a kernel. ++step; activeThread = (tx<step || bdx-step<=tx || ty<step || bdy-step<=ty) ? false : activeThread; // Streaming __syncthreads(); if (0 <= x && x < lx && 0 <= y && y < ly && onGrid && activeThread) { int xSource, ySource; #pragma unroll for (int k = 0; k < 9; ++k) { //THIS IS WRONG ;;; MODULO BDX MAKES NO SENSE xSource = tx - cx[k]; ySource = ty - cy[k]; // xSource += bdx; // ySource += bdy; // xSource %= bdx; // ySource %= bdy; /* perhaps you should check to see if it wraps around, and if so, just ignore the load. this could prevent uncoalesced access and it shouldn't matter since boundary conditions should be already handled by inlet/outlet/obstacles (unless you have a periodic simulation). */ fInS[dirS(k)] = fOutS[xSource + ySource*bdx + k*bdx*bdy]; } /* if (x == 0) { ux = 4.0f * uMax / ((ly-2.0f)*(ly-2.0f)) * ((y-0.5f)*(ly-2.0f) - (y-0.5f)*(y-0.5f)); uy = 0.0f; rho = 1.0f / (1.0f - ux) * ( vert + 2*left ) ; fInS[dirS(1)] = fInS[dirS(3)] + 2.0f/3.0f * rho * ux; fInS[dirS(5)] = fInS[dirS(7)] + 0.5f*(fInS[dirS(4)] - fInS[dirS(2)]) + 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fInS[dirS(8)] = fInS[dirS(6)] + 0.5f*(fInS[dirS(2)] - fInS[dirS(4)]) - 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fInS[dirS(1)] = fInS[dirS(3)] ; fInS[dirS(5)] = fInS[dirS(7)]; fInS[dirS(8)] = fInS[dirS(6)]; } */ if (x == lx-1 && 0 < y && y <= ly-1) { rho = 1.0f; ux = -1.0f + 1.0f / rho * ( fInS[dirS(0)] + fInS[dirS(2)] + fInS[dirS(4)] + 2*(fInS[dirS(1)] + fInS[dirS(5)] + fInS[dirS(8)]) ) ; uy = 0.0f; fInS[dirS(3)] = fInS[dirS(1)] - 2.0f/3.0f * rho * ux; fInS[dirS(7)] = fInS[dirS(5)] + 0.5f*(fInS[dirS(2)]-fInS[dirS(4)]) - 0.5f*rho*uy - 1.0f/6.0f*rho*ux; fInS[dirS(6)] = fInS[dirS(8)] + 0.5f*(fInS[dirS(4)]-fInS[dirS(2)]) + 0.5f*rho*uy - 1.0f/6.0f*rho*ux; /* fInS[dirS(3)] = fInS[dirS(1)]; fInS[dirS(7)] = fInS[dirS(5)]; fInS[dirS(6)] = fInS[dirS(8)]; */ } } } __syncthreads(); if (activeThread && onGrid) { #pragma unroll for (int k = 0; k < 9; ++k) { fIn[dir(k)] = fInS[dirS(k)]; } // fIn[dir(5)] = 2.0f; } else { if (onGrid) { for (int k = 0; k < 9; ++k) { // fIn[dir(k)] = 0.0f; } // fIn[dir(5)] = 3.0f; } } } __global__ void cylinderKernelCollide (float *fIn, float *fOut, char *bbRegion, int iteration) { // Grid location const int x = bx*bdx + tx; const int y = by*bdy + ty; // MACROSCOPIC VARIABLES float temp; float rho = 0.0f; float ux = 0.0f; float uy = 0.0f; float vert = 0.0f; // these three are used for inlets/outlets float left = 0.0f; float right = 0.0f; #pragma unroll for (int k = 0; k < 9; ++k) { temp = (x < lx && y < ly) ? fIn[dir(k)] : 0.0f; rho += temp; ux += cx[k] * temp; uy += cy[k] * temp; if (k == 0 || k == 2 || k == 4) { vert += temp; } if (k == 3 || k == 6 || k == 7) { left += temp; } if (k == 1 || k == 5 || k == 8) { right += temp; } } ux /= rho; uy /= rho; vert /= rho; left /= rho; right /= rho; // MACROSCOPIC (DIRICHLET) BOUNDARY CONDITIONS // Inlet: Poiuseville profile __syncthreads(); if (x == in && 0 < y && y < ly-1) { ux = 4.0f * uMax / ((ly-2.0f)*(ly-2.0f)) * ((y-0.5f)*(ly-2.0f) - (y-0.5f)*(y-0.5f)); uy = 0.0f; rho = 1.0f / (1.0f - ux) * ( vert + 2*left ) ; } // Outlet: constant pressure __syncthreads(); if (x == out && 0 < y && y < ly-1) { rho = 1.0f; ux = -1.0f + 1.0f / rho * ( vert + 2*right ) ; uy = 0.0f; } // MICROSCOPIC BOUNDARY CONDITIONS: // Inlet: Zou/He B.C. __syncthreads(); if (x == in && 0 < y && y < ly-1) { fIn[x + y*lx + 1*lx*ly] = fIn[x+y*lx+3*lx*ly] + 2.0f/3.0f * rho * ux; fIn[x+y*lx+5*lx*ly] = fIn[x+y*lx+7*lx*ly] + 0.5f*(fIn[x+y*lx+4*lx*ly] - fIn[x+y*lx+2*lx*ly]) + 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fIn[x+y*lx+8*lx*ly] = fIn[x+y*lx+6*lx*ly] + 0.5f*(fIn[x+y*lx+2*lx*ly] - fIn[x+y*lx+4*lx*ly]) - 0.5f*rho*uy + 1.0f/6.0f*rho*ux; } // Outlet: Zou/He BC __syncthreads(); if (x == out && 0 < y && y < ly-1) { fIn[dir(3)] = fIn[dir(1)] - 2.0f/3.0f * rho * ux; fIn[dir(7)] = fIn[dir(5)] + 0.5f*(fIn[dir(2)]-fIn[dir(4)]) - 0.5f*rho*uy - 1.0f/6.0f*rho*ux; fIn[dir(6)] = fIn[dir(8)] + 0.5f*(fIn[dir(4)]-fIn[dir(2)]) + 0.5f*rho*uy - 1.0f/6.0f*rho*ux; } // Collision __syncthreads(); float cu; bool isPS =/* false;*/ (x == PSx && y == PSy); if (isPS) { rho = 1.0f + PSamplitude * sin(2*M_PI*iteration/PSperiod); } #pragma unroll for (int k = 0; k < 9; ++k) { cu = 3.0f * (cx[k]*ux + cy[k]*uy); temp = rho * t[k] * ( 1.0f + cu + 0.5*(cu*cu) - 1.5f*(ux*ux + uy*uy)); if (isPS) { fOut[dir(k)] = temp; } else { fOut[dir(k)] = fIn[dir(k)] - omega * (fIn[dir(k)] - temp); } } // Obstacle (bounce-back) __syncthreads(); if (bbRegion[x+y*lx] == (char)1) { #pragma unroll for (int k = 0; k < 9; ++k) { fOut[dir(k)] = fIn[dir(opp[k])]; } } } __global__ void cylinderKernelStream (float *fIn, float *fOut) { const int x = bx*bdx + tx; const int y = by*bdy + ty; // Streaming __syncthreads(); int xSource, ySource; #pragma unroll for (int k = 0; k < 9; ++k) { xSource = x - cx[k]; ySource = y - cy[k]; xSource += lx; ySource += ly; xSource %= lx; ySource %= ly; fIn[dir(k)] = fOut[xSource + ySource*lx + k*lx*ly]; } } void hostCode() { float temp; // Set up constants float tH[9]; tH[0] = 4./9.; tH[1] = 1./9.; tH[2] = 1./9.; tH[3] = 1./9.; tH[4] = 1./9.; tH[5] = 1./36.; tH[6] = 1./36.; tH[7] = 1./36.; tH[8] = 1./36.; hipMemcpyToSymbol(t, tH, 9*sizeof(float)); cudaCheckErrors("copying tH to symbol"); int cxH[9]; int cyH[9]; cxH[0] = 0; cyH[0] = 0; cxH[1] = 1; cyH[1] = 0; cxH[2] = 0; cyH[2] = 1; cxH[3] = -1; cyH[3] = 0; cxH[4] = 0; cyH[4] = -1; cxH[5] = 1; cyH[5] = 1; cxH[6] = -1; cyH[6] = 1; cxH[7] = -1; cyH[7] = -1; cxH[8] = 1; cyH[8] = -1; hipMemcpyToSymbol(cx, cxH, 9*sizeof(int)); cudaCheckErrors("copying cxH to symbol"); hipMemcpyToSymbol(cy, cyH, 9*sizeof(int)); cudaCheckErrors("copying cyH to symbol"); int oppH[9]; // opp = [ 1, 4, 5, 2, 3, 8, 9, 6, 7]; oppH[0] = 0; oppH[1] = 3; oppH[2] = 4; oppH[3] = 1; oppH[4] = 2; oppH[5] = 7; oppH[6] = 8; oppH[7] = 5; oppH[8] = 6; hipMemcpyToSymbol(opp, oppH, 9*sizeof(unsigned int)); cudaCheckErrors("copying oppH to symbol"); bool bbRegionH[lx*ly]; char *bbRegionD = (char *) malloc(9*lx*ly*sizeof(char)); for (int i = 0; i < lx; ++i) { for (int j = 0; j < ly; ++j) { if (j==0 || j==ly-1 /*|| (i==obst_x &&*/ /*pow(i-obst_x,2)+pow(j-obst_y,2) <= pow(obst_r,2))*//* || i==0 || i==lx-1*/) { bbRegionH[i+j*lx] = (char)1; } else { bbRegionH[i+j*lx] = (char)0; } /* if (j == 40) { if (i%50 > 5) { // bbRegionH[i+j*lx] = (char)1; } } */ if (i==leftWall || i == rightWall || (leftWall<=i && i<=rightWall && (j<=btmWall || j>=topWall))) { // bbRegionH[i+j*lx] = (char)1; } if (leftWall<=i && i<=rightWall && j>700) { // bbRegionH[i+j*lx] = (char)1; } if (i==leftWall && (btmWall<j && j<btmWall+slitWidth)) { // bbRegionH[i+j*lx] = (char)0; } if (i==rightWall && (topWall-slitWidth<j && j<topWall)) { // bbRegionH[i+j*lx] = (char)0; } } } srand(1); int X, Y, R, R2; for (int n = 0; n < 1500; ++n) { X = (rand()%(lx-200) + 100)/1; Y = (rand()%ly)/1; R = (rand()%20); //3 + 5*rand())/1; R2 = R*R; for (int i = 0; i < lx; ++i) { for (int j = 0; j < ly; ++j) { if (pow(i-X,2)+pow(j-Y,2) <= R2) { bbRegionH[i+j*lx] = (char)1; } } } } hipMalloc(&bbRegionD, lx*ly*sizeof(char)); cudaCheckErrors("hipMalloc of bbRegionD"); hipMemcpy(bbRegionD, bbRegionH, lx*ly*sizeof(char), hipMemcpyHostToDevice); cudaCheckErrors("copying bbRegionH to device"); // hipMemcpyToSymbol(bbRegion, bbRegionH, lx*ly*sizeof(bool)); // cudaCheckErrors("copying bbRegion to symbol"); // Initialize Poiseuille equilibrium across the lattice float ux; float uy = 0.0f; float rho = 1.0f; float cu; float fInH[9*lx*ly]; for (int j = 0; j < ly; ++j) { ux = 4 * uMax; ux /= ((ly-2)*(ly-2)); ux *= ((j-0.5f)*(ly-2) - (j-0.5f)*(j-0.5f)); for (int i = 0; i < lx; ++i) { for (int k = 0; k < 9; ++k) { cu = 3 * (cxH[k]*ux + cyH[k]*uy); fInH[i + j*lx + k*lx*ly] = rho * tH[k] * ( 1 + cu + 0.5*(cu*cu) - 1.5*(ux*ux + uy*uy)); // fInH[i + j*lx + k*lx*ly] = tH[k]; } } } // transfer lattice to device float *fInD = (float *) malloc(9*lx*ly*sizeof(float)); hipMalloc(&fInD, 9*lx*ly*sizeof(float)); cudaCheckErrors("hipMalloc of fInD"); hipMemcpy(fInD, fInH, 9*lx*ly*sizeof(float), hipMemcpyHostToDevice); cudaCheckErrors("copying fInH to device"); float *fOutD = (float *) malloc(9*lx*ly*sizeof(float)); hipMalloc(&fOutD, 9*lx*ly*sizeof(float)); cudaCheckErrors("allocating fOutD on host"); // set up grid dim3 blocksPerGrid(iceil(lx,BlockFinalSizeX), iceil(ly,BlockFinalSizeY)); // dim3 blocksPerGrid(iceil(lx,BlockSizeX), iceil(ly,BlockSizeY)); dim3 threadsPerBlock(BlockSizeX, BlockSizeY); // LAUNCH THE KERNEL printf("Launching kernel.\n"); hipDeviceSynchronize(); cudaCheckErrors("synchronizing before kernel launch"); // For our images. char rgb[lx*ly*3]; float u[lx*ly]; temp = 0.0f; HsvColor hsv; hsv.s = 255; hsv.v = 255; RgbColor tricolor; double timer = 0.; startTimer(&timer); for (int iteration = 0; iteration < iterations/stepsPerKernel; ++iteration) { hipLaunchKernelGGL(( tiledKernel) , dim3(blocksPerGrid),dim3(threadsPerBlock) , 0, 0, fInD, fOutD, bbRegionD, iteration); // cylinderKernelCollide <<< blocksPerGrid,threadsPerBlock >>> (fInD, fOutD, bbRegionD, iteration); // cudaCheckErrors("launching collide kernel"); // cylinderKernelStream <<< blocksPerGrid,threadsPerBlock >>> (fInD, fOutD); // cudaCheckErrors("launching stream kernel"); // Draw a pretty picture! if ((iteration % tPlot) == tPlot-1) { printf("\n\ndrawing %d (%d)\n", iteration, iteration*stepsPerKernel); hipMemcpy(fInH, fInD, 9*lx*ly*sizeof(float), hipMemcpyDeviceToHost); cudaCheckErrors("copying fInD to host"); for (int i = 0; i < lx; ++i) { for (int j = 0; j < ly; ++j) { ux = 0.0f; uy = 0.0f; if (j==ly/2) { if (i==0) printf("\nfor LHS: \n"); if (i==lx-1) printf("for RHS: \n"); } for (int k = 0; k < 9; ++k) { if (j==ly/2 && (i==0 || i==lx-1)) printf("--%d : %f\n", k, fInH[i+j*lx+k*lx*ly]); ux += cxH[k] * fInH[i + j*lx + k*lx*ly]; uy += cyH[k] * fInH[i + j*lx + k*lx*ly]; } u[i + j*lx] = pow(ux*ux + uy*uy, 0.5); if (temp < u[i + j*lx]) { temp = u[i + j*lx]; } } } temp /= 200.0f; for (int n = 0; n < lx*ly; ++n) { u[n] /= temp; } for (int n = 0; n < lx*ly; ++n) { hsv.h = 200 - (int) u[n]; tricolor = HsvToRgb(hsv); if (bbRegionH[n]) { rgb[3*n] = 0; rgb[3*n + 1] = 0; rgb[3*n + 2] = 0; } else { rgb[3*n] = tricolor.r; rgb[3*n + 1] = tricolor.g; rgb[3*n + 2] = tricolor.b; } } write_bmp(iteration*stepsPerKernel, lx, ly, rgb); } } printf("Kernel launch complete.\n"); double time = stopNreadTimer(&timer); printf("It took %8.2f s to run %8.2f Mlu, which is %8.2f Mlu/s (baseline times %8.2f).\n", time, (double)lx*(double)ly*(double)iterations/pow(10,6), (double)lx*(double)ly*(double)iterations/(pow(10,6)*time), ((double)lx*(double)ly*(double)iterations/time)/3150000.); }
316e1a70712c45ca8f9c58f3e820fe6f4a6dd352.cu
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <project_main.h> #define iterations 3600 #define BlockSizeX 26 #define BlockSizeY 26 #define stepsPerKernel 4 #define BlockFinalSizeX (BlockSizeX - 2*stepsPerKernel) #define BlockFinalSizeY (BlockSizeY - 2*stepsPerKernel) #define tPlot 100000 #define lx 1000 #define ly 1000 #define PSx 50 #define PSy 40 #define PSamplitude 0.1f #define PSperiod 3.0f #define obst_x 333 #define obst_y 300 #define obst_r 150 #define leftWall 300 #define rightWall 500 #define btmWall 0 #define topWall 599 #define slitWidth 30 #define uMax 0.1 #define Re 1000 #define nu uMax * 2 * obst_r / Re #define omega 1.0f / (3.0f * nu + 0.5f) #define in 0 #define out (lx-1) #define tx threadIdx.x #define ty threadIdx.y #define bx blockIdx.x #define by blockIdx.y #define bdx blockDim.x #define bdy blockDim.y #define gdx gridDim.x #define gdy gridDim.y #define dir(K) x + y*lx + K*lx*ly #define dirS(K) tx + ty*bdx + K*bdx*bdy #define iceil(n,d) ((n-1)/d)+1 #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError();\ if (__err != cudaSuccess) { \ printf("Fatal error %s (%s at %s:%d)\n", msg, cudaGetErrorString(__err), __FILE__, __LINE__); \ exit(1); \ } \ } while (0) __device__ float t[9]; //= {4/9, 1/9, 1/9, 1/9, 1/9, 1/36, 1/36, 1/36, 1/36}; __constant__ int cx[9]; __constant__ int cy[9]; __constant__ int opp[9]; __global__ void tiledKernel (float *fIn, float *fOut, char *bbRegion, int iteration) { const int x = bx * (BlockSizeX - 2*stepsPerKernel ) + tx - stepsPerKernel; const int y = by*BlockFinalSizeY + ty - stepsPerKernel; bool onGrid; onGrid = (0 <= x && x < lx && 0 <= y && y < ly); volatile __shared__ float fInS[9 * BlockSizeX * BlockSizeY]; volatile __shared__ float fOutS[9 * BlockSizeX * BlockSizeY]; #pragma unroll for (int k = 0; k < 9; ++k) { fInS[dirS(k)] = (onGrid) ? fIn[dir(k)] : 0.0f; fOutS[dirS(k)] = (onGrid) ? fOut[dir(k)] : 0.0f; } float temp, rho, ux, uy, vert, left, right; bool activeThread = true; #pragma unroll for (int step = 0; step < stepsPerKernel;) { rho = 0.0f; ux = 0.0f; uy = 0.0f; vert = 0.0f; left = 0.0f; right = 0.0f; if (onGrid && activeThread) { // MACROSCOPIC VARIABLES #pragma unroll for (int k = 0; k < 9; ++k) { temp = (onGrid /*x < lx && y < ly*/) ? fInS[dirS(k)] : 0.0f; rho += temp; ux += cx[k] * temp; uy += cy[k] * temp; if (k == 0 || k == 2 || k == 4) { vert += temp; } if (k == 3 || k == 6 || k == 7) { left += temp; } if (k == 1 || k == 5 || k == 8) { right += temp; } } ux /= rho; uy /= rho; vert /= rho; left /= rho; right /= rho; } // MACROSCOPIC (DIRICHLET) BOUNDARY CONDITIONS // Inlet: Poiuseville profile __syncthreads(); if (x == in && 0 < y && y < ly-1) { ux = 4.0f * uMax / ((ly-2.0f)*(ly-2.0f)) * ((y-0.5f)*(ly-2.0f) - (y-0.5f)*(y-0.5f)); uy = 0.0f; rho = 1.0f / (1.0f - ux) * ( vert + 2*left ) ; } // Outlet: constant pressure /* __syncthreads(); if (x == out && 0 < y && y < ly-1) { rho = 1.0f; ux = -1.0f + 1.0f / rho * ( vert + 2*right ) ; uy = 0.0f; } */ // MICROSCOPIC BOUNDARY CONDITIONS: // Inlet: Zou/He B.C. __syncthreads(); if (x == in && 0 < y && y < ly-1) { fInS[dirS(1)] = fInS[dirS(3)] + 2.0f/3.0f * rho * ux; fInS[dirS(5)] = fInS[dirS(7)] + 0.5f*(fInS[dirS(4)]-fInS[dirS(2)]) + 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fInS[dirS(8)] = fInS[dirS(6)] + 0.5f*(fInS[dirS(2)]-fInS[dirS(4)]) - 0.5f*rho*uy + 1.0f/6.0f*rho*ux; } // Outlet: Zou/He BC /* __syncthreads(); if (x == out && 0 < y && y < ly-1) { fInS[dirS(3)] = fInS[dirS(1)] - 2.0f/3.0f * rho * ux; fInS[dirS(7)] = fInS[dirS(5)] + 0.5f*(fInS[dirS(2)]-fInS[dirS(4)]) - 0.5f*rho*uy - 1.0f/6.0f*rho*ux; fInS[dirS(6)] = fInS[dirS(8)] + 0.5f*(fInS[dirS(4)]-fInS[dirS(2)]) + 0.5f*rho*uy - 1.0f/6.0f*rho*ux; } */ // Collision __syncthreads(); if (onGrid && activeThread) { float cu; bool isPS = false; // (x == PSx && y == PSy); if (isPS) { rho = 2.0f + PSamplitude * sin(2*M_PI*iteration/PSperiod); } #pragma unroll for (int k = 0; k < 9; ++k) { cu = 3.0f * (cx[k]*ux + cy[k]*uy); temp = rho * t[k] * ( 1.0f + cu + 0.5*(cu*cu) - 1.5f*(ux*ux + uy*uy)); if (isPS) { fOutS[dirS(k)] = temp; } else { fOutS[dirS(k)] = fInS[dirS(k)] - omega * (fInS[dirS(k)] - temp); } } } // Obstacle (bounce-back) __syncthreads(); if (onGrid && activeThread) { if (bbRegion[x+y*lx] == 1) { #pragma unroll for (int k = 0; k < 9; ++k) { fOutS[dirS(k)] = fInS[dirS(opp[k])]; } } } // increase the border of inactive threads. this is to prevent cross-block talk and allow iteration within a kernel. ++step; activeThread = (tx<step || bdx-step<=tx || ty<step || bdy-step<=ty) ? false : activeThread; // Streaming __syncthreads(); if (0 <= x && x < lx && 0 <= y && y < ly && onGrid && activeThread) { int xSource, ySource; #pragma unroll for (int k = 0; k < 9; ++k) { //THIS IS WRONG ;;; MODULO BDX MAKES NO SENSE xSource = tx - cx[k]; ySource = ty - cy[k]; // xSource += bdx; // ySource += bdy; // xSource %= bdx; // ySource %= bdy; /* perhaps you should check to see if it wraps around, and if so, just ignore the load. this could prevent uncoalesced access and it shouldn't matter since boundary conditions should be already handled by inlet/outlet/obstacles (unless you have a periodic simulation). */ fInS[dirS(k)] = fOutS[xSource + ySource*bdx + k*bdx*bdy]; } /* if (x == 0) { ux = 4.0f * uMax / ((ly-2.0f)*(ly-2.0f)) * ((y-0.5f)*(ly-2.0f) - (y-0.5f)*(y-0.5f)); uy = 0.0f; rho = 1.0f / (1.0f - ux) * ( vert + 2*left ) ; fInS[dirS(1)] = fInS[dirS(3)] + 2.0f/3.0f * rho * ux; fInS[dirS(5)] = fInS[dirS(7)] + 0.5f*(fInS[dirS(4)] - fInS[dirS(2)]) + 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fInS[dirS(8)] = fInS[dirS(6)] + 0.5f*(fInS[dirS(2)] - fInS[dirS(4)]) - 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fInS[dirS(1)] = fInS[dirS(3)] ; fInS[dirS(5)] = fInS[dirS(7)]; fInS[dirS(8)] = fInS[dirS(6)]; } */ if (x == lx-1 && 0 < y && y <= ly-1) { rho = 1.0f; ux = -1.0f + 1.0f / rho * ( fInS[dirS(0)] + fInS[dirS(2)] + fInS[dirS(4)] + 2*(fInS[dirS(1)] + fInS[dirS(5)] + fInS[dirS(8)]) ) ; uy = 0.0f; fInS[dirS(3)] = fInS[dirS(1)] - 2.0f/3.0f * rho * ux; fInS[dirS(7)] = fInS[dirS(5)] + 0.5f*(fInS[dirS(2)]-fInS[dirS(4)]) - 0.5f*rho*uy - 1.0f/6.0f*rho*ux; fInS[dirS(6)] = fInS[dirS(8)] + 0.5f*(fInS[dirS(4)]-fInS[dirS(2)]) + 0.5f*rho*uy - 1.0f/6.0f*rho*ux; /* fInS[dirS(3)] = fInS[dirS(1)]; fInS[dirS(7)] = fInS[dirS(5)]; fInS[dirS(6)] = fInS[dirS(8)]; */ } } } __syncthreads(); if (activeThread && onGrid) { #pragma unroll for (int k = 0; k < 9; ++k) { fIn[dir(k)] = fInS[dirS(k)]; } // fIn[dir(5)] = 2.0f; } else { if (onGrid) { for (int k = 0; k < 9; ++k) { // fIn[dir(k)] = 0.0f; } // fIn[dir(5)] = 3.0f; } } } __global__ void cylinderKernelCollide (float *fIn, float *fOut, char *bbRegion, int iteration) { // Grid location const int x = bx*bdx + tx; const int y = by*bdy + ty; // MACROSCOPIC VARIABLES float temp; float rho = 0.0f; float ux = 0.0f; float uy = 0.0f; float vert = 0.0f; // these three are used for inlets/outlets float left = 0.0f; float right = 0.0f; #pragma unroll for (int k = 0; k < 9; ++k) { temp = (x < lx && y < ly) ? fIn[dir(k)] : 0.0f; rho += temp; ux += cx[k] * temp; uy += cy[k] * temp; if (k == 0 || k == 2 || k == 4) { vert += temp; } if (k == 3 || k == 6 || k == 7) { left += temp; } if (k == 1 || k == 5 || k == 8) { right += temp; } } ux /= rho; uy /= rho; vert /= rho; left /= rho; right /= rho; // MACROSCOPIC (DIRICHLET) BOUNDARY CONDITIONS // Inlet: Poiuseville profile __syncthreads(); if (x == in && 0 < y && y < ly-1) { ux = 4.0f * uMax / ((ly-2.0f)*(ly-2.0f)) * ((y-0.5f)*(ly-2.0f) - (y-0.5f)*(y-0.5f)); uy = 0.0f; rho = 1.0f / (1.0f - ux) * ( vert + 2*left ) ; } // Outlet: constant pressure __syncthreads(); if (x == out && 0 < y && y < ly-1) { rho = 1.0f; ux = -1.0f + 1.0f / rho * ( vert + 2*right ) ; uy = 0.0f; } // MICROSCOPIC BOUNDARY CONDITIONS: // Inlet: Zou/He B.C. __syncthreads(); if (x == in && 0 < y && y < ly-1) { fIn[x + y*lx + 1*lx*ly] = fIn[x+y*lx+3*lx*ly] + 2.0f/3.0f * rho * ux; fIn[x+y*lx+5*lx*ly] = fIn[x+y*lx+7*lx*ly] + 0.5f*(fIn[x+y*lx+4*lx*ly] - fIn[x+y*lx+2*lx*ly]) + 0.5f*rho*uy + 1.0f/6.0f*rho*ux; fIn[x+y*lx+8*lx*ly] = fIn[x+y*lx+6*lx*ly] + 0.5f*(fIn[x+y*lx+2*lx*ly] - fIn[x+y*lx+4*lx*ly]) - 0.5f*rho*uy + 1.0f/6.0f*rho*ux; } // Outlet: Zou/He BC __syncthreads(); if (x == out && 0 < y && y < ly-1) { fIn[dir(3)] = fIn[dir(1)] - 2.0f/3.0f * rho * ux; fIn[dir(7)] = fIn[dir(5)] + 0.5f*(fIn[dir(2)]-fIn[dir(4)]) - 0.5f*rho*uy - 1.0f/6.0f*rho*ux; fIn[dir(6)] = fIn[dir(8)] + 0.5f*(fIn[dir(4)]-fIn[dir(2)]) + 0.5f*rho*uy - 1.0f/6.0f*rho*ux; } // Collision __syncthreads(); float cu; bool isPS =/* false;*/ (x == PSx && y == PSy); if (isPS) { rho = 1.0f + PSamplitude * sin(2*M_PI*iteration/PSperiod); } #pragma unroll for (int k = 0; k < 9; ++k) { cu = 3.0f * (cx[k]*ux + cy[k]*uy); temp = rho * t[k] * ( 1.0f + cu + 0.5*(cu*cu) - 1.5f*(ux*ux + uy*uy)); if (isPS) { fOut[dir(k)] = temp; } else { fOut[dir(k)] = fIn[dir(k)] - omega * (fIn[dir(k)] - temp); } } // Obstacle (bounce-back) __syncthreads(); if (bbRegion[x+y*lx] == (char)1) { #pragma unroll for (int k = 0; k < 9; ++k) { fOut[dir(k)] = fIn[dir(opp[k])]; } } } __global__ void cylinderKernelStream (float *fIn, float *fOut) { const int x = bx*bdx + tx; const int y = by*bdy + ty; // Streaming __syncthreads(); int xSource, ySource; #pragma unroll for (int k = 0; k < 9; ++k) { xSource = x - cx[k]; ySource = y - cy[k]; xSource += lx; ySource += ly; xSource %= lx; ySource %= ly; fIn[dir(k)] = fOut[xSource + ySource*lx + k*lx*ly]; } } void hostCode() { float temp; // Set up constants float tH[9]; tH[0] = 4./9.; tH[1] = 1./9.; tH[2] = 1./9.; tH[3] = 1./9.; tH[4] = 1./9.; tH[5] = 1./36.; tH[6] = 1./36.; tH[7] = 1./36.; tH[8] = 1./36.; cudaMemcpyToSymbol(t, tH, 9*sizeof(float)); cudaCheckErrors("copying tH to symbol"); int cxH[9]; int cyH[9]; cxH[0] = 0; cyH[0] = 0; cxH[1] = 1; cyH[1] = 0; cxH[2] = 0; cyH[2] = 1; cxH[3] = -1; cyH[3] = 0; cxH[4] = 0; cyH[4] = -1; cxH[5] = 1; cyH[5] = 1; cxH[6] = -1; cyH[6] = 1; cxH[7] = -1; cyH[7] = -1; cxH[8] = 1; cyH[8] = -1; cudaMemcpyToSymbol(cx, cxH, 9*sizeof(int)); cudaCheckErrors("copying cxH to symbol"); cudaMemcpyToSymbol(cy, cyH, 9*sizeof(int)); cudaCheckErrors("copying cyH to symbol"); int oppH[9]; // opp = [ 1, 4, 5, 2, 3, 8, 9, 6, 7]; oppH[0] = 0; oppH[1] = 3; oppH[2] = 4; oppH[3] = 1; oppH[4] = 2; oppH[5] = 7; oppH[6] = 8; oppH[7] = 5; oppH[8] = 6; cudaMemcpyToSymbol(opp, oppH, 9*sizeof(unsigned int)); cudaCheckErrors("copying oppH to symbol"); bool bbRegionH[lx*ly]; char *bbRegionD = (char *) malloc(9*lx*ly*sizeof(char)); for (int i = 0; i < lx; ++i) { for (int j = 0; j < ly; ++j) { if (j==0 || j==ly-1 /*|| (i==obst_x &&*/ /*pow(i-obst_x,2)+pow(j-obst_y,2) <= pow(obst_r,2))*//* || i==0 || i==lx-1*/) { bbRegionH[i+j*lx] = (char)1; } else { bbRegionH[i+j*lx] = (char)0; } /* if (j == 40) { if (i%50 > 5) { // bbRegionH[i+j*lx] = (char)1; } } */ if (i==leftWall || i == rightWall || (leftWall<=i && i<=rightWall && (j<=btmWall || j>=topWall))) { // bbRegionH[i+j*lx] = (char)1; } if (leftWall<=i && i<=rightWall && j>700) { // bbRegionH[i+j*lx] = (char)1; } if (i==leftWall && (btmWall<j && j<btmWall+slitWidth)) { // bbRegionH[i+j*lx] = (char)0; } if (i==rightWall && (topWall-slitWidth<j && j<topWall)) { // bbRegionH[i+j*lx] = (char)0; } } } srand(1); int X, Y, R, R2; for (int n = 0; n < 1500; ++n) { X = (rand()%(lx-200) + 100)/1; Y = (rand()%ly)/1; R = (rand()%20); //3 + 5*rand())/1; R2 = R*R; for (int i = 0; i < lx; ++i) { for (int j = 0; j < ly; ++j) { if (pow(i-X,2)+pow(j-Y,2) <= R2) { bbRegionH[i+j*lx] = (char)1; } } } } cudaMalloc(&bbRegionD, lx*ly*sizeof(char)); cudaCheckErrors("cudaMalloc of bbRegionD"); cudaMemcpy(bbRegionD, bbRegionH, lx*ly*sizeof(char), cudaMemcpyHostToDevice); cudaCheckErrors("copying bbRegionH to device"); // cudaMemcpyToSymbol(bbRegion, bbRegionH, lx*ly*sizeof(bool)); // cudaCheckErrors("copying bbRegion to symbol"); // Initialize Poiseuille equilibrium across the lattice float ux; float uy = 0.0f; float rho = 1.0f; float cu; float fInH[9*lx*ly]; for (int j = 0; j < ly; ++j) { ux = 4 * uMax; ux /= ((ly-2)*(ly-2)); ux *= ((j-0.5f)*(ly-2) - (j-0.5f)*(j-0.5f)); for (int i = 0; i < lx; ++i) { for (int k = 0; k < 9; ++k) { cu = 3 * (cxH[k]*ux + cyH[k]*uy); fInH[i + j*lx + k*lx*ly] = rho * tH[k] * ( 1 + cu + 0.5*(cu*cu) - 1.5*(ux*ux + uy*uy)); // fInH[i + j*lx + k*lx*ly] = tH[k]; } } } // transfer lattice to device float *fInD = (float *) malloc(9*lx*ly*sizeof(float)); cudaMalloc(&fInD, 9*lx*ly*sizeof(float)); cudaCheckErrors("cudaMalloc of fInD"); cudaMemcpy(fInD, fInH, 9*lx*ly*sizeof(float), cudaMemcpyHostToDevice); cudaCheckErrors("copying fInH to device"); float *fOutD = (float *) malloc(9*lx*ly*sizeof(float)); cudaMalloc(&fOutD, 9*lx*ly*sizeof(float)); cudaCheckErrors("allocating fOutD on host"); // set up grid dim3 blocksPerGrid(iceil(lx,BlockFinalSizeX), iceil(ly,BlockFinalSizeY)); // dim3 blocksPerGrid(iceil(lx,BlockSizeX), iceil(ly,BlockSizeY)); dim3 threadsPerBlock(BlockSizeX, BlockSizeY); // LAUNCH THE KERNEL printf("Launching kernel.\n"); cudaDeviceSynchronize(); cudaCheckErrors("synchronizing before kernel launch"); // For our images. char rgb[lx*ly*3]; float u[lx*ly]; temp = 0.0f; HsvColor hsv; hsv.s = 255; hsv.v = 255; RgbColor tricolor; double timer = 0.; startTimer(&timer); for (int iteration = 0; iteration < iterations/stepsPerKernel; ++iteration) { tiledKernel <<< blocksPerGrid,threadsPerBlock >>> (fInD, fOutD, bbRegionD, iteration); // cylinderKernelCollide <<< blocksPerGrid,threadsPerBlock >>> (fInD, fOutD, bbRegionD, iteration); // cudaCheckErrors("launching collide kernel"); // cylinderKernelStream <<< blocksPerGrid,threadsPerBlock >>> (fInD, fOutD); // cudaCheckErrors("launching stream kernel"); // Draw a pretty picture! if ((iteration % tPlot) == tPlot-1) { printf("\n\ndrawing %d (%d)\n", iteration, iteration*stepsPerKernel); cudaMemcpy(fInH, fInD, 9*lx*ly*sizeof(float), cudaMemcpyDeviceToHost); cudaCheckErrors("copying fInD to host"); for (int i = 0; i < lx; ++i) { for (int j = 0; j < ly; ++j) { ux = 0.0f; uy = 0.0f; if (j==ly/2) { if (i==0) printf("\nfor LHS: \n"); if (i==lx-1) printf("for RHS: \n"); } for (int k = 0; k < 9; ++k) { if (j==ly/2 && (i==0 || i==lx-1)) printf("--%d : %f\n", k, fInH[i+j*lx+k*lx*ly]); ux += cxH[k] * fInH[i + j*lx + k*lx*ly]; uy += cyH[k] * fInH[i + j*lx + k*lx*ly]; } u[i + j*lx] = pow(ux*ux + uy*uy, 0.5); if (temp < u[i + j*lx]) { temp = u[i + j*lx]; } } } temp /= 200.0f; for (int n = 0; n < lx*ly; ++n) { u[n] /= temp; } for (int n = 0; n < lx*ly; ++n) { hsv.h = 200 - (int) u[n]; tricolor = HsvToRgb(hsv); if (bbRegionH[n]) { rgb[3*n] = 0; rgb[3*n + 1] = 0; rgb[3*n + 2] = 0; } else { rgb[3*n] = tricolor.r; rgb[3*n + 1] = tricolor.g; rgb[3*n + 2] = tricolor.b; } } write_bmp(iteration*stepsPerKernel, lx, ly, rgb); } } printf("Kernel launch complete.\n"); double time = stopNreadTimer(&timer); printf("It took %8.2f s to run %8.2f Mlu, which is %8.2f Mlu/s (baseline times %8.2f).\n", time, (double)lx*(double)ly*(double)iterations/pow(10,6), (double)lx*(double)ly*(double)iterations/(pow(10,6)*time), ((double)lx*(double)ly*(double)iterations/time)/3150000.); }
4b831e732044e26671d89164047d921760414ac9.hip
// !!! This is a file automatically generated by hipify!!! // // Created by jglrxavpok on 04/09/2020. // #include "Lambertian.h" __device__ Lambertian::Lambertian(const Color &a): albedo(a) {} __device__ bool Lambertian::scatter(const Ray &ray, const HitResult &hit, hiprandState_t *rand, Color &attenuation, Ray &scattered) const { Vec3 direction = hit.normal + Vec3::randomInUnitSphere(rand); scattered = Ray(hit.point, direction); attenuation = albedo; return true; }
4b831e732044e26671d89164047d921760414ac9.cu
// // Created by jglrxavpok on 04/09/2020. // #include "Lambertian.h" __device__ Lambertian::Lambertian(const Color &a): albedo(a) {} __device__ bool Lambertian::scatter(const Ray &ray, const HitResult &hit, curandState *rand, Color &attenuation, Ray &scattered) const { Vec3 direction = hit.normal + Vec3::randomInUnitSphere(rand); scattered = Ray(hit.point, direction); attenuation = albedo; return true; }
9f65813729b3c862e9db5a4d4702f81954a84dc3.hip
// !!! This is a file automatically generated by hipify!!! /** * syrk.cu: This file is part of the PolyBench/GPU 1.0 test suite. * * * Contact: Scott Grauer-Gray <sgrauerg@gmail.com> * Will Killian <killian@udel.edu> * Louis-Noel Pouchet <pouchet@cse.ohio-state.edu> * Web address: http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include <hip/hip_runtime.h> #define POLYBENCH_TIME 1 #include "syrk.cuh" #include <polybench.h> #include <polybenchUtilFuncts.h> //define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 0.05 #define GPU_DEVICE 0 #define RUN_ON_CPU void init_arrays(int ni, int nj, DATA_TYPE *alpha, DATA_TYPE *beta, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni), DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { int i, j; *alpha = 32412; *beta = 2123; for (i = 0; i < ni; i++) { for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) i*j) / ni; } } for (i = 0; i < ni; i++) { for (j = 0; j < ni; j++) { C[i][j] = ((DATA_TYPE) i*j) / ni; } } } void syrk(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(A, NI, NJ, ni, nj), DATA_TYPE POLYBENCH_2D(C, NI, NI, ni, ni)) { int i, j, k; /* C := alpha*A*A' + beta*C */ for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NI; j++) { C[i][j] *= beta; } } for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NI; j++) { for (k = 0; k < _PB_NJ; k++) { C[i][j] += alpha * A[i][k] * A[j][k]; } } } } void compareResults(int ni, DATA_TYPE POLYBENCH_2D(C, NI, NI, ni, ni), DATA_TYPE POLYBENCH_2D(C_outputFromGpu, NI, NI, ni, ni)) { int i,j,fail; fail = 0; // Compare C with D for (i=0; i<ni; i++) { for (j=0; j<ni; j++) { if (percentDiff(C[i][j], C_outputFromGpu[i][j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; } } } // print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail); } void GPU_argv_init() { hipDeviceProp_t deviceProp; hipGetDeviceProperties(&deviceProp, GPU_DEVICE); printf("setting device %d with name %s\n",GPU_DEVICE,deviceProp.name); hipSetDevice( GPU_DEVICE ); return; } __global__ void syrk_kernel(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE *a, DATA_TYPE *c) { /* C := alpha*A*A' + beta*C */ int j = blockIdx.x * blockDim.x + threadIdx.x; int i = blockIdx.y * blockDim.y + threadIdx.y; if ((i < _PB_NI) && (j < _PB_NI)) { c[i * NI + j] *= beta; int k; for(k=0; k < _PB_NJ; k++) { c[i * NI + j] += alpha * a[i * NJ + k] * a[j * NJ + k]; } } } void syrkCuda(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(A, NI, NJ, ni, nj), DATA_TYPE POLYBENCH_2D(C, NI, NI, ni, ni), DATA_TYPE POLYBENCH_2D(C_outputFromGpu, NI, NI, ni, ni)) { DATA_TYPE* A_gpu; DATA_TYPE* C_gpu; hipMalloc((void **)&A_gpu, sizeof(DATA_TYPE) * NI * NJ); hipMalloc((void **)&C_gpu, sizeof(DATA_TYPE) * NI * NI); hipMemcpy(A_gpu, A, sizeof(DATA_TYPE) * NI * NJ, hipMemcpyHostToDevice); hipMemcpy(C_gpu, C, sizeof(DATA_TYPE) * NI * NI, hipMemcpyHostToDevice); dim3 block(DIM_THREAD_BLOCK_X, DIM_THREAD_BLOCK_Y); dim3 grid((size_t)(ceil(((float)NI) / ((float)DIM_THREAD_BLOCK_X))), (size_t)ceil(((float)NI) / ((float)DIM_THREAD_BLOCK_Y))); /* Start timer. */ polybench_start_instruments; hipLaunchKernelGGL(( syrk_kernel), dim3(grid),dim3(block), 0, 0, ni, nj, alpha, beta, A_gpu,C_gpu); hipDeviceSynchronize(); /* Stop and print timer. */ printf("GPU Time in seconds:\n"); polybench_stop_instruments; polybench_print_instruments; hipMemcpy(C_outputFromGpu, C_gpu, sizeof(DATA_TYPE) * NI * NI, hipMemcpyDeviceToHost); hipFree(A_gpu); hipFree(C_gpu); } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < ni; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, C[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } int main(int argc, char *argv[]) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ DATA_TYPE alpha; DATA_TYPE beta; POLYBENCH_2D_ARRAY_DECL(A,DATA_TYPE,NI,NJ,ni,nj); POLYBENCH_2D_ARRAY_DECL(C,DATA_TYPE,NI,NI,ni,ni); POLYBENCH_2D_ARRAY_DECL(C_outputFromGpu,DATA_TYPE,NI,NI,ni,ni); init_arrays(ni, nj, &alpha, &beta, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(A)); GPU_argv_init(); syrkCuda(ni, nj, alpha, beta, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(C_outputFromGpu)); #ifdef RUN_ON_CPU /* Start timer. */ polybench_start_instruments; syrk(ni, nj, alpha, beta, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(C)); /* Stop and print timer. */ printf("CPU Time in seconds:\n"); polybench_stop_instruments; polybench_print_instruments; compareResults(ni, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(C_outputFromGpu)); #else //prevent dead code elimination polybench_prevent_dce(print_array(ni, POLYBENCH_ARRAY(C_outputFromGpu))); #endif //RUN_ON_CPU POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(C_outputFromGpu); return 0; } #include <polybench.c>
9f65813729b3c862e9db5a4d4702f81954a84dc3.cu
/** * syrk.cu: This file is part of the PolyBench/GPU 1.0 test suite. * * * Contact: Scott Grauer-Gray <sgrauerg@gmail.com> * Will Killian <killian@udel.edu> * Louis-Noel Pouchet <pouchet@cse.ohio-state.edu> * Web address: http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include <cuda.h> #define POLYBENCH_TIME 1 #include "syrk.cuh" #include <polybench.h> #include <polybenchUtilFuncts.h> //define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 0.05 #define GPU_DEVICE 0 #define RUN_ON_CPU void init_arrays(int ni, int nj, DATA_TYPE *alpha, DATA_TYPE *beta, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni), DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { int i, j; *alpha = 32412; *beta = 2123; for (i = 0; i < ni; i++) { for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) i*j) / ni; } } for (i = 0; i < ni; i++) { for (j = 0; j < ni; j++) { C[i][j] = ((DATA_TYPE) i*j) / ni; } } } void syrk(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(A, NI, NJ, ni, nj), DATA_TYPE POLYBENCH_2D(C, NI, NI, ni, ni)) { int i, j, k; /* C := alpha*A*A' + beta*C */ for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NI; j++) { C[i][j] *= beta; } } for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NI; j++) { for (k = 0; k < _PB_NJ; k++) { C[i][j] += alpha * A[i][k] * A[j][k]; } } } } void compareResults(int ni, DATA_TYPE POLYBENCH_2D(C, NI, NI, ni, ni), DATA_TYPE POLYBENCH_2D(C_outputFromGpu, NI, NI, ni, ni)) { int i,j,fail; fail = 0; // Compare C with D for (i=0; i<ni; i++) { for (j=0; j<ni; j++) { if (percentDiff(C[i][j], C_outputFromGpu[i][j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; } } } // print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail); } void GPU_argv_init() { cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, GPU_DEVICE); printf("setting device %d with name %s\n",GPU_DEVICE,deviceProp.name); cudaSetDevice( GPU_DEVICE ); return; } __global__ void syrk_kernel(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE *a, DATA_TYPE *c) { /* C := alpha*A*A' + beta*C */ int j = blockIdx.x * blockDim.x + threadIdx.x; int i = blockIdx.y * blockDim.y + threadIdx.y; if ((i < _PB_NI) && (j < _PB_NI)) { c[i * NI + j] *= beta; int k; for(k=0; k < _PB_NJ; k++) { c[i * NI + j] += alpha * a[i * NJ + k] * a[j * NJ + k]; } } } void syrkCuda(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(A, NI, NJ, ni, nj), DATA_TYPE POLYBENCH_2D(C, NI, NI, ni, ni), DATA_TYPE POLYBENCH_2D(C_outputFromGpu, NI, NI, ni, ni)) { DATA_TYPE* A_gpu; DATA_TYPE* C_gpu; cudaMalloc((void **)&A_gpu, sizeof(DATA_TYPE) * NI * NJ); cudaMalloc((void **)&C_gpu, sizeof(DATA_TYPE) * NI * NI); cudaMemcpy(A_gpu, A, sizeof(DATA_TYPE) * NI * NJ, cudaMemcpyHostToDevice); cudaMemcpy(C_gpu, C, sizeof(DATA_TYPE) * NI * NI, cudaMemcpyHostToDevice); dim3 block(DIM_THREAD_BLOCK_X, DIM_THREAD_BLOCK_Y); dim3 grid((size_t)(ceil(((float)NI) / ((float)DIM_THREAD_BLOCK_X))), (size_t)ceil(((float)NI) / ((float)DIM_THREAD_BLOCK_Y))); /* Start timer. */ polybench_start_instruments; syrk_kernel<<<grid,block>>>(ni, nj, alpha, beta, A_gpu,C_gpu); cudaThreadSynchronize(); /* Stop and print timer. */ printf("GPU Time in seconds:\n"); polybench_stop_instruments; polybench_print_instruments; cudaMemcpy(C_outputFromGpu, C_gpu, sizeof(DATA_TYPE) * NI * NI, cudaMemcpyDeviceToHost); cudaFree(A_gpu); cudaFree(C_gpu); } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < ni; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, C[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } int main(int argc, char *argv[]) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ DATA_TYPE alpha; DATA_TYPE beta; POLYBENCH_2D_ARRAY_DECL(A,DATA_TYPE,NI,NJ,ni,nj); POLYBENCH_2D_ARRAY_DECL(C,DATA_TYPE,NI,NI,ni,ni); POLYBENCH_2D_ARRAY_DECL(C_outputFromGpu,DATA_TYPE,NI,NI,ni,ni); init_arrays(ni, nj, &alpha, &beta, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(A)); GPU_argv_init(); syrkCuda(ni, nj, alpha, beta, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(C_outputFromGpu)); #ifdef RUN_ON_CPU /* Start timer. */ polybench_start_instruments; syrk(ni, nj, alpha, beta, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(C)); /* Stop and print timer. */ printf("CPU Time in seconds:\n"); polybench_stop_instruments; polybench_print_instruments; compareResults(ni, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(C_outputFromGpu)); #else //prevent dead code elimination polybench_prevent_dce(print_array(ni, POLYBENCH_ARRAY(C_outputFromGpu))); #endif //RUN_ON_CPU POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(C_outputFromGpu); return 0; } #include <polybench.c>
765c134ea30dd69708b51fc03eb1c267793df0b4.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <hip/hip_runtime.h> #include <hiprand/hiprand_kernel.h> #include <hip/hip_runtime.h> #define N 100 #define DIM 2 #define PamM 2e-11 #define S 0.5 char le_entrada(); char inicializa_parametros(); float *aloca_matriz(int, int); void cal_cond_robin(); char parametro_independentes(); char copia_dados_para_gpu(); void copia_dados_para_cpu(); void clear_mem(); //char calcula_pressao_velocidade(int, int, int, int, int); //char atualiza_mult_lagrange(int tid); static void HandleError( hipError_t err, const char *file, int line ) { if (err != hipSuccess) { printf( "%s in %s at line %d\n", hipGetErrorString( err ), file, line ); exit( EXIT_FAILURE ); } } #define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ )) #define HANDLE_NULL( a ) {if (a == NULL) { \ printf( "Host memory failed in %s at line %d\n", \ __FILE__, __LINE__ ); \ exit( EXIT_FAILURE );}} //- - - - - - - - - - - - - - GLOBAIS - - - - - - - - - - - - - - // /* - - - - - - - Estruturas - - - - - - - */ typedef struct{ float *R, *L, *U, *D; float *R_old, *L_old, *U_old, *D_old; }ESTRUTURA_Q; typedef struct{ float *R, *L, *U, *D; float *R_old, *L_old, *U_old, *D_old; }ESTRUTURA_L; typedef struct{ float *R, *L, *U, *D; float *R_old, *L_old, *U_old, *D_old; }ESTRUTURA_B; typedef struct{ float *p, *p_old; }ESTRUTURA_PRESSAO; typedef struct{ float *perm, *font, *epsilon; }ESTRUTURA_MAT; /* - - - - - - - Fim das Estruturas - - - - - - - */ /* - - - - - - - Variaveis das Estruturas - - - - - - - */ ESTRUTURA_Q host_q, dev_q; ESTRUTURA_L host_l, dev_l; ESTRUTURA_B host_b, dev_b; ESTRUTURA_PRESSAO host_pressao, dev_pressao; ESTRUTURA_MAT host_mat, dev_mat; /* - - - - - - - Entradas Externas - - - - - - - */ int tam_mat_interna = 3, tam_mat_real = 3 + 2, max_interacoes = 1000, op_contorno = 1; float tam_regiao = 20000.00, erro_max = 1e-5, valor_contor = 2.00; float h = 20000.00 / 3; // ALTURA H = TAM_REGIAO / TAM_MAT_INTERNA //float *mat_perm = NULL, *mat_font = NULL, *mat_epsilon = NULL; //float *dev_mat_perm = NULL, *mat_font = NULL, *mat_epsilon = NULL; /* - - - - - - - Fim das Entradas Externas - - - - - - - */ /* - - - - - - - Fim das Variaveis das Estruturas - - - - - - - */ /* - - - - - - - Ponteiros para GPU - - - - - - - */ float *dev_aux_1 = NULL, *dev_aux_2 = NULL, dev_erro = NULL, *dev_media = NULL; // float *dev_aux_1 = NULL, dev_erro = 0.0, dev_media = 0.0, dev_sum1 = 0.0, dev_sum2 = 0.0; // // float *dev_q.R = NULL, *dev_q.L = NULL, *dev_q.U = NULL, *dev_q.D = NULL; // float *dev_q.R_old = NULL, *dev_q.L_old = NULL, *dev_q.U_old = NULL, *dev_q.D_old = NULL; // // float *dev_l.R = NULL, *dev_l.L = NULL, *dev_l.U = NULL, *dev_l.D = NULL; // float *dev_l.R_old = NULL, *dev_l.L_old = NULL, *dev_l.U_old = NULL, *dev_l.D_old = NULL; // // float *dev_b.R = NULL, *dev_b.L = NULL, *dev_b.U = NULL, *dev_b.D = NULL; // float *dev_b.R_old = NULL, *dev_b.L_old = NULL, *dev_b.U_old = NULL, *dev_b.D_old = NULL; // // float *dev_pressao.p = NULL, *dev_pressao.p_old = NULL; // //- - - - - - - - - - - - - - FIM - GLOBAIS - - - - - - - - - - - - - - // __device__ char atualiza_mult_lagrange( int tid, ESTRUTURA_Q *dev_q, ESTRUTURA_L *dev_l, ESTRUTURA_B *dev_b ){ int index_mem_central = 0, index_mem_down = 0, index_mem_uper = 0; int index_mem_left = 0, index_mem_right = 0; int offset = (blockDim.x * gridDim.x); // o kernel contem somente a quantidade de elementos internos // portanto a fronteira deve ser contata "+ 2" de cada lado index_mem_central = tid; index_mem_uper = index_mem_central - offset; // (offset -1) = comprimento do kernel index_mem_down = index_mem_central + offset; index_mem_left = index_mem_central - 1; index_mem_right = index_mem_central + 1; dev_l->U[index_mem_central] = dev_b->U[index_mem_central] * (dev_q->U[index_mem_central] + dev_q->D_old[index_mem_uper]) + dev_l->D_old[index_mem_uper]; dev_l->D[index_mem_central] = dev_b->D[index_mem_central] * (dev_q->D[index_mem_central] + dev_q->U_old[index_mem_down]) + dev_l->U_old[index_mem_down]; dev_l->R[index_mem_central] = dev_b->R[index_mem_central] * (dev_q->R[index_mem_central] + dev_q->L_old[index_mem_right]) + dev_l->L_old[index_mem_right]; dev_l->L[index_mem_central] = dev_b->L[index_mem_central] * (dev_q->L[index_mem_central] + dev_q->R_old[index_mem_left]) + dev_l->R_old[index_mem_left]; return 0; } __device__ char calcula_pressao_velocidade( int tid, int uper, int right, int down, int left, ESTRUTURA_Q *dev_q, ESTRUTURA_L *dev_l, ESTRUTURA_B *dev_b, ESTRUTURA_PRESSAO *dev_pressao, ESTRUTURA_MAT *dev_mat ){ float auxU = 0.0, auxD = 0.0, auxR = 0.0, auxL = 0.0, DU = 0.0, DD = 0.0, DR = 0.0, DL = 0.0; int index_mem_central = 0, index_mem_down = 0, index_mem_uper = 0; int index_mem_left = 0, index_mem_right = 0; int offset = (blockDim.x * gridDim.x); // o kernel contem somente a quantidade de elementos internos // portanto a fronteira deve ser contata "+ 2" de cada lado index_mem_central = tid; index_mem_uper = index_mem_central - offset; index_mem_down = index_mem_central + offset; index_mem_left = index_mem_central - 1; index_mem_right = index_mem_central + 1; if(uper == 1){ auxU = dev_mat->epsilon[index_mem_central] / (1 + dev_b->U[index_mem_central] * dev_mat->epsilon[index_mem_central]); DU = auxU * (dev_b->U[index_mem_central] * dev_q->D_old[index_mem_uper] + dev_l->D_old[index_mem_uper]); } if(right == 1){ auxR = dev_mat->epsilon[index_mem_central] / (1 + dev_b->R[index_mem_central] * dev_mat->epsilon[index_mem_central]); DR = auxR * (dev_b->R[index_mem_central] * dev_q->L_old[index_mem_right] + dev_l->L_old[index_mem_right]); } if(down == 1){ auxD = dev_mat->epsilon[index_mem_central] / (1 + dev_b->D[index_mem_central] * dev_mat->epsilon[index_mem_central]); DD = auxD * (dev_b->D[index_mem_central] * dev_q->U_old[index_mem_down] + dev_l->U_old[index_mem_down]); } if(left == 1){ auxL = dev_mat->epsilon[index_mem_central] / (1 + dev_b->L[index_mem_central] * dev_mat->epsilon[index_mem_central]); DL = auxL * (dev_b->L[index_mem_central] * dev_q->R_old[index_mem_left] + dev_l->R_old[index_mem_left]); } dev_pressao->p[index_mem_central] = (dev_mat->font[index_mem_central] + DU + DR + DD + DL) / (auxU + auxR + auxD + auxL); dev_q->L[index_mem_central] = auxL * dev_pressao->p[index_mem_central] - DL; dev_q->R[index_mem_central] = auxR * dev_pressao->p[index_mem_central] - DR; dev_q->U[index_mem_central] = auxU * dev_pressao->p[index_mem_central] - DU; dev_q->D[index_mem_central] = auxD * dev_pressao->p[index_mem_central] - DD; return 0; } __global__ void reducao(float *in){ int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; int i = (dimensao_x * dimensao_y )/ 2; while(i != 0){ if(tid < i) in[tid] += in[tid + i]; if(i % 2 == 1){ if(i>1) in[0] += in[i-1]; } __syncthreads(); i /= 2; } } __global__ void reducao2(float *in_1, float *in_2){ int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; int i = (dimensao_x * dimensao_y )/ 2; while(i != 0){ if(tid < i) in_1[tid] += in_1[tid + i]; in_2[tid] += in_2[tid + i]; if(i % 2 == 1){ if(i>1) in_1[0] += in_1[i-1]; in_2[0] += in_2[i-1]; } __syncthreads(); i /= 2; } } __global__ void escoamento_monofasico( ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b, ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_MAT dev_mat, float *dev_aux_1, const float erro_max, float dev_erro, float *dev_media){ /*int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int offset = x + y * blockDim.x * gridDim.x; a[offset] = offset;*/ /*vificar as condies de contorno*/ int flag_thread_centrais = 1; int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; /*int offset = (blockDim.x * gridDim.x) + 1; // deslocamento para o tamanho da regio (tam_regiao = n + 2) */ int tid = x + y * blockDim.x * gridDim.x; //verificar esse deslocamento para n causar problema (somente na hora de armazenar utilizar o deslocamento) //int tid = (x + y * blockDim.x * gridDim.x) + offset; // tid fornece o indice do vetor int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; int eq_tid_cant_sup_esq = dimensao_x + 1; int eq_tid_cant_sup_dir = dimensao_x + (dimensao_x - 2); // posio extremo sup direito int eq_tid_cant_inf_dir = (dimensao_x * dimensao_y) - (dimensao_x + 2); // posio extremo inf direito int eq_tid_cant_inf_esq = ((dimensao_x) * (dimensao_y - 2)) + 1; // posio extremo inf esquerdo // int offset = (blockDim.x * gridDim.x) + 1 + 2; // o kernel contem somente a quantidade de elementos internos // portanto a fronteira deve ser contata "+ 2" de cada lado int index_mem_central = tid; if(tid == eq_tid_cant_sup_esq){//canto superior esquerdo /*VERIFICAR AS CONDIES DE CONTORNO*/ /* * calcula_pressao_velocidade(); * * Param: ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b, ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_MAT dev_mat * */ calcula_pressao_velocidade( tid, 0, 1, 1, 0, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); /* * * atualiza_mult_lagrange(); * * param: int tid, ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b * */ atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(tid == eq_tid_cant_sup_dir){//canto superior direito /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 0, 0, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(tid == eq_tid_cant_inf_esq){//canto inferior esquerdo /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 0, 0, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(tid == eq_tid_cant_inf_dir){//canto inferior direito /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 0, 0, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange( tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_sup_esq) && (tid < eq_tid_cant_sup_dir)){//fronteira superior /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 0, 1, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_sup_dir) && (tid < eq_tid_cant_inf_dir) && (tid % dimensao_x == dimensao_x - 2)){ //fronteira direita /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 0, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_inf_esq) && (tid < eq_tid_cant_inf_dir)){ //fronteira inferior /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 0, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_sup_esq) && (tid < eq_tid_cant_inf_dir) && (tid < eq_tid_cant_inf_esq) && (tid % dimensao_x == 1)){//fronteira esquerda /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 1, 0, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(flag_thread_centrais && (tid % dimensao_x >= 2) && (tid % dimensao_x <= (dimensao_x - 3)) && (tid > eq_tid_cant_sup_dir) && (tid < eq_tid_cant_inf_esq) ){ /*VERIFICAR AS CONDIES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); } dev_media[tid] = dev_pressao.p[tid]; /* dev_media[0] = reducao(dev_media, 100); dev_media[0] = dev_media[0] / (dimensao_x * dimensao_y); dev_pressao.p[index_mem_central] -= dev_media[0]; dev_l.D[index_mem_central] -= dev_media[0]; dev_l.U[index_mem_central] -= dev_media[0]; dev_l.L[index_mem_central] -= dev_media[0]; dev_l.R[index_mem_central] -= dev_media[0];*/ //avaliando criterio de convergencia /*dev_aux_1[index_mem_central] = dev_pressao.p[index_mem_central] - dev_pressao.p_old[index_mem_central]; __syncthreads(); dev_aux_1[index_mem_central] = dev_aux_1[index_mem_central] * dev_aux_1[index_mem_central]; __syncthreads();*/ //reduo da primeira soma sum1 /*dev_sum1 = reducao(dev_aux_1, 100);*/ //reduo da segunda soma sum2 /*dev_aux_1[index_mem_central] = dev_pressao.p[index_mem_central] * dev_pressao.p[index_mem_central]; __syncthreads(); dev_sum2 = reducao(dev_aux_1, 100); dev_erro = sqrt(dev_sum1 / dev_sum2);*/ //DUVIDA PARA COMO O SINAL DO ERRO /*if (dev_erro > erro_max){ return; } dev_pressao.p_old[index_mem_central] = dev_pressao.p[index_mem_central]; dev_q.U_old[index_mem_central] = dev_q.U[index_mem_central]; dev_q.R_old[index_mem_central] = dev_q.R[index_mem_central]; dev_q.L_old[index_mem_central] = dev_q.L[index_mem_central]; dev_q.D_old[index_mem_central] = dev_q.D[index_mem_central]; dev_l.D_old[index_mem_central] = dev_l.D[index_mem_central]; dev_l.U_old[index_mem_central] = dev_l.U[index_mem_central]; dev_l.L_old[index_mem_central] = dev_l.L[index_mem_central]; dev_l.R_old[index_mem_central] = dev_l.R[index_mem_central]; i++; }*/ } __global__ void perapara_criterio_convergencia(float *dev_aux_1, float *dev_aux_2, float *dev_media, ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_PRESSAO dev_pressao){ // sum1 = 0.; // sum2 = 0.; // for (k=1; k<=n; k++) // for (j=1; j<=n; j++) // { // aux = p[j][k] - p_old[j][k]; // sum1 += aux*aux; // sum2 += p[j][k]*p[j][k]; // } // erro = sqrt(sum1/sum2); //float dev_sum1 = 0.0, dev_sum2 = 0.0; int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; float media = dev_media[0] / (dimensao_x * dimensao_y); /*Media zero nas pressoes e multiplicadores de lagrange*/ dev_pressao.p[tid] -= media; dev_l.D[tid] -= media; dev_l.U[tid] -= media; dev_l.L[tid] -= media; dev_l.R[tid] -= media; dev_aux_1[tid] = dev_pressao.p[tid] - dev_pressao.p_old[tid]; dev_aux_1[tid] = dev_aux_1[tid] * dev_aux_1[tid]; dev_aux_2[tid] = dev_pressao.p[tid] * dev_pressao.p[tid]; // dev_pressao.p_old[tid] = dev_pressao.p[tid]; // dev_q.U_old[tid] = dev_q.U[tid]; // dev_q.R_old[tid] = dev_q.R[tid]; // dev_q.L_old[tid] = dev_q.L[tid]; // dev_q.D_old[tid] = dev_q.D[tid]; // // dev_l.D_old[tid] = dev_l.D[tid]; // dev_l.U_old[tid] = dev_l.U[tid]; // dev_l.L_old[tid] = dev_l.L[tid]; // dev_l.R_old[tid] = dev_l.R[tid]; } __global__ void teste( ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l ){ int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; //dev_pressao.p_old[tid] = dev_pressao.p[tid];hipMemcpy__ dev_q.U_old[tid] = dev_q.U[tid]; dev_q.R_old[tid] = dev_q.R[tid]; dev_q.L_old[tid] = dev_q.L[tid]; dev_q.D_old[tid] = dev_q.D[tid]; dev_l.D_old[tid] = dev_l.D[tid]; dev_l.U_old[tid] = dev_l.U[tid]; dev_l.L_old[tid] = dev_l.L[tid]; dev_l.R_old[tid] = dev_l.R[tid]; } int main(void){ le_entrada(); inicializa_parametros(); cal_cond_robin(); parametro_independentes(); copia_dados_para_gpu(); // dim3 block(comprimento/16 , altura/16); // dim3 thread(16, 16); dim3 block(2, 2); dim3 thread(5, 5); /* * escoamento_monofasico(); * * Param: ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b, ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_MAT dev_mat, float *dev_aux_1, const float erro_max * */ int i = 0, j = 0; while (i < 3){ hipLaunchKernelGGL(( escoamento_monofasico), dim3(block), dim3(thread), 0, 0, dev_q, dev_l, dev_b, dev_pressao, dev_mat, dev_aux_1, 1e-5, dev_erro, dev_media); //hipDeviceSynchronize(); hipLaunchKernelGGL(( reducao), dim3(block), dim3(thread), 0, 0, dev_media ); //hipDeviceSynchronize(); hipLaunchKernelGGL(( perapara_criterio_convergencia), dim3(block), dim3(thread), 0, 0, dev_aux_1, dev_aux_2, dev_media, dev_q, dev_l, dev_pressao); //hipDeviceSynchronize(); //reducao2<<<block, thread>>>( dev_aux_1, dev_aux_2); hipLaunchKernelGGL(( reducao), dim3(block), dim3(thread), 0, 0, dev_aux_1 ); //hipDeviceSynchronize(); hipLaunchKernelGGL(( reducao), dim3(block), dim3(thread), 0, 0, dev_aux_2 ); //hipDeviceSynchronize(); hipLaunchKernelGGL(( teste), dim3(block), dim3(thread), 0, 0, dev_pressao, dev_q, dev_l ); //hipDeviceSynchronize(); HANDLE_ERROR( hipMemset( dev_media, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMemset( dev_aux_1, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMemset( dev_aux_2, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); //hipDeviceSynchronize(); i++; } copia_dados_para_cpu(); /* printf("\ntam_mat_interna = %d\n", tam_mat_interna); printf("tam_mat_real = %d\n", tam_mat_real); printf("max_interacoes = %d\n", max_interacoes); printf("op_contorno = %d\n", op_contorno); printf("tam_regiao = %f\n", tam_regiao); printf("erro_max = %f\n", erro_max); printf("valor_contor = %f\n", valor_contor); printf("\n\n\t\t\tmat_font:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_mat.font[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tmat_perm:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_mat.perm[i*tam_mat_real + j]); //printf("%12.4E ", host_mat.perm[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tmat_epsilon:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_mat.epsilon[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\tbeta U:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.U[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tbeta R:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.R[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tbeta L:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.L[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tbeta D:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\t\tq_U:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.U[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_R:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.R[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_L:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.L[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_D:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.D[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_U:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.U[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_R:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.R[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_L:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.L[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_D:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.D[i*tam_mat_real + j]); printf("\n"); }*/ printf("\npressao:\n"); printf("\n\n\t\t\t\tpressao:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p[i*tam_mat_real + j]); printf("\n"); } printf("\npressao old:\n"); printf("\n\n\t\t\t\tpressao old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p_old[i*tam_mat_real + j]); printf("\n"); } /*printf("\n\n\t\t\t\tb_U:\t\t\t\t\t\t\t\t\tb_U_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.U[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.U_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tb_R:\t\t\t\t\t\t\t\t\tb_R_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.R[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.R_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tb_D:\t\t\t\t\t\t\t\t\tb_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tb_D:\t\t\t\t\t\t\t\t\tb_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\npressao:\n"); printf("\n\n\t\t\t\tpressao:\t\t\t\t\t\t\t\t\tpressao_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p_old[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\t\tl_U:\t\t\t\t\t\t\t\t\tl_U_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.U[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.U_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_R:\t\t\t\t\t\t\t\t\tl_R_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.R[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.R_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_D:\t\t\t\t\t\t\t\t\tl_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_L:\t\t\t\t\t\t\t\t\tl_L_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.L[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.L_old[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\t\tq_U:\t\t\t\t\t\t\t\t\tq_U_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.U[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.U_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_R:\t\t\t\t\t\t\t\t\tq_R_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.R[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.R_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_D:\t\t\t\t\t\t\t\t\tq_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_L:\t\t\t\t\t\t\t\t\tq_L_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.L[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.L_old[i*tam_mat_real + j]); printf("\n"); }*/ clear_mem(); // // system("pause"); return 0; } char le_entrada(){ printf("\n\n\t\t - - CARREGANDO ENTRADA - - \n\n"); FILE *arq = NULL; //arq = fopen("../dir_entrada/parametro_entrada.txt", "r"); arq = fopen("parametro_entrada.txt", "r"); if(arq == NULL){ printf("Erro ao abrir aquivo: 'parametro_entrada.txt'\n\t\tCertifique-se que o arquivo exite.\n"); exit(1); } else{ printf("\t\t - - LENDO ARQUIVO DE ENTRADA - -\n"); /*char c[2], dados[255], buffer[255];*/ char buffer[255]; int cont = 1; while(cont < 9){ fscanf(arq, "%s", buffer); //puts(buffer); int i = 0, j = 0; switch(strlen(buffer)){ case 8: //erro_maximo fscanf(arq, "%f", &erro_max); break; case 10: //tam_regiao fscanf(arq, "%f", &tam_regiao); break; case 11: //opcao_contorno fscanf(arq, "%d", &op_contorno); break; case 12: //valor_contor fscanf(arq, "%f", &valor_contor); break; case 14: //max_interacoes fscanf(arq, "%d", &max_interacoes); break; case 15: //tam_mat_interna fscanf(arq, "%d", &tam_mat_interna); break; case 16: //matriz_de_fontes //uso (tam_mat_interna + 2) - pois ainda no inicializei 'tam_mat_real' host_mat.font = aloca_matriz(tam_mat_interna + 2, tam_mat_interna + 2); for(i = 1; i < (tam_mat_interna + 2) - 1; i ++) for(j = 1; j < (tam_mat_interna + 2) - 1 ; j++) fscanf(arq, "%f", &host_mat.font[i*(tam_mat_interna+2) + j]); break; case 18: //matriz_permeabilidade host_mat.perm = aloca_matriz(tam_mat_interna + 2, tam_mat_interna + 2); host_mat.epsilon = aloca_matriz(tam_mat_interna + 2, tam_mat_interna + 2); for(i = 1; i < (tam_mat_interna + 2) - 1; i ++) for(j = 1; j < (tam_mat_interna + 2) - 1 ; j++) fscanf(arq, "%f", &host_mat.perm[i*(tam_mat_interna+2) + j]); for(i = 1; i < (tam_mat_interna + 2) - 1; i ++) for(j = 1; j < (tam_mat_interna + 2) - 1 ; j++) host_mat.perm[i*(tam_mat_interna+2) + j] = PamM*exp(S * host_mat.perm[i*(tam_mat_interna+2) + j]); break; default: printf("\n\n\t\tHouve algum erro no aquivo de entrada!\n\n"); return 0; } //int tam = strlen(buffer); cont++; } printf("\t\t - - ARQUIVO DE ENTRADA CARREGADO - -\n"); } printf("\n\n\t\t - - ENTRADA CARREGA - - \n\n"); return 1; } float *aloca_matriz(int L, int C){ float *aux = NULL; aux = (float *) calloc(L * C, sizeof(float)); if(aux == NULL){ printf("\n\n\t\tErro ao alocar memoria\n\n"); exit(1); }else{ return (aux); } return NULL; } /* * *VERIFICAR RETORNO * */ void cal_cond_robin(){ float keff = 0.0, numerador = 0.0, denominador = 0.0; float C = 1.0; // Cte adimensional que se ajusta experimentalmente C = 1.0 //Canto superior esquerdo numerador = ( 2 * host_mat.perm[tam_mat_real + 1] * host_mat.perm[tam_mat_real + 2] ); denominador = ( host_mat.perm[tam_mat_real + 1] + host_mat.perm[tam_mat_real + 2] ); keff = numerador / denominador; host_b.R[tam_mat_real + 1] = C*h/keff; numerador = (2 * host_mat.perm[tam_mat_real + 1] * host_mat.perm[(2*tam_mat_real) + 1]); denominador = ( host_mat.perm[tam_mat_real + 1] + host_mat.perm[(2*tam_mat_real) + 1]); keff = numerador / denominador; host_b.D[tam_mat_real + 1] = C*h/keff; //Canto superior direito numerador = ( 2 * host_mat.perm[tam_mat_real + tam_mat_interna] * host_mat.perm[tam_mat_real + (tam_mat_interna - 1)] ); denominador = ( host_mat.perm[tam_mat_real + tam_mat_interna] + host_mat.perm[tam_mat_real + (tam_mat_interna - 1)] ); keff = numerador / denominador; host_b.L[tam_mat_real + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[tam_mat_real + tam_mat_interna] * host_mat.perm[(2 * tam_mat_real) + tam_mat_interna] ); denominador = ( host_mat.perm[tam_mat_real + tam_mat_interna] + host_mat.perm[(2 * tam_mat_real) + tam_mat_interna] ); keff = numerador / denominador; host_b.D[tam_mat_real + tam_mat_interna] = C*h/keff; //Canto infeior esquerdo numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] * host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + 1] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] + host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + 1] ); keff = numerador / denominador; host_b.U[(tam_mat_real * tam_mat_interna) + 1] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] * host_mat.perm[(tam_mat_real * tam_mat_interna) + 2] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] + host_mat.perm[(tam_mat_real * tam_mat_interna) + 2] ); keff = numerador / denominador; host_b.R[(tam_mat_real * tam_mat_interna) + 1] = C*h/keff; //Canto infeior direito numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] * host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + tam_mat_interna] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] + host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + tam_mat_interna] ); keff = numerador / denominador; host_b.U[(tam_mat_real * tam_mat_interna) + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] * host_mat.perm[(tam_mat_real * tam_mat_interna) + (tam_mat_interna - 1)] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] + host_mat.perm[(tam_mat_real * tam_mat_interna) + (tam_mat_interna - 1)] ); keff = numerador / denominador; host_b.L[(tam_mat_real * tam_mat_interna) + tam_mat_interna] = C*h/keff; //Calculo das fronteiras e regio interna para betas int i = 0; for(i = 2; i < tam_mat_interna; i ++){ //Calcula fronteira superior numerador = ( 2 * host_mat.perm[tam_mat_real + i] * host_mat.perm[tam_mat_real + (i-1)] ); denominador = ( host_mat.perm[tam_mat_real + i] + host_mat.perm[tam_mat_real + (i-1)] ); keff = numerador / denominador; host_b.L[tam_mat_real + i] = C*h/keff; numerador = ( 2 * host_mat.perm[tam_mat_real + i] * host_mat.perm[tam_mat_real + (i+1)] ); denominador = ( host_mat.perm[tam_mat_real + i] + host_mat.perm[tam_mat_real + (i+1)] ); keff = numerador / denominador; host_b.R[tam_mat_real + i] = C*h/keff; numerador = ( 2 * host_mat.perm[tam_mat_real + i] * host_mat.perm[(2 * tam_mat_real) + i] ); denominador = ( host_mat.perm[tam_mat_real + i] + host_mat.perm[(2 * tam_mat_real) + i] ); keff = numerador / denominador; host_b.D[tam_mat_real + i] = C*h/keff; //Calcula fronteira esquerda numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + 1] * host_mat.perm[((i - 1) * tam_mat_real) + 1] ); denominador = ( host_mat.perm[(i * tam_mat_real) + 1] + host_mat.perm[((i - 1) * tam_mat_real) + 1] ); keff = numerador / denominador; host_b.U[(i * tam_mat_real) + 1] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + 1] * host_mat.perm[(i * tam_mat_real) + 2] ); denominador = ( host_mat.perm[(i * tam_mat_real) + 1] + host_mat.perm[(i * tam_mat_real) + 2] ); keff = numerador / denominador; host_b.R[(i * tam_mat_real) + 1] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + 1] * host_mat.perm[((i + 1) * tam_mat_real) + 1] ); denominador = ( host_mat.perm[(i * tam_mat_real) + 1] + host_mat.perm[((i + 1) * tam_mat_real) + 1] ); keff = numerador / denominador; host_b.D[(i * tam_mat_real) + 1] = C*h/keff; //Calcula fronteira inferior numerador = ( 2 * host_mat.perm[(tam_mat_interna * tam_mat_real) + i] * host_mat.perm[(tam_mat_interna * tam_mat_real) + (i - 1)] ); denominador = ( host_mat.perm[(tam_mat_interna * tam_mat_real) + i] + host_mat.perm[(tam_mat_interna * tam_mat_real) + (i - 1)] ); keff = numerador / denominador; host_b.L[(tam_mat_interna * tam_mat_real) + i] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_interna * tam_mat_real) + i] * host_mat.perm[((tam_mat_interna - 1) * tam_mat_real) + i] ); denominador = ( host_mat.perm[(tam_mat_interna * tam_mat_real) + i] + host_mat.perm[((tam_mat_interna - 1) * tam_mat_real) + i] ); keff = numerador / denominador; host_b.U[(tam_mat_interna * tam_mat_real) + i] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_interna * tam_mat_real) + i] * host_mat.perm[(tam_mat_interna * tam_mat_real) + (i + 1)] ); denominador = ( host_mat.perm[(tam_mat_interna * tam_mat_real) + i] + host_mat.perm[(tam_mat_interna * tam_mat_real) + (i + 1)] ); keff = numerador / denominador; host_b.R[(tam_mat_interna * tam_mat_real) + i] = C*h/keff; //Calcula fronteira direita numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + tam_mat_interna] * host_mat.perm[((i-1) * tam_mat_real) + tam_mat_interna] ); denominador = ( host_mat.perm[(i * tam_mat_real) + tam_mat_interna] + host_mat.perm[((i-1) * tam_mat_real) + tam_mat_interna] ); keff = numerador / denominador; host_b.U[(i * tam_mat_real) + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + tam_mat_interna] * host_mat.perm[(i * tam_mat_real) + (tam_mat_interna - 1)] ); denominador = ( host_mat.perm[(i * tam_mat_real) + tam_mat_interna] + host_mat.perm[(i * tam_mat_real) + (tam_mat_interna - 1)] ); keff = numerador / denominador; host_b.L[(i * tam_mat_real) + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + tam_mat_interna] * host_mat.perm[((i+1) * tam_mat_real) + tam_mat_interna] ); denominador = ( host_mat.perm[(i * tam_mat_real) + tam_mat_interna] + host_mat.perm[((i+1) * tam_mat_real) + tam_mat_interna] ); keff = numerador / denominador; host_b.D[(i * tam_mat_real) + tam_mat_interna] = C*h/keff; //Calcula dados internos int j = 0; for(j = 2; j < tam_mat_interna; j ++){ numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[(i * tam_mat_real) + (j - 1)] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[(i * tam_mat_real) + (j - 1)] ); keff = numerador / denominador; host_b.L[(i * tam_mat_real) + j] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[(i * tam_mat_real) + (j + 1)] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[(i * tam_mat_real) + (j + 1)] ); keff = numerador / denominador; host_b.R[(i * tam_mat_real) + j] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[((i - 1) * tam_mat_real) + j] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[((i - 1) * tam_mat_real) + j] ); keff = numerador / denominador; host_b.U[(i * tam_mat_real) + j] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[((i + 1) * tam_mat_real) + j] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[((i + 1) * tam_mat_real) + j] ); keff = numerador / denominador; host_b.D[(i * tam_mat_real) + j] = C*h/keff; } } } /* * *VERIFICAR RETORNO * */ char parametro_independentes(){ int i = 0, j = 0; float constante = 2/h; for(i = 0; i < tam_mat_real; i ++) for(j = 0; j < tam_mat_real; j++){ host_mat.epsilon[i*tam_mat_real + j] = constante * host_mat.perm[i*tam_mat_real + j]; host_mat.font[i*tam_mat_real + j] *= h; } return 0; } char copia_dados_para_gpu(){ HANDLE_ERROR( hipMemcpy( dev_q.R, host_q.R, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.L, host_q.L, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.U, host_q.U, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.D, host_q.D, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.R_old, host_q.R_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.L_old, host_q.L_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.U_old, host_q.U_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_q.D_old, host_q.D_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.R, host_l.R, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.L, host_l.L, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.U, host_l.U, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.D, host_l.D, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.R_old, host_l.R_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.L_old, host_l.L_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.U_old, host_l.U_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_l.D_old, host_l.D_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.R, host_b.R, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.L, host_b.L, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.U, host_b.U, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.D, host_b.D, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.R_old, host_b.R_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.L_old, host_b.L_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.U_old, host_b.U_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_b.D_old, host_b.D_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_pressao.p, host_pressao.p, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_pressao.p_old, host_pressao.p_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_mat.perm, host_mat.perm, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_mat.epsilon, host_mat.epsilon, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); HANDLE_ERROR( hipMemcpy( dev_mat.font, host_mat.font, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyHostToDevice ) ); return 0; } void copia_dados_para_cpu(){ HANDLE_ERROR( hipMemcpy( host_q.R, dev_q.R, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.L, dev_q.L, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.U, dev_q.U, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.D, dev_q.D, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.R_old, dev_q.R_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.L_old, dev_q.L_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.U_old, dev_q.U_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_q.D_old, dev_q.D_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.R, dev_l.R, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.L, dev_l.L, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.U, dev_l.U, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.D, dev_l.D, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.R_old, dev_l.R_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.L_old, dev_l.L_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.U_old, dev_l.U_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_l.D_old, dev_l.D_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.R, dev_b.R, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.L, dev_b.L, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.U, dev_b.U, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.D, dev_b.D, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.R_old, dev_b.R_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.L_old, dev_b.L_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.U_old, dev_b.U_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_b.D_old, dev_b.D_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_pressao.p, dev_pressao.p, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_pressao.p_old, dev_pressao.p_old, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_mat.font, dev_mat.font, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_mat.perm, dev_mat.perm, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); HANDLE_ERROR( hipMemcpy( host_mat.epsilon, dev_mat.epsilon, tam_mat_real * tam_mat_real * sizeof(float), hipMemcpyDeviceToHost ) ); } char inicializa_parametros(){ printf("\n\n\t\t- - INICIALIZANDO PARAMETROS - - \n\n\n"); /* * * * CONTRUIR FUNCAO PARA VERIFICAR ERRO DE ALOCAO * VERIFICAR RETORNO */ tam_mat_real = tam_mat_interna + 2; h = tam_regiao / tam_mat_interna; HANDLE_ERROR( hipMalloc( (void**)&dev_q, sizeof(ESTRUTURA_Q) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_l, sizeof(ESTRUTURA_L) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_b, sizeof(ESTRUTURA_B) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_pressao, sizeof(ESTRUTURA_PRESSAO) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_mat, sizeof(ESTRUTURA_MAT) ) ); host_q.R = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.R != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.R, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.L = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.L != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.L, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.U = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.U != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.U, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.D = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.D != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.D, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.R_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.R_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.R_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.L_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.L_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.L_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.U_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.U_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.U_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.D_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.D_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_q.D_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.R = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.R != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.R, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.L = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.L != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.L, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.U = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.U != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.U, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.D = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.D != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.D, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.R_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.R_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.R_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.L_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.L_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.L_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.U_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.U_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.U_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.D_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.D_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_l.D_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.R = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.R != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.R, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.L = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.L != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.L, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.U = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.U != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.U, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.D = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.D != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.D, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.R_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.R_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.R_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.L_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.L_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.L_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.U_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.U_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.U_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.D_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.D_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_b.D_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_pressao.p = aloca_matriz(tam_mat_real, tam_mat_real); if(host_pressao.p != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_pressao.p, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_pressao.p_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_pressao.p_old != NULL) HANDLE_ERROR( hipMalloc( (void**)&dev_pressao.p_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_mat.perm, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_mat.font, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_mat.epsilon, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_aux_1, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_aux_2, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMemset( dev_aux_1, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMemset( dev_aux_2, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&erro_max, sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_erro, sizeof(float) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_media, tam_mat_real * tam_mat_real * sizeof(float)) ); int i = 0; switch(op_contorno){ case 1: //Inicializa contorno superior for(i = 0; i < tam_mat_real; i++){ host_q.D[i] = valor_contor; host_q.D_old[i] = valor_contor; } break; case 2://Inicializa contorno esquerdo for(i = 0; i < tam_mat_real; i++){ host_q.R[i*tam_mat_real] = valor_contor; host_q.R_old[i*tam_mat_real] = valor_contor; } break; case 3://Inicializa contorno direito for(i = 0; i < tam_mat_real; i++){ host_q.L[i*tam_mat_real + (tam_mat_real - 1)] = valor_contor; host_q.L_old[i*tam_mat_real + (tam_mat_real - 1)] = valor_contor; } break; case 4://Inicializa contorno inferior for(i = 0; i < tam_mat_real; i++){ host_q.L[(tam_mat_real-1)*tam_mat_real + i] = valor_contor; host_q.L_old[(tam_mat_real-1)*tam_mat_real + i] = valor_contor; } break; default: printf("\n\n\t\t - - OCORREU ALGUM ERRO NA OPCAO DE CONTORNO - - \n\n"); break; } printf("\n\n\t\t- - FIM DA INICIALIZACAO PARAMETROS - - \n\n\n"); return 1; } void clear_mem(){ HANDLE_ERROR( hipFree (dev_q.U)); HANDLE_ERROR( hipFree (dev_q.R)); HANDLE_ERROR( hipFree (dev_q.D)); HANDLE_ERROR( hipFree (dev_q.L)); free(host_q.U); free(host_q.R); free(host_q.D); free(host_q.L); HANDLE_ERROR( hipFree (dev_l.U)); HANDLE_ERROR( hipFree (dev_l.R)); HANDLE_ERROR( hipFree (dev_l.D)); HANDLE_ERROR( hipFree (dev_l.L)); free(host_l.U); free(host_l.R); free(host_l.D); free(host_l.L); HANDLE_ERROR( hipFree (dev_b.U)); HANDLE_ERROR( hipFree (dev_b.R)); HANDLE_ERROR( hipFree (dev_b.D)); HANDLE_ERROR( hipFree (dev_b.L)); free(host_b.U); free(host_b.R); free(host_b.D); free(host_b.L); HANDLE_ERROR( hipFree (dev_pressao.p)); HANDLE_ERROR( hipFree (dev_pressao.p_old)); free(host_pressao.p); free(host_pressao.p_old); HANDLE_ERROR( hipFree (dev_mat.perm)); HANDLE_ERROR( hipFree (dev_mat.font)); HANDLE_ERROR( hipFree (dev_mat.epsilon)); free(host_mat.perm); free(host_mat.font); free(host_mat.epsilon); }
765c134ea30dd69708b51fc03eb1c267793df0b4.cu
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cuda.h> #include <curand_kernel.h> #include <cuda_runtime.h> #define N 100 #define DIM 2 #define PamM 2e-11 #define S 0.5 char le_entrada(); char inicializa_parametros(); float *aloca_matriz(int, int); void cal_cond_robin(); char parametro_independentes(); char copia_dados_para_gpu(); void copia_dados_para_cpu(); void clear_mem(); //char calcula_pressao_velocidade(int, int, int, int, int); //char atualiza_mult_lagrange(int tid); 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 ); } } #define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ )) #define HANDLE_NULL( a ) {if (a == NULL) { \ printf( "Host memory failed in %s at line %d\n", \ __FILE__, __LINE__ ); \ exit( EXIT_FAILURE );}} //- - - - - - - - - - - - - - GLOBAIS - - - - - - - - - - - - - - // /* - - - - - - - Estruturas - - - - - - - */ typedef struct{ float *R, *L, *U, *D; float *R_old, *L_old, *U_old, *D_old; }ESTRUTURA_Q; typedef struct{ float *R, *L, *U, *D; float *R_old, *L_old, *U_old, *D_old; }ESTRUTURA_L; typedef struct{ float *R, *L, *U, *D; float *R_old, *L_old, *U_old, *D_old; }ESTRUTURA_B; typedef struct{ float *p, *p_old; }ESTRUTURA_PRESSAO; typedef struct{ float *perm, *font, *epsilon; }ESTRUTURA_MAT; /* - - - - - - - Fim das Estruturas - - - - - - - */ /* - - - - - - - Variaveis das Estruturas - - - - - - - */ ESTRUTURA_Q host_q, dev_q; ESTRUTURA_L host_l, dev_l; ESTRUTURA_B host_b, dev_b; ESTRUTURA_PRESSAO host_pressao, dev_pressao; ESTRUTURA_MAT host_mat, dev_mat; /* - - - - - - - Entradas Externas - - - - - - - */ int tam_mat_interna = 3, tam_mat_real = 3 + 2, max_interacoes = 1000, op_contorno = 1; float tam_regiao = 20000.00, erro_max = 1e-5, valor_contor = 2.00; float h = 20000.00 / 3; // ALTURA H = TAM_REGIAO / TAM_MAT_INTERNA //float *mat_perm = NULL, *mat_font = NULL, *mat_epsilon = NULL; //float *dev_mat_perm = NULL, *mat_font = NULL, *mat_epsilon = NULL; /* - - - - - - - Fim das Entradas Externas - - - - - - - */ /* - - - - - - - Fim das Variaveis das Estruturas - - - - - - - */ /* - - - - - - - Ponteiros para GPU - - - - - - - */ float *dev_aux_1 = NULL, *dev_aux_2 = NULL, dev_erro = NULL, *dev_media = NULL; // float *dev_aux_1 = NULL, dev_erro = 0.0, dev_media = 0.0, dev_sum1 = 0.0, dev_sum2 = 0.0; // // float *dev_q.R = NULL, *dev_q.L = NULL, *dev_q.U = NULL, *dev_q.D = NULL; // float *dev_q.R_old = NULL, *dev_q.L_old = NULL, *dev_q.U_old = NULL, *dev_q.D_old = NULL; // // float *dev_l.R = NULL, *dev_l.L = NULL, *dev_l.U = NULL, *dev_l.D = NULL; // float *dev_l.R_old = NULL, *dev_l.L_old = NULL, *dev_l.U_old = NULL, *dev_l.D_old = NULL; // // float *dev_b.R = NULL, *dev_b.L = NULL, *dev_b.U = NULL, *dev_b.D = NULL; // float *dev_b.R_old = NULL, *dev_b.L_old = NULL, *dev_b.U_old = NULL, *dev_b.D_old = NULL; // // float *dev_pressao.p = NULL, *dev_pressao.p_old = NULL; // //- - - - - - - - - - - - - - FIM - GLOBAIS - - - - - - - - - - - - - - // __device__ char atualiza_mult_lagrange( int tid, ESTRUTURA_Q *dev_q, ESTRUTURA_L *dev_l, ESTRUTURA_B *dev_b ){ int index_mem_central = 0, index_mem_down = 0, index_mem_uper = 0; int index_mem_left = 0, index_mem_right = 0; int offset = (blockDim.x * gridDim.x); // o kernel contem somente a quantidade de elementos internos // portanto a fronteira deve ser contata "+ 2" de cada lado index_mem_central = tid; index_mem_uper = index_mem_central - offset; // (offset -1) = comprimento do kernel index_mem_down = index_mem_central + offset; index_mem_left = index_mem_central - 1; index_mem_right = index_mem_central + 1; dev_l->U[index_mem_central] = dev_b->U[index_mem_central] * (dev_q->U[index_mem_central] + dev_q->D_old[index_mem_uper]) + dev_l->D_old[index_mem_uper]; dev_l->D[index_mem_central] = dev_b->D[index_mem_central] * (dev_q->D[index_mem_central] + dev_q->U_old[index_mem_down]) + dev_l->U_old[index_mem_down]; dev_l->R[index_mem_central] = dev_b->R[index_mem_central] * (dev_q->R[index_mem_central] + dev_q->L_old[index_mem_right]) + dev_l->L_old[index_mem_right]; dev_l->L[index_mem_central] = dev_b->L[index_mem_central] * (dev_q->L[index_mem_central] + dev_q->R_old[index_mem_left]) + dev_l->R_old[index_mem_left]; return 0; } __device__ char calcula_pressao_velocidade( int tid, int uper, int right, int down, int left, ESTRUTURA_Q *dev_q, ESTRUTURA_L *dev_l, ESTRUTURA_B *dev_b, ESTRUTURA_PRESSAO *dev_pressao, ESTRUTURA_MAT *dev_mat ){ float auxU = 0.0, auxD = 0.0, auxR = 0.0, auxL = 0.0, DU = 0.0, DD = 0.0, DR = 0.0, DL = 0.0; int index_mem_central = 0, index_mem_down = 0, index_mem_uper = 0; int index_mem_left = 0, index_mem_right = 0; int offset = (blockDim.x * gridDim.x); // o kernel contem somente a quantidade de elementos internos // portanto a fronteira deve ser contata "+ 2" de cada lado index_mem_central = tid; index_mem_uper = index_mem_central - offset; index_mem_down = index_mem_central + offset; index_mem_left = index_mem_central - 1; index_mem_right = index_mem_central + 1; if(uper == 1){ auxU = dev_mat->epsilon[index_mem_central] / (1 + dev_b->U[index_mem_central] * dev_mat->epsilon[index_mem_central]); DU = auxU * (dev_b->U[index_mem_central] * dev_q->D_old[index_mem_uper] + dev_l->D_old[index_mem_uper]); } if(right == 1){ auxR = dev_mat->epsilon[index_mem_central] / (1 + dev_b->R[index_mem_central] * dev_mat->epsilon[index_mem_central]); DR = auxR * (dev_b->R[index_mem_central] * dev_q->L_old[index_mem_right] + dev_l->L_old[index_mem_right]); } if(down == 1){ auxD = dev_mat->epsilon[index_mem_central] / (1 + dev_b->D[index_mem_central] * dev_mat->epsilon[index_mem_central]); DD = auxD * (dev_b->D[index_mem_central] * dev_q->U_old[index_mem_down] + dev_l->U_old[index_mem_down]); } if(left == 1){ auxL = dev_mat->epsilon[index_mem_central] / (1 + dev_b->L[index_mem_central] * dev_mat->epsilon[index_mem_central]); DL = auxL * (dev_b->L[index_mem_central] * dev_q->R_old[index_mem_left] + dev_l->R_old[index_mem_left]); } dev_pressao->p[index_mem_central] = (dev_mat->font[index_mem_central] + DU + DR + DD + DL) / (auxU + auxR + auxD + auxL); dev_q->L[index_mem_central] = auxL * dev_pressao->p[index_mem_central] - DL; dev_q->R[index_mem_central] = auxR * dev_pressao->p[index_mem_central] - DR; dev_q->U[index_mem_central] = auxU * dev_pressao->p[index_mem_central] - DU; dev_q->D[index_mem_central] = auxD * dev_pressao->p[index_mem_central] - DD; return 0; } __global__ void reducao(float *in){ int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; int i = (dimensao_x * dimensao_y )/ 2; while(i != 0){ if(tid < i) in[tid] += in[tid + i]; if(i % 2 == 1){ if(i>1) in[0] += in[i-1]; } __syncthreads(); i /= 2; } } __global__ void reducao2(float *in_1, float *in_2){ int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; int i = (dimensao_x * dimensao_y )/ 2; while(i != 0){ if(tid < i) in_1[tid] += in_1[tid + i]; in_2[tid] += in_2[tid + i]; if(i % 2 == 1){ if(i>1) in_1[0] += in_1[i-1]; in_2[0] += in_2[i-1]; } __syncthreads(); i /= 2; } } __global__ void escoamento_monofasico( ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b, ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_MAT dev_mat, float *dev_aux_1, const float erro_max, float dev_erro, float *dev_media){ /*int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int offset = x + y * blockDim.x * gridDim.x; a[offset] = offset;*/ /*vificar as condições de contorno*/ int flag_thread_centrais = 1; int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; /*int offset = (blockDim.x * gridDim.x) + 1; // deslocamento para o tamanho da região (tam_regiao = n + 2) */ int tid = x + y * blockDim.x * gridDim.x; //verificar esse deslocamento para n causar problema (somente na hora de armazenar utilizar o deslocamento) //int tid = (x + y * blockDim.x * gridDim.x) + offset; // tid fornece o indice do vetor int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; int eq_tid_cant_sup_esq = dimensao_x + 1; int eq_tid_cant_sup_dir = dimensao_x + (dimensao_x - 2); // posição extremo sup direito int eq_tid_cant_inf_dir = (dimensao_x * dimensao_y) - (dimensao_x + 2); // posição extremo inf direito int eq_tid_cant_inf_esq = ((dimensao_x) * (dimensao_y - 2)) + 1; // posição extremo inf esquerdo // int offset = (blockDim.x * gridDim.x) + 1 + 2; // o kernel contem somente a quantidade de elementos internos // portanto a fronteira deve ser contata "+ 2" de cada lado int index_mem_central = tid; if(tid == eq_tid_cant_sup_esq){//canto superior esquerdo /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ /* * calcula_pressao_velocidade(); * * Param: ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b, ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_MAT dev_mat * */ calcula_pressao_velocidade( tid, 0, 1, 1, 0, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); /* * * atualiza_mult_lagrange(); * * param: int tid, ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b * */ atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(tid == eq_tid_cant_sup_dir){//canto superior direito /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 0, 0, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(tid == eq_tid_cant_inf_esq){//canto inferior esquerdo /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 0, 0, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(tid == eq_tid_cant_inf_dir){//canto inferior direito /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 0, 0, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange( tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_sup_esq) && (tid < eq_tid_cant_sup_dir)){//fronteira superior /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 0, 1, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_sup_dir) && (tid < eq_tid_cant_inf_dir) && (tid % dimensao_x == dimensao_x - 2)){ //fronteira direita /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 0, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_inf_esq) && (tid < eq_tid_cant_inf_dir)){ //fronteira inferior /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 0, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if((tid > eq_tid_cant_sup_esq) && (tid < eq_tid_cant_inf_dir) && (tid < eq_tid_cant_inf_esq) && (tid % dimensao_x == 1)){//fronteira esquerda /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 1, 0, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); flag_thread_centrais = 0; } if(flag_thread_centrais && (tid % dimensao_x >= 2) && (tid % dimensao_x <= (dimensao_x - 3)) && (tid > eq_tid_cant_sup_dir) && (tid < eq_tid_cant_inf_esq) ){ /*VERIFICAR AS CONDIÇÕES DE CONTORNO*/ calcula_pressao_velocidade( tid, 1, 1, 1, 1, &dev_q, &dev_l, &dev_b, &dev_pressao, &dev_mat); atualiza_mult_lagrange(tid, &dev_q, &dev_l, &dev_b); } dev_media[tid] = dev_pressao.p[tid]; /* dev_media[0] = reducao(dev_media, 100); dev_media[0] = dev_media[0] / (dimensao_x * dimensao_y); dev_pressao.p[index_mem_central] -= dev_media[0]; dev_l.D[index_mem_central] -= dev_media[0]; dev_l.U[index_mem_central] -= dev_media[0]; dev_l.L[index_mem_central] -= dev_media[0]; dev_l.R[index_mem_central] -= dev_media[0];*/ //avaliando criterio de convergencia /*dev_aux_1[index_mem_central] = dev_pressao.p[index_mem_central] - dev_pressao.p_old[index_mem_central]; __syncthreads(); dev_aux_1[index_mem_central] = dev_aux_1[index_mem_central] * dev_aux_1[index_mem_central]; __syncthreads();*/ //redução da primeira soma sum1 /*dev_sum1 = reducao(dev_aux_1, 100);*/ //redução da segunda soma sum2 /*dev_aux_1[index_mem_central] = dev_pressao.p[index_mem_central] * dev_pressao.p[index_mem_central]; __syncthreads(); dev_sum2 = reducao(dev_aux_1, 100); dev_erro = sqrt(dev_sum1 / dev_sum2);*/ //DUVIDA PARA COMO É O SINAL DO ERRO /*if (dev_erro > erro_max){ return; } dev_pressao.p_old[index_mem_central] = dev_pressao.p[index_mem_central]; dev_q.U_old[index_mem_central] = dev_q.U[index_mem_central]; dev_q.R_old[index_mem_central] = dev_q.R[index_mem_central]; dev_q.L_old[index_mem_central] = dev_q.L[index_mem_central]; dev_q.D_old[index_mem_central] = dev_q.D[index_mem_central]; dev_l.D_old[index_mem_central] = dev_l.D[index_mem_central]; dev_l.U_old[index_mem_central] = dev_l.U[index_mem_central]; dev_l.L_old[index_mem_central] = dev_l.L[index_mem_central]; dev_l.R_old[index_mem_central] = dev_l.R[index_mem_central]; i++; }*/ } __global__ void perapara_criterio_convergencia(float *dev_aux_1, float *dev_aux_2, float *dev_media, ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_PRESSAO dev_pressao){ // sum1 = 0.; // sum2 = 0.; // for (k=1; k<=n; k++) // for (j=1; j<=n; j++) // { // aux = p[j][k] - p_old[j][k]; // sum1 += aux*aux; // sum2 += p[j][k]*p[j][k]; // } // erro = sqrt(sum1/sum2); //float dev_sum1 = 0.0, dev_sum2 = 0.0; int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; int dimensao_x = blockDim.x * gridDim.x; int dimensao_y = blockDim.y * gridDim.y; float media = dev_media[0] / (dimensao_x * dimensao_y); /*Media zero nas pressoes e multiplicadores de lagrange*/ dev_pressao.p[tid] -= media; dev_l.D[tid] -= media; dev_l.U[tid] -= media; dev_l.L[tid] -= media; dev_l.R[tid] -= media; dev_aux_1[tid] = dev_pressao.p[tid] - dev_pressao.p_old[tid]; dev_aux_1[tid] = dev_aux_1[tid] * dev_aux_1[tid]; dev_aux_2[tid] = dev_pressao.p[tid] * dev_pressao.p[tid]; // dev_pressao.p_old[tid] = dev_pressao.p[tid]; // dev_q.U_old[tid] = dev_q.U[tid]; // dev_q.R_old[tid] = dev_q.R[tid]; // dev_q.L_old[tid] = dev_q.L[tid]; // dev_q.D_old[tid] = dev_q.D[tid]; // // dev_l.D_old[tid] = dev_l.D[tid]; // dev_l.U_old[tid] = dev_l.U[tid]; // dev_l.L_old[tid] = dev_l.L[tid]; // dev_l.R_old[tid] = dev_l.R[tid]; } __global__ void teste( ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l ){ int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int tid = x + y * blockDim.x * gridDim.x; //dev_pressao.p_old[tid] = dev_pressao.p[tid];cuMemcpy dev_q.U_old[tid] = dev_q.U[tid]; dev_q.R_old[tid] = dev_q.R[tid]; dev_q.L_old[tid] = dev_q.L[tid]; dev_q.D_old[tid] = dev_q.D[tid]; dev_l.D_old[tid] = dev_l.D[tid]; dev_l.U_old[tid] = dev_l.U[tid]; dev_l.L_old[tid] = dev_l.L[tid]; dev_l.R_old[tid] = dev_l.R[tid]; } int main(void){ le_entrada(); inicializa_parametros(); cal_cond_robin(); parametro_independentes(); copia_dados_para_gpu(); // dim3 block(comprimento/16 , altura/16); // dim3 thread(16, 16); dim3 block(2, 2); dim3 thread(5, 5); /* * escoamento_monofasico(); * * Param: ESTRUTURA_Q dev_q, ESTRUTURA_L dev_l, ESTRUTURA_B dev_b, ESTRUTURA_PRESSAO dev_pressao, ESTRUTURA_MAT dev_mat, float *dev_aux_1, const float erro_max * */ int i = 0, j = 0; while (i < 3){ escoamento_monofasico<<<block, thread>>>( dev_q, dev_l, dev_b, dev_pressao, dev_mat, dev_aux_1, 1e-5, dev_erro, dev_media); //cudaDeviceSynchronize(); reducao<<<block, thread>>>( dev_media ); //cudaDeviceSynchronize(); perapara_criterio_convergencia<<<block, thread>>>( dev_aux_1, dev_aux_2, dev_media, dev_q, dev_l, dev_pressao); //cudaDeviceSynchronize(); //reducao2<<<block, thread>>>( dev_aux_1, dev_aux_2); reducao<<<block, thread>>>( dev_aux_1 ); //cudaDeviceSynchronize(); reducao<<<block, thread>>>( dev_aux_2 ); //cudaDeviceSynchronize(); teste<<<block, thread>>>( dev_pressao, dev_q, dev_l ); //cudaDeviceSynchronize(); HANDLE_ERROR( cudaMemset( dev_media, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMemset( dev_aux_1, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMemset( dev_aux_2, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); //cudaDeviceSynchronize(); i++; } copia_dados_para_cpu(); /* printf("\ntam_mat_interna = %d\n", tam_mat_interna); printf("tam_mat_real = %d\n", tam_mat_real); printf("max_interacoes = %d\n", max_interacoes); printf("op_contorno = %d\n", op_contorno); printf("tam_regiao = %f\n", tam_regiao); printf("erro_max = %f\n", erro_max); printf("valor_contor = %f\n", valor_contor); printf("\n\n\t\t\tmat_font:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_mat.font[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tmat_perm:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_mat.perm[i*tam_mat_real + j]); //printf("%12.4E ", host_mat.perm[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tmat_epsilon:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_mat.epsilon[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\tbeta U:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.U[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tbeta R:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.R[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tbeta L:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.L[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\tbeta D:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\t\tq_U:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.U[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_R:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.R[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_L:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.L[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_D:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.D[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_U:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.U[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_R:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.R[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_L:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.L[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_D:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.D[i*tam_mat_real + j]); printf("\n"); }*/ printf("\npressao:\n"); printf("\n\n\t\t\t\tpressao:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p[i*tam_mat_real + j]); printf("\n"); } printf("\npressao old:\n"); printf("\n\n\t\t\t\tpressao old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p_old[i*tam_mat_real + j]); printf("\n"); } /*printf("\n\n\t\t\t\tb_U:\t\t\t\t\t\t\t\t\tb_U_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.U[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.U_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tb_R:\t\t\t\t\t\t\t\t\tb_R_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.R[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.R_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tb_D:\t\t\t\t\t\t\t\t\tb_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tb_D:\t\t\t\t\t\t\t\t\tb_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_b.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\npressao:\n"); printf("\n\n\t\t\t\tpressao:\t\t\t\t\t\t\t\t\tpressao_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_pressao.p_old[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\t\tl_U:\t\t\t\t\t\t\t\t\tl_U_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.U[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.U_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_R:\t\t\t\t\t\t\t\t\tl_R_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.R[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.R_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_D:\t\t\t\t\t\t\t\t\tl_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tl_L:\t\t\t\t\t\t\t\t\tl_L_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.L[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_l.L_old[i*tam_mat_real + j]); printf("\n"); } printf("\n------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("\n\n\t\t\t\tq_U:\t\t\t\t\t\t\t\t\tq_U_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.U[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.U_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_R:\t\t\t\t\t\t\t\t\tq_R_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.R[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.R_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_D:\t\t\t\t\t\t\t\t\tq_D_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.D[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.D_old[i*tam_mat_real + j]); printf("\n"); } printf("\n\n\t\t\t\tq_L:\t\t\t\t\t\t\t\t\tq_L_old:\n"); for(i = 0; i < tam_mat_real; i ++){ for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.L[i*tam_mat_real + j]); printf("| "); for(j = 0; j < tam_mat_real; j++) printf("%12.4E ", host_q.L_old[i*tam_mat_real + j]); printf("\n"); }*/ clear_mem(); // // system("pause"); return 0; } char le_entrada(){ printf("\n\n\t\t - - CARREGANDO ENTRADA - - \n\n"); FILE *arq = NULL; //arq = fopen("../dir_entrada/parametro_entrada.txt", "r"); arq = fopen("parametro_entrada.txt", "r"); if(arq == NULL){ printf("Erro ao abrir aquivo: 'parametro_entrada.txt'\n\t\tCertifique-se que o arquivo exite.\n"); exit(1); } else{ printf("\t\t - - LENDO ARQUIVO DE ENTRADA - -\n"); /*char c[2], dados[255], buffer[255];*/ char buffer[255]; int cont = 1; while(cont < 9){ fscanf(arq, "%s", buffer); //puts(buffer); int i = 0, j = 0; switch(strlen(buffer)){ case 8: //erro_maximo fscanf(arq, "%f", &erro_max); break; case 10: //tam_regiao fscanf(arq, "%f", &tam_regiao); break; case 11: //opcao_contorno fscanf(arq, "%d", &op_contorno); break; case 12: //valor_contor fscanf(arq, "%f", &valor_contor); break; case 14: //max_interacoes fscanf(arq, "%d", &max_interacoes); break; case 15: //tam_mat_interna fscanf(arq, "%d", &tam_mat_interna); break; case 16: //matriz_de_fontes //uso (tam_mat_interna + 2) - pois ainda não inicializei 'tam_mat_real' host_mat.font = aloca_matriz(tam_mat_interna + 2, tam_mat_interna + 2); for(i = 1; i < (tam_mat_interna + 2) - 1; i ++) for(j = 1; j < (tam_mat_interna + 2) - 1 ; j++) fscanf(arq, "%f", &host_mat.font[i*(tam_mat_interna+2) + j]); break; case 18: //matriz_permeabilidade host_mat.perm = aloca_matriz(tam_mat_interna + 2, tam_mat_interna + 2); host_mat.epsilon = aloca_matriz(tam_mat_interna + 2, tam_mat_interna + 2); for(i = 1; i < (tam_mat_interna + 2) - 1; i ++) for(j = 1; j < (tam_mat_interna + 2) - 1 ; j++) fscanf(arq, "%f", &host_mat.perm[i*(tam_mat_interna+2) + j]); for(i = 1; i < (tam_mat_interna + 2) - 1; i ++) for(j = 1; j < (tam_mat_interna + 2) - 1 ; j++) host_mat.perm[i*(tam_mat_interna+2) + j] = PamM*exp(S * host_mat.perm[i*(tam_mat_interna+2) + j]); break; default: printf("\n\n\t\tHouve algum erro no aquivo de entrada!\n\n"); return 0; } //int tam = strlen(buffer); cont++; } printf("\t\t - - ARQUIVO DE ENTRADA CARREGADO - -\n"); } printf("\n\n\t\t - - ENTRADA CARREGA - - \n\n"); return 1; } float *aloca_matriz(int L, int C){ float *aux = NULL; aux = (float *) calloc(L * C, sizeof(float)); if(aux == NULL){ printf("\n\n\t\tErro ao alocar memoria\n\n"); exit(1); }else{ return (aux); } return NULL; } /* * *VERIFICAR RETORNO * */ void cal_cond_robin(){ float keff = 0.0, numerador = 0.0, denominador = 0.0; float C = 1.0; // Cte adimensional que se ajusta experimentalmente C = 1.0 //Canto superior esquerdo numerador = ( 2 * host_mat.perm[tam_mat_real + 1] * host_mat.perm[tam_mat_real + 2] ); denominador = ( host_mat.perm[tam_mat_real + 1] + host_mat.perm[tam_mat_real + 2] ); keff = numerador / denominador; host_b.R[tam_mat_real + 1] = C*h/keff; numerador = (2 * host_mat.perm[tam_mat_real + 1] * host_mat.perm[(2*tam_mat_real) + 1]); denominador = ( host_mat.perm[tam_mat_real + 1] + host_mat.perm[(2*tam_mat_real) + 1]); keff = numerador / denominador; host_b.D[tam_mat_real + 1] = C*h/keff; //Canto superior direito numerador = ( 2 * host_mat.perm[tam_mat_real + tam_mat_interna] * host_mat.perm[tam_mat_real + (tam_mat_interna - 1)] ); denominador = ( host_mat.perm[tam_mat_real + tam_mat_interna] + host_mat.perm[tam_mat_real + (tam_mat_interna - 1)] ); keff = numerador / denominador; host_b.L[tam_mat_real + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[tam_mat_real + tam_mat_interna] * host_mat.perm[(2 * tam_mat_real) + tam_mat_interna] ); denominador = ( host_mat.perm[tam_mat_real + tam_mat_interna] + host_mat.perm[(2 * tam_mat_real) + tam_mat_interna] ); keff = numerador / denominador; host_b.D[tam_mat_real + tam_mat_interna] = C*h/keff; //Canto infeior esquerdo numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] * host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + 1] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] + host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + 1] ); keff = numerador / denominador; host_b.U[(tam_mat_real * tam_mat_interna) + 1] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] * host_mat.perm[(tam_mat_real * tam_mat_interna) + 2] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + 1] + host_mat.perm[(tam_mat_real * tam_mat_interna) + 2] ); keff = numerador / denominador; host_b.R[(tam_mat_real * tam_mat_interna) + 1] = C*h/keff; //Canto infeior direito numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] * host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + tam_mat_interna] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] + host_mat.perm[(tam_mat_real * (tam_mat_interna - 1)) + tam_mat_interna] ); keff = numerador / denominador; host_b.U[(tam_mat_real * tam_mat_interna) + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] * host_mat.perm[(tam_mat_real * tam_mat_interna) + (tam_mat_interna - 1)] ); denominador = ( host_mat.perm[(tam_mat_real * tam_mat_interna) + tam_mat_interna] + host_mat.perm[(tam_mat_real * tam_mat_interna) + (tam_mat_interna - 1)] ); keff = numerador / denominador; host_b.L[(tam_mat_real * tam_mat_interna) + tam_mat_interna] = C*h/keff; //Calculo das fronteiras e região interna para betas int i = 0; for(i = 2; i < tam_mat_interna; i ++){ //Calcula fronteira superior numerador = ( 2 * host_mat.perm[tam_mat_real + i] * host_mat.perm[tam_mat_real + (i-1)] ); denominador = ( host_mat.perm[tam_mat_real + i] + host_mat.perm[tam_mat_real + (i-1)] ); keff = numerador / denominador; host_b.L[tam_mat_real + i] = C*h/keff; numerador = ( 2 * host_mat.perm[tam_mat_real + i] * host_mat.perm[tam_mat_real + (i+1)] ); denominador = ( host_mat.perm[tam_mat_real + i] + host_mat.perm[tam_mat_real + (i+1)] ); keff = numerador / denominador; host_b.R[tam_mat_real + i] = C*h/keff; numerador = ( 2 * host_mat.perm[tam_mat_real + i] * host_mat.perm[(2 * tam_mat_real) + i] ); denominador = ( host_mat.perm[tam_mat_real + i] + host_mat.perm[(2 * tam_mat_real) + i] ); keff = numerador / denominador; host_b.D[tam_mat_real + i] = C*h/keff; //Calcula fronteira esquerda numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + 1] * host_mat.perm[((i - 1) * tam_mat_real) + 1] ); denominador = ( host_mat.perm[(i * tam_mat_real) + 1] + host_mat.perm[((i - 1) * tam_mat_real) + 1] ); keff = numerador / denominador; host_b.U[(i * tam_mat_real) + 1] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + 1] * host_mat.perm[(i * tam_mat_real) + 2] ); denominador = ( host_mat.perm[(i * tam_mat_real) + 1] + host_mat.perm[(i * tam_mat_real) + 2] ); keff = numerador / denominador; host_b.R[(i * tam_mat_real) + 1] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + 1] * host_mat.perm[((i + 1) * tam_mat_real) + 1] ); denominador = ( host_mat.perm[(i * tam_mat_real) + 1] + host_mat.perm[((i + 1) * tam_mat_real) + 1] ); keff = numerador / denominador; host_b.D[(i * tam_mat_real) + 1] = C*h/keff; //Calcula fronteira inferior numerador = ( 2 * host_mat.perm[(tam_mat_interna * tam_mat_real) + i] * host_mat.perm[(tam_mat_interna * tam_mat_real) + (i - 1)] ); denominador = ( host_mat.perm[(tam_mat_interna * tam_mat_real) + i] + host_mat.perm[(tam_mat_interna * tam_mat_real) + (i - 1)] ); keff = numerador / denominador; host_b.L[(tam_mat_interna * tam_mat_real) + i] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_interna * tam_mat_real) + i] * host_mat.perm[((tam_mat_interna - 1) * tam_mat_real) + i] ); denominador = ( host_mat.perm[(tam_mat_interna * tam_mat_real) + i] + host_mat.perm[((tam_mat_interna - 1) * tam_mat_real) + i] ); keff = numerador / denominador; host_b.U[(tam_mat_interna * tam_mat_real) + i] = C*h/keff; numerador = ( 2 * host_mat.perm[(tam_mat_interna * tam_mat_real) + i] * host_mat.perm[(tam_mat_interna * tam_mat_real) + (i + 1)] ); denominador = ( host_mat.perm[(tam_mat_interna * tam_mat_real) + i] + host_mat.perm[(tam_mat_interna * tam_mat_real) + (i + 1)] ); keff = numerador / denominador; host_b.R[(tam_mat_interna * tam_mat_real) + i] = C*h/keff; //Calcula fronteira direita numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + tam_mat_interna] * host_mat.perm[((i-1) * tam_mat_real) + tam_mat_interna] ); denominador = ( host_mat.perm[(i * tam_mat_real) + tam_mat_interna] + host_mat.perm[((i-1) * tam_mat_real) + tam_mat_interna] ); keff = numerador / denominador; host_b.U[(i * tam_mat_real) + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + tam_mat_interna] * host_mat.perm[(i * tam_mat_real) + (tam_mat_interna - 1)] ); denominador = ( host_mat.perm[(i * tam_mat_real) + tam_mat_interna] + host_mat.perm[(i * tam_mat_real) + (tam_mat_interna - 1)] ); keff = numerador / denominador; host_b.L[(i * tam_mat_real) + tam_mat_interna] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + tam_mat_interna] * host_mat.perm[((i+1) * tam_mat_real) + tam_mat_interna] ); denominador = ( host_mat.perm[(i * tam_mat_real) + tam_mat_interna] + host_mat.perm[((i+1) * tam_mat_real) + tam_mat_interna] ); keff = numerador / denominador; host_b.D[(i * tam_mat_real) + tam_mat_interna] = C*h/keff; //Calcula dados internos int j = 0; for(j = 2; j < tam_mat_interna; j ++){ numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[(i * tam_mat_real) + (j - 1)] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[(i * tam_mat_real) + (j - 1)] ); keff = numerador / denominador; host_b.L[(i * tam_mat_real) + j] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[(i * tam_mat_real) + (j + 1)] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[(i * tam_mat_real) + (j + 1)] ); keff = numerador / denominador; host_b.R[(i * tam_mat_real) + j] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[((i - 1) * tam_mat_real) + j] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[((i - 1) * tam_mat_real) + j] ); keff = numerador / denominador; host_b.U[(i * tam_mat_real) + j] = C*h/keff; numerador = ( 2 * host_mat.perm[(i * tam_mat_real) + j] * host_mat.perm[((i + 1) * tam_mat_real) + j] ); denominador = ( host_mat.perm[(i * tam_mat_real) + j] + host_mat.perm[((i + 1) * tam_mat_real) + j] ); keff = numerador / denominador; host_b.D[(i * tam_mat_real) + j] = C*h/keff; } } } /* * *VERIFICAR RETORNO * */ char parametro_independentes(){ int i = 0, j = 0; float constante = 2/h; for(i = 0; i < tam_mat_real; i ++) for(j = 0; j < tam_mat_real; j++){ host_mat.epsilon[i*tam_mat_real + j] = constante * host_mat.perm[i*tam_mat_real + j]; host_mat.font[i*tam_mat_real + j] *= h; } return 0; } char copia_dados_para_gpu(){ HANDLE_ERROR( cudaMemcpy( dev_q.R, host_q.R, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.L, host_q.L, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.U, host_q.U, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.D, host_q.D, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.R_old, host_q.R_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.L_old, host_q.L_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.U_old, host_q.U_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_q.D_old, host_q.D_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.R, host_l.R, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.L, host_l.L, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.U, host_l.U, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.D, host_l.D, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.R_old, host_l.R_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.L_old, host_l.L_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.U_old, host_l.U_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_l.D_old, host_l.D_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.R, host_b.R, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.L, host_b.L, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.U, host_b.U, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.D, host_b.D, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.R_old, host_b.R_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.L_old, host_b.L_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.U_old, host_b.U_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_b.D_old, host_b.D_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_pressao.p, host_pressao.p, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_pressao.p_old, host_pressao.p_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_mat.perm, host_mat.perm, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_mat.epsilon, host_mat.epsilon, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); HANDLE_ERROR( cudaMemcpy( dev_mat.font, host_mat.font, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyHostToDevice ) ); return 0; } void copia_dados_para_cpu(){ HANDLE_ERROR( cudaMemcpy( host_q.R, dev_q.R, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.L, dev_q.L, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.U, dev_q.U, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.D, dev_q.D, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.R_old, dev_q.R_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.L_old, dev_q.L_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.U_old, dev_q.U_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_q.D_old, dev_q.D_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.R, dev_l.R, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.L, dev_l.L, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.U, dev_l.U, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.D, dev_l.D, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.R_old, dev_l.R_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.L_old, dev_l.L_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.U_old, dev_l.U_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_l.D_old, dev_l.D_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.R, dev_b.R, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.L, dev_b.L, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.U, dev_b.U, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.D, dev_b.D, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.R_old, dev_b.R_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.L_old, dev_b.L_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.U_old, dev_b.U_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_b.D_old, dev_b.D_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_pressao.p, dev_pressao.p, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_pressao.p_old, dev_pressao.p_old, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_mat.font, dev_mat.font, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_mat.perm, dev_mat.perm, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); HANDLE_ERROR( cudaMemcpy( host_mat.epsilon, dev_mat.epsilon, tam_mat_real * tam_mat_real * sizeof(float), cudaMemcpyDeviceToHost ) ); } char inicializa_parametros(){ printf("\n\n\t\t- - INICIALIZANDO PARAMETROS - - \n\n\n"); /* * * * CONTRUIR FUNCAO PARA VERIFICAR ERRO DE ALOCAÇÃO * VERIFICAR RETORNO */ tam_mat_real = tam_mat_interna + 2; h = tam_regiao / tam_mat_interna; HANDLE_ERROR( cudaMalloc( (void**)&dev_q, sizeof(ESTRUTURA_Q) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_l, sizeof(ESTRUTURA_L) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_b, sizeof(ESTRUTURA_B) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_pressao, sizeof(ESTRUTURA_PRESSAO) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_mat, sizeof(ESTRUTURA_MAT) ) ); host_q.R = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.R != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.R, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.L = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.L != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.L, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.U = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.U != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.U, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.D = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.D != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.D, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.R_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.R_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.R_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.L_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.L_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.L_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.U_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.U_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.U_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_q.D_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_q.D_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_q.D_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.R = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.R != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.R, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.L = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.L != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.L, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.U = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.U != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.U, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.D = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.D != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.D, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.R_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.R_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.R_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.L_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.L_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.L_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.U_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.U_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.U_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_l.D_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_l.D_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_l.D_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.R = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.R != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.R, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.L = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.L != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.L, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.U = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.U != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.U, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.D = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.D != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.D, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.R_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.R_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.R_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.L_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.L_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.L_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.U_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.U_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.U_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_b.D_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_b.D_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_b.D_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_pressao.p = aloca_matriz(tam_mat_real, tam_mat_real); if(host_pressao.p != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_pressao.p, tam_mat_real * tam_mat_real * sizeof(float) ) ); host_pressao.p_old = aloca_matriz(tam_mat_real, tam_mat_real); if(host_pressao.p_old != NULL) HANDLE_ERROR( cudaMalloc( (void**)&dev_pressao.p_old, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_mat.perm, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_mat.font, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_mat.epsilon, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_aux_1, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_aux_2, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMemset( dev_aux_1, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMemset( dev_aux_2, 0.0, tam_mat_real * tam_mat_real * sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&erro_max, sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_erro, sizeof(float) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_media, tam_mat_real * tam_mat_real * sizeof(float)) ); int i = 0; switch(op_contorno){ case 1: //Inicializa contorno superior for(i = 0; i < tam_mat_real; i++){ host_q.D[i] = valor_contor; host_q.D_old[i] = valor_contor; } break; case 2://Inicializa contorno esquerdo for(i = 0; i < tam_mat_real; i++){ host_q.R[i*tam_mat_real] = valor_contor; host_q.R_old[i*tam_mat_real] = valor_contor; } break; case 3://Inicializa contorno direito for(i = 0; i < tam_mat_real; i++){ host_q.L[i*tam_mat_real + (tam_mat_real - 1)] = valor_contor; host_q.L_old[i*tam_mat_real + (tam_mat_real - 1)] = valor_contor; } break; case 4://Inicializa contorno inferior for(i = 0; i < tam_mat_real; i++){ host_q.L[(tam_mat_real-1)*tam_mat_real + i] = valor_contor; host_q.L_old[(tam_mat_real-1)*tam_mat_real + i] = valor_contor; } break; default: printf("\n\n\t\t - - OCORREU ALGUM ERRO NA OPCAO DE CONTORNO - - \n\n"); break; } printf("\n\n\t\t- - FIM DA INICIALIZACAO PARAMETROS - - \n\n\n"); return 1; } void clear_mem(){ HANDLE_ERROR( cudaFree (dev_q.U)); HANDLE_ERROR( cudaFree (dev_q.R)); HANDLE_ERROR( cudaFree (dev_q.D)); HANDLE_ERROR( cudaFree (dev_q.L)); free(host_q.U); free(host_q.R); free(host_q.D); free(host_q.L); HANDLE_ERROR( cudaFree (dev_l.U)); HANDLE_ERROR( cudaFree (dev_l.R)); HANDLE_ERROR( cudaFree (dev_l.D)); HANDLE_ERROR( cudaFree (dev_l.L)); free(host_l.U); free(host_l.R); free(host_l.D); free(host_l.L); HANDLE_ERROR( cudaFree (dev_b.U)); HANDLE_ERROR( cudaFree (dev_b.R)); HANDLE_ERROR( cudaFree (dev_b.D)); HANDLE_ERROR( cudaFree (dev_b.L)); free(host_b.U); free(host_b.R); free(host_b.D); free(host_b.L); HANDLE_ERROR( cudaFree (dev_pressao.p)); HANDLE_ERROR( cudaFree (dev_pressao.p_old)); free(host_pressao.p); free(host_pressao.p_old); HANDLE_ERROR( cudaFree (dev_mat.perm)); HANDLE_ERROR( cudaFree (dev_mat.font)); HANDLE_ERROR( cudaFree (dev_mat.epsilon)); free(host_mat.perm); free(host_mat.font); free(host_mat.epsilon); }
42835d493825d5bffb47bb7da18c0981a1e349f1.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /******************************************************************* c* Multimodal Deformable Image Registration * c* via Mutual Information or Bhattacharyya Distantce * c* Version: 1.0 * c* Language: C, CUDA * c* * c* Developer: Yifei Lou * c* Email: yifei.lou@ece.gatech.edu * c* * c* School of Electrical and Computer Engineering * c* Georgia Institute of Technology * c* Atlanta, GA, 30318 * c* Website: http://groups.bme.gatech.edu/groups/bil/ * c* * c* Copyright (c) 2011 * c* All rights reserved. * c* * c* Permission to use, copy, or modify this code and its * c* documentation for scientific purpose is hereby granted * c* without fee, provided that this copyright notice appear in * c* all copies and that both that copyright notice and this * c* permission notice appear in supporting documentation. The use * c* for commercial purposes is prohibited without permission. * c* * c* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * c* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * c* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * c* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * c* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * c* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * c* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT * c* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF* c* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * c* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * c* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * c* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * c* THE POSSIBILITY OF SUCH DAMAGE. * c* * c******************************************************************/ /******************************************************************* c* Short discription * c* Finalize the reconstruction on the current scale and for the * c* entire program, output results, release memory spaces for * c* global variables, etc. * c******************************************************************/ #ifndef _FINALIZE_CU_ #define _FINALIZE_CU_ void fina() { // map output image to its original scale nblocks.x = NBLOCKX; nblocks.y = ((1 + (NX0*NY0*NZ0 - 1)/NTHREAD_PER_BLOCK) - 1) / NBLOCKX + 1; printf("moving image: max = %f, min = %f\n", max_im_move, min_im_move); hipLaunchKernelGGL(( intensityRescale), dim3(nblocks), dim3(NTHREAD_PER_BLOCK), 0, 0, d_im_move[0], max_im_move, min_im_move, -1); // output results outputData(d_im_move[0], DATA_SIZE, outputfilename); outputData(d_mv_x[0], DATA_SIZE, output_mv_x); outputData(d_mv_y[0], DATA_SIZE, output_mv_y); outputData(d_mv_z[0], DATA_SIZE, output_mv_z); // free up the host and device // image pyramid for(int scale =0; scale <NSCALE; scale++) { hipFree(d_im_move[scale]); hipFree(d_im_static[scale]); hipFree(d_mv_x[scale]); hipFree(d_mv_y[scale]); hipFree(d_mv_z[scale]); } // Gaussian kernel hipFree(GaussKernelH); hipFree(GaussKernelHx); // histogram related hipFree(d_jointHistogram); hipFree(d_jointHistogram_conv); hipFree(d_probx); hipFree(d_proby); hipFree(d_Bsum); } void outputData(void *src, int size, const char *outputfilename) // output data to file { // void *tempData_h = malloc( size ); float *tempData_h = (float*) malloc (sizeof(float)*size); if (tempData_h == NULL) { fputs ("Memory error",stderr); exit (2); } cutilSafeCall( hipMemcpy( tempData_h, src, size, hipMemcpyDeviceToHost) ); // copy data from GPU to CPU FILE *fp; fp = fopen(outputfilename,"wb"); if( fp == NULL ) { cout << "Can not open file to write results."; exit(1); } fwrite (tempData_h, size, 1 , fp ); fclose(fp); // write results to file //printf("denoised data =%f\n", tempData_h[53]); free(tempData_h); // free space } #endif
42835d493825d5bffb47bb7da18c0981a1e349f1.cu
/******************************************************************* c* Multimodal Deformable Image Registration * c* via Mutual Information or Bhattacharyya Distantce * c* Version: 1.0 * c* Language: C, CUDA * c* * c* Developer: Yifei Lou * c* Email: yifei.lou@ece.gatech.edu * c* * c* School of Electrical and Computer Engineering * c* Georgia Institute of Technology * c* Atlanta, GA, 30318 * c* Website: http://groups.bme.gatech.edu/groups/bil/ * c* * c* Copyright (c) 2011 * c* All rights reserved. * c* * c* Permission to use, copy, or modify this code and its * c* documentation for scientific purpose is hereby granted * c* without fee, provided that this copyright notice appear in * c* all copies and that both that copyright notice and this * c* permission notice appear in supporting documentation. The use * c* for commercial purposes is prohibited without permission. * c* * c* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * c* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * c* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * c* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * c* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * c* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * c* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT * c* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF* c* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * c* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * c* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * c* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * c* THE POSSIBILITY OF SUCH DAMAGE. * c* * c******************************************************************/ /******************************************************************* c* Short discription * c* Finalize the reconstruction on the current scale and for the * c* entire program, output results, release memory spaces for * c* global variables, etc. * c******************************************************************/ #ifndef _FINALIZE_CU_ #define _FINALIZE_CU_ void fina() { // map output image to its original scale nblocks.x = NBLOCKX; nblocks.y = ((1 + (NX0*NY0*NZ0 - 1)/NTHREAD_PER_BLOCK) - 1) / NBLOCKX + 1; printf("moving image: max = %f, min = %f\n", max_im_move, min_im_move); intensityRescale<<<nblocks, NTHREAD_PER_BLOCK>>>(d_im_move[0], max_im_move, min_im_move, -1); // output results outputData(d_im_move[0], DATA_SIZE, outputfilename); outputData(d_mv_x[0], DATA_SIZE, output_mv_x); outputData(d_mv_y[0], DATA_SIZE, output_mv_y); outputData(d_mv_z[0], DATA_SIZE, output_mv_z); // free up the host and device // image pyramid for(int scale =0; scale <NSCALE; scale++) { cudaFree(d_im_move[scale]); cudaFree(d_im_static[scale]); cudaFree(d_mv_x[scale]); cudaFree(d_mv_y[scale]); cudaFree(d_mv_z[scale]); } // Gaussian kernel cudaFree(GaussKernelH); cudaFree(GaussKernelHx); // histogram related cudaFree(d_jointHistogram); cudaFree(d_jointHistogram_conv); cudaFree(d_probx); cudaFree(d_proby); cudaFree(d_Bsum); } void outputData(void *src, int size, const char *outputfilename) // output data to file { // void *tempData_h = malloc( size ); float *tempData_h = (float*) malloc (sizeof(float)*size); if (tempData_h == NULL) { fputs ("Memory error",stderr); exit (2); } cutilSafeCall( cudaMemcpy( tempData_h, src, size, cudaMemcpyDeviceToHost) ); // copy data from GPU to CPU FILE *fp; fp = fopen(outputfilename,"wb"); if( fp == NULL ) { cout << "Can not open file to write results."; exit(1); } fwrite (tempData_h, size, 1 , fp ); fclose(fp); // write results to file //printf("denoised data =%f\n", tempData_h[53]); free(tempData_h); // free space } #endif
8f7b1c0d979d46446b06cb1d6b5c36819a3f1de5.hip
// !!! This is a file automatically generated by hipify!!! //*************************************************************************** // Name: Broday Walker // // Links: // 1. https://devblogs.nvidia.com/how-query-device-properties-and-handle-errors-cuda-cc/ // 2. https://www.cs.cmu.edu/afs/cs/academic/class/15668-s11/www/cuda-doc/html/group__CUDART__DEVICE_g5aa4f47938af8276f08074d09b7d520c.html#g5aa4f47938af8276f08074d09b7d520c // 3. https://devtalk.nvidia.com/default/topic/461911/tesla-c1060-max-blocks-per-streaming-multiprocessor/ // 4. https://stackoverflow.com/questions/502856/whats-the-difference-between-size-t-and-int-in-c // // To run for the gtx queue: sbatch gtxProperties // To run for the v100 queue: sbatch voltaProperties //*************************************************************************** #include <stdio.h> #include <hip/hip_runtime.h> int main() { hipDeviceProp_t prop; hipGetDeviceProperties(&prop, 0); printf("=============================\n"); // Device name printf("Device name: %s\n", prop.name); // Size of shared memory per block printf("Size of shared memory per block: %zu\n", prop.sharedMemPerBlock); // Number of registers per block printf("Number of registers per block: %d\n", prop.regsPerBlock); // Warp size printf("Warp size: %d\n", prop.warpSize); // Maximum number of threads per block printf("Maximum number of threads per block: %d\n", prop.maxThreadsPerBlock); // Maximum number of threads for 3D layout (X, Y, Z) printf("Maximum number of threads for 3d layout (X, Y, Z): " "%d, %d, %d\n", prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]); // Maximum grid size (X, Y, Z) printf("Maximum grid size (X, Y, Z): %d, %d, %d\n", prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]); // Maximum number of blocks per streaming processor (SM) printf("Maximum number of blocks per streaming processor: " "not given\n"); printf("=============================\n"); return 0; }
8f7b1c0d979d46446b06cb1d6b5c36819a3f1de5.cu
//*************************************************************************** // Name: Broday Walker // // Links: // 1. https://devblogs.nvidia.com/how-query-device-properties-and-handle-errors-cuda-cc/ // 2. https://www.cs.cmu.edu/afs/cs/academic/class/15668-s11/www/cuda-doc/html/group__CUDART__DEVICE_g5aa4f47938af8276f08074d09b7d520c.html#g5aa4f47938af8276f08074d09b7d520c // 3. https://devtalk.nvidia.com/default/topic/461911/tesla-c1060-max-blocks-per-streaming-multiprocessor/ // 4. https://stackoverflow.com/questions/502856/whats-the-difference-between-size-t-and-int-in-c // // To run for the gtx queue: sbatch gtxProperties // To run for the v100 queue: sbatch voltaProperties //*************************************************************************** #include <stdio.h> #include <cuda.h> int main() { cudaDeviceProp prop; cudaGetDeviceProperties(&prop, 0); printf("=============================\n"); // Device name printf("Device name: %s\n", prop.name); // Size of shared memory per block printf("Size of shared memory per block: %zu\n", prop.sharedMemPerBlock); // Number of registers per block printf("Number of registers per block: %d\n", prop.regsPerBlock); // Warp size printf("Warp size: %d\n", prop.warpSize); // Maximum number of threads per block printf("Maximum number of threads per block: %d\n", prop.maxThreadsPerBlock); // Maximum number of threads for 3D layout (X, Y, Z) printf("Maximum number of threads for 3d layout (X, Y, Z): " "%d, %d, %d\n", prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]); // Maximum grid size (X, Y, Z) printf("Maximum grid size (X, Y, Z): %d, %d, %d\n", prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]); // Maximum number of blocks per streaming processor (SM) printf("Maximum number of blocks per streaming processor: " "not given\n"); printf("=============================\n"); return 0; }
9de4a1b978ff9c8f153741bd72e35cd1ff723c23.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void arr_times_const_checkerboard(float*a,float b, float * c, int N, int sx,int sy,int sz) { int ids=blockIdx.x*blockDim.x+threadIdx.x; // which source array element do I have to deal with? if(ids>=N) return; // not in range ... quit int px=(ids/2)%sx; // my x pos int py=(ids/2)/sx; // my y pos float minus1=(1-2*((px+py)%2)); c[ids]=a[ids]*b*minus1; }
9de4a1b978ff9c8f153741bd72e35cd1ff723c23.cu
#include "includes.h" __global__ void arr_times_const_checkerboard(float*a,float b, float * c, int N, int sx,int sy,int sz) { int ids=blockIdx.x*blockDim.x+threadIdx.x; // which source array element do I have to deal with? if(ids>=N) return; // not in range ... quit int px=(ids/2)%sx; // my x pos int py=(ids/2)/sx; // my y pos float minus1=(1-2*((px+py)%2)); c[ids]=a[ids]*b*minus1; }
2162909a75451b17911230b186479ebe6261eb6e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "World.h" #include <cstdio> __global__ void initWorld_gpu(World * w) { w->pixel_sampler = new MultiJitteredSampler(); w->pixel_sampler->init(w->num_rays_per_pixel, 67); w->ray_tracer = new PrimaryRayTracer(w); } void initWorld(World *w, int2 res, float size, int num_rays_per_pixel) { w->vp.init(res, size); w->num_rays_per_pixel = num_rays_per_pixel; w->background_color = make_float3(0, 0, 0.25); w->image = (float3*)malloc(sizeof(float3) * res.x * res.y); printf("Allocated memory to image: %.2fKBs\n", float(sizeof(float3) * res.x * res.y) / 1024); fflush(stdout); SYNC_AND_CHECK_CUDA_ERRORS; hipLaunchKernelGGL(( initWorld_gpu) , dim3(1), dim3(1) , 0, 0, w); SYNC_AND_CHECK_CUDA_ERRORS; }
2162909a75451b17911230b186479ebe6261eb6e.cu
#include "World.h" #include <cstdio> __global__ void initWorld_gpu(World * w) { w->pixel_sampler = new MultiJitteredSampler(); w->pixel_sampler->init(w->num_rays_per_pixel, 67); w->ray_tracer = new PrimaryRayTracer(w); } void initWorld(World *w, int2 res, float size, int num_rays_per_pixel) { w->vp.init(res, size); w->num_rays_per_pixel = num_rays_per_pixel; w->background_color = make_float3(0, 0, 0.25); w->image = (float3*)malloc(sizeof(float3) * res.x * res.y); printf("Allocated memory to image: %.2fKBs\n", float(sizeof(float3) * res.x * res.y) / 1024); fflush(stdout); SYNC_AND_CHECK_CUDA_ERRORS; initWorld_gpu <<< 1, 1 >>>(w); SYNC_AND_CHECK_CUDA_ERRORS; }
bb4efa6f0198310109b551247aafbda3ddb5d772.hip
// !!! This is a file automatically generated by hipify!!! #include "pipeline.h" #include "pipeline-image.h" #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> //for printf #include <stdlib.h> //for malloc #include <string.h> //for memset #include <stdint.h> #include "hip/hip_runtime.h" #define BX_ (32) #define BY_ (4) #define WORK_ (8) #if 0 #define ECHO(estr) LOG("---\t%s\n",estr) #else #define ECHO(estr) #endif static void breakme() {} #define LOG(...) printf(__VA_ARGS__) #define REPORT(estr,msg) LOG("%s(%d): %s()\n\t%s\n\t%s\n",__FILE__,__LINE__,__FUNCTION__,estr,msg) #define TRY(e) do{ECHO(#e);if(!(e)){REPORT(#e,"Evaluated to false.");breakme(); goto Error;}}while(0) #define FAIL(msg) do{REPORT("Failure.",msg);goto Error;} while(0) #define NEW(T,e,N) TRY((e)=(T*)malloc(sizeof(T)*(N))) #define ZERO(T,e,N) memset((e),0,sizeof(T)*(N)) #define CUREPORT(ecode,estr) LOG("%s(%d): %s()\n\t%s\n\t%s\n",__FILE__,__LINE__,__FUNCTION__,estr,hipGetErrorString(ecode)) #define CUTRY(e) do{ hipError_t ecode; ECHO(#e); ecode=(e); if(ecode!=hipSuccess){CUREPORT(ecode,#e);goto Error;}}while(0) #define CUWARN(e) do{ hipError_t ecode; ECHO(#e); ecode=(e); if(ecode!=hipSuccess){CUREPORT(ecode,#e); }}while(0) #define CUNEW(T,e,N) CUTRY(hipMalloc((void**)&(e),sizeof(T)*(N))) #define CUZERO(T,e,N) CUTRY(hipMemset((e),0,sizeof(T)*(N))) #define countof(e) (sizeof(e)/sizeof(*(e))) #define CEIL(num,den) (((num)+(den)-(1))/(den)) /** * The parameter collection that gets passed to the kernel */ struct pipeline_ctx_t { unsigned * __restrict__ ilut; ///< look up table for unwarp (ctx.w/2 number of elements). Set by launch on first call or if width changes. float * __restrict__ lut_norms0, * __restrict__ lut_norms1; unsigned istride, ///< number of elements between rows of source. ostride; ///< number of elements between rows of output. unsigned w,h; ///< source width and height (height is nrows*nchan) }; /** * The object that manages pipeline execution. */ typedef struct pipeline_t_ { pipeline_ctx_t ctx; unsigned count, ///< the number of frames that have been pushed to the accumulator every; ///< the number of frames to average double samples_per_scan; bool invert; unsigned downsample; unsigned alignment; ///< output rows are aligned to this target number of elements. unsigned nbytes_tmp; float norm, ///< 1.0/the frame count as a float - set by launcher (eg. for ctx.every=4, this should be 0.25) m,b; ///< slope and intercept for intensity scaling void * __restrict__ src, ///< device buffer * __restrict__ dst; ///< device buffer float * __restrict__ tmp; ///< device buffer } *pipeline_t; // // --- KERNELS --- // // should schedule for destination (2*width/WORK/BX,height/2/BY) blocks [eg for 4864x512 -> (38,8)] // dst width must be aligned to WORK*BX (256) // height must be aligned to BY*2 (64) // ilut must be aligned to WORK*BX and sized 2*dst width // template<typename T, ///< pixel type (input and output) unsigned BX, ///< block size in X unsigned BY, ///< block size in Y (channel dimension unrolled into Y) unsigned WORK ///< number of elements to process per thread > __global__ void __launch_bounds__(BX*BY,1) /* max threads, min blocks */ warp_kernel(pipeline_ctx_t ctx, const T* __restrict__ src, float* __restrict__ dst) { const unsigned ox=threadIdx.x+blockIdx.x*WORK*BX, oy=threadIdx.y+blockIdx.y*BY; unsigned * __restrict__ ilut = ctx.ilut + ox; dst+=ox+oy*ctx.ostride*2; src+= oy*ctx.istride; if(blockIdx.x<ctx.ostride/(WORK*BX)) // forward scan { #pragma unroll for(int i=0;i<WORK;++i) { const int j0=ilut[i*BX], j1=ilut[i*BX+1]; float v0=0.0f,v1=0.0f; if(j0>0) v1=ctx.lut_norms1[j0-1]*src[j0-1]; for(int j=j0;j<j1;++j) v0+=ctx.lut_norms0[j]*src[j]; dst[i*BX]+=v0+v1; } } else { // backward scan #pragma unroll for(int i=0;i<WORK;++i) { const int j1=ilut[i*BX+1], j0=ilut[i*BX+2]; float v0=0.0f; for(int j=j0;j<j1;++j) v0+=ctx.lut_norms0[j]*src[j]; float v1=ctx.lut_norms1[j1]*src[j1]; dst[i*BX]+=v0+v1; } } } /** * Cast array from float to T. * Rounds pixel values, so this isn't appropriate for converting to floating point types. * src and dst should be the same shape but may be different types. * Both must have width aligned to BX*WORK * Both must have heigh aligned to BY */ template<typename T, ///< pixel type (input and output) unsigned BX, ///< block size in X unsigned BY, ///< block size in Y (channel dimension unrolled into Y) unsigned WORK ///< number of elements to process per thread > __global__ void __launch_bounds__(BX*BY,1) cast_kernel(T*__restrict__ dst, const float* __restrict__ src, unsigned stride,const float m, const float b) { const int ox=threadIdx.x+blockIdx.x*WORK*BX, oy=threadIdx.y+blockIdx.y*BY; //if(oy>=h) return; // for unaligned y, uncomment and add an argument to the kernel call src+=ox+oy*stride; dst+=ox+oy*stride; #pragma unroll for(int i=0;i<WORK;++i) dst[i*BX]=round(fmaf(src[i*BX],m,b)); } // // --- PUBLIC INTERFACE --- // pipeline_t pipeline_make(const pipeline_param_t *params) { pipeline_t self=NULL; TRY(params); NEW(pipeline_t_,self,1); ZERO(pipeline_t_,self,1); self->every = (params->frame_average_count<1)?1:params->frame_average_count; self->samples_per_scan = params->sample_rate_MHz*1.0e6/(double)params->scan_rate_Hz; self->invert = (params->invert_intensity!=0); self->downsample = (params->pixel_average_count<=1)?1:params->pixel_average_count; self->alignment = BX_*WORK_; self->norm = 1.0f/(float)self->every; self->m = 1.0f;; self->b = 0.0f; return self; Error: return NULL; } void pipeline_free(pipeline_t *self) { if(self && *self) { void *ptrs[]={self[0]->ctx.ilut, self[0]->ctx.lut_norms0, self[0]->src, self[0]->dst, self[0]->tmp}; for(int i=0;i<countof(ptrs);++i) if(ptrs[i]) CUWARN(hipFree(ptrs[i])); free(*self); *self=NULL; } } #define EPS (1e-3) static unsigned pipeline_get_output_width(pipeline_t self, const double inwidth) { const double d=1.0-inwidth/self->samples_per_scan; // 1 - duty //max derivative of the cosine warp adjusted to cos(2pi*(d/2)) is the zero point //and the positive part of the warp function goes from 0 to 1. const double maxslope=M_PI*(1.0-d)/inwidth/cos(M_PI*d); const double amplitude=1.0/maxslope; const unsigned w=self->alignment*(unsigned)(amplitude/self->downsample/self->alignment); TRY(-EPS<d && d<=(0.5+EPS)); TRY(0<w && w<inwidth); return w; Error: return 0; } #undef EPS extern "C" int pipeline_get_output_dims(pipeline_t self, const pipeline_image_t src, unsigned *w, unsigned *h, unsigned *nchan) { TRY(self && src); if(nchan) *nchan=src->nchan; if(h) *h=src->h*2; if(w) TRY(*w=pipeline_get_output_width(self,src->w)); return 1; Error: return 0; } static int pipeline_alloc_lut(pipeline_t self, unsigned inwidth) { unsigned N=self->alignment*CEIL(inwidth,self->alignment); // pad to aligned width if(self->ctx.ilut) { CUTRY(hipFree(self->ctx.ilut)); CUTRY(hipFree(self->ctx.lut_norms0)); } const unsigned ow = pipeline_get_output_width(self,inwidth); CUNEW(unsigned,self->ctx.ilut, 2*(ow+1)); CUNEW(float ,self->ctx.lut_norms0,2*N+1); return 1; Error: self->ctx.ilut=NULL; self->ctx.lut_norms0=NULL; return 0; } static void dump(const char* name, void* data, size_t nbytes) { FILE* fp=0; TRY(fp=fopen(name,"wb")); fwrite(data,1,nbytes,fp); fclose(fp); Error:; } static double f(double x) { return 0.5*(1.0-cos(2.0*M_PI*x)); } static int pipeline_fill_lut(pipeline_t self, unsigned inwidth) { int isok=1; unsigned * __restrict__ lut=0; unsigned * __restrict__ ilut=0; float * __restrict__ norms=0; // useful constants const double d = (1.0-inwidth/self->samples_per_scan)/2.0; // 0.5*(1 - duty) const unsigned ow = pipeline_get_output_width(self,inwidth); const double s = (1.0-2.0*d)/(double)inwidth; const double A = ow/(1.0-f(d)); const double Afd = A*f(d); const unsigned halfw = inwidth/2; const unsigned N = self->alignment*CEIL(inwidth,self->alignment); // pad to aligned width // alloc temporary space NEW(unsigned ,lut ,inwidth); NEW(unsigned ,ilut ,2*(ow+1)); NEW(float ,norms,2*N+1); ZERO(unsigned,lut ,inwidth); ZERO(unsigned,ilut ,2*(ow+1)); ZERO(float ,norms,2*N+1); // compute lookup for(unsigned i=0;i<inwidth;++i) { double p0=d+s*i, p1=d+s*(i+1); double v0=A*f(p0)-Afd, v1=A*f(p1)-Afd; int j,k; if(v0<0.0) v0=0.0; if(v1<0.0) v1=0.0; if(v0>v1) { double v=v0;v0=v1;v1=v; } //swap j = (int) v0; k = (int) v1; TRY( (k-j)<2 ); // longest length should be 1, so shouldn't straddle more than two pixels lut[i] = j + (i<halfw?0:ow); if( (k-j)==0 ) { norms[i] = v1-v0; norms[i+N] = 0.0; } else { //k-j==1 -> k=1+j norms[i] = k-v0; norms[i+N] = v1-k; } } // interval encode lookup table on output side { unsigned last=0; for(unsigned i=0;i<halfw;++i) if(last!=lut[i]) ilut[last=lut[i]]=i; ilut[ow ]=inwidth/2; // add elements to deal with discontinuity ilut[ow+1]=inwidth; // subtract one to prevent reading off end ilut+=2; for(unsigned i=halfw;i<inwidth;++i) if(last!=lut[i]) ilut[(last=lut[i])]=i; ilut-=2; } #if 0 dump("lut.u32",lut ,inwidth*sizeof(*lut)); dump("norms.f32",norms,2*N *sizeof(*norms)); dump("ilut.u32",ilut ,2*(ow+1) *sizeof(*ilut)); #endif // upload CUTRY(hipMemcpy(self->ctx.ilut ,ilut , 2*(ow+1)*sizeof(*ilut),hipMemcpyHostToDevice)); CUTRY(hipMemcpy(self->ctx.lut_norms0,norms,(2*N+1)*sizeof(*norms) ,hipMemcpyHostToDevice)); self->ctx.lut_norms1=self->ctx.lut_norms0+N; Finalize: if(lut) free(lut); if(ilut) free(ilut); if(norms) free(norms); return isok; Error: isok=0; goto Finalize; } static int pipeline_upload(pipeline_t self, pipeline_image_t dst, const pipeline_image_t src) { if(self->src && (self->ctx.w!=src->w || self->ctx.h!=src->h*src->nchan)) // if there's a shape change, realloc { CUTRY(hipFree(self->src)); self->src=0; CUTRY(hipFree(self->dst)); self->dst=0; CUTRY(hipFree(self->tmp)); self->tmp=0; } dst->h++; // pad by a line if(!self->src) { CUTRY(hipMalloc((void**)&self->src,pipeline_image_nbytes(src)+1024)); CUTRY(hipMalloc((void**)&self->dst,pipeline_image_nbytes(dst))); CUTRY(hipMalloc((void**)&self->tmp,self->nbytes_tmp=pipeline_image_nelem(dst)*sizeof(float))); CUTRY(hipMemset(self->tmp,0,pipeline_image_nelem(dst)*sizeof(float))); } CUTRY(hipMemcpy(self->src,src->data,pipeline_image_nbytes(src),hipMemcpyHostToDevice)); dst->h--; // restore original number of lines self->ctx.w=src->w; self->ctx.h=src->h*src->nchan; self->ctx.istride=src->stride; self->ctx.ostride=dst->stride; return 1; Error: return 0; } static int pipeline_download(pipeline_t self, pipeline_image_t dst) { TRY(self->dst); CUTRY(hipMemcpy(dst->data,self->dst,pipeline_image_nbytes(dst),hipMemcpyDeviceToHost)); return 1; Error: return 0; } template<typename Tsrc, typename Tdst,unsigned BX,unsigned BY,unsigned WORK> static int launch(pipeline_t self, int *emit) { unsigned ow=pipeline_get_output_width(self,self->ctx.w); dim3 threads(BX,BY), blocks(CEIL(2*ow,BX*WORK),CEIL(self->ctx.h,BY)); // for the cast from tmp to dst TRY(emit); #if 1 if(self->every>1) // frame averaging enabled { if( ((self->count+1)%self->every)==0 ) { *emit=1; hipLaunchKernelGGL(( warp_kernel<Tsrc,BX,BY,WORK>), dim3(blocks),dim3(threads), 0, 0, self->ctx,(Tsrc*)self->src,self->tmp); hipLaunchKernelGGL(( cast_kernel<Tdst,BX,BY,WORK>), dim3(blocks),dim3(threads), 0, 0, (Tdst*)self->dst,self->tmp,self->ctx.ostride*2,self->m*self->norm,self->b); } else { *emit=0; hipLaunchKernelGGL(( warp_kernel<Tsrc,BX,BY,WORK>), dim3(blocks),dim3(threads), 0, 0, self->ctx,(Tsrc*)self->src,self->tmp); } self->count++; } else // frame averaging disabled #endif { if(emit) *emit=1; hipLaunchKernelGGL(( warp_kernel<Tsrc,BX,BY,WORK>), dim3(blocks),dim3(threads), 0, 0, self->ctx,(Tsrc*)self->src,self->tmp); hipLaunchKernelGGL(( cast_kernel<Tdst,BX,BY,WORK>), dim3(blocks),dim3(threads), 0, 0, (Tdst*)self->dst,self->tmp,self->ctx.ostride*2,self->m,self->b); CUTRY(hipGetLastError()); } if(*emit) CUTRY(hipMemset(self->tmp,0,self->nbytes_tmp)); return 1; Error: return 0; } // generics /** Requires a macro \c CASE(T) to be defined where \c T is a type parameter. * Requires a macro \c FAIL to be defined that handles when an invalid \a type_id is used. * \param[in] type_id Must be a valid nd_type_id_t. */ #define TYPECASE(type_id) \ switch(type_id) \ { \ case u8_id :CASE(uint8_t ); break; \ case u16_id:CASE(uint16_t); break; \ case u32_id:CASE(uint32_t); break; \ case u64_id:CASE(uint64_t); break; \ case i8_id :CASE(int8_t ); break; \ case i16_id:CASE(int16_t); break; \ case i32_id:CASE(int32_t); break; \ case i64_id:CASE(int64_t); break; \ case f32_id:CASE(float); break; \ case f64_id:CASE(double); break; \ default: \ FAIL("Unsupported pixel type."); \ } /** Requires a macro \c CASE2(T1,T2) to be defined where \c T1 and \c T2 are * type parameters. * Requires a macro \c FAIL to be defined that handles when an invalid \a type_id is used. * \param[in] type_id Must be a valid nd_type_id_t. * \param[in] T A type name. This should follow the u8,u16,u32,... form. Usually * these types are defined in the implemenation function where this * macro is instanced. */ #define TYPECASE2(type_id,T) \ switch(type_id) \ { \ case u8_id :CASE2(T,uint8_t); break; \ case u16_id:CASE2(T,uint16_t); break; \ case u32_id:CASE2(T,uint32_t); break; \ case u64_id:CASE2(T,uint64_t); break; \ case i8_id :CASE2(T,int8_t); break; \ case i16_id:CASE2(T,int16_t); break; \ case i32_id:CASE2(T,int32_t); break; \ case i64_id:CASE2(T,int64_t); break; \ case f32_id:CASE2(T,float); break; \ case f64_id:CASE2(T,double); break; \ default: \ FAIL("Unsupported pixel type."); \ } int isaligned(unsigned x, unsigned n) { return (x%n)==0; } int pipeline_exec(pipeline_t self, pipeline_image_t dst, const pipeline_image_t src, int *emit) { TRY(emit); TRY(isaligned(src->w,BX_)); TRY(isaligned(src->h,BY_)); TRY(isaligned(dst->w,BX_*WORK_)); TRY(dst->h==2*src->h); { int count=0; CUTRY(hipGetDeviceCount(&count)); CUTRY(hipSetDevice(count-1)); } if(src->w>self->ctx.w) { TRY(pipeline_alloc_lut(self,src->w)); TRY(pipeline_fill_lut(self,src->w)); } pipeline_image_conversion_params(dst,src,self->invert,&self->m,&self->b); TRY(pipeline_upload(self,dst,src)); // updates context size and stride as well // launch kernel #define CASE2(TSRC,TDST) launch<TSRC,TDST,BX_,BY_,WORK_>(self,emit) #define CASE(T) TYPECASE2(src->type,T) { TYPECASE(dst->type); } #undef CASE #undef CASE2 if(*emit) TRY(pipeline_download(self,dst)); return 1; Error: return 0; } #undef TYPECASE #undef TYPECASE2
bb4efa6f0198310109b551247aafbda3ddb5d772.cu
#include "pipeline.h" #include "pipeline-image.h" #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> //for printf #include <stdlib.h> //for malloc #include <string.h> //for memset #include <stdint.h> #include "cuda_runtime.h" #define BX_ (32) #define BY_ (4) #define WORK_ (8) #if 0 #define ECHO(estr) LOG("---\t%s\n",estr) #else #define ECHO(estr) #endif static void breakme() {} #define LOG(...) printf(__VA_ARGS__) #define REPORT(estr,msg) LOG("%s(%d): %s()\n\t%s\n\t%s\n",__FILE__,__LINE__,__FUNCTION__,estr,msg) #define TRY(e) do{ECHO(#e);if(!(e)){REPORT(#e,"Evaluated to false.");breakme(); goto Error;}}while(0) #define FAIL(msg) do{REPORT("Failure.",msg);goto Error;} while(0) #define NEW(T,e,N) TRY((e)=(T*)malloc(sizeof(T)*(N))) #define ZERO(T,e,N) memset((e),0,sizeof(T)*(N)) #define CUREPORT(ecode,estr) LOG("%s(%d): %s()\n\t%s\n\t%s\n",__FILE__,__LINE__,__FUNCTION__,estr,cudaGetErrorString(ecode)) #define CUTRY(e) do{ cudaError_t ecode; ECHO(#e); ecode=(e); if(ecode!=cudaSuccess){CUREPORT(ecode,#e);goto Error;}}while(0) #define CUWARN(e) do{ cudaError_t ecode; ECHO(#e); ecode=(e); if(ecode!=cudaSuccess){CUREPORT(ecode,#e); }}while(0) #define CUNEW(T,e,N) CUTRY(cudaMalloc((void**)&(e),sizeof(T)*(N))) #define CUZERO(T,e,N) CUTRY(cudaMemset((e),0,sizeof(T)*(N))) #define countof(e) (sizeof(e)/sizeof(*(e))) #define CEIL(num,den) (((num)+(den)-(1))/(den)) /** * The parameter collection that gets passed to the kernel */ struct pipeline_ctx_t { unsigned * __restrict__ ilut; ///< look up table for unwarp (ctx.w/2 number of elements). Set by launch on first call or if width changes. float * __restrict__ lut_norms0, * __restrict__ lut_norms1; unsigned istride, ///< number of elements between rows of source. ostride; ///< number of elements between rows of output. unsigned w,h; ///< source width and height (height is nrows*nchan) }; /** * The object that manages pipeline execution. */ typedef struct pipeline_t_ { pipeline_ctx_t ctx; unsigned count, ///< the number of frames that have been pushed to the accumulator every; ///< the number of frames to average double samples_per_scan; bool invert; unsigned downsample; unsigned alignment; ///< output rows are aligned to this target number of elements. unsigned nbytes_tmp; float norm, ///< 1.0/the frame count as a float - set by launcher (eg. for ctx.every=4, this should be 0.25) m,b; ///< slope and intercept for intensity scaling void * __restrict__ src, ///< device buffer * __restrict__ dst; ///< device buffer float * __restrict__ tmp; ///< device buffer } *pipeline_t; // // --- KERNELS --- // // should schedule for destination (2*width/WORK/BX,height/2/BY) blocks [eg for 4864x512 -> (38,8)] // dst width must be aligned to WORK*BX (256) // height must be aligned to BY*2 (64) // ilut must be aligned to WORK*BX and sized 2*dst width // template<typename T, ///< pixel type (input and output) unsigned BX, ///< block size in X unsigned BY, ///< block size in Y (channel dimension unrolled into Y) unsigned WORK ///< number of elements to process per thread > __global__ void __launch_bounds__(BX*BY,1) /* max threads, min blocks */ warp_kernel(pipeline_ctx_t ctx, const T* __restrict__ src, float* __restrict__ dst) { const unsigned ox=threadIdx.x+blockIdx.x*WORK*BX, oy=threadIdx.y+blockIdx.y*BY; unsigned * __restrict__ ilut = ctx.ilut + ox; dst+=ox+oy*ctx.ostride*2; src+= oy*ctx.istride; if(blockIdx.x<ctx.ostride/(WORK*BX)) // forward scan { #pragma unroll for(int i=0;i<WORK;++i) { const int j0=ilut[i*BX], j1=ilut[i*BX+1]; float v0=0.0f,v1=0.0f; if(j0>0) v1=ctx.lut_norms1[j0-1]*src[j0-1]; for(int j=j0;j<j1;++j) v0+=ctx.lut_norms0[j]*src[j]; dst[i*BX]+=v0+v1; } } else { // backward scan #pragma unroll for(int i=0;i<WORK;++i) { const int j1=ilut[i*BX+1], j0=ilut[i*BX+2]; float v0=0.0f; for(int j=j0;j<j1;++j) v0+=ctx.lut_norms0[j]*src[j]; float v1=ctx.lut_norms1[j1]*src[j1]; dst[i*BX]+=v0+v1; } } } /** * Cast array from float to T. * Rounds pixel values, so this isn't appropriate for converting to floating point types. * src and dst should be the same shape but may be different types. * Both must have width aligned to BX*WORK * Both must have heigh aligned to BY */ template<typename T, ///< pixel type (input and output) unsigned BX, ///< block size in X unsigned BY, ///< block size in Y (channel dimension unrolled into Y) unsigned WORK ///< number of elements to process per thread > __global__ void __launch_bounds__(BX*BY,1) cast_kernel(T*__restrict__ dst, const float* __restrict__ src, unsigned stride,const float m, const float b) { const int ox=threadIdx.x+blockIdx.x*WORK*BX, oy=threadIdx.y+blockIdx.y*BY; //if(oy>=h) return; // for unaligned y, uncomment and add an argument to the kernel call src+=ox+oy*stride; dst+=ox+oy*stride; #pragma unroll for(int i=0;i<WORK;++i) dst[i*BX]=round(fmaf(src[i*BX],m,b)); } // // --- PUBLIC INTERFACE --- // pipeline_t pipeline_make(const pipeline_param_t *params) { pipeline_t self=NULL; TRY(params); NEW(pipeline_t_,self,1); ZERO(pipeline_t_,self,1); self->every = (params->frame_average_count<1)?1:params->frame_average_count; self->samples_per_scan = params->sample_rate_MHz*1.0e6/(double)params->scan_rate_Hz; self->invert = (params->invert_intensity!=0); self->downsample = (params->pixel_average_count<=1)?1:params->pixel_average_count; self->alignment = BX_*WORK_; self->norm = 1.0f/(float)self->every; self->m = 1.0f;; self->b = 0.0f; return self; Error: return NULL; } void pipeline_free(pipeline_t *self) { if(self && *self) { void *ptrs[]={self[0]->ctx.ilut, self[0]->ctx.lut_norms0, self[0]->src, self[0]->dst, self[0]->tmp}; for(int i=0;i<countof(ptrs);++i) if(ptrs[i]) CUWARN(cudaFree(ptrs[i])); free(*self); *self=NULL; } } #define EPS (1e-3) static unsigned pipeline_get_output_width(pipeline_t self, const double inwidth) { const double d=1.0-inwidth/self->samples_per_scan; // 1 - duty //max derivative of the cosine warp adjusted to cos(2pi*(d/2)) is the zero point //and the positive part of the warp function goes from 0 to 1. const double maxslope=M_PI*(1.0-d)/inwidth/cos(M_PI*d); const double amplitude=1.0/maxslope; const unsigned w=self->alignment*(unsigned)(amplitude/self->downsample/self->alignment); TRY(-EPS<d && d<=(0.5+EPS)); TRY(0<w && w<inwidth); return w; Error: return 0; } #undef EPS extern "C" int pipeline_get_output_dims(pipeline_t self, const pipeline_image_t src, unsigned *w, unsigned *h, unsigned *nchan) { TRY(self && src); if(nchan) *nchan=src->nchan; if(h) *h=src->h*2; if(w) TRY(*w=pipeline_get_output_width(self,src->w)); return 1; Error: return 0; } static int pipeline_alloc_lut(pipeline_t self, unsigned inwidth) { unsigned N=self->alignment*CEIL(inwidth,self->alignment); // pad to aligned width if(self->ctx.ilut) { CUTRY(cudaFree(self->ctx.ilut)); CUTRY(cudaFree(self->ctx.lut_norms0)); } const unsigned ow = pipeline_get_output_width(self,inwidth); CUNEW(unsigned,self->ctx.ilut, 2*(ow+1)); CUNEW(float ,self->ctx.lut_norms0,2*N+1); return 1; Error: self->ctx.ilut=NULL; self->ctx.lut_norms0=NULL; return 0; } static void dump(const char* name, void* data, size_t nbytes) { FILE* fp=0; TRY(fp=fopen(name,"wb")); fwrite(data,1,nbytes,fp); fclose(fp); Error:; } static double f(double x) { return 0.5*(1.0-cos(2.0*M_PI*x)); } static int pipeline_fill_lut(pipeline_t self, unsigned inwidth) { int isok=1; unsigned * __restrict__ lut=0; unsigned * __restrict__ ilut=0; float * __restrict__ norms=0; // useful constants const double d = (1.0-inwidth/self->samples_per_scan)/2.0; // 0.5*(1 - duty) const unsigned ow = pipeline_get_output_width(self,inwidth); const double s = (1.0-2.0*d)/(double)inwidth; const double A = ow/(1.0-f(d)); const double Afd = A*f(d); const unsigned halfw = inwidth/2; const unsigned N = self->alignment*CEIL(inwidth,self->alignment); // pad to aligned width // alloc temporary space NEW(unsigned ,lut ,inwidth); NEW(unsigned ,ilut ,2*(ow+1)); NEW(float ,norms,2*N+1); ZERO(unsigned,lut ,inwidth); ZERO(unsigned,ilut ,2*(ow+1)); ZERO(float ,norms,2*N+1); // compute lookup for(unsigned i=0;i<inwidth;++i) { double p0=d+s*i, p1=d+s*(i+1); double v0=A*f(p0)-Afd, v1=A*f(p1)-Afd; int j,k; if(v0<0.0) v0=0.0; if(v1<0.0) v1=0.0; if(v0>v1) { double v=v0;v0=v1;v1=v; } //swap j = (int) v0; k = (int) v1; TRY( (k-j)<2 ); // longest length should be 1, so shouldn't straddle more than two pixels lut[i] = j + (i<halfw?0:ow); if( (k-j)==0 ) { norms[i] = v1-v0; norms[i+N] = 0.0; } else { //k-j==1 -> k=1+j norms[i] = k-v0; norms[i+N] = v1-k; } } // interval encode lookup table on output side { unsigned last=0; for(unsigned i=0;i<halfw;++i) if(last!=lut[i]) ilut[last=lut[i]]=i; ilut[ow ]=inwidth/2; // add elements to deal with discontinuity ilut[ow+1]=inwidth; // subtract one to prevent reading off end ilut+=2; for(unsigned i=halfw;i<inwidth;++i) if(last!=lut[i]) ilut[(last=lut[i])]=i; ilut-=2; } #if 0 dump("lut.u32",lut ,inwidth*sizeof(*lut)); dump("norms.f32",norms,2*N *sizeof(*norms)); dump("ilut.u32",ilut ,2*(ow+1) *sizeof(*ilut)); #endif // upload CUTRY(cudaMemcpy(self->ctx.ilut ,ilut , 2*(ow+1)*sizeof(*ilut),cudaMemcpyHostToDevice)); CUTRY(cudaMemcpy(self->ctx.lut_norms0,norms,(2*N+1)*sizeof(*norms) ,cudaMemcpyHostToDevice)); self->ctx.lut_norms1=self->ctx.lut_norms0+N; Finalize: if(lut) free(lut); if(ilut) free(ilut); if(norms) free(norms); return isok; Error: isok=0; goto Finalize; } static int pipeline_upload(pipeline_t self, pipeline_image_t dst, const pipeline_image_t src) { if(self->src && (self->ctx.w!=src->w || self->ctx.h!=src->h*src->nchan)) // if there's a shape change, realloc { CUTRY(cudaFree(self->src)); self->src=0; CUTRY(cudaFree(self->dst)); self->dst=0; CUTRY(cudaFree(self->tmp)); self->tmp=0; } dst->h++; // pad by a line if(!self->src) { CUTRY(cudaMalloc((void**)&self->src,pipeline_image_nbytes(src)+1024)); CUTRY(cudaMalloc((void**)&self->dst,pipeline_image_nbytes(dst))); CUTRY(cudaMalloc((void**)&self->tmp,self->nbytes_tmp=pipeline_image_nelem(dst)*sizeof(float))); CUTRY(cudaMemset(self->tmp,0,pipeline_image_nelem(dst)*sizeof(float))); } CUTRY(cudaMemcpy(self->src,src->data,pipeline_image_nbytes(src),cudaMemcpyHostToDevice)); dst->h--; // restore original number of lines self->ctx.w=src->w; self->ctx.h=src->h*src->nchan; self->ctx.istride=src->stride; self->ctx.ostride=dst->stride; return 1; Error: return 0; } static int pipeline_download(pipeline_t self, pipeline_image_t dst) { TRY(self->dst); CUTRY(cudaMemcpy(dst->data,self->dst,pipeline_image_nbytes(dst),cudaMemcpyDeviceToHost)); return 1; Error: return 0; } template<typename Tsrc, typename Tdst,unsigned BX,unsigned BY,unsigned WORK> static int launch(pipeline_t self, int *emit) { unsigned ow=pipeline_get_output_width(self,self->ctx.w); dim3 threads(BX,BY), blocks(CEIL(2*ow,BX*WORK),CEIL(self->ctx.h,BY)); // for the cast from tmp to dst TRY(emit); #if 1 if(self->every>1) // frame averaging enabled { if( ((self->count+1)%self->every)==0 ) { *emit=1; warp_kernel<Tsrc,BX,BY,WORK><<<blocks,threads>>>(self->ctx,(Tsrc*)self->src,self->tmp); cast_kernel<Tdst,BX,BY,WORK><<<blocks,threads>>>((Tdst*)self->dst,self->tmp,self->ctx.ostride*2,self->m*self->norm,self->b); } else { *emit=0; warp_kernel<Tsrc,BX,BY,WORK><<<blocks,threads>>>(self->ctx,(Tsrc*)self->src,self->tmp); } self->count++; } else // frame averaging disabled #endif { if(emit) *emit=1; warp_kernel<Tsrc,BX,BY,WORK><<<blocks,threads>>>(self->ctx,(Tsrc*)self->src,self->tmp); cast_kernel<Tdst,BX,BY,WORK><<<blocks,threads>>>((Tdst*)self->dst,self->tmp,self->ctx.ostride*2,self->m,self->b); CUTRY(cudaGetLastError()); } if(*emit) CUTRY(cudaMemset(self->tmp,0,self->nbytes_tmp)); return 1; Error: return 0; } // generics /** Requires a macro \c CASE(T) to be defined where \c T is a type parameter. * Requires a macro \c FAIL to be defined that handles when an invalid \a type_id is used. * \param[in] type_id Must be a valid nd_type_id_t. */ #define TYPECASE(type_id) \ switch(type_id) \ { \ case u8_id :CASE(uint8_t ); break; \ case u16_id:CASE(uint16_t); break; \ case u32_id:CASE(uint32_t); break; \ case u64_id:CASE(uint64_t); break; \ case i8_id :CASE(int8_t ); break; \ case i16_id:CASE(int16_t); break; \ case i32_id:CASE(int32_t); break; \ case i64_id:CASE(int64_t); break; \ case f32_id:CASE(float); break; \ case f64_id:CASE(double); break; \ default: \ FAIL("Unsupported pixel type."); \ } /** Requires a macro \c CASE2(T1,T2) to be defined where \c T1 and \c T2 are * type parameters. * Requires a macro \c FAIL to be defined that handles when an invalid \a type_id is used. * \param[in] type_id Must be a valid nd_type_id_t. * \param[in] T A type name. This should follow the u8,u16,u32,... form. Usually * these types are defined in the implemenation function where this * macro is instanced. */ #define TYPECASE2(type_id,T) \ switch(type_id) \ { \ case u8_id :CASE2(T,uint8_t); break; \ case u16_id:CASE2(T,uint16_t); break; \ case u32_id:CASE2(T,uint32_t); break; \ case u64_id:CASE2(T,uint64_t); break; \ case i8_id :CASE2(T,int8_t); break; \ case i16_id:CASE2(T,int16_t); break; \ case i32_id:CASE2(T,int32_t); break; \ case i64_id:CASE2(T,int64_t); break; \ case f32_id:CASE2(T,float); break; \ case f64_id:CASE2(T,double); break; \ default: \ FAIL("Unsupported pixel type."); \ } int isaligned(unsigned x, unsigned n) { return (x%n)==0; } int pipeline_exec(pipeline_t self, pipeline_image_t dst, const pipeline_image_t src, int *emit) { TRY(emit); TRY(isaligned(src->w,BX_)); TRY(isaligned(src->h,BY_)); TRY(isaligned(dst->w,BX_*WORK_)); TRY(dst->h==2*src->h); { int count=0; CUTRY(cudaGetDeviceCount(&count)); CUTRY(cudaSetDevice(count-1)); } if(src->w>self->ctx.w) { TRY(pipeline_alloc_lut(self,src->w)); TRY(pipeline_fill_lut(self,src->w)); } pipeline_image_conversion_params(dst,src,self->invert,&self->m,&self->b); TRY(pipeline_upload(self,dst,src)); // updates context size and stride as well // launch kernel #define CASE2(TSRC,TDST) launch<TSRC,TDST,BX_,BY_,WORK_>(self,emit) #define CASE(T) TYPECASE2(src->type,T) { TYPECASE(dst->type); } #undef CASE #undef CASE2 if(*emit) TRY(pipeline_download(self,dst)); return 1; Error: return 0; } #undef TYPECASE #undef TYPECASE2
42f9702166befbc445a61644422c30e2072e6f13.hip
// !!! This is a file automatically generated by hipify!!! #include <stdbool.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <hiprand/hiprand_kernel.h> #include <stdlib.h> #include <hip/hip_runtime.h> #include <sys/time.h> #include "addKernel.hip" #include<chrono> #include<iostream> using namespace std; using namespace std::chrono; int blocks_[20][2] = {{8,8},{16,16},{24,24},{32,32},{1,64},{1,128},{1,192},{1,256},{1,320},{1,384},{1,448},{1,512},{1,576},{1,640},{1,704},{1,768},{1,832},{1,896},{1,960},{1,1024}}; int matrices_[7][2] = {{240,240},{496,496},{784,784},{1016,1016},{1232,1232},{1680,1680},{2024,2024}}; int main(int argc, char **argv) { hipSetDevice(0); char* p;int matrix_len=strtol(argv[1], &p, 10); for(int matrix_looper=0;matrix_looper<matrix_len;matrix_looper++){ for(int block_looper=0;block_looper<20;block_looper++){ int XSIZE=matrices_[matrix_looper][0],YSIZE=matrices_[matrix_looper][1],BLOCKX=blocks_[block_looper][0],BLOCKY=blocks_[block_looper][1]; float *A = NULL; hipMalloc(&A, XSIZE*YSIZE); int size = XSIZE*YSIZE; int iXSIZE= XSIZE; int iYSIZE= YSIZE; while(iXSIZE%BLOCKX!=0) { iXSIZE++; } while(iYSIZE%BLOCKY!=0) { iYSIZE++; } dim3 gridBlock(iXSIZE/BLOCKX, iYSIZE/BLOCKY); dim3 threadBlock(BLOCKX, BLOCKY); hipFree(0);hipLaunchKernelGGL(( addKernel), dim3(gridBlock),dim3(threadBlock), 0, 0, A,size); hipDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) {hipLaunchKernelGGL(( addKernel), dim3(gridBlock),dim3(threadBlock), 0, 0, A,size); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) {hipLaunchKernelGGL(( addKernel), dim3(gridBlock),dim3(threadBlock), 0, 0, A,size); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
42f9702166befbc445a61644422c30e2072e6f13.cu
#include <stdbool.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <curand_kernel.h> #include <stdlib.h> #include <cuda.h> #include <sys/time.h> #include "addKernel.cu" #include<chrono> #include<iostream> using namespace std; using namespace std::chrono; int blocks_[20][2] = {{8,8},{16,16},{24,24},{32,32},{1,64},{1,128},{1,192},{1,256},{1,320},{1,384},{1,448},{1,512},{1,576},{1,640},{1,704},{1,768},{1,832},{1,896},{1,960},{1,1024}}; int matrices_[7][2] = {{240,240},{496,496},{784,784},{1016,1016},{1232,1232},{1680,1680},{2024,2024}}; int main(int argc, char **argv) { cudaSetDevice(0); char* p;int matrix_len=strtol(argv[1], &p, 10); for(int matrix_looper=0;matrix_looper<matrix_len;matrix_looper++){ for(int block_looper=0;block_looper<20;block_looper++){ int XSIZE=matrices_[matrix_looper][0],YSIZE=matrices_[matrix_looper][1],BLOCKX=blocks_[block_looper][0],BLOCKY=blocks_[block_looper][1]; float *A = NULL; cudaMalloc(&A, XSIZE*YSIZE); int size = XSIZE*YSIZE; int iXSIZE= XSIZE; int iYSIZE= YSIZE; while(iXSIZE%BLOCKX!=0) { iXSIZE++; } while(iYSIZE%BLOCKY!=0) { iYSIZE++; } dim3 gridBlock(iXSIZE/BLOCKX, iYSIZE/BLOCKY); dim3 threadBlock(BLOCKX, BLOCKY); cudaFree(0); addKernel<<<gridBlock,threadBlock>>>(A,size); cudaDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) { addKernel<<<gridBlock,threadBlock>>>(A,size); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) { addKernel<<<gridBlock,threadBlock>>>(A,size); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
7c0ea5d52da1ef3a49a66bb07e6524bf68730734.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" //pass //--gridDim=1 --blockDim=32 --no-inline __global__ void kernel(uint4 *out) { uint4 vector = {0,0,0,0}; out[threadIdx.x] = vector; }
7c0ea5d52da1ef3a49a66bb07e6524bf68730734.cu
//pass //--gridDim=1 --blockDim=32 --no-inline __global__ void kernel(uint4 *out) { uint4 vector = {0,0,0,0}; out[threadIdx.x] = vector; }
c7b1bb7c8efc2f384ff201b2eb04074939a9229f.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Homework 2 // Image Blurring // // In this homework we are blurring an image. To do this, imagine that we have // a square array of weight values. For each pixel in the image, imagine that we // overlay this square array of weights on top of the image such that the center // of the weight array is aligned with the current pixel. To compute a blurred // pixel value, we multiply each pair of numbers that line up. In other words, we // multiply each weight with the pixel underneath it. Finally, we add up all of the // multiplied numbers and assign that value to our output for the current pixel. // We repeat this process for all the pixels in the image. // To help get you started, we have included some useful notes here. //**************************************************************************** // For a color image that has multiple channels, we suggest separating // the different color channels so that each color is stored contiguously // instead of being interleaved. This will simplify your code. // That is instead of RGBARGBARGBARGBA... we suggest transforming to three // arrays (as in the previous homework we ignore the alpha channel again): // 1) RRRRRRRR... // 2) GGGGGGGG... // 3) BBBBBBBB... // // The original layout is known an Array of Structures (AoS) whereas the // format we are converting to is known as a Structure of Arrays (SoA). // As a warm-up, we will ask you to write the kernel that performs this // separation. You should then write the "meat" of the assignment, // which is the kernel that performs the actual blur. We provide code that // re-combines your blurred results for each color channel. //**************************************************************************** // You must fill in the gaussian_blur kernel to perform the blurring of the // inputChannel, using the array of weights, and put the result in the outputChannel. // Here is an example of computing a blur, using a weighted average, for a single // pixel in a small image. // // Array of weights: // // 0.0 0.2 0.0 // 0.2 0.2 0.2 // 0.0 0.2 0.0 // // Image (note that we align the array of weights to the center of the box): // // 1 2 5 2 0 3 // ------- // 3 |2 5 1| 6 0 0.0*2 + 0.2*5 + 0.0*1 + // | | // 4 |3 6 2| 1 4 -> 0.2*3 + 0.2*6 + 0.2*2 + -> 3.2 // | | // 0 |4 0 3| 4 2 0.0*4 + 0.2*0 + 0.0*3 // ------- // 9 6 5 0 3 9 // // (1) (2) (3) // // A good starting place is to map each thread to a pixel as you have before. // Then every thread can perform steps 2 and 3 in the diagram above // completely independently of one another. // Note that the array of weights is square, so its height is the same as its width. // We refer to the array of weights as a filter, and we refer to its width with the // variable filterWidth. //**************************************************************************** // Your homework submission will be evaluated based on correctness and speed. // We test each pixel against a reference solution. If any pixel differs by // more than some small threshold value, the system will tell you that your // solution is incorrect, and it will let you try again. // Once you have gotten that working correctly, then you can think about using // shared memory and having the threads cooperate to achieve better performance. //**************************************************************************** // Also note that we've supplied a helpful debugging function called checkCudaErrors. // You should wrap your allocation and copying statements like we've done in the // code we're supplying you. Here is an example of the unsafe way to allocate // memory on the GPU: // // hipMalloc(&d_red, sizeof(unsigned char) * numRows * numCols); // // Here is an example of the safe way to do the same thing: // // checkCudaErrors(hipMalloc(&d_red, sizeof(unsigned char) * numRows * numCols)); // // Writing code the safe way requires slightly more typing, but is very helpful for // catching mistakes. If you write code the unsafe way and you make a mistake, then // any subsequent kernels won't compute anything, and it will be hard to figure out // why. Writing code the safe way will inform you as soon as you make a mistake. // Finally, remember to free the memory you allocate at the end of the function. //**************************************************************************** #include "utils.h" #include <stdio.h> #define MAX(A,B) (A>B ? A : B) #define MIN(A,B) (A<B ? A : B) __global__ void gaussian_blur(const unsigned char* const inputChannel, unsigned char* const outputChannel, int numRows, int numCols, const float* const filter, const int filterWidth) { // TODO const int2 thread_2D_pos = make_int2( blockIdx.x * blockDim.x + threadIdx.x, blockIdx.y * blockDim.y + threadIdx.y); if (thread_2D_pos.x >= numCols || thread_2D_pos.y >= numRows) return; const int thread_1D_pos = thread_2D_pos.y * numCols + thread_2D_pos.x; const int rowIdx = thread_2D_pos.y; const int colIdx = thread_2D_pos.x; // float value = 0.; // for (int i = 0; i < filterWidth; ++i){ // for (int j = 0; j< filterWidth; ++j){ // const int iIdx = MIN(MAX(rowIdx - filterWidth/2 + i,0), numRows-1); // const int jIdx = MIN(MAX(colIdx - filterWidth/2 + j,0), numCols-1); // if (thread_1D_pos == 6000) printf("i=%d, j=%d, iIdx=%d, jIdx=%d\n", i, j, iIdx, jIdx); // value += filter[filterWidth*i+j]*static_cast<float>(inputChannel[numCols*iIdx+jIdx]); // } // } float result = 0.f; //For every value in the filter around the pixel (c, r) for (int filter_r = -filterWidth/2; filter_r <= filterWidth/2; ++filter_r) { for (int filter_c = -filterWidth/2; filter_c <= filterWidth/2; ++filter_c) { //Find the global image position for this filter position //clamp to boundary of the image int image_r = MIN(numRows - 1, MAX(rowIdx + filter_r, 0)); int image_c = MIN(numCols - 1, MAX(colIdx + filter_c, 0)); float image_value = static_cast<float>(inputChannel[image_r * numCols + image_c]); float filter_value = filter[(filter_r + filterWidth/2) * filterWidth + filter_c + filterWidth/2]; result += image_value * filter_value; } } outputChannel[thread_1D_pos] = static_cast<unsigned char>(result); // outputChannel[thread_1D_pos] = inputChannel[numCols*rowIdx+colIdx]; // NOTE: Be sure to compute any intermediate results in floating point // before storing the final result as unsigned char. // NOTE: Be careful not to try to access memory that is outside the bounds of // the image. You'll want code that performs the following check before accessing // GPU memory: // // if ( absolute_image_position_x >= numCols || // absolute_image_position_y >= numRows ) // { // return; // } // NOTE: If a thread's absolute position 2D position is within the image, but some of // its neighbors are outside the image, then you will need to be extra careful. Instead // of trying to read such a neighbor value from GPU memory (which won't work because // the value is out of bounds), you should explicitly clamp the neighbor values you read // to be within the bounds of the image. If this is not clear to you, then please refer // to sequential reference solution for the exact clamping semantics you should follow. } //This kernel takes in an image represented as a uchar4 and splits //it into three images consisting of only one color channel each __global__ void separateChannels(const uchar4* const inputImageRGBA, int numRows, int numCols, unsigned char* const redChannel, unsigned char* const greenChannel, unsigned char* const blueChannel) { const int2 thread_2D_pos = make_int2( blockIdx.x * blockDim.x + threadIdx.x, blockIdx.y * blockDim.y + threadIdx.y); const int thread_1D_pos = thread_2D_pos.y * numCols + thread_2D_pos.x; //make sure we don't try and access memory outside the image //by having any threads mapped there return early if (thread_2D_pos.x >= numCols || thread_2D_pos.y >= numRows) return; redChannel[thread_1D_pos] = inputImageRGBA[thread_1D_pos].x; greenChannel[thread_1D_pos] = inputImageRGBA[thread_1D_pos].y; blueChannel[thread_1D_pos] = inputImageRGBA[thread_1D_pos].z; // TODO // // NOTE: Be careful not to try to access memory that is outside the bounds of // the image. You'll want code that performs the following check before accessing // GPU memory: // // if ( absolute_image_position_x >= numCols || // absolute_image_position_y >= numRows ) // { // return; // } } //This kernel takes in three color channels and recombines them //into one image. The alpha channel is set to 255 to represent //that this image has no transparency. __global__ void recombineChannels(const unsigned char* const redChannel, const unsigned char* const greenChannel, const unsigned char* const blueChannel, uchar4* const outputImageRGBA, int numRows, int numCols) { const int2 thread_2D_pos = make_int2( blockIdx.x * blockDim.x + threadIdx.x, blockIdx.y * blockDim.y + threadIdx.y); const int thread_1D_pos = thread_2D_pos.y * numCols + thread_2D_pos.x; //make sure we don't try and access memory outside the image //by having any threads mapped there return early if (thread_2D_pos.x >= numCols || thread_2D_pos.y >= numRows) return; unsigned char red = redChannel[thread_1D_pos]; unsigned char green = greenChannel[thread_1D_pos]; unsigned char blue = blueChannel[thread_1D_pos]; //Alpha should be 255 for no transparency uchar4 outputPixel = make_uchar4(red, green, blue, 255); outputImageRGBA[thread_1D_pos] = outputPixel; } unsigned char *d_red, *d_green, *d_blue; float *d_filter; void allocateMemoryAndCopyToGPU(const size_t numRowsImage, const size_t numColsImage, const float* const h_filter, const size_t filterWidth) { //allocate memory for the three different channels //original checkCudaErrors(hipMalloc(&d_red, sizeof(unsigned char) * numRowsImage * numColsImage)); checkCudaErrors(hipMalloc(&d_green, sizeof(unsigned char) * numRowsImage * numColsImage)); checkCudaErrors(hipMalloc(&d_blue, sizeof(unsigned char) * numRowsImage * numColsImage)); checkCudaErrors(hipMalloc(&d_filter, sizeof(float) * filterWidth * filterWidth)); checkCudaErrors(hipMemcpy(d_filter, h_filter, sizeof(float) * filterWidth * filterWidth, hipMemcpyHostToDevice)); //TODO: //Allocate memory for the filter on the GPU //Use the pointer d_filter that we have already declared for you //You need to allocate memory for the filter with hipMalloc //be sure to use checkCudaErrors like the above examples to //be able to tell if anything goes wrong //IMPORTANT: Notice that we pass a pointer to a pointer to hipMalloc //TODO: //Copy the filter on the host (h_filter) to the memory you just allocated //on the GPU. hipMemcpy(dst, src, numBytes, hipMemcpyHostToDevice); //Remember to use checkCudaErrors! } void your_gaussian_blur(const uchar4 * const h_inputImageRGBA, uchar4 * const d_inputImageRGBA, uchar4* const d_outputImageRGBA, const size_t numRows, const size_t numCols, unsigned char *d_redBlurred, unsigned char *d_greenBlurred, unsigned char *d_blueBlurred, const int filterWidth) { //TODO: Set reasonable block size (i.e., number of threads per block) const dim3 blockSize(8, 8, 1); //TODO: //Compute correct grid size (i.e., number of blocks per kernel launch) //from the image size and and block size. const dim3 gridSize((numCols+7)/8, (numRows+7)/8, 1); //TODO: Launch a kernel for separating the RGBA image into different color channels hipLaunchKernelGGL(( separateChannels), dim3(gridSize), dim3(blockSize), 0, 0, d_inputImageRGBA, numRows, numCols, d_red, d_green, d_blue); // Call hipDeviceSynchronize(), then call checkCudaErrors() immediately after // launching your kernel to make sure that you didn't make any mistakes. hipDeviceSynchronize(); checkCudaErrors(hipGetLastError()); //TODO: Call your convolution kernel here 3 times, once for each color channel. hipLaunchKernelGGL(( gaussian_blur), dim3(gridSize), dim3(blockSize), 0, 0, d_red, d_redBlurred, numRows, numCols, d_filter, filterWidth); hipLaunchKernelGGL(( gaussian_blur), dim3(gridSize), dim3(blockSize), 0, 0, d_green, d_greenBlurred, numRows, numCols, d_filter, filterWidth); hipLaunchKernelGGL(( gaussian_blur), dim3(gridSize), dim3(blockSize), 0, 0, d_blue, d_blueBlurred, numRows, numCols, d_filter, filterWidth); // Again, call hipDeviceSynchronize(), then call checkCudaErrors() immediately after // launching your kernel to make sure that you didn't make any mistakes. hipDeviceSynchronize(); checkCudaErrors(hipGetLastError()); // Now we recombine your results. We take care of launching this kernel for you. // // NOTE: This kernel launch depends on the gridSize and blockSize variables, // which you must set yourself. hipLaunchKernelGGL(( recombineChannels), dim3(gridSize), dim3(blockSize), 0, 0, d_redBlurred, d_greenBlurred, d_blueBlurred, d_outputImageRGBA, numRows, numCols); hipDeviceSynchronize(); checkCudaErrors(hipGetLastError()); } //Free all the memory that we allocated //TODO: make sure you free any arrays that you allocated void cleanup() { checkCudaErrors(hipFree(d_red)); checkCudaErrors(hipFree(d_green)); checkCudaErrors(hipFree(d_blue)); }
c7b1bb7c8efc2f384ff201b2eb04074939a9229f.cu
// Homework 2 // Image Blurring // // In this homework we are blurring an image. To do this, imagine that we have // a square array of weight values. For each pixel in the image, imagine that we // overlay this square array of weights on top of the image such that the center // of the weight array is aligned with the current pixel. To compute a blurred // pixel value, we multiply each pair of numbers that line up. In other words, we // multiply each weight with the pixel underneath it. Finally, we add up all of the // multiplied numbers and assign that value to our output for the current pixel. // We repeat this process for all the pixels in the image. // To help get you started, we have included some useful notes here. //**************************************************************************** // For a color image that has multiple channels, we suggest separating // the different color channels so that each color is stored contiguously // instead of being interleaved. This will simplify your code. // That is instead of RGBARGBARGBARGBA... we suggest transforming to three // arrays (as in the previous homework we ignore the alpha channel again): // 1) RRRRRRRR... // 2) GGGGGGGG... // 3) BBBBBBBB... // // The original layout is known an Array of Structures (AoS) whereas the // format we are converting to is known as a Structure of Arrays (SoA). // As a warm-up, we will ask you to write the kernel that performs this // separation. You should then write the "meat" of the assignment, // which is the kernel that performs the actual blur. We provide code that // re-combines your blurred results for each color channel. //**************************************************************************** // You must fill in the gaussian_blur kernel to perform the blurring of the // inputChannel, using the array of weights, and put the result in the outputChannel. // Here is an example of computing a blur, using a weighted average, for a single // pixel in a small image. // // Array of weights: // // 0.0 0.2 0.0 // 0.2 0.2 0.2 // 0.0 0.2 0.0 // // Image (note that we align the array of weights to the center of the box): // // 1 2 5 2 0 3 // ------- // 3 |2 5 1| 6 0 0.0*2 + 0.2*5 + 0.0*1 + // | | // 4 |3 6 2| 1 4 -> 0.2*3 + 0.2*6 + 0.2*2 + -> 3.2 // | | // 0 |4 0 3| 4 2 0.0*4 + 0.2*0 + 0.0*3 // ------- // 9 6 5 0 3 9 // // (1) (2) (3) // // A good starting place is to map each thread to a pixel as you have before. // Then every thread can perform steps 2 and 3 in the diagram above // completely independently of one another. // Note that the array of weights is square, so its height is the same as its width. // We refer to the array of weights as a filter, and we refer to its width with the // variable filterWidth. //**************************************************************************** // Your homework submission will be evaluated based on correctness and speed. // We test each pixel against a reference solution. If any pixel differs by // more than some small threshold value, the system will tell you that your // solution is incorrect, and it will let you try again. // Once you have gotten that working correctly, then you can think about using // shared memory and having the threads cooperate to achieve better performance. //**************************************************************************** // Also note that we've supplied a helpful debugging function called checkCudaErrors. // You should wrap your allocation and copying statements like we've done in the // code we're supplying you. Here is an example of the unsafe way to allocate // memory on the GPU: // // cudaMalloc(&d_red, sizeof(unsigned char) * numRows * numCols); // // Here is an example of the safe way to do the same thing: // // checkCudaErrors(cudaMalloc(&d_red, sizeof(unsigned char) * numRows * numCols)); // // Writing code the safe way requires slightly more typing, but is very helpful for // catching mistakes. If you write code the unsafe way and you make a mistake, then // any subsequent kernels won't compute anything, and it will be hard to figure out // why. Writing code the safe way will inform you as soon as you make a mistake. // Finally, remember to free the memory you allocate at the end of the function. //**************************************************************************** #include "utils.h" #include <stdio.h> #define MAX(A,B) (A>B ? A : B) #define MIN(A,B) (A<B ? A : B) __global__ void gaussian_blur(const unsigned char* const inputChannel, unsigned char* const outputChannel, int numRows, int numCols, const float* const filter, const int filterWidth) { // TODO const int2 thread_2D_pos = make_int2( blockIdx.x * blockDim.x + threadIdx.x, blockIdx.y * blockDim.y + threadIdx.y); if (thread_2D_pos.x >= numCols || thread_2D_pos.y >= numRows) return; const int thread_1D_pos = thread_2D_pos.y * numCols + thread_2D_pos.x; const int rowIdx = thread_2D_pos.y; const int colIdx = thread_2D_pos.x; // float value = 0.; // for (int i = 0; i < filterWidth; ++i){ // for (int j = 0; j< filterWidth; ++j){ // const int iIdx = MIN(MAX(rowIdx - filterWidth/2 + i,0), numRows-1); // const int jIdx = MIN(MAX(colIdx - filterWidth/2 + j,0), numCols-1); // if (thread_1D_pos == 6000) printf("i=%d, j=%d, iIdx=%d, jIdx=%d\n", i, j, iIdx, jIdx); // value += filter[filterWidth*i+j]*static_cast<float>(inputChannel[numCols*iIdx+jIdx]); // } // } float result = 0.f; //For every value in the filter around the pixel (c, r) for (int filter_r = -filterWidth/2; filter_r <= filterWidth/2; ++filter_r) { for (int filter_c = -filterWidth/2; filter_c <= filterWidth/2; ++filter_c) { //Find the global image position for this filter position //clamp to boundary of the image int image_r = MIN(numRows - 1, MAX(rowIdx + filter_r, 0)); int image_c = MIN(numCols - 1, MAX(colIdx + filter_c, 0)); float image_value = static_cast<float>(inputChannel[image_r * numCols + image_c]); float filter_value = filter[(filter_r + filterWidth/2) * filterWidth + filter_c + filterWidth/2]; result += image_value * filter_value; } } outputChannel[thread_1D_pos] = static_cast<unsigned char>(result); // outputChannel[thread_1D_pos] = inputChannel[numCols*rowIdx+colIdx]; // NOTE: Be sure to compute any intermediate results in floating point // before storing the final result as unsigned char. // NOTE: Be careful not to try to access memory that is outside the bounds of // the image. You'll want code that performs the following check before accessing // GPU memory: // // if ( absolute_image_position_x >= numCols || // absolute_image_position_y >= numRows ) // { // return; // } // NOTE: If a thread's absolute position 2D position is within the image, but some of // its neighbors are outside the image, then you will need to be extra careful. Instead // of trying to read such a neighbor value from GPU memory (which won't work because // the value is out of bounds), you should explicitly clamp the neighbor values you read // to be within the bounds of the image. If this is not clear to you, then please refer // to sequential reference solution for the exact clamping semantics you should follow. } //This kernel takes in an image represented as a uchar4 and splits //it into three images consisting of only one color channel each __global__ void separateChannels(const uchar4* const inputImageRGBA, int numRows, int numCols, unsigned char* const redChannel, unsigned char* const greenChannel, unsigned char* const blueChannel) { const int2 thread_2D_pos = make_int2( blockIdx.x * blockDim.x + threadIdx.x, blockIdx.y * blockDim.y + threadIdx.y); const int thread_1D_pos = thread_2D_pos.y * numCols + thread_2D_pos.x; //make sure we don't try and access memory outside the image //by having any threads mapped there return early if (thread_2D_pos.x >= numCols || thread_2D_pos.y >= numRows) return; redChannel[thread_1D_pos] = inputImageRGBA[thread_1D_pos].x; greenChannel[thread_1D_pos] = inputImageRGBA[thread_1D_pos].y; blueChannel[thread_1D_pos] = inputImageRGBA[thread_1D_pos].z; // TODO // // NOTE: Be careful not to try to access memory that is outside the bounds of // the image. You'll want code that performs the following check before accessing // GPU memory: // // if ( absolute_image_position_x >= numCols || // absolute_image_position_y >= numRows ) // { // return; // } } //This kernel takes in three color channels and recombines them //into one image. The alpha channel is set to 255 to represent //that this image has no transparency. __global__ void recombineChannels(const unsigned char* const redChannel, const unsigned char* const greenChannel, const unsigned char* const blueChannel, uchar4* const outputImageRGBA, int numRows, int numCols) { const int2 thread_2D_pos = make_int2( blockIdx.x * blockDim.x + threadIdx.x, blockIdx.y * blockDim.y + threadIdx.y); const int thread_1D_pos = thread_2D_pos.y * numCols + thread_2D_pos.x; //make sure we don't try and access memory outside the image //by having any threads mapped there return early if (thread_2D_pos.x >= numCols || thread_2D_pos.y >= numRows) return; unsigned char red = redChannel[thread_1D_pos]; unsigned char green = greenChannel[thread_1D_pos]; unsigned char blue = blueChannel[thread_1D_pos]; //Alpha should be 255 for no transparency uchar4 outputPixel = make_uchar4(red, green, blue, 255); outputImageRGBA[thread_1D_pos] = outputPixel; } unsigned char *d_red, *d_green, *d_blue; float *d_filter; void allocateMemoryAndCopyToGPU(const size_t numRowsImage, const size_t numColsImage, const float* const h_filter, const size_t filterWidth) { //allocate memory for the three different channels //original checkCudaErrors(cudaMalloc(&d_red, sizeof(unsigned char) * numRowsImage * numColsImage)); checkCudaErrors(cudaMalloc(&d_green, sizeof(unsigned char) * numRowsImage * numColsImage)); checkCudaErrors(cudaMalloc(&d_blue, sizeof(unsigned char) * numRowsImage * numColsImage)); checkCudaErrors(cudaMalloc(&d_filter, sizeof(float) * filterWidth * filterWidth)); checkCudaErrors(cudaMemcpy(d_filter, h_filter, sizeof(float) * filterWidth * filterWidth, cudaMemcpyHostToDevice)); //TODO: //Allocate memory for the filter on the GPU //Use the pointer d_filter that we have already declared for you //You need to allocate memory for the filter with cudaMalloc //be sure to use checkCudaErrors like the above examples to //be able to tell if anything goes wrong //IMPORTANT: Notice that we pass a pointer to a pointer to cudaMalloc //TODO: //Copy the filter on the host (h_filter) to the memory you just allocated //on the GPU. cudaMemcpy(dst, src, numBytes, cudaMemcpyHostToDevice); //Remember to use checkCudaErrors! } void your_gaussian_blur(const uchar4 * const h_inputImageRGBA, uchar4 * const d_inputImageRGBA, uchar4* const d_outputImageRGBA, const size_t numRows, const size_t numCols, unsigned char *d_redBlurred, unsigned char *d_greenBlurred, unsigned char *d_blueBlurred, const int filterWidth) { //TODO: Set reasonable block size (i.e., number of threads per block) const dim3 blockSize(8, 8, 1); //TODO: //Compute correct grid size (i.e., number of blocks per kernel launch) //from the image size and and block size. const dim3 gridSize((numCols+7)/8, (numRows+7)/8, 1); //TODO: Launch a kernel for separating the RGBA image into different color channels separateChannels<<<gridSize, blockSize>>>(d_inputImageRGBA, numRows, numCols, d_red, d_green, d_blue); // Call cudaDeviceSynchronize(), then call checkCudaErrors() immediately after // launching your kernel to make sure that you didn't make any mistakes. cudaDeviceSynchronize(); checkCudaErrors(cudaGetLastError()); //TODO: Call your convolution kernel here 3 times, once for each color channel. gaussian_blur<<<gridSize, blockSize>>>(d_red, d_redBlurred, numRows, numCols, d_filter, filterWidth); gaussian_blur<<<gridSize, blockSize>>>(d_green, d_greenBlurred, numRows, numCols, d_filter, filterWidth); gaussian_blur<<<gridSize, blockSize>>>(d_blue, d_blueBlurred, numRows, numCols, d_filter, filterWidth); // Again, call cudaDeviceSynchronize(), then call checkCudaErrors() immediately after // launching your kernel to make sure that you didn't make any mistakes. cudaDeviceSynchronize(); checkCudaErrors(cudaGetLastError()); // Now we recombine your results. We take care of launching this kernel for you. // // NOTE: This kernel launch depends on the gridSize and blockSize variables, // which you must set yourself. recombineChannels<<<gridSize, blockSize>>>(d_redBlurred, d_greenBlurred, d_blueBlurred, d_outputImageRGBA, numRows, numCols); cudaDeviceSynchronize(); checkCudaErrors(cudaGetLastError()); } //Free all the memory that we allocated //TODO: make sure you free any arrays that you allocated void cleanup() { checkCudaErrors(cudaFree(d_red)); checkCudaErrors(cudaFree(d_green)); checkCudaErrors(cudaFree(d_blue)); }
8e450d4ba51305a5da0982613c35b3b3b82950ad.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <algorithm> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "utils.h" #define BLOCK_SIZE 256 typedef struct { double x, y, z;} Vec3d; void randomizeVec3d(Vec3d *data, int n) { for (int i = 0; i < n; i++) { data[i].x = drand48(); data[i].y = drand48(); data[i].z = drand48(); } } double errorVec3d_LInf(Vec3d *data1, Vec3d *data2, int n) { double err = 0.; double abv = 0.; for (int i = 0; i < n; i++) { err = ::max(err, fabs(data1[i].x -data2[i].x)); err = ::max(err, fabs(data1[i].y -data2[i].y)); err = ::max(err, fabs(data1[i].z -data2[i].z)); abv = ::max(abv, fabs(data1[i].x)); abv = ::max(abv, fabs(data1[i].y)); abv = ::max(abv, fabs(data1[i].z)); } return err/abv; } double errorVec3d_L2(Vec3d *data1, Vec3d *data2, int n) { double err = 0.; double abv = 0.; for (int i = 0; i < n; i++) { err += pow(data1[i].x -data2[i].x, 2); err += pow(data1[i].y -data2[i].y, 2); err += pow(data1[i].z -data2[i].z, 2); abv += pow(data1[i].x, 2); abv += pow(data1[i].y, 2); abv += pow(data1[i].z, 2); } return sqrt(err)/sqrt(abv); } void CPU_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { #pragma omp parallel for schedule(dynamic) for (int i = 0; i < num_points; i++) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int j = 0; j < num_quad_points; j++) { // compute the vector from target to source (6 flop) double diff_x = points[i].x - gamma[j].x; double diff_y = points[i].y - gamma[j].y; double diff_z = points[i].z - gamma[j].z; // compute distance between target and source (9 flop) double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double norm_diff = sqrt(distSqr); double invDist3 = 1. / (norm_diff * norm_diff * norm_diff); // compute cross product and reweight using distance (15 flop) B_x += invDist3 * (dgamma_by_dphi[j].y * diff_z - dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (dgamma_by_dphi[j].z * diff_x - dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (dgamma_by_dphi[j].x * diff_y - dgamma_by_dphi[j].y * diff_x); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } __global__ void GPU_nosmem_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int j = 0; j < num_quad_points; j++) { // compute the vector from target to source double diff_x = points[i].x - gamma[j].x; double diff_y = points[i].y - gamma[j].y; double diff_z = points[i].z - gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double norm_diff = sqrt(distSqr); double invDist3 = 1. / (norm_diff * norm_diff * norm_diff); // compute cross product and reweight using distance B_x += invDist3 * (dgamma_by_dphi[j].y * diff_z - dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (dgamma_by_dphi[j].z * diff_x - dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (dgamma_by_dphi[j].x * diff_y - dgamma_by_dphi[j].y * diff_x); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } // GPU version, shared memory,ntargets == nsources are multiples of BLOCK_SIZE __global__ void GPU_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int tile = 0; tile < gridDim.x; tile++) { // shared memory __shared__ Vec3d share_gamma[BLOCK_SIZE]; __shared__ Vec3d share_dgamma_by_dphi[BLOCK_SIZE]; share_gamma[threadIdx.x] = gamma[tile*blockDim.x + threadIdx.x]; share_dgamma_by_dphi[threadIdx.x] = dgamma_by_dphi[tile*blockDim.x + threadIdx.x]; __syncthreads(); // In block, compute B-S //#pragma unroll for (int j = 0; j < BLOCK_SIZE; j++){ // compute the vector from target to source double diff_x = points[i].x - share_gamma[j].x; double diff_y = points[i].y - share_gamma[j].y; double diff_z = points[i].z - share_gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double norm_diff = sqrt(distSqr); double invDist3 = 1. / (norm_diff * norm_diff * norm_diff); // compute cross product and reweight using distance B_x += invDist3 * (share_dgamma_by_dphi[j].y * diff_z - share_dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (share_dgamma_by_dphi[j].z * diff_x - share_dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (share_dgamma_by_dphi[j].x * diff_y - share_dgamma_by_dphi[j].y * diff_x); } __syncthreads(); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } // GPU no shared memory, use rsqrt __global__ void GPU_rsqrt_nosmem_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int j = 0; j < num_quad_points; j++) { // compute the vector from target to source double diff_x = points[i].x - gamma[j].x; double diff_y = points[i].y - gamma[j].y; double diff_z = points[i].z - gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double inv_norm_diff = rsqrt(distSqr); double invDist3 = inv_norm_diff*inv_norm_diff*inv_norm_diff; // compute cross product and reweight using distance B_x += invDist3 * (dgamma_by_dphi[j].y * diff_z - dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (dgamma_by_dphi[j].z * diff_x - dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (dgamma_by_dphi[j].x * diff_y - dgamma_by_dphi[j].y * diff_x); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } // GPU version, using rsqrt, shared memory,ntargets == nsources are multiples of BLOCK_SIZE __global__ void GPU_rsqrt_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int tile = 0; tile < gridDim.x; tile++) { // shared memory __shared__ Vec3d share_gamma[BLOCK_SIZE]; __shared__ Vec3d share_dgamma_by_dphi[BLOCK_SIZE]; share_gamma[threadIdx.x] = gamma[tile*blockDim.x + threadIdx.x]; share_dgamma_by_dphi[threadIdx.x] = dgamma_by_dphi[tile*blockDim.x + threadIdx.x]; __syncthreads(); // In block, compute B-S //#pragma unroll for (int j = 0; j < BLOCK_SIZE; j++){ // compute the vector from target to source double diff_x = points[i].x - share_gamma[j].x; double diff_y = points[i].y - share_gamma[j].y; double diff_z = points[i].z - share_gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double inv_norm_diff = rsqrt(distSqr); double invDist3 = inv_norm_diff*inv_norm_diff*inv_norm_diff; // compute cross product and reweight using distance B_x += invDist3 * (share_dgamma_by_dphi[j].y * diff_z - share_dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (share_dgamma_by_dphi[j].z * diff_x - share_dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (share_dgamma_by_dphi[j].x * diff_y - share_dgamma_by_dphi[j].y * diff_x); } __syncthreads(); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } int main(const int argc, const char** argv) { // set values const long PFIRST = pow(2, 10); const long PLAST = pow(2, 16); FILE * pFile; pFile = fopen ("data.txt","w"); Timer t; fprintf(pFile, " p "); fprintf(pFile, "t_CPU t_GPU_ns t_GPU t_ns_rs t_rs "); fprintf(pFile, "flops_CPU flops_GPU_ns flops_GPU flops_ns_rs flops_rs "); fprintf(pFile, "band_CPU band_GPU_ns band_GPU band_ns_rs band_rs "); //fprintf(pFile, "err_GPU_ns err_GPU err_ns_rs err_rs"); fprintf(pFile, "\n"); // allocate memory for (long p = PFIRST; p <= PLAST; p *= 2) { long nsources = p, ntargets = p; long repeat = 1e8/(nsources*ntargets)+1; long bytes_targets = 3 * ntargets * sizeof(double); long bytes_sources = 3 * nsources * sizeof(double); // CPU memory Vec3d *points = (Vec3d*) malloc(bytes_targets); Vec3d *gamma = (Vec3d*) malloc(bytes_sources); Vec3d *dgamma_by_dphi = (Vec3d*) malloc(bytes_sources); Vec3d *B = (Vec3d*) malloc(bytes_targets); // CPU computation Vec3d *B1 = (Vec3d*) malloc(bytes_targets); // GPU computation // GPU memory Vec3d *gpu_points, *gpu_gamma, *gpu_dgamma_by_dphi, *gpu_B; hipMalloc(&gpu_points, bytes_targets); hipMalloc(&gpu_gamma, bytes_sources); hipMalloc(&gpu_dgamma_by_dphi, bytes_sources); hipMalloc(&gpu_B, bytes_targets); int nBlocks = (ntargets + BLOCK_SIZE - 1) / BLOCK_SIZE; //initialize with randomized data randomizeVec3d(points, ntargets); randomizeVec3d(gamma, nsources); randomizeVec3d(dgamma_by_dphi, nsources); randomizeVec3d(B, ntargets); // copy data to GPU //hipMemcpy(gpu_points, points, bytes_targets, hipMemcpyHostToDevice); //hipMemcpy(gpu_gamma, gamma, bytes_sources, hipMemcpyHostToDevice); //hipMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, hipMemcpyHostToDevice); //hipMemcpy(gpu_B, B, bytes_targets, hipMemcpyHostToDevice); // CPU computation t.tic(); for (long i = 0; i < repeat; i++) { CPU_biot_savart_B(ntargets, nsources, points, gamma, dgamma_by_dphi, B); } double tt = t.toc(); double fp = repeat * 30*ntargets*nsources/tt/1e9; double bd = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt /1e9; // GPU nonsmem computation hipDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { hipMemcpy(gpu_points, points, bytes_targets, hipMemcpyHostToDevice); hipMemcpy(gpu_gamma, gamma, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_B, B, bytes_targets, hipMemcpyHostToDevice); hipLaunchKernelGGL(( GPU_nosmem_biot_savart_B), dim3(nBlocks), dim3(BLOCK_SIZE), 0, 0, ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); hipMemcpy(B1, gpu_B, bytes_targets, hipMemcpyDeviceToHost); } hipDeviceSynchronize(); double tt1 = t.toc(); double fp1 = repeat * 30*ntargets*nsources/tt1/1e9; double bd1 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt1 /1e9; double err1 = errorVec3d_LInf(B, B1, ntargets); // GPU computation with shared memory hipDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { hipMemcpy(gpu_points, points, bytes_targets, hipMemcpyHostToDevice); hipMemcpy(gpu_gamma, gamma, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_B, B, bytes_targets, hipMemcpyHostToDevice); hipLaunchKernelGGL(( GPU_biot_savart_B), dim3(nBlocks), dim3(BLOCK_SIZE), 0, 0, ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); hipMemcpy(B1, gpu_B, bytes_targets, hipMemcpyDeviceToHost); } hipDeviceSynchronize(); double tt2 = t.toc(); double fp2 = repeat * 30*ntargets*nsources/tt2/1e9; double bd2 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt2 /1e9; double err2 = errorVec3d_LInf(B, B1, ntargets); // GPU nonsmem computation using rsqrt hipDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { hipMemcpy(gpu_points, points, bytes_targets, hipMemcpyHostToDevice); hipMemcpy(gpu_gamma, gamma, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_B, B, bytes_targets, hipMemcpyHostToDevice); hipLaunchKernelGGL(( GPU_rsqrt_nosmem_biot_savart_B), dim3(nBlocks), dim3(BLOCK_SIZE), 0, 0, ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); hipMemcpy(B1, gpu_B, bytes_targets, hipMemcpyDeviceToHost); } hipDeviceSynchronize(); double tt3 = t.toc(); double fp3 = repeat * 29*ntargets*nsources/tt3/1e9; double bd3 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt3 /1e9; double err3 = errorVec3d_LInf(B, B1, ntargets); // GPU computation with shared memory, using rsqrt hipDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { hipMemcpy(gpu_points, points, bytes_targets, hipMemcpyHostToDevice); hipMemcpy(gpu_gamma, gamma, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, hipMemcpyHostToDevice); hipMemcpy(gpu_B, B, bytes_targets, hipMemcpyHostToDevice); hipLaunchKernelGGL(( GPU_rsqrt_biot_savart_B), dim3(nBlocks), dim3(BLOCK_SIZE), 0, 0, ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); hipMemcpy(B1, gpu_B, bytes_targets, hipMemcpyDeviceToHost); } hipDeviceSynchronize(); double tt4 = t.toc(); double fp4 = repeat * 29*ntargets*nsources/tt4/1e9; double bd4 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt4 /1e9; double err4 = errorVec3d_LInf(B, B1, ntargets); fprintf(pFile, "%10d ", p); fprintf(pFile, "%10f %10f %10f %10f %10f ", tt/repeat, tt1/repeat, tt2/repeat, tt3/repeat, tt4/repeat); fprintf(pFile, "%10f %10f %10f %10f %10f ", fp, fp1, fp2, fp3, fp4); fprintf(pFile, "%10f %10f %10f %10f %10f ", bd, bd1, bd2, bd3, bd4); // fprintf(pFile, "%10f %10f %10f %10f", err1, err2, err3, err4); fprintf(pFile, "\n"); // print some results // for (int i = 0; i < 2; i++){ // printf(" %e, %e | %e, %e | %e, %e\n", B[i].x, B1[i].x, B[i].y, B1[i].y, B[i].z, B1[i].z); //} // free memory free(points); free(gamma); free(dgamma_by_dphi); free(B); free(B1); hipFree(gpu_points); hipFree(gpu_gamma); hipFree(gpu_dgamma_by_dphi); hipFree(gpu_B); } fclose (pFile); }
8e450d4ba51305a5da0982613c35b3b3b82950ad.cu
#include <algorithm> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "utils.h" #define BLOCK_SIZE 256 typedef struct { double x, y, z;} Vec3d; void randomizeVec3d(Vec3d *data, int n) { for (int i = 0; i < n; i++) { data[i].x = drand48(); data[i].y = drand48(); data[i].z = drand48(); } } double errorVec3d_LInf(Vec3d *data1, Vec3d *data2, int n) { double err = 0.; double abv = 0.; for (int i = 0; i < n; i++) { err = std::max(err, fabs(data1[i].x -data2[i].x)); err = std::max(err, fabs(data1[i].y -data2[i].y)); err = std::max(err, fabs(data1[i].z -data2[i].z)); abv = std::max(abv, fabs(data1[i].x)); abv = std::max(abv, fabs(data1[i].y)); abv = std::max(abv, fabs(data1[i].z)); } return err/abv; } double errorVec3d_L2(Vec3d *data1, Vec3d *data2, int n) { double err = 0.; double abv = 0.; for (int i = 0; i < n; i++) { err += pow(data1[i].x -data2[i].x, 2); err += pow(data1[i].y -data2[i].y, 2); err += pow(data1[i].z -data2[i].z, 2); abv += pow(data1[i].x, 2); abv += pow(data1[i].y, 2); abv += pow(data1[i].z, 2); } return sqrt(err)/sqrt(abv); } void CPU_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { #pragma omp parallel for schedule(dynamic) for (int i = 0; i < num_points; i++) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int j = 0; j < num_quad_points; j++) { // compute the vector from target to source (6 flop) double diff_x = points[i].x - gamma[j].x; double diff_y = points[i].y - gamma[j].y; double diff_z = points[i].z - gamma[j].z; // compute distance between target and source (9 flop) double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double norm_diff = sqrt(distSqr); double invDist3 = 1. / (norm_diff * norm_diff * norm_diff); // compute cross product and reweight using distance (15 flop) B_x += invDist3 * (dgamma_by_dphi[j].y * diff_z - dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (dgamma_by_dphi[j].z * diff_x - dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (dgamma_by_dphi[j].x * diff_y - dgamma_by_dphi[j].y * diff_x); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } __global__ void GPU_nosmem_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int j = 0; j < num_quad_points; j++) { // compute the vector from target to source double diff_x = points[i].x - gamma[j].x; double diff_y = points[i].y - gamma[j].y; double diff_z = points[i].z - gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double norm_diff = sqrt(distSqr); double invDist3 = 1. / (norm_diff * norm_diff * norm_diff); // compute cross product and reweight using distance B_x += invDist3 * (dgamma_by_dphi[j].y * diff_z - dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (dgamma_by_dphi[j].z * diff_x - dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (dgamma_by_dphi[j].x * diff_y - dgamma_by_dphi[j].y * diff_x); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } // GPU version, shared memory,ntargets == nsources are multiples of BLOCK_SIZE __global__ void GPU_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int tile = 0; tile < gridDim.x; tile++) { // shared memory __shared__ Vec3d share_gamma[BLOCK_SIZE]; __shared__ Vec3d share_dgamma_by_dphi[BLOCK_SIZE]; share_gamma[threadIdx.x] = gamma[tile*blockDim.x + threadIdx.x]; share_dgamma_by_dphi[threadIdx.x] = dgamma_by_dphi[tile*blockDim.x + threadIdx.x]; __syncthreads(); // In block, compute B-S //#pragma unroll for (int j = 0; j < BLOCK_SIZE; j++){ // compute the vector from target to source double diff_x = points[i].x - share_gamma[j].x; double diff_y = points[i].y - share_gamma[j].y; double diff_z = points[i].z - share_gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double norm_diff = sqrt(distSqr); double invDist3 = 1. / (norm_diff * norm_diff * norm_diff); // compute cross product and reweight using distance B_x += invDist3 * (share_dgamma_by_dphi[j].y * diff_z - share_dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (share_dgamma_by_dphi[j].z * diff_x - share_dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (share_dgamma_by_dphi[j].x * diff_y - share_dgamma_by_dphi[j].y * diff_x); } __syncthreads(); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } // GPU no shared memory, use rsqrt __global__ void GPU_rsqrt_nosmem_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int j = 0; j < num_quad_points; j++) { // compute the vector from target to source double diff_x = points[i].x - gamma[j].x; double diff_y = points[i].y - gamma[j].y; double diff_z = points[i].z - gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double inv_norm_diff = rsqrt(distSqr); double invDist3 = inv_norm_diff*inv_norm_diff*inv_norm_diff; // compute cross product and reweight using distance B_x += invDist3 * (dgamma_by_dphi[j].y * diff_z - dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (dgamma_by_dphi[j].z * diff_x - dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (dgamma_by_dphi[j].x * diff_y - dgamma_by_dphi[j].y * diff_x); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } // GPU version, using rsqrt, shared memory,ntargets == nsources are multiples of BLOCK_SIZE __global__ void GPU_rsqrt_biot_savart_B(int num_points, int num_quad_points, Vec3d *points, Vec3d *gamma, Vec3d *dgamma_by_dphi, Vec3d *B) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < num_points) { // initialize double B_x = 0.; double B_y = 0.; double B_z = 0.; for (int tile = 0; tile < gridDim.x; tile++) { // shared memory __shared__ Vec3d share_gamma[BLOCK_SIZE]; __shared__ Vec3d share_dgamma_by_dphi[BLOCK_SIZE]; share_gamma[threadIdx.x] = gamma[tile*blockDim.x + threadIdx.x]; share_dgamma_by_dphi[threadIdx.x] = dgamma_by_dphi[tile*blockDim.x + threadIdx.x]; __syncthreads(); // In block, compute B-S //#pragma unroll for (int j = 0; j < BLOCK_SIZE; j++){ // compute the vector from target to source double diff_x = points[i].x - share_gamma[j].x; double diff_y = points[i].y - share_gamma[j].y; double diff_z = points[i].z - share_gamma[j].z; // compute distance between target and source double distSqr = diff_x*diff_x + diff_y*diff_y + diff_z*diff_z; double inv_norm_diff = rsqrt(distSqr); double invDist3 = inv_norm_diff*inv_norm_diff*inv_norm_diff; // compute cross product and reweight using distance B_x += invDist3 * (share_dgamma_by_dphi[j].y * diff_z - share_dgamma_by_dphi[j].z * diff_y); B_y += invDist3 * (share_dgamma_by_dphi[j].z * diff_x - share_dgamma_by_dphi[j].x * diff_z); B_z += invDist3 * (share_dgamma_by_dphi[j].x * diff_y - share_dgamma_by_dphi[j].y * diff_x); } __syncthreads(); } B[i].x = B_x; B[i].y = B_y; B[i].z = B_z; } } int main(const int argc, const char** argv) { // set values const long PFIRST = pow(2, 10); const long PLAST = pow(2, 16); FILE * pFile; pFile = fopen ("data.txt","w"); Timer t; fprintf(pFile, " p "); fprintf(pFile, "t_CPU t_GPU_ns t_GPU t_ns_rs t_rs "); fprintf(pFile, "flops_CPU flops_GPU_ns flops_GPU flops_ns_rs flops_rs "); fprintf(pFile, "band_CPU band_GPU_ns band_GPU band_ns_rs band_rs "); //fprintf(pFile, "err_GPU_ns err_GPU err_ns_rs err_rs"); fprintf(pFile, "\n"); // allocate memory for (long p = PFIRST; p <= PLAST; p *= 2) { long nsources = p, ntargets = p; long repeat = 1e8/(nsources*ntargets)+1; long bytes_targets = 3 * ntargets * sizeof(double); long bytes_sources = 3 * nsources * sizeof(double); // CPU memory Vec3d *points = (Vec3d*) malloc(bytes_targets); Vec3d *gamma = (Vec3d*) malloc(bytes_sources); Vec3d *dgamma_by_dphi = (Vec3d*) malloc(bytes_sources); Vec3d *B = (Vec3d*) malloc(bytes_targets); // CPU computation Vec3d *B1 = (Vec3d*) malloc(bytes_targets); // GPU computation // GPU memory Vec3d *gpu_points, *gpu_gamma, *gpu_dgamma_by_dphi, *gpu_B; cudaMalloc(&gpu_points, bytes_targets); cudaMalloc(&gpu_gamma, bytes_sources); cudaMalloc(&gpu_dgamma_by_dphi, bytes_sources); cudaMalloc(&gpu_B, bytes_targets); int nBlocks = (ntargets + BLOCK_SIZE - 1) / BLOCK_SIZE; //initialize with randomized data randomizeVec3d(points, ntargets); randomizeVec3d(gamma, nsources); randomizeVec3d(dgamma_by_dphi, nsources); randomizeVec3d(B, ntargets); // copy data to GPU //cudaMemcpy(gpu_points, points, bytes_targets, cudaMemcpyHostToDevice); //cudaMemcpy(gpu_gamma, gamma, bytes_sources, cudaMemcpyHostToDevice); //cudaMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, cudaMemcpyHostToDevice); //cudaMemcpy(gpu_B, B, bytes_targets, cudaMemcpyHostToDevice); // CPU computation t.tic(); for (long i = 0; i < repeat; i++) { CPU_biot_savart_B(ntargets, nsources, points, gamma, dgamma_by_dphi, B); } double tt = t.toc(); double fp = repeat * 30*ntargets*nsources/tt/1e9; double bd = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt /1e9; // GPU nonsmem computation cudaDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { cudaMemcpy(gpu_points, points, bytes_targets, cudaMemcpyHostToDevice); cudaMemcpy(gpu_gamma, gamma, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_B, B, bytes_targets, cudaMemcpyHostToDevice); GPU_nosmem_biot_savart_B<<<nBlocks, BLOCK_SIZE>>>(ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); cudaMemcpy(B1, gpu_B, bytes_targets, cudaMemcpyDeviceToHost); } cudaDeviceSynchronize(); double tt1 = t.toc(); double fp1 = repeat * 30*ntargets*nsources/tt1/1e9; double bd1 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt1 /1e9; double err1 = errorVec3d_LInf(B, B1, ntargets); // GPU computation with shared memory cudaDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { cudaMemcpy(gpu_points, points, bytes_targets, cudaMemcpyHostToDevice); cudaMemcpy(gpu_gamma, gamma, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_B, B, bytes_targets, cudaMemcpyHostToDevice); GPU_biot_savart_B<<<nBlocks, BLOCK_SIZE>>>(ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); cudaMemcpy(B1, gpu_B, bytes_targets, cudaMemcpyDeviceToHost); } cudaDeviceSynchronize(); double tt2 = t.toc(); double fp2 = repeat * 30*ntargets*nsources/tt2/1e9; double bd2 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt2 /1e9; double err2 = errorVec3d_LInf(B, B1, ntargets); // GPU nonsmem computation using rsqrt cudaDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { cudaMemcpy(gpu_points, points, bytes_targets, cudaMemcpyHostToDevice); cudaMemcpy(gpu_gamma, gamma, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_B, B, bytes_targets, cudaMemcpyHostToDevice); GPU_rsqrt_nosmem_biot_savart_B<<<nBlocks, BLOCK_SIZE>>>(ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); cudaMemcpy(B1, gpu_B, bytes_targets, cudaMemcpyDeviceToHost); } cudaDeviceSynchronize(); double tt3 = t.toc(); double fp3 = repeat * 29*ntargets*nsources/tt3/1e9; double bd3 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt3 /1e9; double err3 = errorVec3d_LInf(B, B1, ntargets); // GPU computation with shared memory, using rsqrt cudaDeviceSynchronize(); t.tic(); for (long i = 0; i < repeat; i++) { cudaMemcpy(gpu_points, points, bytes_targets, cudaMemcpyHostToDevice); cudaMemcpy(gpu_gamma, gamma, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_dgamma_by_dphi, dgamma_by_dphi, bytes_sources, cudaMemcpyHostToDevice); cudaMemcpy(gpu_B, B, bytes_targets, cudaMemcpyHostToDevice); GPU_rsqrt_biot_savart_B<<<nBlocks, BLOCK_SIZE>>>(ntargets, nsources, gpu_points, gpu_gamma, gpu_dgamma_by_dphi, gpu_B); cudaMemcpy(B1, gpu_B, bytes_targets, cudaMemcpyDeviceToHost); } cudaDeviceSynchronize(); double tt4 = t.toc(); double fp4 = repeat * 29*ntargets*nsources/tt4/1e9; double bd4 = repeat*(2*bytes_targets+2*ntargets*bytes_sources)/ tt4 /1e9; double err4 = errorVec3d_LInf(B, B1, ntargets); fprintf(pFile, "%10d ", p); fprintf(pFile, "%10f %10f %10f %10f %10f ", tt/repeat, tt1/repeat, tt2/repeat, tt3/repeat, tt4/repeat); fprintf(pFile, "%10f %10f %10f %10f %10f ", fp, fp1, fp2, fp3, fp4); fprintf(pFile, "%10f %10f %10f %10f %10f ", bd, bd1, bd2, bd3, bd4); // fprintf(pFile, "%10f %10f %10f %10f", err1, err2, err3, err4); fprintf(pFile, "\n"); // print some results // for (int i = 0; i < 2; i++){ // printf(" %e, %e | %e, %e | %e, %e\n", B[i].x, B1[i].x, B[i].y, B1[i].y, B[i].z, B1[i].z); //} // free memory free(points); free(gamma); free(dgamma_by_dphi); free(B); free(B1); cudaFree(gpu_points); cudaFree(gpu_gamma); cudaFree(gpu_dgamma_by_dphi); cudaFree(gpu_B); } fclose (pFile); }
7cbb050ef7bf480632891bf1ba3d25a0e7e45704.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // N- #include <iostream> __global__ void add(int *a, int *b, int *c) { c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x]; } void random_ints(int *a, int n) { int i; for (i = 0; i < n; ++i) a[i] = rand() %5000; } #define N 512 int main(void) { // host a, b, c int *a, *b, *c; // device a, b, c int *dev_a, *dev_b, *dev_c; int size = N * sizeof(int); // device a, b, c hipMalloc((void**)&dev_a, size); hipMalloc((void**)&dev_b, size); hipMalloc((void**)&dev_c, size); a = (int*)malloc(size); b = (int*)malloc(size); c = (int*)malloc(size); random_ints(a, N); random_ints(b, N); // device hipMemcpy(dev_a, a, size, hipMemcpyHostToDevice); hipMemcpy(dev_b, b, size, hipMemcpyHostToDevice); // launch add() kernel with N parallel blocks hipLaunchKernelGGL(( add), dim3(N), dim3(1) , 0, 0, dev_a, dev_b, dev_c); // device host c hipMemcpy(c, dev_c, size, hipMemcpyDeviceToHost); for (std::size_t i = 0; i < 10; ++i) { std::cout << a[i] << "+" << b[i] << "=" << c[i] << std::endl; } free(a); free(b); free(c); hipFree(dev_a); hipFree(dev_b); hipFree(dev_c); return 0; }
7cbb050ef7bf480632891bf1ba3d25a0e7e45704.cu
// Сложение двух чисел с использованием N-блоков по одному треду #include <iostream> __global__ void add(int *a, int *b, int *c) { c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x]; } void random_ints(int *a, int n) { int i; for (i = 0; i < n; ++i) a[i] = rand() %5000; } #define N 512 int main(void) { // host копии a, b, c int *a, *b, *c; // device копии a, b, c int *dev_a, *dev_b, *dev_c; int size = N * sizeof(int); //выделяем память для device копий a, b, c cudaMalloc((void**)&dev_a, size); cudaMalloc((void**)&dev_b, size); cudaMalloc((void**)&dev_c, size); a = (int*)malloc(size); b = (int*)malloc(size); c = (int*)malloc(size); random_ints(a, N); random_ints(b, N); // копируем ввод на device cudaMemcpy(dev_a, a, size, cudaMemcpyHostToDevice); cudaMemcpy(dev_b, b, size, cudaMemcpyHostToDevice); // launch add() kernel with N parallel blocks add<<< N, 1 >>>(dev_a, dev_b, dev_c); // копируем результат работы device обратно на host – копию c cudaMemcpy(c, dev_c, size, cudaMemcpyDeviceToHost); for (std::size_t i = 0; i < 10; ++i) { std::cout << a[i] << "+" << b[i] << "=" << c[i] << std::endl; } free(a); free(b); free(c); cudaFree(dev_a); cudaFree(dev_b); cudaFree(dev_c); return 0; }
b621f15c8bdabf4e62e8892984753cbc8414bd6d.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (C) 2009-2010, NVIDIA Corporation, all rights reserved. * Third party copyrights are property of their respective owners. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: $ * Ported to PCL by Koen Buys : Attention Work in progress! */ //////////////////////////////////////////////////////////////////////////////// // // NVIDIA CUDA implementation of Viola-Jones Object Detection Framework // // The algorithm and code are explained in the upcoming GPU Computing Gems // chapter in detail: // // Anton Obukhov, "Haar Classifiers for Object Detection with CUDA" // PDF URL placeholder // email: aobukhov@nvidia.com, devsupport@nvidia.com // // Credits for help with the code to: // Alexey Mendelenko, Cyril Crassin, and Mikhail Smirnov. // //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <cstdio> #include "NCV.hpp" #include "NCVAlg.hpp" #include "NPP_staging.hpp" #include "NCVRuntimeTemplates.hpp" #include "NCVHaarObjectDetection.hpp" //============================================================================== // // BlockScan file // //============================================================================== NCV_CT_ASSERT(K_WARP_SIZE == 32); //this is required for the manual unroll of the loop in warpScanInclusive //Almost the same as naive scan1Inclusive, but doesn't need __syncthreads() //assuming size <= WARP_SIZE and size is power of 2 __device__ Ncv32u warpScanInclusive(Ncv32u idata, volatile Ncv32u *s_Data) { Ncv32u pos = 2 * threadIdx.x - (threadIdx.x & (K_WARP_SIZE - 1)); s_Data[pos] = 0; pos += K_WARP_SIZE; s_Data[pos] = idata; s_Data[pos] += s_Data[pos - 1]; s_Data[pos] += s_Data[pos - 2]; s_Data[pos] += s_Data[pos - 4]; s_Data[pos] += s_Data[pos - 8]; s_Data[pos] += s_Data[pos - 16]; return s_Data[pos]; } __device__ __forceinline__ Ncv32u warpScanExclusive(Ncv32u idata, volatile Ncv32u *s_Data) { return warpScanInclusive(idata, s_Data) - idata; } template <Ncv32u tiNumScanThreads> __device__ Ncv32u scan1Inclusive(Ncv32u idata, volatile Ncv32u *s_Data) { if (tiNumScanThreads > K_WARP_SIZE) { //Bottom-level inclusive warp scan Ncv32u warpResult = warpScanInclusive(idata, s_Data); //Save top elements of each warp for exclusive warp scan //sync to wait for warp scans to complete (because s_Data is being overwritten) __syncthreads(); if( (threadIdx.x & (K_WARP_SIZE - 1)) == (K_WARP_SIZE - 1) ) { s_Data[threadIdx.x >> K_LOG2_WARP_SIZE] = warpResult; } //wait for warp scans to complete __syncthreads(); if( threadIdx.x < (tiNumScanThreads / K_WARP_SIZE) ) { //grab top warp elements Ncv32u val = s_Data[threadIdx.x]; //calculate exclusive scan and write back to shared memory s_Data[threadIdx.x] = warpScanExclusive(val, s_Data); } //return updated warp scans with exclusive scan results __syncthreads(); return warpResult + s_Data[threadIdx.x >> K_LOG2_WARP_SIZE]; } else { return warpScanInclusive(idata, s_Data); } } //============================================================================== // // HaarClassifierCascade file // //============================================================================== const Ncv32u MAX_GRID_DIM = 65535; const Ncv32u NUM_THREADS_ANCHORSPARALLEL = 64; #define NUM_THREADS_CLASSIFIERPARALLEL_LOG2 6 #define NUM_THREADS_CLASSIFIERPARALLEL (1 << NUM_THREADS_CLASSIFIERPARALLEL_LOG2) /** \internal * Haar features solid array. */ texture<uint2, 1, hipReadModeElementType> texHaarFeatures; /** \internal * Haar classifiers flattened trees container. * Two parts: first contains root nodes, second - nodes that are referred by root nodes. * Drawback: breaks tree locality (might cause more cache misses * Advantage: No need to introduce additional 32-bit field to index root nodes offsets */ texture<uint4, 1, hipReadModeElementType> texHaarClassifierNodes; texture<Ncv32u, 1, hipReadModeElementType> texIImage; __device__ HaarStage64 getStage(Ncv32u iStage, HaarStage64 *d_Stages) { return d_Stages[iStage]; } template <NcvBool tbCacheTextureCascade> __device__ HaarClassifierNode128 getClassifierNode(Ncv32u iNode, HaarClassifierNode128 *d_ClassifierNodes) { HaarClassifierNode128 tmpNode; if (tbCacheTextureCascade) { tmpNode._ui4 = tex1Dfetch(texHaarClassifierNodes, iNode); } else { tmpNode = d_ClassifierNodes[iNode]; } return tmpNode; } template <NcvBool tbCacheTextureCascade> __device__ void getFeature(Ncv32u iFeature, HaarFeature64 *d_Features, Ncv32f *weight, Ncv32u *rectX, Ncv32u *rectY, Ncv32u *rectWidth, Ncv32u *rectHeight) { HaarFeature64 feature; if (tbCacheTextureCascade) { feature._ui2 = tex1Dfetch(texHaarFeatures, iFeature); } else { feature = d_Features[iFeature]; } feature.getRect(rectX, rectY, rectWidth, rectHeight); *weight = feature.getWeight(); } template <NcvBool tbCacheTextureIImg> __device__ Ncv32u getElemIImg(Ncv32u x, Ncv32u *d_IImg) { if (tbCacheTextureIImg) { return tex1Dfetch(texIImage, x); } else { return d_IImg[x]; } } __device__ Ncv32u d_outMaskPosition; __device__ void compactBlockWriteOutAnchorParallel(Ncv32u threadPassFlag, Ncv32u threadElem, Ncv32u *vectorOut) { __shared__ Ncv32u shmem[NUM_THREADS_ANCHORSPARALLEL * 2]; __shared__ Ncv32u numPassed; __shared__ Ncv32u outMaskOffset; Ncv32u incScan = scan1Inclusive<NUM_THREADS_ANCHORSPARALLEL>(threadPassFlag, shmem); __syncthreads(); if (threadIdx.x == NUM_THREADS_ANCHORSPARALLEL-1) { numPassed = incScan; outMaskOffset = atomicAdd(&d_outMaskPosition, incScan); } if (threadPassFlag) { Ncv32u excScan = incScan - threadPassFlag; shmem[excScan] = threadElem; } __syncthreads(); if (threadIdx.x < numPassed) { vectorOut[outMaskOffset + threadIdx.x] = shmem[threadIdx.x]; } } template <NcvBool tbInitMaskPositively, NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbReadPixelIndexFromVector, NcvBool tbDoAtomicCompaction> __global__ void applyHaarClassifierAnchorParallel(Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { Ncv32u y_offs; Ncv32u x_offs; Ncv32u maskOffset; Ncv32u outMaskVal; NcvBool bInactiveThread = false; if (tbReadPixelIndexFromVector) { maskOffset = (MAX_GRID_DIM * blockIdx.y + blockIdx.x) * NUM_THREADS_ANCHORSPARALLEL + threadIdx.x; if (maskOffset >= mask1Dlen) { if (tbDoAtomicCompaction) bInactiveThread = true; else return; } if (!tbDoAtomicCompaction || tbDoAtomicCompaction && !bInactiveThread) { outMaskVal = d_inMask[maskOffset]; y_offs = outMaskVal >> 16; x_offs = outMaskVal & 0xFFFF; } } else { y_offs = blockIdx.y; x_offs = blockIdx.x * NUM_THREADS_ANCHORSPARALLEL + threadIdx.x; if (x_offs >= mask2Dstride) { if (tbDoAtomicCompaction) bInactiveThread = true; else return; } if (!tbDoAtomicCompaction || tbDoAtomicCompaction && !bInactiveThread) { maskOffset = y_offs * mask2Dstride + x_offs; if ((x_offs >= anchorsRoi.width) || (!tbInitMaskPositively && d_inMask != d_outMask && d_inMask[maskOffset] == OBJDET_MASK_ELEMENT_INVALID_32U)) { if (tbDoAtomicCompaction) { bInactiveThread = true; } else { d_outMask[maskOffset] = OBJDET_MASK_ELEMENT_INVALID_32U; return; } } outMaskVal = (y_offs << 16) | x_offs; } } NcvBool bPass = true; if (!tbDoAtomicCompaction || tbDoAtomicCompaction) { Ncv32f pixelStdDev = 0.0f; if (!bInactiveThread) pixelStdDev = d_weights[y_offs * weightsStride + x_offs]; for (Ncv32u iStage = startStageInc; iStage < endStageExc; iStage++) { Ncv32f curStageSum = 0.0f; HaarStage64 curStage = getStage(iStage, d_Stages); Ncv32u numRootNodesInStage = curStage.getNumClassifierRootNodes(); Ncv32u curRootNodeOffset = curStage.getStartClassifierRootNodeOffset(); Ncv32f stageThreshold = curStage.getStageThreshold(); while (numRootNodesInStage--) { NcvBool bMoreNodesToTraverse = true; Ncv32u iNode = curRootNodeOffset; if (bPass && !bInactiveThread) { while (bMoreNodesToTraverse) { HaarClassifierNode128 curNode = getClassifierNode<tbCacheTextureCascade>(iNode, d_ClassifierNodes); HaarFeatureDescriptor32 featuresDesc = curNode.getFeatureDesc(); Ncv32u curNodeFeaturesNum = featuresDesc.getNumFeatures(); Ncv32u iFeature = featuresDesc.getFeaturesOffset(); Ncv32f curNodeVal = 0.0f; for (Ncv32u iRect=0; iRect<curNodeFeaturesNum; iRect++) { Ncv32f rectWeight; Ncv32u rectX, rectY, rectWidth, rectHeight; getFeature<tbCacheTextureCascade> (iFeature + iRect, d_Features, &rectWeight, &rectX, &rectY, &rectWidth, &rectHeight); Ncv32u iioffsTL = (y_offs + rectY) * IImgStride + (x_offs + rectX); Ncv32u iioffsTR = iioffsTL + rectWidth; Ncv32u iioffsBL = iioffsTL + rectHeight * IImgStride; Ncv32u iioffsBR = iioffsBL + rectWidth; Ncv32u rectSum = getElemIImg<tbCacheTextureIImg>(iioffsBR, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsBL, d_IImg) + getElemIImg<tbCacheTextureIImg>(iioffsTL, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsTR, d_IImg); #if defined CPU_FP_COMPLIANCE || defined DISABLE_MAD_SELECTIVELY curNodeVal += __fmul_rn((Ncv32f)rectSum, rectWeight); #else curNodeVal += (Ncv32f)rectSum * rectWeight; #endif } HaarClassifierNodeDescriptor32 nodeLeft = curNode.getLeftNodeDesc(); HaarClassifierNodeDescriptor32 nodeRight = curNode.getRightNodeDesc(); Ncv32f nodeThreshold = curNode.getThreshold(); HaarClassifierNodeDescriptor32 nextNodeDescriptor; NcvBool nextNodeIsLeaf; if (curNodeVal < scaleArea * pixelStdDev * nodeThreshold) { nextNodeDescriptor = nodeLeft; nextNodeIsLeaf = featuresDesc.isLeftNodeLeaf(); } else { nextNodeDescriptor = nodeRight; nextNodeIsLeaf = featuresDesc.isRightNodeLeaf(); } if (nextNodeIsLeaf) { Ncv32f tmpLeafValue = nextNodeDescriptor.getLeafValue(); curStageSum += tmpLeafValue; bMoreNodesToTraverse = false; } else { iNode = nextNodeDescriptor.getNextNodeOffset(); } } } __syncthreads(); curRootNodeOffset++; } if (curStageSum < stageThreshold) { bPass = false; outMaskVal = OBJDET_MASK_ELEMENT_INVALID_32U; } } } __syncthreads(); if (!tbDoAtomicCompaction) { if (!tbReadPixelIndexFromVector || (tbReadPixelIndexFromVector && (!bPass || d_inMask != d_outMask))) { d_outMask[maskOffset] = outMaskVal; } } else { compactBlockWriteOutAnchorParallel(bPass && !bInactiveThread, outMaskVal, d_outMask); } } template <NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbDoAtomicCompaction> __global__ void applyHaarClassifierClassifierParallel(Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { Ncv32u maskOffset = MAX_GRID_DIM * blockIdx.y + blockIdx.x; if (maskOffset >= mask1Dlen) { return; } Ncv32u outMaskVal = d_inMask[maskOffset]; Ncv32u y_offs = outMaskVal >> 16; Ncv32u x_offs = outMaskVal & 0xFFFF; Ncv32f pixelStdDev = d_weights[y_offs * weightsStride + x_offs]; NcvBool bPass = true; for (Ncv32u iStage = startStageInc; iStage<endStageExc; iStage++) { //this variable is subject to reduction Ncv32f curStageSum = 0.0f; HaarStage64 curStage = getStage(iStage, d_Stages); Ncv32s numRootNodesInStage = curStage.getNumClassifierRootNodes(); Ncv32u curRootNodeOffset = curStage.getStartClassifierRootNodeOffset() + threadIdx.x; Ncv32f stageThreshold = curStage.getStageThreshold(); Ncv32u numRootChunks = (numRootNodesInStage + NUM_THREADS_CLASSIFIERPARALLEL - 1) >> NUM_THREADS_CLASSIFIERPARALLEL_LOG2; for (Ncv32u chunkId=0; chunkId<numRootChunks; chunkId++) { NcvBool bMoreNodesToTraverse = true; if (chunkId * NUM_THREADS_CLASSIFIERPARALLEL + threadIdx.x < numRootNodesInStage) { Ncv32u iNode = curRootNodeOffset; while (bMoreNodesToTraverse) { HaarClassifierNode128 curNode = getClassifierNode<tbCacheTextureCascade>(iNode, d_ClassifierNodes); HaarFeatureDescriptor32 featuresDesc = curNode.getFeatureDesc(); Ncv32u curNodeFeaturesNum = featuresDesc.getNumFeatures(); Ncv32u iFeature = featuresDesc.getFeaturesOffset(); Ncv32f curNodeVal = 0.0f; //TODO: fetch into shmem if size suffices. Shmem can be shared with reduce for (Ncv32u iRect=0; iRect<curNodeFeaturesNum; iRect++) { Ncv32f rectWeight; Ncv32u rectX, rectY, rectWidth, rectHeight; getFeature<tbCacheTextureCascade> (iFeature + iRect, d_Features, &rectWeight, &rectX, &rectY, &rectWidth, &rectHeight); Ncv32u iioffsTL = (y_offs + rectY) * IImgStride + (x_offs + rectX); Ncv32u iioffsTR = iioffsTL + rectWidth; Ncv32u iioffsBL = iioffsTL + rectHeight * IImgStride; Ncv32u iioffsBR = iioffsBL + rectWidth; Ncv32u rectSum = getElemIImg<tbCacheTextureIImg>(iioffsBR, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsBL, d_IImg) + getElemIImg<tbCacheTextureIImg>(iioffsTL, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsTR, d_IImg); #if defined CPU_FP_COMPLIANCE || defined DISABLE_MAD_SELECTIVELY curNodeVal += __fmul_rn((Ncv32f)rectSum, rectWeight); #else curNodeVal += (Ncv32f)rectSum * rectWeight; #endif } HaarClassifierNodeDescriptor32 nodeLeft = curNode.getLeftNodeDesc(); HaarClassifierNodeDescriptor32 nodeRight = curNode.getRightNodeDesc(); Ncv32f nodeThreshold = curNode.getThreshold(); HaarClassifierNodeDescriptor32 nextNodeDescriptor; NcvBool nextNodeIsLeaf; if (curNodeVal < scaleArea * pixelStdDev * nodeThreshold) { nextNodeDescriptor = nodeLeft; nextNodeIsLeaf = featuresDesc.isLeftNodeLeaf(); } else { nextNodeDescriptor = nodeRight; nextNodeIsLeaf = featuresDesc.isRightNodeLeaf(); } if (nextNodeIsLeaf) { Ncv32f tmpLeafValue = nextNodeDescriptor.getLeafValue(); curStageSum += tmpLeafValue; bMoreNodesToTraverse = false; } else { iNode = nextNodeDescriptor.getNextNodeOffset(); } } } __syncthreads(); curRootNodeOffset += NUM_THREADS_CLASSIFIERPARALLEL; } Ncv32f finalStageSum = subReduce<Ncv32f, functorAddValues<Ncv32f>, NUM_THREADS_CLASSIFIERPARALLEL>(curStageSum); if (finalStageSum < stageThreshold) { bPass = false; outMaskVal = OBJDET_MASK_ELEMENT_INVALID_32U; break; } } if (!tbDoAtomicCompaction) { if (!bPass || d_inMask != d_outMask) { if (!threadIdx.x) { d_outMask[maskOffset] = outMaskVal; } } } else { if (bPass && !threadIdx.x) { Ncv32u outMaskOffset = atomicAdd(&d_outMaskPosition, 1); d_outMask[outMaskOffset] = outMaskVal; } } } template <NcvBool tbMaskByInmask, NcvBool tbDoAtomicCompaction> __global__ void initializeMaskVector(Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u step) { Ncv32u y_offs = blockIdx.y; Ncv32u x_offs = blockIdx.x * NUM_THREADS_ANCHORSPARALLEL + threadIdx.x; Ncv32u outMaskOffset = y_offs * gridDim.x * blockDim.x + x_offs; Ncv32u y_offs_upsc = step * y_offs; Ncv32u x_offs_upsc = step * x_offs; Ncv32u inMaskOffset = y_offs_upsc * mask2Dstride + x_offs_upsc; Ncv32u outElem = OBJDET_MASK_ELEMENT_INVALID_32U; if (x_offs_upsc < anchorsRoi.width && (!tbMaskByInmask || d_inMask[inMaskOffset] != OBJDET_MASK_ELEMENT_INVALID_32U)) { outElem = (y_offs_upsc << 16) | x_offs_upsc; } if (!tbDoAtomicCompaction) { d_outMask[outMaskOffset] = outElem; } else { compactBlockWriteOutAnchorParallel(outElem != OBJDET_MASK_ELEMENT_INVALID_32U, outElem, d_outMask); } } struct applyHaarClassifierAnchorParallelFunctor { dim3 gridConf, blockConf; hipStream_t cuStream; //Kernel arguments are stored as members; Ncv32u *d_IImg; Ncv32u IImgStride; Ncv32f *d_weights; Ncv32u weightsStride; HaarFeature64 *d_Features; HaarClassifierNode128 *d_ClassifierNodes; HaarStage64 *d_Stages; Ncv32u *d_inMask; Ncv32u *d_outMask; Ncv32u mask1Dlen; Ncv32u mask2Dstride; NcvSize32u anchorsRoi; Ncv32u startStageInc; Ncv32u endStageExc; Ncv32f scaleArea; //Arguments are passed through the constructor applyHaarClassifierAnchorParallelFunctor(dim3 _gridConf, dim3 _blockConf, hipStream_t _cuStream, Ncv32u *_d_IImg, Ncv32u _IImgStride, Ncv32f *_d_weights, Ncv32u _weightsStride, HaarFeature64 *_d_Features, HaarClassifierNode128 *_d_ClassifierNodes, HaarStage64 *_d_Stages, Ncv32u *_d_inMask, Ncv32u *_d_outMask, Ncv32u _mask1Dlen, Ncv32u _mask2Dstride, NcvSize32u _anchorsRoi, Ncv32u _startStageInc, Ncv32u _endStageExc, Ncv32f _scaleArea) : gridConf(_gridConf), blockConf(_blockConf), cuStream(_cuStream), d_IImg(_d_IImg), IImgStride(_IImgStride), d_weights(_d_weights), weightsStride(_weightsStride), d_Features(_d_Features), d_ClassifierNodes(_d_ClassifierNodes), d_Stages(_d_Stages), d_inMask(_d_inMask), d_outMask(_d_outMask), mask1Dlen(_mask1Dlen), mask2Dstride(_mask2Dstride), anchorsRoi(_anchorsRoi), startStageInc(_startStageInc), endStageExc(_endStageExc), scaleArea(_scaleArea) {} template<class TList> void call(TList tl) { hipLaunchKernelGGL(( applyHaarClassifierAnchorParallel < Loki::TL::TypeAt<TList, 0>::Result::value, Loki::TL::TypeAt<TList, 1>::Result::value, Loki::TL::TypeAt<TList, 2>::Result::value, Loki::TL::TypeAt<TList, 3>::Result::value, Loki::TL::TypeAt<TList, 4>::Result::value >) , dim3(gridConf), dim3(blockConf), 0, cuStream, d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); } }; void applyHaarClassifierAnchorParallelDynTemplate(NcvBool tbInitMaskPositively, NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbReadPixelIndexFromVector, NcvBool tbDoAtomicCompaction, dim3 gridConf, dim3 blockConf, hipStream_t cuStream, Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { applyHaarClassifierAnchorParallelFunctor functor(gridConf, blockConf, cuStream, d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); //Second parameter is the number of "dynamic" template parameters NCVRuntimeTemplateBool::KernelCaller<Loki::NullType, 5, applyHaarClassifierAnchorParallelFunctor> ::call( &functor, tbInitMaskPositively, tbCacheTextureIImg, tbCacheTextureCascade, tbReadPixelIndexFromVector, tbDoAtomicCompaction); } struct applyHaarClassifierClassifierParallelFunctor { dim3 gridConf, blockConf; hipStream_t cuStream; //Kernel arguments are stored as members; Ncv32u *d_IImg; Ncv32u IImgStride; Ncv32f *d_weights; Ncv32u weightsStride; HaarFeature64 *d_Features; HaarClassifierNode128 *d_ClassifierNodes; HaarStage64 *d_Stages; Ncv32u *d_inMask; Ncv32u *d_outMask; Ncv32u mask1Dlen; Ncv32u mask2Dstride; NcvSize32u anchorsRoi; Ncv32u startStageInc; Ncv32u endStageExc; Ncv32f scaleArea; //Arguments are passed through the constructor applyHaarClassifierClassifierParallelFunctor(dim3 _gridConf, dim3 _blockConf, hipStream_t _cuStream, Ncv32u *_d_IImg, Ncv32u _IImgStride, Ncv32f *_d_weights, Ncv32u _weightsStride, HaarFeature64 *_d_Features, HaarClassifierNode128 *_d_ClassifierNodes, HaarStage64 *_d_Stages, Ncv32u *_d_inMask, Ncv32u *_d_outMask, Ncv32u _mask1Dlen, Ncv32u _mask2Dstride, NcvSize32u _anchorsRoi, Ncv32u _startStageInc, Ncv32u _endStageExc, Ncv32f _scaleArea) : gridConf(_gridConf), blockConf(_blockConf), cuStream(_cuStream), d_IImg(_d_IImg), IImgStride(_IImgStride), d_weights(_d_weights), weightsStride(_weightsStride), d_Features(_d_Features), d_ClassifierNodes(_d_ClassifierNodes), d_Stages(_d_Stages), d_inMask(_d_inMask), d_outMask(_d_outMask), mask1Dlen(_mask1Dlen), mask2Dstride(_mask2Dstride), anchorsRoi(_anchorsRoi), startStageInc(_startStageInc), endStageExc(_endStageExc), scaleArea(_scaleArea) {} template<class TList> void call(TList tl) { hipLaunchKernelGGL(( applyHaarClassifierClassifierParallel < Loki::TL::TypeAt<TList, 0>::Result::value, Loki::TL::TypeAt<TList, 1>::Result::value, Loki::TL::TypeAt<TList, 2>::Result::value >) , dim3(gridConf), dim3(blockConf), 0, cuStream, d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); } }; void applyHaarClassifierClassifierParallelDynTemplate(NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbDoAtomicCompaction, dim3 gridConf, dim3 blockConf, hipStream_t cuStream, Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { applyHaarClassifierClassifierParallelFunctor functor(gridConf, blockConf, cuStream, d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); //Second parameter is the number of "dynamic" template parameters NCVRuntimeTemplateBool::KernelCaller<Loki::NullType, 3, applyHaarClassifierClassifierParallelFunctor> ::call( &functor, tbCacheTextureIImg, tbCacheTextureCascade, tbDoAtomicCompaction); } struct initializeMaskVectorFunctor { dim3 gridConf, blockConf; hipStream_t cuStream; //Kernel arguments are stored as members; Ncv32u *d_inMask; Ncv32u *d_outMask; Ncv32u mask1Dlen; Ncv32u mask2Dstride; NcvSize32u anchorsRoi; Ncv32u step; //Arguments are passed through the constructor initializeMaskVectorFunctor(dim3 _gridConf, dim3 _blockConf, hipStream_t _cuStream, Ncv32u *_d_inMask, Ncv32u *_d_outMask, Ncv32u _mask1Dlen, Ncv32u _mask2Dstride, NcvSize32u _anchorsRoi, Ncv32u _step) : gridConf(_gridConf), blockConf(_blockConf), cuStream(_cuStream), d_inMask(_d_inMask), d_outMask(_d_outMask), mask1Dlen(_mask1Dlen), mask2Dstride(_mask2Dstride), anchorsRoi(_anchorsRoi), step(_step) {} template<class TList> void call(TList tl) { hipLaunchKernelGGL(( initializeMaskVector < Loki::TL::TypeAt<TList, 0>::Result::value, Loki::TL::TypeAt<TList, 1>::Result::value >) , dim3(gridConf), dim3(blockConf), 0, cuStream, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, step); } }; void initializeMaskVectorDynTemplate(NcvBool tbMaskByInmask, NcvBool tbDoAtomicCompaction, dim3 gridConf, dim3 blockConf, hipStream_t cuStream, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u step) { initializeMaskVectorFunctor functor(gridConf, blockConf, cuStream, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, step); //Second parameter is the number of "dynamic" template parameters NCVRuntimeTemplateBool::KernelCaller<Loki::NullType, 2, initializeMaskVectorFunctor> ::call( &functor, tbMaskByInmask, tbDoAtomicCompaction); } Ncv32u getStageNumWithNotLessThanNclassifiers(Ncv32u N, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages) { for (Ncv32u i = 0; i<haar.NumStages; i++) { if (h_HaarStages.ptr()[i].getNumClassifierRootNodes() >= N) { return i; } } return haar.NumStages; } NCVStatus ncvApplyHaarClassifierCascade_device(NCVMatrix<Ncv32u> &d_integralImage, NCVMatrix<Ncv32f> &d_weights, NCVMatrixAlloc<Ncv32u> &d_pixelMask, Ncv32u &numDetections, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarStage64> &d_HaarStages, NCVVector<HaarClassifierNode128> &d_HaarNodes, NCVVector<HaarFeature64> &d_HaarFeatures, NcvBool bMaskElements, NcvSize32u anchorsRoi, Ncv32u pixelStep, Ncv32f scaleArea, INCVMemAllocator &gpuAllocator, INCVMemAllocator &cpuAllocator, hipDeviceProp_t &devProp, hipStream_t cuStream) { ncvAssertReturn(d_integralImage.memType() == d_weights.memType() && d_integralImage.memType() == d_pixelMask.memType() && d_integralImage.memType() == gpuAllocator.memType() && (d_integralImage.memType() == NCVMemoryTypeDevice || d_integralImage.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(d_HaarStages.memType() == d_HaarNodes.memType() && d_HaarStages.memType() == d_HaarFeatures.memType() && (d_HaarStages.memType() == NCVMemoryTypeDevice || d_HaarStages.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_HaarStages.memType() != NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(gpuAllocator.isInitialized() && cpuAllocator.isInitialized(), NCV_ALLOCATOR_NOT_INITIALIZED); ncvAssertReturn((d_integralImage.ptr() != NULL && d_weights.ptr() != NULL && d_pixelMask.ptr() != NULL && h_HaarStages.ptr() != NULL && d_HaarStages.ptr() != NULL && d_HaarNodes.ptr() != NULL && d_HaarFeatures.ptr() != NULL) || gpuAllocator.isCounting(), NCV_NULL_PTR); ncvAssertReturn(anchorsRoi.width > 0 && anchorsRoi.height > 0 && d_pixelMask.width() >= anchorsRoi.width && d_pixelMask.height() >= anchorsRoi.height && d_weights.width() >= anchorsRoi.width && d_weights.height() >= anchorsRoi.height && d_integralImage.width() >= anchorsRoi.width + haar.ClassifierSize.width && d_integralImage.height() >= anchorsRoi.height + haar.ClassifierSize.height, NCV_DIMENSIONS_INVALID); ncvAssertReturn(scaleArea > 0, NCV_INVALID_SCALE); ncvAssertReturn(d_HaarStages.length() >= haar.NumStages && d_HaarNodes.length() >= haar.NumClassifierTotalNodes && d_HaarFeatures.length() >= haar.NumFeatures && d_HaarStages.length() == h_HaarStages.length() && haar.NumClassifierRootNodes <= haar.NumClassifierTotalNodes, NCV_DIMENSIONS_INVALID); ncvAssertReturn(haar.bNeedsTiltedII == false || gpuAllocator.isCounting(), NCV_NOIMPL_HAAR_TILTED_FEATURES); ncvAssertReturn(pixelStep == 1 || pixelStep == 2, NCV_HAAR_INVALID_PIXEL_STEP); NCV_SET_SKIP_COND(gpuAllocator.isCounting()); #if defined _SELF_TEST_ NCVStatus ncvStat; NCVMatrixAlloc<Ncv32u> h_integralImage(cpuAllocator, d_integralImage.width, d_integralImage.height, d_integralImage.pitch); ncvAssertReturn(h_integralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32f> h_weights(cpuAllocator, d_weights.width, d_weights.height, d_weights.pitch); ncvAssertReturn(h_weights.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> h_pixelMask(cpuAllocator, d_pixelMask.width, d_pixelMask.height, d_pixelMask.pitch); ncvAssertReturn(h_pixelMask.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<HaarClassifierNode128> h_HaarNodes(cpuAllocator, d_HaarNodes.length); ncvAssertReturn(h_HaarNodes.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<HaarFeature64> h_HaarFeatures(cpuAllocator, d_HaarFeatures.length); ncvAssertReturn(h_HaarFeatures.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> h_pixelMask_d(cpuAllocator, d_pixelMask.width, d_pixelMask.height, d_pixelMask.pitch); ncvAssertReturn(h_pixelMask_d.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCV_SKIP_COND_BEGIN ncvStat = d_pixelMask.copySolid(h_pixelMask, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_integralImage.copySolid(h_integralImage, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_weights.copySolid(h_weights, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_HaarNodes.copySolid(h_HaarNodes, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_HaarFeatures.copySolid(h_HaarFeatures, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(hipStreamSynchronize(0), NCV_CUDA_ERROR); for (Ncv32u i=0; i<(Ncv32u)anchorsRoi.height; i++) { for (Ncv32u j=0; j<d_pixelMask.stride(); j++) { if ((i%pixelStep==0) && (j%pixelStep==0) && (j<(Ncv32u)anchorsRoi.width)) { if (!bMaskElements || h_pixelMask.ptr[i*d_pixelMask.stride()+j] != OBJDET_MASK_ELEMENT_INVALID_32U) { h_pixelMask.ptr[i*d_pixelMask.stride()+j] = (i << 16) | j; } } else { h_pixelMask.ptr[i*d_pixelMask.stride()+j] = OBJDET_MASK_ELEMENT_INVALID_32U; } } } NCV_SKIP_COND_END #endif NCVVectorReuse<Ncv32u> d_vecPixelMask(d_pixelMask.getSegment(), anchorsRoi.height * d_pixelMask.stride()); ncvAssertReturn(d_vecPixelMask.isMemReused(), NCV_ALLOCATOR_BAD_REUSE); NCVVectorAlloc<Ncv32u> d_vecPixelMaskTmp(gpuAllocator, static_cast<Ncv32u>(d_vecPixelMask.length())); ncvAssertReturn(d_vecPixelMaskTmp.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<Ncv32u> hp_pool32u(cpuAllocator, 2); ncvAssertReturn(hp_pool32u.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); Ncv32u *hp_zero = &hp_pool32u.ptr()[0]; Ncv32u *hp_numDet = &hp_pool32u.ptr()[1]; NCV_SKIP_COND_BEGIN *hp_zero = 0; *hp_numDet = 0; NCV_SKIP_COND_END Ncv32f scaleAreaPixels = scaleArea * ((haar.ClassifierSize.width - 2*HAAR_STDDEV_BORDER) * (haar.ClassifierSize.height - 2*HAAR_STDDEV_BORDER)); NcvBool bTexCacheCascade = devProp.major < 2; NcvBool bTexCacheIImg = true; //this works better even on Fermi so far NcvBool bDoAtomicCompaction = devProp.major >= 2 || (devProp.major == 1 && devProp.minor >= 3); NCVVector<Ncv32u> *d_ptrNowData = &d_vecPixelMask; NCVVector<Ncv32u> *d_ptrNowTmp = &d_vecPixelMaskTmp; Ncv32u szNppCompactTmpBuf; nppsStCompactGetSize_32u(static_cast<Ncv32u>(d_vecPixelMask.length()), &szNppCompactTmpBuf, devProp); if (bDoAtomicCompaction) { szNppCompactTmpBuf = 0; } NCVVectorAlloc<Ncv8u> d_tmpBufCompact(gpuAllocator, szNppCompactTmpBuf); NCV_SKIP_COND_BEGIN if (bTexCacheIImg) { hipChannelFormatDesc cfdTexIImage; cfdTexIImage = hipCreateChannelDesc<Ncv32u>(); std::size_t alignmentOffset; ncvAssertCUDAReturn(hipBindTexture(&alignmentOffset, texIImage, d_integralImage.ptr(), cfdTexIImage, (anchorsRoi.height + haar.ClassifierSize.height) * d_integralImage.pitch()), NCV_CUDA_ERROR); ncvAssertReturn(alignmentOffset==0, NCV_TEXTURE_BIND_ERROR); } if (bTexCacheCascade) { hipChannelFormatDesc cfdTexHaarFeatures; hipChannelFormatDesc cfdTexHaarClassifierNodes; cfdTexHaarFeatures = hipCreateChannelDesc<uint2>(); cfdTexHaarClassifierNodes = hipCreateChannelDesc<uint4>(); std::size_t alignmentOffset; ncvAssertCUDAReturn(hipBindTexture(&alignmentOffset, texHaarFeatures, d_HaarFeatures.ptr(), cfdTexHaarFeatures,sizeof(HaarFeature64) * haar.NumFeatures), NCV_CUDA_ERROR); ncvAssertReturn(alignmentOffset==0, NCV_TEXTURE_BIND_ERROR); ncvAssertCUDAReturn(hipBindTexture(&alignmentOffset, texHaarClassifierNodes, d_HaarNodes.ptr(), cfdTexHaarClassifierNodes, sizeof(HaarClassifierNode128) * haar.NumClassifierTotalNodes), NCV_CUDA_ERROR); ncvAssertReturn(alignmentOffset==0, NCV_TEXTURE_BIND_ERROR); } Ncv32u stageStartAnchorParallel = 0; Ncv32u stageMiddleSwitch = getStageNumWithNotLessThanNclassifiers(NUM_THREADS_CLASSIFIERPARALLEL, haar, h_HaarStages); Ncv32u stageEndClassifierParallel = haar.NumStages; if (stageMiddleSwitch == 0) { stageMiddleSwitch = 1; } //create stages subdivision for pixel-parallel processing const Ncv32u compactEveryNstage = bDoAtomicCompaction ? 7 : 1; Ncv32u curStop = stageStartAnchorParallel; std::vector<Ncv32u> pixParallelStageStops; while (curStop < stageMiddleSwitch) { pixParallelStageStops.push_back(curStop); curStop += compactEveryNstage; } if (curStop > compactEveryNstage && curStop - stageMiddleSwitch > compactEveryNstage / 2) { pixParallelStageStops[pixParallelStageStops.size()-1] = (stageMiddleSwitch - (curStop - 2 * compactEveryNstage)) / 2; } pixParallelStageStops.push_back(stageMiddleSwitch); Ncv32u pixParallelStageStopsIndex = 0; if (pixelStep != 1 || bMaskElements) { if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, hipMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 gridInit((((anchorsRoi.width + pixelStep - 1) / pixelStep + NUM_THREADS_ANCHORSPARALLEL - 1) / NUM_THREADS_ANCHORSPARALLEL), (anchorsRoi.height + pixelStep - 1) / pixelStep); dim3 blockInit(NUM_THREADS_ANCHORSPARALLEL); if (gridInit.x == 0 || gridInit.y == 0) { numDetections = 0; return NCV_SUCCESS; } initializeMaskVectorDynTemplate(bMaskElements, bDoAtomicCompaction, gridInit, blockInit, cuStream, d_ptrNowData->ptr(), d_ptrNowTmp->ptr(), static_cast<Ncv32u>(d_vecPixelMask.length()), d_pixelMask.stride(), anchorsRoi, pixelStep); ncvAssertCUDAReturn(hipGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, hipMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); swap(d_ptrNowData, d_ptrNowTmp); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowTmp->ptr(), static_cast<Ncv32u>(d_vecPixelMask.length()), d_ptrNowData->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturn(nppSt == NPPST_SUCCESS, NCV_NPP_ERROR); } numDetections = *hp_numDet; } else { // // 1. Run the first pixel-input pixel-parallel classifier for few stages // if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, hipMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 grid1(((d_pixelMask.stride() + NUM_THREADS_ANCHORSPARALLEL - 1) / NUM_THREADS_ANCHORSPARALLEL), anchorsRoi.height); dim3 block1(NUM_THREADS_ANCHORSPARALLEL); applyHaarClassifierAnchorParallelDynTemplate( true, //tbInitMaskPositively bTexCacheIImg, //tbCacheTextureIImg bTexCacheCascade, //tbCacheTextureCascade pixParallelStageStops[pixParallelStageStopsIndex] != 0,//tbReadPixelIndexFromVector bDoAtomicCompaction, //tbDoAtomicCompaction grid1, block1, cuStream, d_integralImage.ptr(), d_integralImage.stride(), d_weights.ptr(), d_weights.stride(), d_HaarFeatures.ptr(), d_HaarNodes.ptr(), d_HaarStages.ptr(), d_ptrNowData->ptr(), bDoAtomicCompaction ? d_ptrNowTmp->ptr() : d_ptrNowData->ptr(), 0, d_pixelMask.stride(), anchorsRoi, pixParallelStageStops[pixParallelStageStopsIndex], pixParallelStageStops[pixParallelStageStopsIndex+1], scaleAreaPixels); ncvAssertCUDAReturn(hipGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, hipMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowData->ptr(), static_cast<Ncv32u>(d_vecPixelMask.length()), d_ptrNowTmp->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturnNcvStat(nppSt); } swap(d_ptrNowData, d_ptrNowTmp); numDetections = *hp_numDet; pixParallelStageStopsIndex++; } // // 2. Run pixel-parallel stages // for (; pixParallelStageStopsIndex < pixParallelStageStops.size()-1; pixParallelStageStopsIndex++) { if (numDetections == 0) { break; } if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, hipMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 grid2((numDetections + NUM_THREADS_ANCHORSPARALLEL - 1) / NUM_THREADS_ANCHORSPARALLEL); if (numDetections > MAX_GRID_DIM) { grid2.x = MAX_GRID_DIM; grid2.y = (numDetections + MAX_GRID_DIM - 1) / MAX_GRID_DIM; } dim3 block2(NUM_THREADS_ANCHORSPARALLEL); applyHaarClassifierAnchorParallelDynTemplate( false, //tbInitMaskPositively bTexCacheIImg, //tbCacheTextureIImg bTexCacheCascade, //tbCacheTextureCascade pixParallelStageStops[pixParallelStageStopsIndex] != 0 || pixelStep != 1 || bMaskElements,//tbReadPixelIndexFromVector bDoAtomicCompaction, //tbDoAtomicCompaction grid2, block2, cuStream, d_integralImage.ptr(), d_integralImage.stride(), d_weights.ptr(), d_weights.stride(), d_HaarFeatures.ptr(), d_HaarNodes.ptr(), d_HaarStages.ptr(), d_ptrNowData->ptr(), bDoAtomicCompaction ? d_ptrNowTmp->ptr() : d_ptrNowData->ptr(), numDetections, d_pixelMask.stride(), anchorsRoi, pixParallelStageStops[pixParallelStageStopsIndex], pixParallelStageStops[pixParallelStageStopsIndex+1], scaleAreaPixels); ncvAssertCUDAReturn(hipGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, hipMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowData->ptr(), numDetections, d_ptrNowTmp->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturnNcvStat(nppSt); } swap(d_ptrNowData, d_ptrNowTmp); numDetections = *hp_numDet; } // // 3. Run all left stages in one stage-parallel kernel // if (numDetections > 0 && stageMiddleSwitch < stageEndClassifierParallel) { if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, hipMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 grid3(numDetections); if (numDetections > MAX_GRID_DIM) { grid3.x = MAX_GRID_DIM; grid3.y = (numDetections + MAX_GRID_DIM - 1) / MAX_GRID_DIM; } dim3 block3(NUM_THREADS_CLASSIFIERPARALLEL); applyHaarClassifierClassifierParallelDynTemplate( bTexCacheIImg, //tbCacheTextureIImg bTexCacheCascade, //tbCacheTextureCascade bDoAtomicCompaction, //tbDoAtomicCompaction grid3, block3, cuStream, d_integralImage.ptr(), d_integralImage.stride(), d_weights.ptr(), d_weights.stride(), d_HaarFeatures.ptr(), d_HaarNodes.ptr(), d_HaarStages.ptr(), d_ptrNowData->ptr(), bDoAtomicCompaction ? d_ptrNowTmp->ptr() : d_ptrNowData->ptr(), numDetections, d_pixelMask.stride(), anchorsRoi, stageMiddleSwitch, stageEndClassifierParallel, scaleAreaPixels); ncvAssertCUDAReturn(hipGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, hipMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowData->ptr(), numDetections, d_ptrNowTmp->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturnNcvStat(nppSt); } swap(d_ptrNowData, d_ptrNowTmp); numDetections = *hp_numDet; } if (d_ptrNowData != &d_vecPixelMask) { d_vecPixelMaskTmp.copySolid(d_vecPixelMask, cuStream); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } #if defined _SELF_TEST_ ncvStat = d_pixelMask.copySolid(h_pixelMask_d, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { std::sort(h_pixelMask_d.ptr, h_pixelMask_d.ptr + numDetections); } Ncv32u fpu_oldcw, fpu_cw; _controlfp_s(&fpu_cw, 0, 0); fpu_oldcw = fpu_cw; _controlfp_s(&fpu_cw, _PC_24, _MCW_PC); Ncv32u numDetGold; ncvStat = ncvApplyHaarClassifierCascade_host(h_integralImage, h_weights, h_pixelMask, numDetGold, haar, h_HaarStages, h_HaarNodes, h_HaarFeatures, bMaskElements, anchorsRoi, pixelStep, scaleArea); ncvAssertReturnNcvStat(ncvStat); _controlfp_s(&fpu_cw, fpu_oldcw, _MCW_PC); bool bPass = true; if (numDetGold != numDetections) { printf("NCVHaarClassifierCascade::applyHaarClassifierCascade numdetections don't match: cpu=%d, gpu=%d\n", numDetGold, numDetections); bPass = false; } else { for (Ncv32u i=0; i<::max(numDetGold, numDetections) && bPass; i++) { if (h_pixelMask.ptr[i] != h_pixelMask_d.ptr[i]) { printf("NCVHaarClassifierCascade::applyHaarClassifierCascade self test failed: i=%d, cpu=%d, gpu=%d\n", i, h_pixelMask.ptr[i], h_pixelMask_d.ptr[i]); bPass = false; } } } printf("NCVHaarClassifierCascade::applyHaarClassifierCascade %s\n", bPass?"PASSED":"FAILED"); #endif NCV_SKIP_COND_END return NCV_SUCCESS; } //============================================================================== // // HypothesesOperations file // //============================================================================== const Ncv32u NUM_GROW_THREADS = 128; __device__ __host__ NcvRect32u pixelToRect(Ncv32u pixel, Ncv32u width, Ncv32u height, Ncv32f scale) { NcvRect32u res; res.x = (Ncv32u)(scale * (pixel & 0xFFFF)); res.y = (Ncv32u)(scale * (pixel >> 16)); res.width = (Ncv32u)(scale * width); res.height = (Ncv32u)(scale * height); return res; } __global__ void growDetectionsKernel(Ncv32u *pixelMask, Ncv32u numElements, NcvRect32u *hypotheses, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32f curScale) { Ncv32u blockId = blockIdx.y * 65535 + blockIdx.x; Ncv32u elemAddr = blockId * NUM_GROW_THREADS + threadIdx.x; if (elemAddr >= numElements) { return; } hypotheses[elemAddr] = pixelToRect(pixelMask[elemAddr], rectWidth, rectHeight, curScale); } NCVStatus ncvGrowDetectionsVector_device(NCVVector<Ncv32u> &pixelMask, Ncv32u numPixelMaskDetections, NCVVector<NcvRect32u> &hypotheses, Ncv32u &totalDetections, Ncv32u totalMaxDetections, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32f curScale, hipStream_t cuStream) { ncvAssertReturn(pixelMask.ptr() != NULL && hypotheses.ptr() != NULL, NCV_NULL_PTR); ncvAssertReturn(pixelMask.memType() == hypotheses.memType() && pixelMask.memType() == NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(rectWidth > 0 && rectHeight > 0 && curScale > 0, NCV_INVALID_ROI); ncvAssertReturn(curScale > 0, NCV_INVALID_SCALE); ncvAssertReturn(totalMaxDetections <= hypotheses.length() && numPixelMaskDetections <= pixelMask.length(), NCV_INCONSISTENT_INPUT); NCVStatus ncvStat = NCV_SUCCESS; Ncv32u numDetsToCopy = numPixelMaskDetections; if (numDetsToCopy == 0) { return ncvStat; } if (totalDetections + numPixelMaskDetections > totalMaxDetections) { ncvStat = NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW; numDetsToCopy = totalMaxDetections - totalDetections; } dim3 block(NUM_GROW_THREADS); dim3 grid((numDetsToCopy + NUM_GROW_THREADS - 1) / NUM_GROW_THREADS); if (grid.x > 65535) { grid.y = (grid.x + 65534) / 65535; grid.x = 65535; } hipLaunchKernelGGL(( growDetectionsKernel), dim3(grid), dim3(block), 0, cuStream, pixelMask.ptr(), numDetsToCopy, hypotheses.ptr() + totalDetections, rectWidth, rectHeight, curScale); ncvAssertCUDAReturn(hipGetLastError(), NCV_CUDA_ERROR); totalDetections += numDetsToCopy; return ncvStat; } //============================================================================== // // Pipeline file // //============================================================================== NCVStatus ncvDetectObjectsMultiScale_device(NCVMatrix<Ncv8u> &d_srcImg, NcvSize32u srcRoi, NCVVector<NcvRect32u> &d_dstRects, Ncv32u &dstNumRects, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarStage64> &d_HaarStages, NCVVector<HaarClassifierNode128> &d_HaarNodes, NCVVector<HaarFeature64> &d_HaarFeatures, NcvSize32u minObjSize, Ncv32u minNeighbors, //default 4 Ncv32f scaleStep, //default 1.2f Ncv32u pixelStep, //default 1 Ncv32u flags, //default NCVPipeObjDet_Default INCVMemAllocator &gpuAllocator, INCVMemAllocator &cpuAllocator, hipDeviceProp_t &devProp, hipStream_t cuStream) { ncvAssertReturn(d_srcImg.memType() == d_dstRects.memType() && d_srcImg.memType() == gpuAllocator.memType() && (d_srcImg.memType() == NCVMemoryTypeDevice || d_srcImg.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(d_HaarStages.memType() == d_HaarNodes.memType() && d_HaarStages.memType() == d_HaarFeatures.memType() && (d_HaarStages.memType() == NCVMemoryTypeDevice || d_HaarStages.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_HaarStages.memType() != NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(gpuAllocator.isInitialized() && cpuAllocator.isInitialized(), NCV_ALLOCATOR_NOT_INITIALIZED); ncvAssertReturn((d_srcImg.ptr() != NULL && d_dstRects.ptr() != NULL && h_HaarStages.ptr() != NULL && d_HaarStages.ptr() != NULL && d_HaarNodes.ptr() != NULL && d_HaarFeatures.ptr() != NULL) || gpuAllocator.isCounting(), NCV_NULL_PTR); ncvAssertReturn(srcRoi.width > 0 && srcRoi.height > 0 && d_srcImg.width() >= srcRoi.width && d_srcImg.height() >= srcRoi.height && srcRoi.width >= minObjSize.width && srcRoi.height >= minObjSize.height && d_dstRects.length() >= 1, NCV_DIMENSIONS_INVALID); ncvAssertReturn(scaleStep > 1.0f, NCV_INVALID_SCALE); ncvAssertReturn(d_HaarStages.length() >= haar.NumStages && d_HaarNodes.length() >= haar.NumClassifierTotalNodes && d_HaarFeatures.length() >= haar.NumFeatures && d_HaarStages.length() == h_HaarStages.length() && haar.NumClassifierRootNodes <= haar.NumClassifierTotalNodes, NCV_DIMENSIONS_INVALID); ncvAssertReturn(haar.bNeedsTiltedII == false, NCV_NOIMPL_HAAR_TILTED_FEATURES); ncvAssertReturn(pixelStep == 1 || pixelStep == 2, NCV_HAAR_INVALID_PIXEL_STEP); //TODO: set NPP active stream to cuStream NCVStatus ncvStat; NCV_SET_SKIP_COND(gpuAllocator.isCounting()); Ncv32u integralWidth = d_srcImg.width() + 1; Ncv32u integralHeight = d_srcImg.height() + 1; NCVMatrixAlloc<Ncv32u> d_integralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_integralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv64u> d_sqIntegralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_sqIntegralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32f> d_rectStdDev(gpuAllocator, d_srcImg.width(), d_srcImg.height()); ncvAssertReturn(d_rectStdDev.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> d_pixelMask(gpuAllocator, d_srcImg.width(), d_srcImg.height()); ncvAssertReturn(d_pixelMask.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> d_scaledIntegralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_scaledIntegralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv64u> d_scaledSqIntegralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_scaledSqIntegralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<NcvRect32u> d_hypothesesIntermediate(gpuAllocator, d_srcImg.width() * d_srcImg.height()); ncvAssertReturn(d_hypothesesIntermediate.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<NcvRect32u> h_hypothesesIntermediate(cpuAllocator, d_srcImg.width() * d_srcImg.height()); ncvAssertReturn(h_hypothesesIntermediate.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVStatus nppStat; Ncv32u szTmpBufIntegral, szTmpBufSqIntegral; nppStat = nppiStIntegralGetSize_8u32u(NcvSize32u(d_srcImg.width(), d_srcImg.height()), &szTmpBufIntegral, devProp); ncvAssertReturnNcvStat(nppStat); nppStat = nppiStSqrIntegralGetSize_8u64u(NcvSize32u(d_srcImg.width(), d_srcImg.height()), &szTmpBufSqIntegral, devProp); ncvAssertReturnNcvStat(nppStat); NCVVectorAlloc<Ncv8u> d_tmpIIbuf(gpuAllocator, ::max(szTmpBufIntegral, szTmpBufSqIntegral)); ncvAssertReturn(d_tmpIIbuf.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCV_SKIP_COND_BEGIN nppStat = nppiStIntegral_8u32u_C1R(d_srcImg.ptr(), d_srcImg.pitch(), d_integralImage.ptr(), d_integralImage.pitch(), NcvSize32u(d_srcImg.width(), d_srcImg.height()), d_tmpIIbuf.ptr(), szTmpBufIntegral, devProp); ncvAssertReturnNcvStat(nppStat); nppStat = nppiStSqrIntegral_8u64u_C1R(d_srcImg.ptr(), d_srcImg.pitch(), d_sqIntegralImage.ptr(), d_sqIntegralImage.pitch(), NcvSize32u(d_srcImg.width(), d_srcImg.height()), d_tmpIIbuf.ptr(), szTmpBufSqIntegral, devProp); ncvAssertReturnNcvStat(nppStat); NCV_SKIP_COND_END dstNumRects = 0; Ncv32u lastCheckedScale = 0; NcvBool bReverseTraverseScale = ((flags & NCVPipeObjDet_FindLargestObject) != 0); std::vector<Ncv32u> scalesVector; NcvBool bFoundLargestFace = false; for (Ncv32f scaleIter = 1.0f; ; scaleIter *= scaleStep) { Ncv32u scale = (Ncv32u)scaleIter; if (lastCheckedScale == scale) { continue; } lastCheckedScale = scale; if (haar.ClassifierSize.width * (Ncv32s)scale < minObjSize.width || haar.ClassifierSize.height * (Ncv32s)scale < minObjSize.height) { continue; } NcvSize32s srcRoi, srcIIRoi, scaledIIRoi, searchRoi; srcRoi.width = d_srcImg.width(); srcRoi.height = d_srcImg.height(); srcIIRoi.width = srcRoi.width + 1; srcIIRoi.height = srcRoi.height + 1; scaledIIRoi.width = srcIIRoi.width / scale; scaledIIRoi.height = srcIIRoi.height / scale; searchRoi.width = scaledIIRoi.width - haar.ClassifierSize.width; searchRoi.height = scaledIIRoi.height - haar.ClassifierSize.height; if (searchRoi.width <= 0 || searchRoi.height <= 0) { break; } scalesVector.push_back(scale); if (gpuAllocator.isCounting()) { break; } } if (bReverseTraverseScale) { std::reverse(scalesVector.begin(), scalesVector.end()); } //TODO: handle _fair_scale_ flag for (Ncv32u i=0; i<scalesVector.size(); i++) { Ncv32u scale = scalesVector[i]; NcvSize32u srcRoi, scaledIIRoi, searchRoi; NcvSize32u srcIIRoi; srcRoi.width = d_srcImg.width(); srcRoi.height = d_srcImg.height(); srcIIRoi.width = srcRoi.width + 1; srcIIRoi.height = srcRoi.height + 1; scaledIIRoi.width = srcIIRoi.width / scale; scaledIIRoi.height = srcIIRoi.height / scale; searchRoi.width = scaledIIRoi.width - haar.ClassifierSize.width; searchRoi.height = scaledIIRoi.height - haar.ClassifierSize.height; NCV_SKIP_COND_BEGIN nppStat = nppiStDecimate_32u_C1R( d_integralImage.ptr(), d_integralImage.pitch(), d_scaledIntegralImage.ptr(), d_scaledIntegralImage.pitch(), srcIIRoi, scale, true); ncvAssertReturnNcvStat(nppStat); nppStat = nppiStDecimate_64u_C1R( d_sqIntegralImage.ptr(), d_sqIntegralImage.pitch(), d_scaledSqIntegralImage.ptr(), d_scaledSqIntegralImage.pitch(), srcIIRoi, scale, true); ncvAssertReturnNcvStat(nppStat); const NcvRect32u rect( HAAR_STDDEV_BORDER, HAAR_STDDEV_BORDER, haar.ClassifierSize.width - 2*HAAR_STDDEV_BORDER, haar.ClassifierSize.height - 2*HAAR_STDDEV_BORDER); nppStat = nppiStRectStdDev_32f_C1R( d_scaledIntegralImage.ptr(), d_scaledIntegralImage.pitch(), d_scaledSqIntegralImage.ptr(), d_scaledSqIntegralImage.pitch(), d_rectStdDev.ptr(), d_rectStdDev.pitch(), NcvSize32u(searchRoi.width, searchRoi.height), rect, (Ncv32f)scale*scale, true); ncvAssertReturnNcvStat(nppStat); NCV_SKIP_COND_END Ncv32u detectionsOnThisScale; ncvStat = ncvApplyHaarClassifierCascade_device( d_scaledIntegralImage, d_rectStdDev, d_pixelMask, detectionsOnThisScale, haar, h_HaarStages, d_HaarStages, d_HaarNodes, d_HaarFeatures, false, searchRoi, pixelStep, (Ncv32f)scale*scale, gpuAllocator, cpuAllocator, devProp, cuStream); ncvAssertReturnNcvStat(nppStat); NCV_SKIP_COND_BEGIN NCVVectorReuse<Ncv32u> d_vecPixelMask(d_pixelMask.getSegment()); ncvStat = ncvGrowDetectionsVector_device( d_vecPixelMask, detectionsOnThisScale, d_hypothesesIntermediate, dstNumRects, static_cast<Ncv32u>(d_hypothesesIntermediate.length()), haar.ClassifierSize.width, haar.ClassifierSize.height, (Ncv32f)scale, cuStream); ncvAssertReturn(ncvStat == NCV_SUCCESS, ncvStat); if (flags & NCVPipeObjDet_FindLargestObject) { if (dstNumRects == 0) { continue; } if (dstNumRects != 0) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvStat = d_hypothesesIntermediate.copySolid(h_hypothesesIntermediate, cuStream, dstNumRects * sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } Ncv32u numStrongHypothesesNow = dstNumRects; // TODO Fix this to be back operational /* ncvStat = ncvGroupRectangles_host( h_hypothesesIntermediate, numStrongHypothesesNow, minNeighbors, RECT_SIMILARITY_PROPORTION, NULL); ncvAssertReturnNcvStat(ncvStat); */ if (numStrongHypothesesNow > 0) { NcvRect32u maxRect = h_hypothesesIntermediate.ptr()[0]; for (Ncv32u j=1; j<numStrongHypothesesNow; j++) { if (maxRect.width < h_hypothesesIntermediate.ptr()[j].width) { maxRect = h_hypothesesIntermediate.ptr()[j]; } } h_hypothesesIntermediate.ptr()[0] = maxRect; dstNumRects = 1; ncvStat = h_hypothesesIntermediate.copySolid(d_dstRects, cuStream, sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); bFoundLargestFace = true; break; } } NCV_SKIP_COND_END if (gpuAllocator.isCounting()) { break; } } NCVStatus ncvRetCode = NCV_SUCCESS; NCV_SKIP_COND_BEGIN if (flags & NCVPipeObjDet_FindLargestObject) { if (!bFoundLargestFace) { dstNumRects = 0; } } else { //TODO: move hypotheses filtration to GPU pipeline (the only CPU-resident element of the pipeline left) if (dstNumRects != 0) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvStat = d_hypothesesIntermediate.copySolid(h_hypothesesIntermediate, cuStream, dstNumRects * sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); } // Todo fix this to be back operational /* ncvStat = ncvGroupRectangles_host( h_hypothesesIntermediate, dstNumRects, minNeighbors, RECT_SIMILARITY_PROPORTION, NULL); ncvAssertReturnNcvStat(ncvStat); */ if (dstNumRects > d_dstRects.length()) { ncvRetCode = NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW; dstNumRects = static_cast<Ncv32u>(d_dstRects.length()); } if (dstNumRects != 0) { ncvStat = h_hypothesesIntermediate.copySolid(d_dstRects, cuStream, dstNumRects * sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); } } if (flags & NCVPipeObjDet_VisualizeInPlace) { ncvAssertCUDAReturn(hipStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvDrawRects_8u_device(d_srcImg.ptr(), d_srcImg.stride(), d_srcImg.width(), d_srcImg.height(), d_dstRects.ptr(), dstNumRects, 255, cuStream); } NCV_SKIP_COND_END return ncvRetCode; } //============================================================================== // // Purely Host code: classifier IO, mock-ups // //============================================================================== #ifdef _SELF_TEST_ #include <float.h> #endif #define NVBIN_HAAR_SIZERESERVED 16 #define NVBIN_HAAR_VERSION 0x1 NCVStatus ncvApplyHaarClassifierCascade_host(NCVMatrix<Ncv32u> &h_integralImage, NCVMatrix<Ncv32f> &h_weights, NCVMatrixAlloc<Ncv32u> &h_pixelMask, Ncv32u &numDetections, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarClassifierNode128> &h_HaarNodes, NCVVector<HaarFeature64> &h_HaarFeatures, NcvBool bMaskElements, NcvSize32u anchorsRoi, Ncv32u pixelStep, Ncv32f scaleArea) { ncvAssertReturn(h_integralImage.memType() == h_weights.memType() && h_integralImage.memType() == h_pixelMask.memType() && (h_integralImage.memType() == NCVMemoryTypeHostPageable || h_integralImage.memType() == NCVMemoryTypeHostPinned), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_HaarStages.memType() == h_HaarNodes.memType() && h_HaarStages.memType() == h_HaarFeatures.memType() && (h_HaarStages.memType() == NCVMemoryTypeHostPageable || h_HaarStages.memType() == NCVMemoryTypeHostPinned), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_integralImage.ptr() != NULL && h_weights.ptr() != NULL && h_pixelMask.ptr() != NULL && h_HaarStages.ptr() != NULL && h_HaarNodes.ptr() != NULL && h_HaarFeatures.ptr() != NULL, NCV_NULL_PTR); ncvAssertReturn(anchorsRoi.width > 0 && anchorsRoi.height > 0 && h_pixelMask.width() >= anchorsRoi.width && h_pixelMask.height() >= anchorsRoi.height && h_weights.width() >= anchorsRoi.width && h_weights.height() >= anchorsRoi.height && h_integralImage.width() >= anchorsRoi.width + haar.ClassifierSize.width && h_integralImage.height() >= anchorsRoi.height + haar.ClassifierSize.height, NCV_DIMENSIONS_INVALID); ncvAssertReturn(scaleArea > 0, NCV_INVALID_SCALE); ncvAssertReturn(h_HaarStages.length() >= haar.NumStages && h_HaarNodes.length() >= haar.NumClassifierTotalNodes && h_HaarFeatures.length() >= haar.NumFeatures && h_HaarStages.length() == h_HaarStages.length() && haar.NumClassifierRootNodes <= haar.NumClassifierTotalNodes, NCV_DIMENSIONS_INVALID); ncvAssertReturn(haar.bNeedsTiltedII == false, NCV_NOIMPL_HAAR_TILTED_FEATURES); ncvAssertReturn(pixelStep == 1 || pixelStep == 2, NCV_HAAR_INVALID_PIXEL_STEP); Ncv32f scaleAreaPixels = scaleArea * ((haar.ClassifierSize.width - 2*HAAR_STDDEV_BORDER) * (haar.ClassifierSize.height - 2*HAAR_STDDEV_BORDER)); for (Ncv32u i=0; i<anchorsRoi.height; i++) { for (Ncv32u j=0; j<h_pixelMask.stride(); j++) { if (i % pixelStep != 0 || j % pixelStep != 0 || j >= anchorsRoi.width) { h_pixelMask.ptr()[i * h_pixelMask.stride() + j] = OBJDET_MASK_ELEMENT_INVALID_32U; } else { for (Ncv32u iStage = 0; iStage < haar.NumStages; iStage++) { Ncv32f curStageSum = 0.0f; Ncv32u numRootNodesInStage = h_HaarStages.ptr()[iStage].getNumClassifierRootNodes(); Ncv32u curRootNodeOffset = h_HaarStages.ptr()[iStage].getStartClassifierRootNodeOffset(); if (iStage == 0) { if (bMaskElements && h_pixelMask.ptr()[i * h_pixelMask.stride() + j] == OBJDET_MASK_ELEMENT_INVALID_32U) { break; } else { h_pixelMask.ptr()[i * h_pixelMask.stride() + j] = ((i << 16) | j); } } else if (h_pixelMask.ptr()[i * h_pixelMask.stride() + j] == OBJDET_MASK_ELEMENT_INVALID_32U) { break; } while (numRootNodesInStage--) { NcvBool bMoreNodesToTraverse = true; Ncv32u curNodeOffset = curRootNodeOffset; while (bMoreNodesToTraverse) { HaarClassifierNode128 curNode = h_HaarNodes.ptr()[curNodeOffset]; HaarFeatureDescriptor32 curFeatDesc = curNode.getFeatureDesc(); Ncv32u curNodeFeaturesNum = curFeatDesc.getNumFeatures(); Ncv32u curNodeFeaturesOffs = curFeatDesc.getFeaturesOffset(); Ncv32f curNodeVal = 0.f; for (Ncv32u iRect=0; iRect<curNodeFeaturesNum; iRect++) { HaarFeature64 feature = h_HaarFeatures.ptr()[curNodeFeaturesOffs + iRect]; Ncv32u rectX, rectY, rectWidth, rectHeight; feature.getRect(&rectX, &rectY, &rectWidth, &rectHeight); Ncv32f rectWeight = feature.getWeight(); Ncv32u iioffsTL = (i + rectY) * h_integralImage.stride() + (j + rectX); Ncv32u iioffsTR = iioffsTL + rectWidth; Ncv32u iioffsBL = iioffsTL + rectHeight * h_integralImage.stride(); Ncv32u iioffsBR = iioffsBL + rectWidth; Ncv32u iivalTL = h_integralImage.ptr()[iioffsTL]; Ncv32u iivalTR = h_integralImage.ptr()[iioffsTR]; Ncv32u iivalBL = h_integralImage.ptr()[iioffsBL]; Ncv32u iivalBR = h_integralImage.ptr()[iioffsBR]; Ncv32u rectSum = iivalBR - iivalBL + iivalTL - iivalTR; curNodeVal += (Ncv32f)rectSum * rectWeight; } HaarClassifierNodeDescriptor32 nodeLeft = curNode.getLeftNodeDesc(); HaarClassifierNodeDescriptor32 nodeRight = curNode.getRightNodeDesc(); Ncv32f nodeThreshold = curNode.getThreshold(); HaarClassifierNodeDescriptor32 nextNodeDescriptor; NcvBool nextNodeIsLeaf; if (curNodeVal < scaleAreaPixels * h_weights.ptr()[i * h_weights.stride() + j] * nodeThreshold) { nextNodeDescriptor = nodeLeft; nextNodeIsLeaf = curFeatDesc.isLeftNodeLeaf(); } else { nextNodeDescriptor = nodeRight; nextNodeIsLeaf = curFeatDesc.isRightNodeLeaf(); } if (nextNodeIsLeaf) { Ncv32f tmpLeafValue = nextNodeDescriptor.getLeafValueHost(); curStageSum += tmpLeafValue; bMoreNodesToTraverse = false; } else { curNodeOffset = nextNodeDescriptor.getNextNodeOffset(); } } curRootNodeOffset++; } Ncv32f tmpStageThreshold = h_HaarStages.ptr()[iStage].getStageThreshold(); if (curStageSum < tmpStageThreshold) { //drop h_pixelMask.ptr()[i * h_pixelMask.stride() + j] = OBJDET_MASK_ELEMENT_INVALID_32U; break; } } } } } std::sort(h_pixelMask.ptr(), h_pixelMask.ptr() + anchorsRoi.height * h_pixelMask.stride()); Ncv32u i = 0; for (; i<anchorsRoi.height * h_pixelMask.stride(); i++) { if (h_pixelMask.ptr()[i] == OBJDET_MASK_ELEMENT_INVALID_32U) { break; } } numDetections = i; return NCV_SUCCESS; } NCVStatus ncvGrowDetectionsVector_host(NCVVector<Ncv32u> &pixelMask, Ncv32u numPixelMaskDetections, NCVVector<NcvRect32u> &hypotheses, Ncv32u &totalDetections, Ncv32u totalMaxDetections, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32f curScale) { ncvAssertReturn(pixelMask.ptr() != NULL && hypotheses.ptr() != NULL, NCV_NULL_PTR); ncvAssertReturn(pixelMask.memType() == hypotheses.memType() && pixelMask.memType() != NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(rectWidth > 0 && rectHeight > 0 && curScale > 0, NCV_INVALID_ROI); ncvAssertReturn(curScale > 0, NCV_INVALID_SCALE); ncvAssertReturn(totalMaxDetections <= hypotheses.length() && numPixelMaskDetections <= pixelMask.length(), NCV_INCONSISTENT_INPUT); NCVStatus ncvStat = NCV_SUCCESS; Ncv32u numDetsToCopy = numPixelMaskDetections; if (numDetsToCopy == 0) { return ncvStat; } if (totalDetections + numPixelMaskDetections > totalMaxDetections) { ncvStat = NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW; numDetsToCopy = totalMaxDetections - totalDetections; } for (Ncv32u i=0; i<numDetsToCopy; i++) { hypotheses.ptr()[totalDetections + i] = pixelToRect(pixelMask.ptr()[i], rectWidth, rectHeight, curScale); } totalDetections += numDetsToCopy; return ncvStat; } NCVStatus ncvHaarStoreNVBIN_host(const std::string &filename, HaarClassifierCascadeDescriptor haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarClassifierNode128> &h_HaarNodes, NCVVector<HaarFeature64> &h_HaarFeatures) { ncvAssertReturn(h_HaarStages.length() >= haar.NumStages, NCV_INCONSISTENT_INPUT); ncvAssertReturn(h_HaarNodes.length() >= haar.NumClassifierTotalNodes, NCV_INCONSISTENT_INPUT); ncvAssertReturn(h_HaarFeatures.length() >= haar.NumFeatures, NCV_INCONSISTENT_INPUT); ncvAssertReturn(h_HaarStages.memType() == NCVMemoryTypeHostPinned && h_HaarNodes.memType() == NCVMemoryTypeHostPinned && h_HaarFeatures.memType() == NCVMemoryTypeHostPinned, NCV_MEM_RESIDENCE_ERROR); Ncv32u szStages = haar.NumStages * sizeof(HaarStage64); Ncv32u szClassifiers = haar.NumClassifierTotalNodes * sizeof(HaarClassifierNode128); Ncv32u szFeatures = haar.NumFeatures * sizeof(HaarFeature64); Ncv32u dataOffset = 0; std::vector<unsigned char> fdata; fdata.resize(szStages+szClassifiers+szFeatures+1024, 0); //header *(Ncv32u *)(&fdata[0]+dataOffset) = NVBIN_HAAR_VERSION; //data dataOffset = NVBIN_HAAR_SIZERESERVED; *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumStages; dataOffset += sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumClassifierRootNodes; dataOffset += sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumClassifierTotalNodes; dataOffset += sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumFeatures; dataOffset += sizeof(Ncv32u); *(NcvSize32u *)(&fdata[0]+dataOffset) = haar.ClassifierSize; dataOffset += sizeof(NcvSize32u); *(NcvBool *)(&fdata[0]+dataOffset) = haar.bNeedsTiltedII; dataOffset += sizeof(NcvBool); *(NcvBool *)(&fdata[0]+dataOffset) = haar.bHasStumpsOnly; dataOffset += sizeof(NcvBool); memcpy(&fdata[0]+dataOffset, h_HaarStages.ptr(), szStages); dataOffset += szStages; memcpy(&fdata[0]+dataOffset, h_HaarNodes.ptr(), szClassifiers); dataOffset += szClassifiers; memcpy(&fdata[0]+dataOffset, h_HaarFeatures.ptr(), szFeatures); dataOffset += szFeatures; Ncv32u fsize = dataOffset; //TODO: CRC32 here //update header dataOffset = sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = fsize; FILE *fp = fopen(filename.c_str(), "wb"); ncvAssertReturn(fp != NULL, NCV_FILE_ERROR); fwrite(&fdata[0], fsize, 1, fp); fclose(fp); return NCV_SUCCESS; }
b621f15c8bdabf4e62e8892984753cbc8414bd6d.cu
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (C) 2009-2010, NVIDIA Corporation, all rights reserved. * Third party copyrights are property of their respective owners. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: $ * Ported to PCL by Koen Buys : Attention Work in progress! */ //////////////////////////////////////////////////////////////////////////////// // // NVIDIA CUDA implementation of Viola-Jones Object Detection Framework // // The algorithm and code are explained in the upcoming GPU Computing Gems // chapter in detail: // // Anton Obukhov, "Haar Classifiers for Object Detection with CUDA" // PDF URL placeholder // email: aobukhov@nvidia.com, devsupport@nvidia.com // // Credits for help with the code to: // Alexey Mendelenko, Cyril Crassin, and Mikhail Smirnov. // //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <cstdio> #include "NCV.hpp" #include "NCVAlg.hpp" #include "NPP_staging.hpp" #include "NCVRuntimeTemplates.hpp" #include "NCVHaarObjectDetection.hpp" //============================================================================== // // BlockScan file // //============================================================================== NCV_CT_ASSERT(K_WARP_SIZE == 32); //this is required for the manual unroll of the loop in warpScanInclusive //Almost the same as naive scan1Inclusive, but doesn't need __syncthreads() //assuming size <= WARP_SIZE and size is power of 2 __device__ Ncv32u warpScanInclusive(Ncv32u idata, volatile Ncv32u *s_Data) { Ncv32u pos = 2 * threadIdx.x - (threadIdx.x & (K_WARP_SIZE - 1)); s_Data[pos] = 0; pos += K_WARP_SIZE; s_Data[pos] = idata; s_Data[pos] += s_Data[pos - 1]; s_Data[pos] += s_Data[pos - 2]; s_Data[pos] += s_Data[pos - 4]; s_Data[pos] += s_Data[pos - 8]; s_Data[pos] += s_Data[pos - 16]; return s_Data[pos]; } __device__ __forceinline__ Ncv32u warpScanExclusive(Ncv32u idata, volatile Ncv32u *s_Data) { return warpScanInclusive(idata, s_Data) - idata; } template <Ncv32u tiNumScanThreads> __device__ Ncv32u scan1Inclusive(Ncv32u idata, volatile Ncv32u *s_Data) { if (tiNumScanThreads > K_WARP_SIZE) { //Bottom-level inclusive warp scan Ncv32u warpResult = warpScanInclusive(idata, s_Data); //Save top elements of each warp for exclusive warp scan //sync to wait for warp scans to complete (because s_Data is being overwritten) __syncthreads(); if( (threadIdx.x & (K_WARP_SIZE - 1)) == (K_WARP_SIZE - 1) ) { s_Data[threadIdx.x >> K_LOG2_WARP_SIZE] = warpResult; } //wait for warp scans to complete __syncthreads(); if( threadIdx.x < (tiNumScanThreads / K_WARP_SIZE) ) { //grab top warp elements Ncv32u val = s_Data[threadIdx.x]; //calculate exclusive scan and write back to shared memory s_Data[threadIdx.x] = warpScanExclusive(val, s_Data); } //return updated warp scans with exclusive scan results __syncthreads(); return warpResult + s_Data[threadIdx.x >> K_LOG2_WARP_SIZE]; } else { return warpScanInclusive(idata, s_Data); } } //============================================================================== // // HaarClassifierCascade file // //============================================================================== const Ncv32u MAX_GRID_DIM = 65535; const Ncv32u NUM_THREADS_ANCHORSPARALLEL = 64; #define NUM_THREADS_CLASSIFIERPARALLEL_LOG2 6 #define NUM_THREADS_CLASSIFIERPARALLEL (1 << NUM_THREADS_CLASSIFIERPARALLEL_LOG2) /** \internal * Haar features solid array. */ texture<uint2, 1, cudaReadModeElementType> texHaarFeatures; /** \internal * Haar classifiers flattened trees container. * Two parts: first contains root nodes, second - nodes that are referred by root nodes. * Drawback: breaks tree locality (might cause more cache misses * Advantage: No need to introduce additional 32-bit field to index root nodes offsets */ texture<uint4, 1, cudaReadModeElementType> texHaarClassifierNodes; texture<Ncv32u, 1, cudaReadModeElementType> texIImage; __device__ HaarStage64 getStage(Ncv32u iStage, HaarStage64 *d_Stages) { return d_Stages[iStage]; } template <NcvBool tbCacheTextureCascade> __device__ HaarClassifierNode128 getClassifierNode(Ncv32u iNode, HaarClassifierNode128 *d_ClassifierNodes) { HaarClassifierNode128 tmpNode; if (tbCacheTextureCascade) { tmpNode._ui4 = tex1Dfetch(texHaarClassifierNodes, iNode); } else { tmpNode = d_ClassifierNodes[iNode]; } return tmpNode; } template <NcvBool tbCacheTextureCascade> __device__ void getFeature(Ncv32u iFeature, HaarFeature64 *d_Features, Ncv32f *weight, Ncv32u *rectX, Ncv32u *rectY, Ncv32u *rectWidth, Ncv32u *rectHeight) { HaarFeature64 feature; if (tbCacheTextureCascade) { feature._ui2 = tex1Dfetch(texHaarFeatures, iFeature); } else { feature = d_Features[iFeature]; } feature.getRect(rectX, rectY, rectWidth, rectHeight); *weight = feature.getWeight(); } template <NcvBool tbCacheTextureIImg> __device__ Ncv32u getElemIImg(Ncv32u x, Ncv32u *d_IImg) { if (tbCacheTextureIImg) { return tex1Dfetch(texIImage, x); } else { return d_IImg[x]; } } __device__ Ncv32u d_outMaskPosition; __device__ void compactBlockWriteOutAnchorParallel(Ncv32u threadPassFlag, Ncv32u threadElem, Ncv32u *vectorOut) { __shared__ Ncv32u shmem[NUM_THREADS_ANCHORSPARALLEL * 2]; __shared__ Ncv32u numPassed; __shared__ Ncv32u outMaskOffset; Ncv32u incScan = scan1Inclusive<NUM_THREADS_ANCHORSPARALLEL>(threadPassFlag, shmem); __syncthreads(); if (threadIdx.x == NUM_THREADS_ANCHORSPARALLEL-1) { numPassed = incScan; outMaskOffset = atomicAdd(&d_outMaskPosition, incScan); } if (threadPassFlag) { Ncv32u excScan = incScan - threadPassFlag; shmem[excScan] = threadElem; } __syncthreads(); if (threadIdx.x < numPassed) { vectorOut[outMaskOffset + threadIdx.x] = shmem[threadIdx.x]; } } template <NcvBool tbInitMaskPositively, NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbReadPixelIndexFromVector, NcvBool tbDoAtomicCompaction> __global__ void applyHaarClassifierAnchorParallel(Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { Ncv32u y_offs; Ncv32u x_offs; Ncv32u maskOffset; Ncv32u outMaskVal; NcvBool bInactiveThread = false; if (tbReadPixelIndexFromVector) { maskOffset = (MAX_GRID_DIM * blockIdx.y + blockIdx.x) * NUM_THREADS_ANCHORSPARALLEL + threadIdx.x; if (maskOffset >= mask1Dlen) { if (tbDoAtomicCompaction) bInactiveThread = true; else return; } if (!tbDoAtomicCompaction || tbDoAtomicCompaction && !bInactiveThread) { outMaskVal = d_inMask[maskOffset]; y_offs = outMaskVal >> 16; x_offs = outMaskVal & 0xFFFF; } } else { y_offs = blockIdx.y; x_offs = blockIdx.x * NUM_THREADS_ANCHORSPARALLEL + threadIdx.x; if (x_offs >= mask2Dstride) { if (tbDoAtomicCompaction) bInactiveThread = true; else return; } if (!tbDoAtomicCompaction || tbDoAtomicCompaction && !bInactiveThread) { maskOffset = y_offs * mask2Dstride + x_offs; if ((x_offs >= anchorsRoi.width) || (!tbInitMaskPositively && d_inMask != d_outMask && d_inMask[maskOffset] == OBJDET_MASK_ELEMENT_INVALID_32U)) { if (tbDoAtomicCompaction) { bInactiveThread = true; } else { d_outMask[maskOffset] = OBJDET_MASK_ELEMENT_INVALID_32U; return; } } outMaskVal = (y_offs << 16) | x_offs; } } NcvBool bPass = true; if (!tbDoAtomicCompaction || tbDoAtomicCompaction) { Ncv32f pixelStdDev = 0.0f; if (!bInactiveThread) pixelStdDev = d_weights[y_offs * weightsStride + x_offs]; for (Ncv32u iStage = startStageInc; iStage < endStageExc; iStage++) { Ncv32f curStageSum = 0.0f; HaarStage64 curStage = getStage(iStage, d_Stages); Ncv32u numRootNodesInStage = curStage.getNumClassifierRootNodes(); Ncv32u curRootNodeOffset = curStage.getStartClassifierRootNodeOffset(); Ncv32f stageThreshold = curStage.getStageThreshold(); while (numRootNodesInStage--) { NcvBool bMoreNodesToTraverse = true; Ncv32u iNode = curRootNodeOffset; if (bPass && !bInactiveThread) { while (bMoreNodesToTraverse) { HaarClassifierNode128 curNode = getClassifierNode<tbCacheTextureCascade>(iNode, d_ClassifierNodes); HaarFeatureDescriptor32 featuresDesc = curNode.getFeatureDesc(); Ncv32u curNodeFeaturesNum = featuresDesc.getNumFeatures(); Ncv32u iFeature = featuresDesc.getFeaturesOffset(); Ncv32f curNodeVal = 0.0f; for (Ncv32u iRect=0; iRect<curNodeFeaturesNum; iRect++) { Ncv32f rectWeight; Ncv32u rectX, rectY, rectWidth, rectHeight; getFeature<tbCacheTextureCascade> (iFeature + iRect, d_Features, &rectWeight, &rectX, &rectY, &rectWidth, &rectHeight); Ncv32u iioffsTL = (y_offs + rectY) * IImgStride + (x_offs + rectX); Ncv32u iioffsTR = iioffsTL + rectWidth; Ncv32u iioffsBL = iioffsTL + rectHeight * IImgStride; Ncv32u iioffsBR = iioffsBL + rectWidth; Ncv32u rectSum = getElemIImg<tbCacheTextureIImg>(iioffsBR, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsBL, d_IImg) + getElemIImg<tbCacheTextureIImg>(iioffsTL, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsTR, d_IImg); #if defined CPU_FP_COMPLIANCE || defined DISABLE_MAD_SELECTIVELY curNodeVal += __fmul_rn((Ncv32f)rectSum, rectWeight); #else curNodeVal += (Ncv32f)rectSum * rectWeight; #endif } HaarClassifierNodeDescriptor32 nodeLeft = curNode.getLeftNodeDesc(); HaarClassifierNodeDescriptor32 nodeRight = curNode.getRightNodeDesc(); Ncv32f nodeThreshold = curNode.getThreshold(); HaarClassifierNodeDescriptor32 nextNodeDescriptor; NcvBool nextNodeIsLeaf; if (curNodeVal < scaleArea * pixelStdDev * nodeThreshold) { nextNodeDescriptor = nodeLeft; nextNodeIsLeaf = featuresDesc.isLeftNodeLeaf(); } else { nextNodeDescriptor = nodeRight; nextNodeIsLeaf = featuresDesc.isRightNodeLeaf(); } if (nextNodeIsLeaf) { Ncv32f tmpLeafValue = nextNodeDescriptor.getLeafValue(); curStageSum += tmpLeafValue; bMoreNodesToTraverse = false; } else { iNode = nextNodeDescriptor.getNextNodeOffset(); } } } __syncthreads(); curRootNodeOffset++; } if (curStageSum < stageThreshold) { bPass = false; outMaskVal = OBJDET_MASK_ELEMENT_INVALID_32U; } } } __syncthreads(); if (!tbDoAtomicCompaction) { if (!tbReadPixelIndexFromVector || (tbReadPixelIndexFromVector && (!bPass || d_inMask != d_outMask))) { d_outMask[maskOffset] = outMaskVal; } } else { compactBlockWriteOutAnchorParallel(bPass && !bInactiveThread, outMaskVal, d_outMask); } } template <NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbDoAtomicCompaction> __global__ void applyHaarClassifierClassifierParallel(Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { Ncv32u maskOffset = MAX_GRID_DIM * blockIdx.y + blockIdx.x; if (maskOffset >= mask1Dlen) { return; } Ncv32u outMaskVal = d_inMask[maskOffset]; Ncv32u y_offs = outMaskVal >> 16; Ncv32u x_offs = outMaskVal & 0xFFFF; Ncv32f pixelStdDev = d_weights[y_offs * weightsStride + x_offs]; NcvBool bPass = true; for (Ncv32u iStage = startStageInc; iStage<endStageExc; iStage++) { //this variable is subject to reduction Ncv32f curStageSum = 0.0f; HaarStage64 curStage = getStage(iStage, d_Stages); Ncv32s numRootNodesInStage = curStage.getNumClassifierRootNodes(); Ncv32u curRootNodeOffset = curStage.getStartClassifierRootNodeOffset() + threadIdx.x; Ncv32f stageThreshold = curStage.getStageThreshold(); Ncv32u numRootChunks = (numRootNodesInStage + NUM_THREADS_CLASSIFIERPARALLEL - 1) >> NUM_THREADS_CLASSIFIERPARALLEL_LOG2; for (Ncv32u chunkId=0; chunkId<numRootChunks; chunkId++) { NcvBool bMoreNodesToTraverse = true; if (chunkId * NUM_THREADS_CLASSIFIERPARALLEL + threadIdx.x < numRootNodesInStage) { Ncv32u iNode = curRootNodeOffset; while (bMoreNodesToTraverse) { HaarClassifierNode128 curNode = getClassifierNode<tbCacheTextureCascade>(iNode, d_ClassifierNodes); HaarFeatureDescriptor32 featuresDesc = curNode.getFeatureDesc(); Ncv32u curNodeFeaturesNum = featuresDesc.getNumFeatures(); Ncv32u iFeature = featuresDesc.getFeaturesOffset(); Ncv32f curNodeVal = 0.0f; //TODO: fetch into shmem if size suffices. Shmem can be shared with reduce for (Ncv32u iRect=0; iRect<curNodeFeaturesNum; iRect++) { Ncv32f rectWeight; Ncv32u rectX, rectY, rectWidth, rectHeight; getFeature<tbCacheTextureCascade> (iFeature + iRect, d_Features, &rectWeight, &rectX, &rectY, &rectWidth, &rectHeight); Ncv32u iioffsTL = (y_offs + rectY) * IImgStride + (x_offs + rectX); Ncv32u iioffsTR = iioffsTL + rectWidth; Ncv32u iioffsBL = iioffsTL + rectHeight * IImgStride; Ncv32u iioffsBR = iioffsBL + rectWidth; Ncv32u rectSum = getElemIImg<tbCacheTextureIImg>(iioffsBR, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsBL, d_IImg) + getElemIImg<tbCacheTextureIImg>(iioffsTL, d_IImg) - getElemIImg<tbCacheTextureIImg>(iioffsTR, d_IImg); #if defined CPU_FP_COMPLIANCE || defined DISABLE_MAD_SELECTIVELY curNodeVal += __fmul_rn((Ncv32f)rectSum, rectWeight); #else curNodeVal += (Ncv32f)rectSum * rectWeight; #endif } HaarClassifierNodeDescriptor32 nodeLeft = curNode.getLeftNodeDesc(); HaarClassifierNodeDescriptor32 nodeRight = curNode.getRightNodeDesc(); Ncv32f nodeThreshold = curNode.getThreshold(); HaarClassifierNodeDescriptor32 nextNodeDescriptor; NcvBool nextNodeIsLeaf; if (curNodeVal < scaleArea * pixelStdDev * nodeThreshold) { nextNodeDescriptor = nodeLeft; nextNodeIsLeaf = featuresDesc.isLeftNodeLeaf(); } else { nextNodeDescriptor = nodeRight; nextNodeIsLeaf = featuresDesc.isRightNodeLeaf(); } if (nextNodeIsLeaf) { Ncv32f tmpLeafValue = nextNodeDescriptor.getLeafValue(); curStageSum += tmpLeafValue; bMoreNodesToTraverse = false; } else { iNode = nextNodeDescriptor.getNextNodeOffset(); } } } __syncthreads(); curRootNodeOffset += NUM_THREADS_CLASSIFIERPARALLEL; } Ncv32f finalStageSum = subReduce<Ncv32f, functorAddValues<Ncv32f>, NUM_THREADS_CLASSIFIERPARALLEL>(curStageSum); if (finalStageSum < stageThreshold) { bPass = false; outMaskVal = OBJDET_MASK_ELEMENT_INVALID_32U; break; } } if (!tbDoAtomicCompaction) { if (!bPass || d_inMask != d_outMask) { if (!threadIdx.x) { d_outMask[maskOffset] = outMaskVal; } } } else { if (bPass && !threadIdx.x) { Ncv32u outMaskOffset = atomicAdd(&d_outMaskPosition, 1); d_outMask[outMaskOffset] = outMaskVal; } } } template <NcvBool tbMaskByInmask, NcvBool tbDoAtomicCompaction> __global__ void initializeMaskVector(Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u step) { Ncv32u y_offs = blockIdx.y; Ncv32u x_offs = blockIdx.x * NUM_THREADS_ANCHORSPARALLEL + threadIdx.x; Ncv32u outMaskOffset = y_offs * gridDim.x * blockDim.x + x_offs; Ncv32u y_offs_upsc = step * y_offs; Ncv32u x_offs_upsc = step * x_offs; Ncv32u inMaskOffset = y_offs_upsc * mask2Dstride + x_offs_upsc; Ncv32u outElem = OBJDET_MASK_ELEMENT_INVALID_32U; if (x_offs_upsc < anchorsRoi.width && (!tbMaskByInmask || d_inMask[inMaskOffset] != OBJDET_MASK_ELEMENT_INVALID_32U)) { outElem = (y_offs_upsc << 16) | x_offs_upsc; } if (!tbDoAtomicCompaction) { d_outMask[outMaskOffset] = outElem; } else { compactBlockWriteOutAnchorParallel(outElem != OBJDET_MASK_ELEMENT_INVALID_32U, outElem, d_outMask); } } struct applyHaarClassifierAnchorParallelFunctor { dim3 gridConf, blockConf; cudaStream_t cuStream; //Kernel arguments are stored as members; Ncv32u *d_IImg; Ncv32u IImgStride; Ncv32f *d_weights; Ncv32u weightsStride; HaarFeature64 *d_Features; HaarClassifierNode128 *d_ClassifierNodes; HaarStage64 *d_Stages; Ncv32u *d_inMask; Ncv32u *d_outMask; Ncv32u mask1Dlen; Ncv32u mask2Dstride; NcvSize32u anchorsRoi; Ncv32u startStageInc; Ncv32u endStageExc; Ncv32f scaleArea; //Arguments are passed through the constructor applyHaarClassifierAnchorParallelFunctor(dim3 _gridConf, dim3 _blockConf, cudaStream_t _cuStream, Ncv32u *_d_IImg, Ncv32u _IImgStride, Ncv32f *_d_weights, Ncv32u _weightsStride, HaarFeature64 *_d_Features, HaarClassifierNode128 *_d_ClassifierNodes, HaarStage64 *_d_Stages, Ncv32u *_d_inMask, Ncv32u *_d_outMask, Ncv32u _mask1Dlen, Ncv32u _mask2Dstride, NcvSize32u _anchorsRoi, Ncv32u _startStageInc, Ncv32u _endStageExc, Ncv32f _scaleArea) : gridConf(_gridConf), blockConf(_blockConf), cuStream(_cuStream), d_IImg(_d_IImg), IImgStride(_IImgStride), d_weights(_d_weights), weightsStride(_weightsStride), d_Features(_d_Features), d_ClassifierNodes(_d_ClassifierNodes), d_Stages(_d_Stages), d_inMask(_d_inMask), d_outMask(_d_outMask), mask1Dlen(_mask1Dlen), mask2Dstride(_mask2Dstride), anchorsRoi(_anchorsRoi), startStageInc(_startStageInc), endStageExc(_endStageExc), scaleArea(_scaleArea) {} template<class TList> void call(TList tl) { applyHaarClassifierAnchorParallel < Loki::TL::TypeAt<TList, 0>::Result::value, Loki::TL::TypeAt<TList, 1>::Result::value, Loki::TL::TypeAt<TList, 2>::Result::value, Loki::TL::TypeAt<TList, 3>::Result::value, Loki::TL::TypeAt<TList, 4>::Result::value > <<<gridConf, blockConf, 0, cuStream>>> (d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); } }; void applyHaarClassifierAnchorParallelDynTemplate(NcvBool tbInitMaskPositively, NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbReadPixelIndexFromVector, NcvBool tbDoAtomicCompaction, dim3 gridConf, dim3 blockConf, cudaStream_t cuStream, Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { applyHaarClassifierAnchorParallelFunctor functor(gridConf, blockConf, cuStream, d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); //Second parameter is the number of "dynamic" template parameters NCVRuntimeTemplateBool::KernelCaller<Loki::NullType, 5, applyHaarClassifierAnchorParallelFunctor> ::call( &functor, tbInitMaskPositively, tbCacheTextureIImg, tbCacheTextureCascade, tbReadPixelIndexFromVector, tbDoAtomicCompaction); } struct applyHaarClassifierClassifierParallelFunctor { dim3 gridConf, blockConf; cudaStream_t cuStream; //Kernel arguments are stored as members; Ncv32u *d_IImg; Ncv32u IImgStride; Ncv32f *d_weights; Ncv32u weightsStride; HaarFeature64 *d_Features; HaarClassifierNode128 *d_ClassifierNodes; HaarStage64 *d_Stages; Ncv32u *d_inMask; Ncv32u *d_outMask; Ncv32u mask1Dlen; Ncv32u mask2Dstride; NcvSize32u anchorsRoi; Ncv32u startStageInc; Ncv32u endStageExc; Ncv32f scaleArea; //Arguments are passed through the constructor applyHaarClassifierClassifierParallelFunctor(dim3 _gridConf, dim3 _blockConf, cudaStream_t _cuStream, Ncv32u *_d_IImg, Ncv32u _IImgStride, Ncv32f *_d_weights, Ncv32u _weightsStride, HaarFeature64 *_d_Features, HaarClassifierNode128 *_d_ClassifierNodes, HaarStage64 *_d_Stages, Ncv32u *_d_inMask, Ncv32u *_d_outMask, Ncv32u _mask1Dlen, Ncv32u _mask2Dstride, NcvSize32u _anchorsRoi, Ncv32u _startStageInc, Ncv32u _endStageExc, Ncv32f _scaleArea) : gridConf(_gridConf), blockConf(_blockConf), cuStream(_cuStream), d_IImg(_d_IImg), IImgStride(_IImgStride), d_weights(_d_weights), weightsStride(_weightsStride), d_Features(_d_Features), d_ClassifierNodes(_d_ClassifierNodes), d_Stages(_d_Stages), d_inMask(_d_inMask), d_outMask(_d_outMask), mask1Dlen(_mask1Dlen), mask2Dstride(_mask2Dstride), anchorsRoi(_anchorsRoi), startStageInc(_startStageInc), endStageExc(_endStageExc), scaleArea(_scaleArea) {} template<class TList> void call(TList tl) { applyHaarClassifierClassifierParallel < Loki::TL::TypeAt<TList, 0>::Result::value, Loki::TL::TypeAt<TList, 1>::Result::value, Loki::TL::TypeAt<TList, 2>::Result::value > <<<gridConf, blockConf, 0, cuStream>>> (d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); } }; void applyHaarClassifierClassifierParallelDynTemplate(NcvBool tbCacheTextureIImg, NcvBool tbCacheTextureCascade, NcvBool tbDoAtomicCompaction, dim3 gridConf, dim3 blockConf, cudaStream_t cuStream, Ncv32u *d_IImg, Ncv32u IImgStride, Ncv32f *d_weights, Ncv32u weightsStride, HaarFeature64 *d_Features, HaarClassifierNode128 *d_ClassifierNodes, HaarStage64 *d_Stages, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u startStageInc, Ncv32u endStageExc, Ncv32f scaleArea) { applyHaarClassifierClassifierParallelFunctor functor(gridConf, blockConf, cuStream, d_IImg, IImgStride, d_weights, weightsStride, d_Features, d_ClassifierNodes, d_Stages, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, startStageInc, endStageExc, scaleArea); //Second parameter is the number of "dynamic" template parameters NCVRuntimeTemplateBool::KernelCaller<Loki::NullType, 3, applyHaarClassifierClassifierParallelFunctor> ::call( &functor, tbCacheTextureIImg, tbCacheTextureCascade, tbDoAtomicCompaction); } struct initializeMaskVectorFunctor { dim3 gridConf, blockConf; cudaStream_t cuStream; //Kernel arguments are stored as members; Ncv32u *d_inMask; Ncv32u *d_outMask; Ncv32u mask1Dlen; Ncv32u mask2Dstride; NcvSize32u anchorsRoi; Ncv32u step; //Arguments are passed through the constructor initializeMaskVectorFunctor(dim3 _gridConf, dim3 _blockConf, cudaStream_t _cuStream, Ncv32u *_d_inMask, Ncv32u *_d_outMask, Ncv32u _mask1Dlen, Ncv32u _mask2Dstride, NcvSize32u _anchorsRoi, Ncv32u _step) : gridConf(_gridConf), blockConf(_blockConf), cuStream(_cuStream), d_inMask(_d_inMask), d_outMask(_d_outMask), mask1Dlen(_mask1Dlen), mask2Dstride(_mask2Dstride), anchorsRoi(_anchorsRoi), step(_step) {} template<class TList> void call(TList tl) { initializeMaskVector < Loki::TL::TypeAt<TList, 0>::Result::value, Loki::TL::TypeAt<TList, 1>::Result::value > <<<gridConf, blockConf, 0, cuStream>>> (d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, step); } }; void initializeMaskVectorDynTemplate(NcvBool tbMaskByInmask, NcvBool tbDoAtomicCompaction, dim3 gridConf, dim3 blockConf, cudaStream_t cuStream, Ncv32u *d_inMask, Ncv32u *d_outMask, Ncv32u mask1Dlen, Ncv32u mask2Dstride, NcvSize32u anchorsRoi, Ncv32u step) { initializeMaskVectorFunctor functor(gridConf, blockConf, cuStream, d_inMask, d_outMask, mask1Dlen, mask2Dstride, anchorsRoi, step); //Second parameter is the number of "dynamic" template parameters NCVRuntimeTemplateBool::KernelCaller<Loki::NullType, 2, initializeMaskVectorFunctor> ::call( &functor, tbMaskByInmask, tbDoAtomicCompaction); } Ncv32u getStageNumWithNotLessThanNclassifiers(Ncv32u N, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages) { for (Ncv32u i = 0; i<haar.NumStages; i++) { if (h_HaarStages.ptr()[i].getNumClassifierRootNodes() >= N) { return i; } } return haar.NumStages; } NCVStatus ncvApplyHaarClassifierCascade_device(NCVMatrix<Ncv32u> &d_integralImage, NCVMatrix<Ncv32f> &d_weights, NCVMatrixAlloc<Ncv32u> &d_pixelMask, Ncv32u &numDetections, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarStage64> &d_HaarStages, NCVVector<HaarClassifierNode128> &d_HaarNodes, NCVVector<HaarFeature64> &d_HaarFeatures, NcvBool bMaskElements, NcvSize32u anchorsRoi, Ncv32u pixelStep, Ncv32f scaleArea, INCVMemAllocator &gpuAllocator, INCVMemAllocator &cpuAllocator, cudaDeviceProp &devProp, cudaStream_t cuStream) { ncvAssertReturn(d_integralImage.memType() == d_weights.memType() && d_integralImage.memType() == d_pixelMask.memType() && d_integralImage.memType() == gpuAllocator.memType() && (d_integralImage.memType() == NCVMemoryTypeDevice || d_integralImage.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(d_HaarStages.memType() == d_HaarNodes.memType() && d_HaarStages.memType() == d_HaarFeatures.memType() && (d_HaarStages.memType() == NCVMemoryTypeDevice || d_HaarStages.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_HaarStages.memType() != NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(gpuAllocator.isInitialized() && cpuAllocator.isInitialized(), NCV_ALLOCATOR_NOT_INITIALIZED); ncvAssertReturn((d_integralImage.ptr() != NULL && d_weights.ptr() != NULL && d_pixelMask.ptr() != NULL && h_HaarStages.ptr() != NULL && d_HaarStages.ptr() != NULL && d_HaarNodes.ptr() != NULL && d_HaarFeatures.ptr() != NULL) || gpuAllocator.isCounting(), NCV_NULL_PTR); ncvAssertReturn(anchorsRoi.width > 0 && anchorsRoi.height > 0 && d_pixelMask.width() >= anchorsRoi.width && d_pixelMask.height() >= anchorsRoi.height && d_weights.width() >= anchorsRoi.width && d_weights.height() >= anchorsRoi.height && d_integralImage.width() >= anchorsRoi.width + haar.ClassifierSize.width && d_integralImage.height() >= anchorsRoi.height + haar.ClassifierSize.height, NCV_DIMENSIONS_INVALID); ncvAssertReturn(scaleArea > 0, NCV_INVALID_SCALE); ncvAssertReturn(d_HaarStages.length() >= haar.NumStages && d_HaarNodes.length() >= haar.NumClassifierTotalNodes && d_HaarFeatures.length() >= haar.NumFeatures && d_HaarStages.length() == h_HaarStages.length() && haar.NumClassifierRootNodes <= haar.NumClassifierTotalNodes, NCV_DIMENSIONS_INVALID); ncvAssertReturn(haar.bNeedsTiltedII == false || gpuAllocator.isCounting(), NCV_NOIMPL_HAAR_TILTED_FEATURES); ncvAssertReturn(pixelStep == 1 || pixelStep == 2, NCV_HAAR_INVALID_PIXEL_STEP); NCV_SET_SKIP_COND(gpuAllocator.isCounting()); #if defined _SELF_TEST_ NCVStatus ncvStat; NCVMatrixAlloc<Ncv32u> h_integralImage(cpuAllocator, d_integralImage.width, d_integralImage.height, d_integralImage.pitch); ncvAssertReturn(h_integralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32f> h_weights(cpuAllocator, d_weights.width, d_weights.height, d_weights.pitch); ncvAssertReturn(h_weights.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> h_pixelMask(cpuAllocator, d_pixelMask.width, d_pixelMask.height, d_pixelMask.pitch); ncvAssertReturn(h_pixelMask.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<HaarClassifierNode128> h_HaarNodes(cpuAllocator, d_HaarNodes.length); ncvAssertReturn(h_HaarNodes.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<HaarFeature64> h_HaarFeatures(cpuAllocator, d_HaarFeatures.length); ncvAssertReturn(h_HaarFeatures.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> h_pixelMask_d(cpuAllocator, d_pixelMask.width, d_pixelMask.height, d_pixelMask.pitch); ncvAssertReturn(h_pixelMask_d.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCV_SKIP_COND_BEGIN ncvStat = d_pixelMask.copySolid(h_pixelMask, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_integralImage.copySolid(h_integralImage, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_weights.copySolid(h_weights, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_HaarNodes.copySolid(h_HaarNodes, 0); ncvAssertReturnNcvStat(ncvStat); ncvStat = d_HaarFeatures.copySolid(h_HaarFeatures, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); for (Ncv32u i=0; i<(Ncv32u)anchorsRoi.height; i++) { for (Ncv32u j=0; j<d_pixelMask.stride(); j++) { if ((i%pixelStep==0) && (j%pixelStep==0) && (j<(Ncv32u)anchorsRoi.width)) { if (!bMaskElements || h_pixelMask.ptr[i*d_pixelMask.stride()+j] != OBJDET_MASK_ELEMENT_INVALID_32U) { h_pixelMask.ptr[i*d_pixelMask.stride()+j] = (i << 16) | j; } } else { h_pixelMask.ptr[i*d_pixelMask.stride()+j] = OBJDET_MASK_ELEMENT_INVALID_32U; } } } NCV_SKIP_COND_END #endif NCVVectorReuse<Ncv32u> d_vecPixelMask(d_pixelMask.getSegment(), anchorsRoi.height * d_pixelMask.stride()); ncvAssertReturn(d_vecPixelMask.isMemReused(), NCV_ALLOCATOR_BAD_REUSE); NCVVectorAlloc<Ncv32u> d_vecPixelMaskTmp(gpuAllocator, static_cast<Ncv32u>(d_vecPixelMask.length())); ncvAssertReturn(d_vecPixelMaskTmp.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<Ncv32u> hp_pool32u(cpuAllocator, 2); ncvAssertReturn(hp_pool32u.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); Ncv32u *hp_zero = &hp_pool32u.ptr()[0]; Ncv32u *hp_numDet = &hp_pool32u.ptr()[1]; NCV_SKIP_COND_BEGIN *hp_zero = 0; *hp_numDet = 0; NCV_SKIP_COND_END Ncv32f scaleAreaPixels = scaleArea * ((haar.ClassifierSize.width - 2*HAAR_STDDEV_BORDER) * (haar.ClassifierSize.height - 2*HAAR_STDDEV_BORDER)); NcvBool bTexCacheCascade = devProp.major < 2; NcvBool bTexCacheIImg = true; //this works better even on Fermi so far NcvBool bDoAtomicCompaction = devProp.major >= 2 || (devProp.major == 1 && devProp.minor >= 3); NCVVector<Ncv32u> *d_ptrNowData = &d_vecPixelMask; NCVVector<Ncv32u> *d_ptrNowTmp = &d_vecPixelMaskTmp; Ncv32u szNppCompactTmpBuf; nppsStCompactGetSize_32u(static_cast<Ncv32u>(d_vecPixelMask.length()), &szNppCompactTmpBuf, devProp); if (bDoAtomicCompaction) { szNppCompactTmpBuf = 0; } NCVVectorAlloc<Ncv8u> d_tmpBufCompact(gpuAllocator, szNppCompactTmpBuf); NCV_SKIP_COND_BEGIN if (bTexCacheIImg) { cudaChannelFormatDesc cfdTexIImage; cfdTexIImage = cudaCreateChannelDesc<Ncv32u>(); std::size_t alignmentOffset; ncvAssertCUDAReturn(cudaBindTexture(&alignmentOffset, texIImage, d_integralImage.ptr(), cfdTexIImage, (anchorsRoi.height + haar.ClassifierSize.height) * d_integralImage.pitch()), NCV_CUDA_ERROR); ncvAssertReturn(alignmentOffset==0, NCV_TEXTURE_BIND_ERROR); } if (bTexCacheCascade) { cudaChannelFormatDesc cfdTexHaarFeatures; cudaChannelFormatDesc cfdTexHaarClassifierNodes; cfdTexHaarFeatures = cudaCreateChannelDesc<uint2>(); cfdTexHaarClassifierNodes = cudaCreateChannelDesc<uint4>(); std::size_t alignmentOffset; ncvAssertCUDAReturn(cudaBindTexture(&alignmentOffset, texHaarFeatures, d_HaarFeatures.ptr(), cfdTexHaarFeatures,sizeof(HaarFeature64) * haar.NumFeatures), NCV_CUDA_ERROR); ncvAssertReturn(alignmentOffset==0, NCV_TEXTURE_BIND_ERROR); ncvAssertCUDAReturn(cudaBindTexture(&alignmentOffset, texHaarClassifierNodes, d_HaarNodes.ptr(), cfdTexHaarClassifierNodes, sizeof(HaarClassifierNode128) * haar.NumClassifierTotalNodes), NCV_CUDA_ERROR); ncvAssertReturn(alignmentOffset==0, NCV_TEXTURE_BIND_ERROR); } Ncv32u stageStartAnchorParallel = 0; Ncv32u stageMiddleSwitch = getStageNumWithNotLessThanNclassifiers(NUM_THREADS_CLASSIFIERPARALLEL, haar, h_HaarStages); Ncv32u stageEndClassifierParallel = haar.NumStages; if (stageMiddleSwitch == 0) { stageMiddleSwitch = 1; } //create stages subdivision for pixel-parallel processing const Ncv32u compactEveryNstage = bDoAtomicCompaction ? 7 : 1; Ncv32u curStop = stageStartAnchorParallel; std::vector<Ncv32u> pixParallelStageStops; while (curStop < stageMiddleSwitch) { pixParallelStageStops.push_back(curStop); curStop += compactEveryNstage; } if (curStop > compactEveryNstage && curStop - stageMiddleSwitch > compactEveryNstage / 2) { pixParallelStageStops[pixParallelStageStops.size()-1] = (stageMiddleSwitch - (curStop - 2 * compactEveryNstage)) / 2; } pixParallelStageStops.push_back(stageMiddleSwitch); Ncv32u pixParallelStageStopsIndex = 0; if (pixelStep != 1 || bMaskElements) { if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 gridInit((((anchorsRoi.width + pixelStep - 1) / pixelStep + NUM_THREADS_ANCHORSPARALLEL - 1) / NUM_THREADS_ANCHORSPARALLEL), (anchorsRoi.height + pixelStep - 1) / pixelStep); dim3 blockInit(NUM_THREADS_ANCHORSPARALLEL); if (gridInit.x == 0 || gridInit.y == 0) { numDetections = 0; return NCV_SUCCESS; } initializeMaskVectorDynTemplate(bMaskElements, bDoAtomicCompaction, gridInit, blockInit, cuStream, d_ptrNowData->ptr(), d_ptrNowTmp->ptr(), static_cast<Ncv32u>(d_vecPixelMask.length()), d_pixelMask.stride(), anchorsRoi, pixelStep); ncvAssertCUDAReturn(cudaGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); swap(d_ptrNowData, d_ptrNowTmp); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowTmp->ptr(), static_cast<Ncv32u>(d_vecPixelMask.length()), d_ptrNowData->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturn(nppSt == NPPST_SUCCESS, NCV_NPP_ERROR); } numDetections = *hp_numDet; } else { // // 1. Run the first pixel-input pixel-parallel classifier for few stages // if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 grid1(((d_pixelMask.stride() + NUM_THREADS_ANCHORSPARALLEL - 1) / NUM_THREADS_ANCHORSPARALLEL), anchorsRoi.height); dim3 block1(NUM_THREADS_ANCHORSPARALLEL); applyHaarClassifierAnchorParallelDynTemplate( true, //tbInitMaskPositively bTexCacheIImg, //tbCacheTextureIImg bTexCacheCascade, //tbCacheTextureCascade pixParallelStageStops[pixParallelStageStopsIndex] != 0,//tbReadPixelIndexFromVector bDoAtomicCompaction, //tbDoAtomicCompaction grid1, block1, cuStream, d_integralImage.ptr(), d_integralImage.stride(), d_weights.ptr(), d_weights.stride(), d_HaarFeatures.ptr(), d_HaarNodes.ptr(), d_HaarStages.ptr(), d_ptrNowData->ptr(), bDoAtomicCompaction ? d_ptrNowTmp->ptr() : d_ptrNowData->ptr(), 0, d_pixelMask.stride(), anchorsRoi, pixParallelStageStops[pixParallelStageStopsIndex], pixParallelStageStops[pixParallelStageStopsIndex+1], scaleAreaPixels); ncvAssertCUDAReturn(cudaGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowData->ptr(), static_cast<Ncv32u>(d_vecPixelMask.length()), d_ptrNowTmp->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturnNcvStat(nppSt); } swap(d_ptrNowData, d_ptrNowTmp); numDetections = *hp_numDet; pixParallelStageStopsIndex++; } // // 2. Run pixel-parallel stages // for (; pixParallelStageStopsIndex < pixParallelStageStops.size()-1; pixParallelStageStopsIndex++) { if (numDetections == 0) { break; } if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 grid2((numDetections + NUM_THREADS_ANCHORSPARALLEL - 1) / NUM_THREADS_ANCHORSPARALLEL); if (numDetections > MAX_GRID_DIM) { grid2.x = MAX_GRID_DIM; grid2.y = (numDetections + MAX_GRID_DIM - 1) / MAX_GRID_DIM; } dim3 block2(NUM_THREADS_ANCHORSPARALLEL); applyHaarClassifierAnchorParallelDynTemplate( false, //tbInitMaskPositively bTexCacheIImg, //tbCacheTextureIImg bTexCacheCascade, //tbCacheTextureCascade pixParallelStageStops[pixParallelStageStopsIndex] != 0 || pixelStep != 1 || bMaskElements,//tbReadPixelIndexFromVector bDoAtomicCompaction, //tbDoAtomicCompaction grid2, block2, cuStream, d_integralImage.ptr(), d_integralImage.stride(), d_weights.ptr(), d_weights.stride(), d_HaarFeatures.ptr(), d_HaarNodes.ptr(), d_HaarStages.ptr(), d_ptrNowData->ptr(), bDoAtomicCompaction ? d_ptrNowTmp->ptr() : d_ptrNowData->ptr(), numDetections, d_pixelMask.stride(), anchorsRoi, pixParallelStageStops[pixParallelStageStopsIndex], pixParallelStageStops[pixParallelStageStopsIndex+1], scaleAreaPixels); ncvAssertCUDAReturn(cudaGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowData->ptr(), numDetections, d_ptrNowTmp->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturnNcvStat(nppSt); } swap(d_ptrNowData, d_ptrNowTmp); numDetections = *hp_numDet; } // // 3. Run all left stages in one stage-parallel kernel // if (numDetections > 0 && stageMiddleSwitch < stageEndClassifierParallel) { if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaMemcpyToSymbolAsync(d_outMaskPosition, hp_zero, sizeof(Ncv32u), 0, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } dim3 grid3(numDetections); if (numDetections > MAX_GRID_DIM) { grid3.x = MAX_GRID_DIM; grid3.y = (numDetections + MAX_GRID_DIM - 1) / MAX_GRID_DIM; } dim3 block3(NUM_THREADS_CLASSIFIERPARALLEL); applyHaarClassifierClassifierParallelDynTemplate( bTexCacheIImg, //tbCacheTextureIImg bTexCacheCascade, //tbCacheTextureCascade bDoAtomicCompaction, //tbDoAtomicCompaction grid3, block3, cuStream, d_integralImage.ptr(), d_integralImage.stride(), d_weights.ptr(), d_weights.stride(), d_HaarFeatures.ptr(), d_HaarNodes.ptr(), d_HaarStages.ptr(), d_ptrNowData->ptr(), bDoAtomicCompaction ? d_ptrNowTmp->ptr() : d_ptrNowData->ptr(), numDetections, d_pixelMask.stride(), anchorsRoi, stageMiddleSwitch, stageEndClassifierParallel, scaleAreaPixels); ncvAssertCUDAReturn(cudaGetLastError(), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaMemcpyFromSymbolAsync(hp_numDet, d_outMaskPosition, sizeof(Ncv32u), 0, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } else { NCVStatus nppSt; nppSt = nppsStCompact_32u(d_ptrNowData->ptr(), numDetections, d_ptrNowTmp->ptr(), hp_numDet, OBJDET_MASK_ELEMENT_INVALID_32U, d_tmpBufCompact.ptr(), szNppCompactTmpBuf, devProp); ncvAssertReturnNcvStat(nppSt); } swap(d_ptrNowData, d_ptrNowTmp); numDetections = *hp_numDet; } if (d_ptrNowData != &d_vecPixelMask) { d_vecPixelMaskTmp.copySolid(d_vecPixelMask, cuStream); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } #if defined _SELF_TEST_ ncvStat = d_pixelMask.copySolid(h_pixelMask_d, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); if (bDoAtomicCompaction) { std::sort(h_pixelMask_d.ptr, h_pixelMask_d.ptr + numDetections); } Ncv32u fpu_oldcw, fpu_cw; _controlfp_s(&fpu_cw, 0, 0); fpu_oldcw = fpu_cw; _controlfp_s(&fpu_cw, _PC_24, _MCW_PC); Ncv32u numDetGold; ncvStat = ncvApplyHaarClassifierCascade_host(h_integralImage, h_weights, h_pixelMask, numDetGold, haar, h_HaarStages, h_HaarNodes, h_HaarFeatures, bMaskElements, anchorsRoi, pixelStep, scaleArea); ncvAssertReturnNcvStat(ncvStat); _controlfp_s(&fpu_cw, fpu_oldcw, _MCW_PC); bool bPass = true; if (numDetGold != numDetections) { printf("NCVHaarClassifierCascade::applyHaarClassifierCascade numdetections don't match: cpu=%d, gpu=%d\n", numDetGold, numDetections); bPass = false; } else { for (Ncv32u i=0; i<std::max(numDetGold, numDetections) && bPass; i++) { if (h_pixelMask.ptr[i] != h_pixelMask_d.ptr[i]) { printf("NCVHaarClassifierCascade::applyHaarClassifierCascade self test failed: i=%d, cpu=%d, gpu=%d\n", i, h_pixelMask.ptr[i], h_pixelMask_d.ptr[i]); bPass = false; } } } printf("NCVHaarClassifierCascade::applyHaarClassifierCascade %s\n", bPass?"PASSED":"FAILED"); #endif NCV_SKIP_COND_END return NCV_SUCCESS; } //============================================================================== // // HypothesesOperations file // //============================================================================== const Ncv32u NUM_GROW_THREADS = 128; __device__ __host__ NcvRect32u pixelToRect(Ncv32u pixel, Ncv32u width, Ncv32u height, Ncv32f scale) { NcvRect32u res; res.x = (Ncv32u)(scale * (pixel & 0xFFFF)); res.y = (Ncv32u)(scale * (pixel >> 16)); res.width = (Ncv32u)(scale * width); res.height = (Ncv32u)(scale * height); return res; } __global__ void growDetectionsKernel(Ncv32u *pixelMask, Ncv32u numElements, NcvRect32u *hypotheses, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32f curScale) { Ncv32u blockId = blockIdx.y * 65535 + blockIdx.x; Ncv32u elemAddr = blockId * NUM_GROW_THREADS + threadIdx.x; if (elemAddr >= numElements) { return; } hypotheses[elemAddr] = pixelToRect(pixelMask[elemAddr], rectWidth, rectHeight, curScale); } NCVStatus ncvGrowDetectionsVector_device(NCVVector<Ncv32u> &pixelMask, Ncv32u numPixelMaskDetections, NCVVector<NcvRect32u> &hypotheses, Ncv32u &totalDetections, Ncv32u totalMaxDetections, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32f curScale, cudaStream_t cuStream) { ncvAssertReturn(pixelMask.ptr() != NULL && hypotheses.ptr() != NULL, NCV_NULL_PTR); ncvAssertReturn(pixelMask.memType() == hypotheses.memType() && pixelMask.memType() == NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(rectWidth > 0 && rectHeight > 0 && curScale > 0, NCV_INVALID_ROI); ncvAssertReturn(curScale > 0, NCV_INVALID_SCALE); ncvAssertReturn(totalMaxDetections <= hypotheses.length() && numPixelMaskDetections <= pixelMask.length(), NCV_INCONSISTENT_INPUT); NCVStatus ncvStat = NCV_SUCCESS; Ncv32u numDetsToCopy = numPixelMaskDetections; if (numDetsToCopy == 0) { return ncvStat; } if (totalDetections + numPixelMaskDetections > totalMaxDetections) { ncvStat = NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW; numDetsToCopy = totalMaxDetections - totalDetections; } dim3 block(NUM_GROW_THREADS); dim3 grid((numDetsToCopy + NUM_GROW_THREADS - 1) / NUM_GROW_THREADS); if (grid.x > 65535) { grid.y = (grid.x + 65534) / 65535; grid.x = 65535; } growDetectionsKernel<<<grid, block, 0, cuStream>>>(pixelMask.ptr(), numDetsToCopy, hypotheses.ptr() + totalDetections, rectWidth, rectHeight, curScale); ncvAssertCUDAReturn(cudaGetLastError(), NCV_CUDA_ERROR); totalDetections += numDetsToCopy; return ncvStat; } //============================================================================== // // Pipeline file // //============================================================================== NCVStatus ncvDetectObjectsMultiScale_device(NCVMatrix<Ncv8u> &d_srcImg, NcvSize32u srcRoi, NCVVector<NcvRect32u> &d_dstRects, Ncv32u &dstNumRects, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarStage64> &d_HaarStages, NCVVector<HaarClassifierNode128> &d_HaarNodes, NCVVector<HaarFeature64> &d_HaarFeatures, NcvSize32u minObjSize, Ncv32u minNeighbors, //default 4 Ncv32f scaleStep, //default 1.2f Ncv32u pixelStep, //default 1 Ncv32u flags, //default NCVPipeObjDet_Default INCVMemAllocator &gpuAllocator, INCVMemAllocator &cpuAllocator, cudaDeviceProp &devProp, cudaStream_t cuStream) { ncvAssertReturn(d_srcImg.memType() == d_dstRects.memType() && d_srcImg.memType() == gpuAllocator.memType() && (d_srcImg.memType() == NCVMemoryTypeDevice || d_srcImg.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(d_HaarStages.memType() == d_HaarNodes.memType() && d_HaarStages.memType() == d_HaarFeatures.memType() && (d_HaarStages.memType() == NCVMemoryTypeDevice || d_HaarStages.memType() == NCVMemoryTypeNone), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_HaarStages.memType() != NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(gpuAllocator.isInitialized() && cpuAllocator.isInitialized(), NCV_ALLOCATOR_NOT_INITIALIZED); ncvAssertReturn((d_srcImg.ptr() != NULL && d_dstRects.ptr() != NULL && h_HaarStages.ptr() != NULL && d_HaarStages.ptr() != NULL && d_HaarNodes.ptr() != NULL && d_HaarFeatures.ptr() != NULL) || gpuAllocator.isCounting(), NCV_NULL_PTR); ncvAssertReturn(srcRoi.width > 0 && srcRoi.height > 0 && d_srcImg.width() >= srcRoi.width && d_srcImg.height() >= srcRoi.height && srcRoi.width >= minObjSize.width && srcRoi.height >= minObjSize.height && d_dstRects.length() >= 1, NCV_DIMENSIONS_INVALID); ncvAssertReturn(scaleStep > 1.0f, NCV_INVALID_SCALE); ncvAssertReturn(d_HaarStages.length() >= haar.NumStages && d_HaarNodes.length() >= haar.NumClassifierTotalNodes && d_HaarFeatures.length() >= haar.NumFeatures && d_HaarStages.length() == h_HaarStages.length() && haar.NumClassifierRootNodes <= haar.NumClassifierTotalNodes, NCV_DIMENSIONS_INVALID); ncvAssertReturn(haar.bNeedsTiltedII == false, NCV_NOIMPL_HAAR_TILTED_FEATURES); ncvAssertReturn(pixelStep == 1 || pixelStep == 2, NCV_HAAR_INVALID_PIXEL_STEP); //TODO: set NPP active stream to cuStream NCVStatus ncvStat; NCV_SET_SKIP_COND(gpuAllocator.isCounting()); Ncv32u integralWidth = d_srcImg.width() + 1; Ncv32u integralHeight = d_srcImg.height() + 1; NCVMatrixAlloc<Ncv32u> d_integralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_integralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv64u> d_sqIntegralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_sqIntegralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32f> d_rectStdDev(gpuAllocator, d_srcImg.width(), d_srcImg.height()); ncvAssertReturn(d_rectStdDev.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> d_pixelMask(gpuAllocator, d_srcImg.width(), d_srcImg.height()); ncvAssertReturn(d_pixelMask.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv32u> d_scaledIntegralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_scaledIntegralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVMatrixAlloc<Ncv64u> d_scaledSqIntegralImage(gpuAllocator, integralWidth, integralHeight); ncvAssertReturn(d_scaledSqIntegralImage.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<NcvRect32u> d_hypothesesIntermediate(gpuAllocator, d_srcImg.width() * d_srcImg.height()); ncvAssertReturn(d_hypothesesIntermediate.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<NcvRect32u> h_hypothesesIntermediate(cpuAllocator, d_srcImg.width() * d_srcImg.height()); ncvAssertReturn(h_hypothesesIntermediate.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVStatus nppStat; Ncv32u szTmpBufIntegral, szTmpBufSqIntegral; nppStat = nppiStIntegralGetSize_8u32u(NcvSize32u(d_srcImg.width(), d_srcImg.height()), &szTmpBufIntegral, devProp); ncvAssertReturnNcvStat(nppStat); nppStat = nppiStSqrIntegralGetSize_8u64u(NcvSize32u(d_srcImg.width(), d_srcImg.height()), &szTmpBufSqIntegral, devProp); ncvAssertReturnNcvStat(nppStat); NCVVectorAlloc<Ncv8u> d_tmpIIbuf(gpuAllocator, std::max(szTmpBufIntegral, szTmpBufSqIntegral)); ncvAssertReturn(d_tmpIIbuf.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCV_SKIP_COND_BEGIN nppStat = nppiStIntegral_8u32u_C1R(d_srcImg.ptr(), d_srcImg.pitch(), d_integralImage.ptr(), d_integralImage.pitch(), NcvSize32u(d_srcImg.width(), d_srcImg.height()), d_tmpIIbuf.ptr(), szTmpBufIntegral, devProp); ncvAssertReturnNcvStat(nppStat); nppStat = nppiStSqrIntegral_8u64u_C1R(d_srcImg.ptr(), d_srcImg.pitch(), d_sqIntegralImage.ptr(), d_sqIntegralImage.pitch(), NcvSize32u(d_srcImg.width(), d_srcImg.height()), d_tmpIIbuf.ptr(), szTmpBufSqIntegral, devProp); ncvAssertReturnNcvStat(nppStat); NCV_SKIP_COND_END dstNumRects = 0; Ncv32u lastCheckedScale = 0; NcvBool bReverseTraverseScale = ((flags & NCVPipeObjDet_FindLargestObject) != 0); std::vector<Ncv32u> scalesVector; NcvBool bFoundLargestFace = false; for (Ncv32f scaleIter = 1.0f; ; scaleIter *= scaleStep) { Ncv32u scale = (Ncv32u)scaleIter; if (lastCheckedScale == scale) { continue; } lastCheckedScale = scale; if (haar.ClassifierSize.width * (Ncv32s)scale < minObjSize.width || haar.ClassifierSize.height * (Ncv32s)scale < minObjSize.height) { continue; } NcvSize32s srcRoi, srcIIRoi, scaledIIRoi, searchRoi; srcRoi.width = d_srcImg.width(); srcRoi.height = d_srcImg.height(); srcIIRoi.width = srcRoi.width + 1; srcIIRoi.height = srcRoi.height + 1; scaledIIRoi.width = srcIIRoi.width / scale; scaledIIRoi.height = srcIIRoi.height / scale; searchRoi.width = scaledIIRoi.width - haar.ClassifierSize.width; searchRoi.height = scaledIIRoi.height - haar.ClassifierSize.height; if (searchRoi.width <= 0 || searchRoi.height <= 0) { break; } scalesVector.push_back(scale); if (gpuAllocator.isCounting()) { break; } } if (bReverseTraverseScale) { std::reverse(scalesVector.begin(), scalesVector.end()); } //TODO: handle _fair_scale_ flag for (Ncv32u i=0; i<scalesVector.size(); i++) { Ncv32u scale = scalesVector[i]; NcvSize32u srcRoi, scaledIIRoi, searchRoi; NcvSize32u srcIIRoi; srcRoi.width = d_srcImg.width(); srcRoi.height = d_srcImg.height(); srcIIRoi.width = srcRoi.width + 1; srcIIRoi.height = srcRoi.height + 1; scaledIIRoi.width = srcIIRoi.width / scale; scaledIIRoi.height = srcIIRoi.height / scale; searchRoi.width = scaledIIRoi.width - haar.ClassifierSize.width; searchRoi.height = scaledIIRoi.height - haar.ClassifierSize.height; NCV_SKIP_COND_BEGIN nppStat = nppiStDecimate_32u_C1R( d_integralImage.ptr(), d_integralImage.pitch(), d_scaledIntegralImage.ptr(), d_scaledIntegralImage.pitch(), srcIIRoi, scale, true); ncvAssertReturnNcvStat(nppStat); nppStat = nppiStDecimate_64u_C1R( d_sqIntegralImage.ptr(), d_sqIntegralImage.pitch(), d_scaledSqIntegralImage.ptr(), d_scaledSqIntegralImage.pitch(), srcIIRoi, scale, true); ncvAssertReturnNcvStat(nppStat); const NcvRect32u rect( HAAR_STDDEV_BORDER, HAAR_STDDEV_BORDER, haar.ClassifierSize.width - 2*HAAR_STDDEV_BORDER, haar.ClassifierSize.height - 2*HAAR_STDDEV_BORDER); nppStat = nppiStRectStdDev_32f_C1R( d_scaledIntegralImage.ptr(), d_scaledIntegralImage.pitch(), d_scaledSqIntegralImage.ptr(), d_scaledSqIntegralImage.pitch(), d_rectStdDev.ptr(), d_rectStdDev.pitch(), NcvSize32u(searchRoi.width, searchRoi.height), rect, (Ncv32f)scale*scale, true); ncvAssertReturnNcvStat(nppStat); NCV_SKIP_COND_END Ncv32u detectionsOnThisScale; ncvStat = ncvApplyHaarClassifierCascade_device( d_scaledIntegralImage, d_rectStdDev, d_pixelMask, detectionsOnThisScale, haar, h_HaarStages, d_HaarStages, d_HaarNodes, d_HaarFeatures, false, searchRoi, pixelStep, (Ncv32f)scale*scale, gpuAllocator, cpuAllocator, devProp, cuStream); ncvAssertReturnNcvStat(nppStat); NCV_SKIP_COND_BEGIN NCVVectorReuse<Ncv32u> d_vecPixelMask(d_pixelMask.getSegment()); ncvStat = ncvGrowDetectionsVector_device( d_vecPixelMask, detectionsOnThisScale, d_hypothesesIntermediate, dstNumRects, static_cast<Ncv32u>(d_hypothesesIntermediate.length()), haar.ClassifierSize.width, haar.ClassifierSize.height, (Ncv32f)scale, cuStream); ncvAssertReturn(ncvStat == NCV_SUCCESS, ncvStat); if (flags & NCVPipeObjDet_FindLargestObject) { if (dstNumRects == 0) { continue; } if (dstNumRects != 0) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvStat = d_hypothesesIntermediate.copySolid(h_hypothesesIntermediate, cuStream, dstNumRects * sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } Ncv32u numStrongHypothesesNow = dstNumRects; // TODO Fix this to be back operational /* ncvStat = ncvGroupRectangles_host( h_hypothesesIntermediate, numStrongHypothesesNow, minNeighbors, RECT_SIMILARITY_PROPORTION, NULL); ncvAssertReturnNcvStat(ncvStat); */ if (numStrongHypothesesNow > 0) { NcvRect32u maxRect = h_hypothesesIntermediate.ptr()[0]; for (Ncv32u j=1; j<numStrongHypothesesNow; j++) { if (maxRect.width < h_hypothesesIntermediate.ptr()[j].width) { maxRect = h_hypothesesIntermediate.ptr()[j]; } } h_hypothesesIntermediate.ptr()[0] = maxRect; dstNumRects = 1; ncvStat = h_hypothesesIntermediate.copySolid(d_dstRects, cuStream, sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); bFoundLargestFace = true; break; } } NCV_SKIP_COND_END if (gpuAllocator.isCounting()) { break; } } NCVStatus ncvRetCode = NCV_SUCCESS; NCV_SKIP_COND_BEGIN if (flags & NCVPipeObjDet_FindLargestObject) { if (!bFoundLargestFace) { dstNumRects = 0; } } else { //TODO: move hypotheses filtration to GPU pipeline (the only CPU-resident element of the pipeline left) if (dstNumRects != 0) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvStat = d_hypothesesIntermediate.copySolid(h_hypothesesIntermediate, cuStream, dstNumRects * sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); } // Todo fix this to be back operational /* ncvStat = ncvGroupRectangles_host( h_hypothesesIntermediate, dstNumRects, minNeighbors, RECT_SIMILARITY_PROPORTION, NULL); ncvAssertReturnNcvStat(ncvStat); */ if (dstNumRects > d_dstRects.length()) { ncvRetCode = NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW; dstNumRects = static_cast<Ncv32u>(d_dstRects.length()); } if (dstNumRects != 0) { ncvStat = h_hypothesesIntermediate.copySolid(d_dstRects, cuStream, dstNumRects * sizeof(NcvRect32u)); ncvAssertReturnNcvStat(ncvStat); } } if (flags & NCVPipeObjDet_VisualizeInPlace) { ncvAssertCUDAReturn(cudaStreamSynchronize(cuStream), NCV_CUDA_ERROR); ncvDrawRects_8u_device(d_srcImg.ptr(), d_srcImg.stride(), d_srcImg.width(), d_srcImg.height(), d_dstRects.ptr(), dstNumRects, 255, cuStream); } NCV_SKIP_COND_END return ncvRetCode; } //============================================================================== // // Purely Host code: classifier IO, mock-ups // //============================================================================== #ifdef _SELF_TEST_ #include <float.h> #endif #define NVBIN_HAAR_SIZERESERVED 16 #define NVBIN_HAAR_VERSION 0x1 NCVStatus ncvApplyHaarClassifierCascade_host(NCVMatrix<Ncv32u> &h_integralImage, NCVMatrix<Ncv32f> &h_weights, NCVMatrixAlloc<Ncv32u> &h_pixelMask, Ncv32u &numDetections, HaarClassifierCascadeDescriptor &haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarClassifierNode128> &h_HaarNodes, NCVVector<HaarFeature64> &h_HaarFeatures, NcvBool bMaskElements, NcvSize32u anchorsRoi, Ncv32u pixelStep, Ncv32f scaleArea) { ncvAssertReturn(h_integralImage.memType() == h_weights.memType() && h_integralImage.memType() == h_pixelMask.memType() && (h_integralImage.memType() == NCVMemoryTypeHostPageable || h_integralImage.memType() == NCVMemoryTypeHostPinned), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_HaarStages.memType() == h_HaarNodes.memType() && h_HaarStages.memType() == h_HaarFeatures.memType() && (h_HaarStages.memType() == NCVMemoryTypeHostPageable || h_HaarStages.memType() == NCVMemoryTypeHostPinned), NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(h_integralImage.ptr() != NULL && h_weights.ptr() != NULL && h_pixelMask.ptr() != NULL && h_HaarStages.ptr() != NULL && h_HaarNodes.ptr() != NULL && h_HaarFeatures.ptr() != NULL, NCV_NULL_PTR); ncvAssertReturn(anchorsRoi.width > 0 && anchorsRoi.height > 0 && h_pixelMask.width() >= anchorsRoi.width && h_pixelMask.height() >= anchorsRoi.height && h_weights.width() >= anchorsRoi.width && h_weights.height() >= anchorsRoi.height && h_integralImage.width() >= anchorsRoi.width + haar.ClassifierSize.width && h_integralImage.height() >= anchorsRoi.height + haar.ClassifierSize.height, NCV_DIMENSIONS_INVALID); ncvAssertReturn(scaleArea > 0, NCV_INVALID_SCALE); ncvAssertReturn(h_HaarStages.length() >= haar.NumStages && h_HaarNodes.length() >= haar.NumClassifierTotalNodes && h_HaarFeatures.length() >= haar.NumFeatures && h_HaarStages.length() == h_HaarStages.length() && haar.NumClassifierRootNodes <= haar.NumClassifierTotalNodes, NCV_DIMENSIONS_INVALID); ncvAssertReturn(haar.bNeedsTiltedII == false, NCV_NOIMPL_HAAR_TILTED_FEATURES); ncvAssertReturn(pixelStep == 1 || pixelStep == 2, NCV_HAAR_INVALID_PIXEL_STEP); Ncv32f scaleAreaPixels = scaleArea * ((haar.ClassifierSize.width - 2*HAAR_STDDEV_BORDER) * (haar.ClassifierSize.height - 2*HAAR_STDDEV_BORDER)); for (Ncv32u i=0; i<anchorsRoi.height; i++) { for (Ncv32u j=0; j<h_pixelMask.stride(); j++) { if (i % pixelStep != 0 || j % pixelStep != 0 || j >= anchorsRoi.width) { h_pixelMask.ptr()[i * h_pixelMask.stride() + j] = OBJDET_MASK_ELEMENT_INVALID_32U; } else { for (Ncv32u iStage = 0; iStage < haar.NumStages; iStage++) { Ncv32f curStageSum = 0.0f; Ncv32u numRootNodesInStage = h_HaarStages.ptr()[iStage].getNumClassifierRootNodes(); Ncv32u curRootNodeOffset = h_HaarStages.ptr()[iStage].getStartClassifierRootNodeOffset(); if (iStage == 0) { if (bMaskElements && h_pixelMask.ptr()[i * h_pixelMask.stride() + j] == OBJDET_MASK_ELEMENT_INVALID_32U) { break; } else { h_pixelMask.ptr()[i * h_pixelMask.stride() + j] = ((i << 16) | j); } } else if (h_pixelMask.ptr()[i * h_pixelMask.stride() + j] == OBJDET_MASK_ELEMENT_INVALID_32U) { break; } while (numRootNodesInStage--) { NcvBool bMoreNodesToTraverse = true; Ncv32u curNodeOffset = curRootNodeOffset; while (bMoreNodesToTraverse) { HaarClassifierNode128 curNode = h_HaarNodes.ptr()[curNodeOffset]; HaarFeatureDescriptor32 curFeatDesc = curNode.getFeatureDesc(); Ncv32u curNodeFeaturesNum = curFeatDesc.getNumFeatures(); Ncv32u curNodeFeaturesOffs = curFeatDesc.getFeaturesOffset(); Ncv32f curNodeVal = 0.f; for (Ncv32u iRect=0; iRect<curNodeFeaturesNum; iRect++) { HaarFeature64 feature = h_HaarFeatures.ptr()[curNodeFeaturesOffs + iRect]; Ncv32u rectX, rectY, rectWidth, rectHeight; feature.getRect(&rectX, &rectY, &rectWidth, &rectHeight); Ncv32f rectWeight = feature.getWeight(); Ncv32u iioffsTL = (i + rectY) * h_integralImage.stride() + (j + rectX); Ncv32u iioffsTR = iioffsTL + rectWidth; Ncv32u iioffsBL = iioffsTL + rectHeight * h_integralImage.stride(); Ncv32u iioffsBR = iioffsBL + rectWidth; Ncv32u iivalTL = h_integralImage.ptr()[iioffsTL]; Ncv32u iivalTR = h_integralImage.ptr()[iioffsTR]; Ncv32u iivalBL = h_integralImage.ptr()[iioffsBL]; Ncv32u iivalBR = h_integralImage.ptr()[iioffsBR]; Ncv32u rectSum = iivalBR - iivalBL + iivalTL - iivalTR; curNodeVal += (Ncv32f)rectSum * rectWeight; } HaarClassifierNodeDescriptor32 nodeLeft = curNode.getLeftNodeDesc(); HaarClassifierNodeDescriptor32 nodeRight = curNode.getRightNodeDesc(); Ncv32f nodeThreshold = curNode.getThreshold(); HaarClassifierNodeDescriptor32 nextNodeDescriptor; NcvBool nextNodeIsLeaf; if (curNodeVal < scaleAreaPixels * h_weights.ptr()[i * h_weights.stride() + j] * nodeThreshold) { nextNodeDescriptor = nodeLeft; nextNodeIsLeaf = curFeatDesc.isLeftNodeLeaf(); } else { nextNodeDescriptor = nodeRight; nextNodeIsLeaf = curFeatDesc.isRightNodeLeaf(); } if (nextNodeIsLeaf) { Ncv32f tmpLeafValue = nextNodeDescriptor.getLeafValueHost(); curStageSum += tmpLeafValue; bMoreNodesToTraverse = false; } else { curNodeOffset = nextNodeDescriptor.getNextNodeOffset(); } } curRootNodeOffset++; } Ncv32f tmpStageThreshold = h_HaarStages.ptr()[iStage].getStageThreshold(); if (curStageSum < tmpStageThreshold) { //drop h_pixelMask.ptr()[i * h_pixelMask.stride() + j] = OBJDET_MASK_ELEMENT_INVALID_32U; break; } } } } } std::sort(h_pixelMask.ptr(), h_pixelMask.ptr() + anchorsRoi.height * h_pixelMask.stride()); Ncv32u i = 0; for (; i<anchorsRoi.height * h_pixelMask.stride(); i++) { if (h_pixelMask.ptr()[i] == OBJDET_MASK_ELEMENT_INVALID_32U) { break; } } numDetections = i; return NCV_SUCCESS; } NCVStatus ncvGrowDetectionsVector_host(NCVVector<Ncv32u> &pixelMask, Ncv32u numPixelMaskDetections, NCVVector<NcvRect32u> &hypotheses, Ncv32u &totalDetections, Ncv32u totalMaxDetections, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32f curScale) { ncvAssertReturn(pixelMask.ptr() != NULL && hypotheses.ptr() != NULL, NCV_NULL_PTR); ncvAssertReturn(pixelMask.memType() == hypotheses.memType() && pixelMask.memType() != NCVMemoryTypeDevice, NCV_MEM_RESIDENCE_ERROR); ncvAssertReturn(rectWidth > 0 && rectHeight > 0 && curScale > 0, NCV_INVALID_ROI); ncvAssertReturn(curScale > 0, NCV_INVALID_SCALE); ncvAssertReturn(totalMaxDetections <= hypotheses.length() && numPixelMaskDetections <= pixelMask.length(), NCV_INCONSISTENT_INPUT); NCVStatus ncvStat = NCV_SUCCESS; Ncv32u numDetsToCopy = numPixelMaskDetections; if (numDetsToCopy == 0) { return ncvStat; } if (totalDetections + numPixelMaskDetections > totalMaxDetections) { ncvStat = NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW; numDetsToCopy = totalMaxDetections - totalDetections; } for (Ncv32u i=0; i<numDetsToCopy; i++) { hypotheses.ptr()[totalDetections + i] = pixelToRect(pixelMask.ptr()[i], rectWidth, rectHeight, curScale); } totalDetections += numDetsToCopy; return ncvStat; } NCVStatus ncvHaarStoreNVBIN_host(const std::string &filename, HaarClassifierCascadeDescriptor haar, NCVVector<HaarStage64> &h_HaarStages, NCVVector<HaarClassifierNode128> &h_HaarNodes, NCVVector<HaarFeature64> &h_HaarFeatures) { ncvAssertReturn(h_HaarStages.length() >= haar.NumStages, NCV_INCONSISTENT_INPUT); ncvAssertReturn(h_HaarNodes.length() >= haar.NumClassifierTotalNodes, NCV_INCONSISTENT_INPUT); ncvAssertReturn(h_HaarFeatures.length() >= haar.NumFeatures, NCV_INCONSISTENT_INPUT); ncvAssertReturn(h_HaarStages.memType() == NCVMemoryTypeHostPinned && h_HaarNodes.memType() == NCVMemoryTypeHostPinned && h_HaarFeatures.memType() == NCVMemoryTypeHostPinned, NCV_MEM_RESIDENCE_ERROR); Ncv32u szStages = haar.NumStages * sizeof(HaarStage64); Ncv32u szClassifiers = haar.NumClassifierTotalNodes * sizeof(HaarClassifierNode128); Ncv32u szFeatures = haar.NumFeatures * sizeof(HaarFeature64); Ncv32u dataOffset = 0; std::vector<unsigned char> fdata; fdata.resize(szStages+szClassifiers+szFeatures+1024, 0); //header *(Ncv32u *)(&fdata[0]+dataOffset) = NVBIN_HAAR_VERSION; //data dataOffset = NVBIN_HAAR_SIZERESERVED; *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumStages; dataOffset += sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumClassifierRootNodes; dataOffset += sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumClassifierTotalNodes; dataOffset += sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = haar.NumFeatures; dataOffset += sizeof(Ncv32u); *(NcvSize32u *)(&fdata[0]+dataOffset) = haar.ClassifierSize; dataOffset += sizeof(NcvSize32u); *(NcvBool *)(&fdata[0]+dataOffset) = haar.bNeedsTiltedII; dataOffset += sizeof(NcvBool); *(NcvBool *)(&fdata[0]+dataOffset) = haar.bHasStumpsOnly; dataOffset += sizeof(NcvBool); memcpy(&fdata[0]+dataOffset, h_HaarStages.ptr(), szStages); dataOffset += szStages; memcpy(&fdata[0]+dataOffset, h_HaarNodes.ptr(), szClassifiers); dataOffset += szClassifiers; memcpy(&fdata[0]+dataOffset, h_HaarFeatures.ptr(), szFeatures); dataOffset += szFeatures; Ncv32u fsize = dataOffset; //TODO: CRC32 here //update header dataOffset = sizeof(Ncv32u); *(Ncv32u *)(&fdata[0]+dataOffset) = fsize; FILE *fp = fopen(filename.c_str(), "wb"); ncvAssertReturn(fp != NULL, NCV_FILE_ERROR); fwrite(&fdata[0], fsize, 1, fp); fclose(fp); return NCV_SUCCESS; }
85001b9e0b5cd983d22d031e81febae6850d681b.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #define N 256 #define MaxColor 255 int *a; __device__ double CxMin = -2.5; __device__ double CxMax = 1.5; __device__ double CyMin = -2.0; __device__ double CyMax = 2.0; __device__ int seriesConverges(int x, int y,int width){ double Cx,Cy,PixelHeight,PixelWidth; double Zx,Zy,Zx2,Zy2; PixelWidth = (CxMax-CxMin)/width; PixelHeight = (CyMax-CyMin)/width; Cy = CyMin +x*PixelHeight; if (fabs(Cy) < PixelHeight/2) { Cy = 0.0; } Cx = CxMin + y*PixelWidth; int color = 1; Zx = 0.0; Zy = 0.0; Zx2 = 0.0; Zy2 = 0.0; for (int i = 0; i < 512 && ((Zx2+Zy2)<4); i++) { Zx2 = Zx*Zx; Zy2 = Zy*Zy; Zy *= Zx; Zy += Zy+Cy; Zx = Zx2-Zy2+Cx; color++; } return color; } __global__ void mandelKernel(int *a, int width) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < width) { for (int j = 0; j < width; j++) { a[i*width+j] = seriesConverges(i,j,width); } } } void mandelDevice(int *a, int tam) { float time; hipEvent_t start, stop; int *aD; int size = N*N*tam*tam*sizeof(int); int tam2 = N*N*tam*tam; int bsize =ceil((float)tam2/(float)1024); dim3 bloques(bsize); dim3 hilos (1024); hipSetDevice(0); hipMalloc(&aD, size); hipMemcpy(aD, a, size, hipMemcpyDefault); hipEventCreate(&start); hipEventCreate(&stop); hipEventRecord(start, 0); hipLaunchKernelGGL(( mandelKernel), dim3(bloques), dim3(hilos), 0, 0, aD,N*tam); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&time, start, stop); printf("%3.1f \n", time); hipMemcpy(a, aD, size, hipMemcpyDefault); hipFree(aD); } int main() { FILE *fp; static unsigned char color[3]; int colorValue; for(int counter = 50; counter<=50; counter++){ a = (int *)calloc(N*N*counter*counter,sizeof(int)); mandelDevice(a, counter); fp = fopen("mandelbrotSet2.ppm","wb"); fprintf(fp,"P6\n #\n %d\n %d\n %d\n",N*counter,N*counter,MaxColor); for (int i = 0; i < N*counter; i++) { for(int j = 0; j < N*counter; j++) { colorValue = a[i*N*counter+j]; color[0] = (unsigned char)colorValue%MaxColor; color[1] = (unsigned char)colorValue%MaxColor; color[2] = (unsigned char)colorValue%MaxColor; fwrite(color,1,3,fp); } } fclose(fp); free(a); } return 0; }
85001b9e0b5cd983d22d031e81febae6850d681b.cu
#include <stdio.h> #include <stdlib.h> #include <math.h> #define N 256 #define MaxColor 255 int *a; __device__ double CxMin = -2.5; __device__ double CxMax = 1.5; __device__ double CyMin = -2.0; __device__ double CyMax = 2.0; __device__ int seriesConverges(int x, int y,int width){ double Cx,Cy,PixelHeight,PixelWidth; double Zx,Zy,Zx2,Zy2; PixelWidth = (CxMax-CxMin)/width; PixelHeight = (CyMax-CyMin)/width; Cy = CyMin +x*PixelHeight; if (fabs(Cy) < PixelHeight/2) { Cy = 0.0; } Cx = CxMin + y*PixelWidth; int color = 1; Zx = 0.0; Zy = 0.0; Zx2 = 0.0; Zy2 = 0.0; for (int i = 0; i < 512 && ((Zx2+Zy2)<4); i++) { Zx2 = Zx*Zx; Zy2 = Zy*Zy; Zy *= Zx; Zy += Zy+Cy; Zx = Zx2-Zy2+Cx; color++; } return color; } __global__ void mandelKernel(int *a, int width) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < width) { for (int j = 0; j < width; j++) { a[i*width+j] = seriesConverges(i,j,width); } } } void mandelDevice(int *a, int tam) { float time; cudaEvent_t start, stop; int *aD; int size = N*N*tam*tam*sizeof(int); int tam2 = N*N*tam*tam; int bsize =ceil((float)tam2/(float)1024); dim3 bloques(bsize); dim3 hilos (1024); cudaSetDevice(0); cudaMalloc(&aD, size); cudaMemcpy(aD, a, size, cudaMemcpyDefault); cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start, 0); mandelKernel<<<bloques, hilos>>>(aD,N*tam); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&time, start, stop); printf("%3.1f \n", time); cudaMemcpy(a, aD, size, cudaMemcpyDefault); cudaFree(aD); } int main() { FILE *fp; static unsigned char color[3]; int colorValue; for(int counter = 50; counter<=50; counter++){ a = (int *)calloc(N*N*counter*counter,sizeof(int)); mandelDevice(a, counter); fp = fopen("mandelbrotSet2.ppm","wb"); fprintf(fp,"P6\n #\n %d\n %d\n %d\n",N*counter,N*counter,MaxColor); for (int i = 0; i < N*counter; i++) { for(int j = 0; j < N*counter; j++) { colorValue = a[i*N*counter+j]; color[0] = (unsigned char)colorValue%MaxColor; color[1] = (unsigned char)colorValue%MaxColor; color[2] = (unsigned char)colorValue%MaxColor; fwrite(color,1,3,fp); } } fclose(fp); free(a); } return 0; }
096af14b0b5e1be8488bfe91693703f2b2c236ca.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kernel.h" template <unsigned nthdsPerCTA> __launch_bounds__(nthdsPerCTA) __global__ void pReLUKernel( const int n, const float negativeSlope, const float* input, float* output) { for (int i = blockIdx.x * nthdsPerCTA + threadIdx.x; i < n; i += gridDim.x * nthdsPerCTA) { output[i] = input[i] > 0 ? input[i] : input[i] * negativeSlope; } } pluginStatus_t lReLUGPU( hipStream_t stream, const int n, const float negativeSlope, const void* input, void* output) { const int BS = 512; const int GS = (n + BS - 1) / BS; hipLaunchKernelGGL(( pReLUKernel<BS>), dim3(GS), dim3(BS), 0, stream, n, negativeSlope, (const float*) input, (float*) output); return STATUS_SUCCESS; } pluginStatus_t lReLUInference( hipStream_t stream, const int n, const float negativeSlope, const void* input, void* output) { return lReLUGPU(stream, n, negativeSlope, (const float*) input, (float*) output); }
096af14b0b5e1be8488bfe91693703f2b2c236ca.cu
/* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kernel.h" template <unsigned nthdsPerCTA> __launch_bounds__(nthdsPerCTA) __global__ void pReLUKernel( const int n, const float negativeSlope, const float* input, float* output) { for (int i = blockIdx.x * nthdsPerCTA + threadIdx.x; i < n; i += gridDim.x * nthdsPerCTA) { output[i] = input[i] > 0 ? input[i] : input[i] * negativeSlope; } } pluginStatus_t lReLUGPU( cudaStream_t stream, const int n, const float negativeSlope, const void* input, void* output) { const int BS = 512; const int GS = (n + BS - 1) / BS; pReLUKernel<BS><<<GS, BS, 0, stream>>>(n, negativeSlope, (const float*) input, (float*) output); return STATUS_SUCCESS; } pluginStatus_t lReLUInference( cudaStream_t stream, const int n, const float negativeSlope, const void* input, void* output) { return lReLUGPU(stream, n, negativeSlope, (const float*) input, (float*) output); }
ec5d0b3f0a9f9d2cae9afc5eb93fd4b0a7dbff53.hip
// !!! This is a file automatically generated by hipify!!! /* (C) 2012 Jeff Chien CUDA functions. */ #include <cmath> #include <ctime> #include <climits> #include <iostream> #include <vector> #include <hip/hip_runtime.h> #include <cutil_inline.h> #include <hiprand/hiprand_kernel.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include "common.h" #include "hip/hip_runtime.h" #include "cuda_internal.cuh" #include "vec.cuh" static dim3 gridDim3(GRID_SIZE, 1, 1), blockDim3(BLOCK_SIZE, 1, 1); // Initializes this vector to a random vector between minLen and maxLen (that has a random direction) CUDA_DEVICE_CALLABLE void pdla::vec::rand(hiprandState_t* rand, float minLen, float maxLen) { float len = minLen + (maxLen - minLen) * hiprand_uniform(rand); float theta = TAU * hiprand_uniform(rand); x = len * cos(theta); y = len * sin(theta); } __global__ void kernel(context_t* ctx) { int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= ctx->numSeeds) return; // PRNGs for the drifting particle hiprandState_t partRand; hiprand_init(ctx->randSeed, ctx->numSeeds, 0, &partRand); // Setup particle data pdla::vec seedPos(ctx->seedPos[index]), oldPartPos, partPos, walk; oldPartPos.rand(&partRand, ctx->maxRadius + 3, ctx->maxRadius + 4); // Until someone collided with something pdla_time_t time, resTime; time = ctx->time; // Cache resTime from the context so that we don't have to get it every time while(time < (resTime = ctx->resTime)) { // Process in strides of 1024 to average out the cost of retrieving resTime // TODO: figure out correct stride length as function of seed count for(pdla_time_t maxTime = time + 1024; time < maxTime; time++) { // 1) Drift particle walk.rand(&partRand, 0.4f, 0.6f); partPos = oldPartPos + walk; // 2) Check collision pdla::vec seedVec = seedPos - oldPartPos; float t = seedVec.dot(walk) / walk.dot(walk); if(t < 0) t = 0; else if(t > 1) t = 1; // 3) If collision, set global vars (don't care about overwriting, but assign has to be atomic). float dist = (seedPos - (oldPartPos + walk * t)).len(); if(dist < 2) { // Rewind so that particle is just touching seed float sintheta, costheta; __sincosf(acosf(seedVec.dot(walk) / (seedVec.len() * walk.len())), &sintheta, &costheta); float len = seedVec.len() * costheta - sqrtf(4 - seedVec.dot(seedVec) * sintheta * sintheta); partPos = oldPartPos + walk * (len / walk.len()); unsigned int index = atomicInc(&ctx->resCount, NUM_KERNELS); atomicCAS(&ctx->resTime, ULLONG_MAX, time); // Change the result ctx->res[index].time = time; ctx->res[index].pos = partPos; } // 4) Set up for next iteration (bounding box) oldPartPos = partPos; oldPartPos.boundingBox(ctx->maxRadius + 4); } } } __global__ void addSeed(context_t* ctx) { // Get index of first result int minIndex = 0; for(int i = 1; i < ctx->resCount; i++) if(ctx->res[i].time < ctx->res[minIndex].time) minIndex = i; // Get the first result result_t res = ctx->res[minIndex]; // Set context ctx->time = res.time + 1; if(res.pos.len() > ctx->maxRadius) ctx->maxRadius = res.pos.len(); ctx->resCount = 0; ctx->resTime = ULLONG_MAX; ctx->seedPos[ctx->numSeeds] = res.pos; ctx->seedT[ctx->numSeeds] = res.time; ctx->numSeeds++; } void pdla::init_cuda() { cutilSafeCall(hipSetDevice(0)); } pdla::pdla_result_t pdla::run(int numSeeds) { if(numSeeds > NUM_KERNELS) { std::cerr << "Cannot have more seeds (" << numSeeds << ") than kernels (" << NUM_KERNELS << ")!" << std::endl; abort(); } // Initialize device memory thrust::device_vector<context_t> ctx(1); thrust::device_vector<result_t> results(NUM_KERNELS); thrust::device_vector<vec> seedPos(NUM_KERNELS + 1); thrust::device_vector<pdla_time_t> seedT(NUM_KERNELS + 1); // Initialize context // Note: (thrust device vector).data().get() gets the pointer to device memory context_t tmp; tmp.randSeed = time(0); tmp.time = 0; tmp.maxRadius = 0; tmp.numSeeds = 1; tmp.resCount = 0; tmp.resTime = ULLONG_MAX; tmp.seedPos = seedPos.data().get(); tmp.seedT = seedT.data().get(); tmp.res = results.data().get(); seedPos[0] = vec(0, 0); seedT[0] = 0; ctx[0] = tmp; // Take time clock_t t0 = clock(); // Send instructions to GPU for(int i = 1; i < numSeeds; i++) { hipLaunchKernelGGL(( kernel), dim3(gridDim3), dim3(blockDim3), 0, 0, ctx.data().get()); hipLaunchKernelGGL(( addSeed), dim3(1), dim3(1), 0, 0, ctx.data().get()); } // Wait for execution to finish hipDeviceSynchronize(); // Take time again clock_t t1 = clock(); // Copy results from Thrust containers to STL containers pdla_result_t p = {std::vector<vec>(numSeeds), std::vector<pdla_time_t>(numSeeds), 1.0f * (t1 - t0) / CLOCKS_PER_SEC}; for(int i = 0; i < numSeeds; i++) { p.pos[i] = seedPos[i]; p.time[i] = seedT[i]; } return(p); } std::ostream& pdla::operator<< (std::ostream &out, vec &v) { out << "<" << v.x << ", " << v.y << ">"; return(out); }
ec5d0b3f0a9f9d2cae9afc5eb93fd4b0a7dbff53.cu
/* (C) 2012 Jeff Chien CUDA functions. */ #include <cmath> #include <ctime> #include <climits> #include <iostream> #include <vector> #include <cuda.h> #include <cutil_inline.h> #include <curand_kernel.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include "common.h" #include "cuda.h" #include "cuda_internal.cuh" #include "vec.cuh" static dim3 gridDim3(GRID_SIZE, 1, 1), blockDim3(BLOCK_SIZE, 1, 1); // Initializes this vector to a random vector between minLen and maxLen (that has a random direction) CUDA_DEVICE_CALLABLE void pdla::vec::rand(curandState* rand, float minLen, float maxLen) { float len = minLen + (maxLen - minLen) * curand_uniform(rand); float theta = TAU * curand_uniform(rand); x = len * cos(theta); y = len * sin(theta); } __global__ void kernel(context_t* ctx) { int index = blockIdx.x * blockDim.x + threadIdx.x; if(index >= ctx->numSeeds) return; // PRNGs for the drifting particle curandState partRand; curand_init(ctx->randSeed, ctx->numSeeds, 0, &partRand); // Setup particle data pdla::vec seedPos(ctx->seedPos[index]), oldPartPos, partPos, walk; oldPartPos.rand(&partRand, ctx->maxRadius + 3, ctx->maxRadius + 4); // Until someone collided with something pdla_time_t time, resTime; time = ctx->time; // Cache resTime from the context so that we don't have to get it every time while(time < (resTime = ctx->resTime)) { // Process in strides of 1024 to average out the cost of retrieving resTime // TODO: figure out correct stride length as function of seed count for(pdla_time_t maxTime = time + 1024; time < maxTime; time++) { // 1) Drift particle walk.rand(&partRand, 0.4f, 0.6f); partPos = oldPartPos + walk; // 2) Check collision pdla::vec seedVec = seedPos - oldPartPos; float t = seedVec.dot(walk) / walk.dot(walk); if(t < 0) t = 0; else if(t > 1) t = 1; // 3) If collision, set global vars (don't care about overwriting, but assign has to be atomic). float dist = (seedPos - (oldPartPos + walk * t)).len(); if(dist < 2) { // Rewind so that particle is just touching seed float sintheta, costheta; __sincosf(acosf(seedVec.dot(walk) / (seedVec.len() * walk.len())), &sintheta, &costheta); float len = seedVec.len() * costheta - sqrtf(4 - seedVec.dot(seedVec) * sintheta * sintheta); partPos = oldPartPos + walk * (len / walk.len()); unsigned int index = atomicInc(&ctx->resCount, NUM_KERNELS); atomicCAS(&ctx->resTime, ULLONG_MAX, time); // Change the result ctx->res[index].time = time; ctx->res[index].pos = partPos; } // 4) Set up for next iteration (bounding box) oldPartPos = partPos; oldPartPos.boundingBox(ctx->maxRadius + 4); } } } __global__ void addSeed(context_t* ctx) { // Get index of first result int minIndex = 0; for(int i = 1; i < ctx->resCount; i++) if(ctx->res[i].time < ctx->res[minIndex].time) minIndex = i; // Get the first result result_t res = ctx->res[minIndex]; // Set context ctx->time = res.time + 1; if(res.pos.len() > ctx->maxRadius) ctx->maxRadius = res.pos.len(); ctx->resCount = 0; ctx->resTime = ULLONG_MAX; ctx->seedPos[ctx->numSeeds] = res.pos; ctx->seedT[ctx->numSeeds] = res.time; ctx->numSeeds++; } void pdla::init_cuda() { cutilSafeCall(cudaSetDevice(0)); } pdla::pdla_result_t pdla::run(int numSeeds) { if(numSeeds > NUM_KERNELS) { std::cerr << "Cannot have more seeds (" << numSeeds << ") than kernels (" << NUM_KERNELS << ")!" << std::endl; abort(); } // Initialize device memory thrust::device_vector<context_t> ctx(1); thrust::device_vector<result_t> results(NUM_KERNELS); thrust::device_vector<vec> seedPos(NUM_KERNELS + 1); thrust::device_vector<pdla_time_t> seedT(NUM_KERNELS + 1); // Initialize context // Note: (thrust device vector).data().get() gets the pointer to device memory context_t tmp; tmp.randSeed = time(0); tmp.time = 0; tmp.maxRadius = 0; tmp.numSeeds = 1; tmp.resCount = 0; tmp.resTime = ULLONG_MAX; tmp.seedPos = seedPos.data().get(); tmp.seedT = seedT.data().get(); tmp.res = results.data().get(); seedPos[0] = vec(0, 0); seedT[0] = 0; ctx[0] = tmp; // Take time clock_t t0 = clock(); // Send instructions to GPU for(int i = 1; i < numSeeds; i++) { kernel<<<gridDim3, blockDim3>>>(ctx.data().get()); addSeed<<<1, 1>>>(ctx.data().get()); } // Wait for execution to finish cudaThreadSynchronize(); // Take time again clock_t t1 = clock(); // Copy results from Thrust containers to STL containers pdla_result_t p = {std::vector<vec>(numSeeds), std::vector<pdla_time_t>(numSeeds), 1.0f * (t1 - t0) / CLOCKS_PER_SEC}; for(int i = 0; i < numSeeds; i++) { p.pos[i] = seedPos[i]; p.time[i] = seedT[i]; } return(p); } std::ostream& pdla::operator<< (std::ostream &out, vec &v) { out << "<" << v.x << ", " << v.y << ">"; return(out); }
b00b6c6834ba92d2f38e78aab9995586ae318423.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // matrix multiplication // CA_LAB4 #include<stdio.h> #include<iostream> #include<cstdlib> #include<time.h> #include<cuda.h> #define TILE_WIDTH 32 #define DEBUG 0 using namespace std; void print(float *A, int n, int m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cout << A[n*i+j] << " "; cout<<endl; } void init_matrix (float *mat, float value, int n, int m) { int size = n * m; for (int i = 0; i < size; i++) mat[i] = value; } void multMatrixSeq (float *mA, float *mB, float *mC, int n, int m, int o) { for (int i = 0; i < n; i++) { for (int j = 0; j < o; j++) { float sum = 0; for (int k = 0; k < m; k++) { sum += mA[m*i+k] * mB[o*k+j]; } mC[o*i+j] = sum; } } } __global__ void CU_multMatrixThread (float *mA, float *mB, float *mC, int n, int m, int o) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; if ((row<n) && (col<o)) { float temp = 0; for (int i = 0; i < m; i++) temp += mA[row*m+i] * mB[i*o+col]; mC[row*o+col] = temp; } } __global__ void CU_multMatrixTiled(float *mA, float *mB, float *mC, int n, int m, int o){ __shared__ float tmpM1[TILE_WIDTH][TILE_WIDTH]; __shared__ float tmpM2[TILE_WIDTH][TILE_WIDTH]; int bx = blockIdx.x; int by = blockIdx.y; int tx = threadIdx.x; int ty = threadIdx.y; int row = by * TILE_WIDTH + ty; int col = bx * TILE_WIDTH + tx; float Pvalue = 0; for (int k = 0; k < (m + TILE_WIDTH - 1) / TILE_WIDTH; ++k) { if (k*TILE_WIDTH + tx < m && row < n) tmpM1[ty][tx] = mA[row * m + k*TILE_WIDTH + tx]; else tmpM1[ty][tx] = 0; if (k*TILE_WIDTH + ty < m && col < o) tmpM2[ty][tx] = mB[(k*TILE_WIDTH + ty) * o + col]; else tmpM2[ty][tx] =0; __syncthreads(); for(int k = 0; k < TILE_WIDTH; ++k) Pvalue += tmpM1[ty][k] * tmpM2[k][tx]; __syncthreads(); } if (row < n && col < o) mC[row * o + col] = Pvalue; } void multMatrixTiled(float *A, float *B, float *C, int n, int m, int o) { float blockSize = TILE_WIDTH; float *mA, *mB, *mC; hipMalloc(&mA, n * m * sizeof(float)); hipMalloc(&mB, m * o * sizeof(float)); hipMalloc(&mC, n * o * sizeof(float)); hipMemcpy(mA, A, n * m * sizeof(float), hipMemcpyHostToDevice); hipMemcpy(mB, B, m * o * sizeof(float), hipMemcpyHostToDevice); dim3 threads(blockSize,blockSize,1); dim3 blocks(ceil(o/blockSize),ceil(n/blockSize),1); hipLaunchKernelGGL(( CU_multMatrixThread), dim3(blocks),dim3(threads), 0, 0, mA,mB,mC,n,m,o); hipMemcpy (C, mC, n * o * sizeof(float), hipMemcpyDeviceToHost); hipFree(mA); hipFree(mB); hipFree(mC); } void multMatrixThread(float *A, float *B, float *C, int n, int m, int o) { float blockSize = TILE_WIDTH; float *mA, *mB, *mC; hipMalloc(&mA, n * m * sizeof(float)); hipMalloc(&mB, m * o * sizeof(float)); hipMalloc(&mC, n * o * sizeof(float)); hipMemcpy(mA, A, n * m * sizeof(float), hipMemcpyHostToDevice); hipMemcpy(mB, B, m * o * sizeof(float), hipMemcpyHostToDevice); dim3 threads(blockSize,blockSize,1); dim3 blocks(ceil(o/blockSize),ceil(n/blockSize),1); hipLaunchKernelGGL(( CU_multMatrixThread), dim3(blocks),dim3(threads), 0, 0, mA,mB,mC,n,m,o); hipMemcpy (C, mC, n * o * sizeof(float), hipMemcpyDeviceToHost); hipFree(mA); hipFree(mB); hipFree(mC); } int compareMatrix (float *A, float *B,int n, int m) { int size = n * m; for (int i = 0; i < size; i++ ) { if (A[i] != B[i]) { cout<<"the sequential result and parallel result are not equal"<<endl; return 0; } } cout<<"the sequential result and parallel result are equal"<<endl; return 0; } int main(int argc, char* argv[]) { clock_t start, finish; double elapsedsequential, elapsedParallel, elapsedParallelTiles, optimizationP, optimizationT; int kkkkk = atoi(argv[1]); int n = kkkkk; int m = kkkkk; int o = kkkkk; float *matA = (float *) malloc(n * m * sizeof(float)); float *matB = (float *) malloc(m * o * sizeof(float)); float *matCS = (float *) malloc(n * o * sizeof(float)); float *matCP = (float *) malloc(n * o * sizeof(float)); float *matCPT = (float *) malloc(n * o * sizeof(float)); init_matrix(matA,1.5,n,m); init_matrix(matB,1.5,m,o); init_matrix(matCS,0,n,o); init_matrix(matCP,0,n,o); init_matrix(matCPT,0,n,o); start = clock(); multMatrixSeq(matA,matB,matCS,n,m,o); finish = clock(); elapsedsequential = (((double) (finish - start)) / CLOCKS_PER_SEC ); cout<< "sequential matrix multiplication: " << elapsedsequential << "sec"<< endl<< endl; start = clock(); multMatrixThread(matA,matB,matCP,n,m,o); finish = clock(); elapsedParallel = (((double) (finish - start)) / CLOCKS_PER_SEC ); cout<< "parallel matrix multiplication without using Tiles: " << elapsedParallel << "sec"<< endl<< endl; start = clock(); multMatrixTiled(matA,matB,matCPT,n,m,o); finish = clock(); elapsedParallelTiles = (((double) (finish - start)) / CLOCKS_PER_SEC ); cout<< "parallel matrix multiplication using Tiles: " << elapsedParallelTiles << "sec"<< endl<< endl; optimizationP = elapsedsequential/elapsedParallel; cout<< "speedup without using Tiles: " << optimizationP <<endl; optimizationT = elapsedsequential/elapsedParallelTiles; cout<< "speedup using Tiles: " << optimizationT <<endl; cout<< "check parallel result without using Tiles: " <<endl; compareMatrix(matCS,matCP,n,o); cout<< "check parallel result using Tiles: " <<endl; compareMatrix(matCS,matCPT,n,o); if (DEBUG) { print(matCS,n,o); cout<<endl; print(matCP,n,o); cout<<endl; print(matCPT,n,o); } free (matA); free (matB); free (matCS); free (matCP); free (matCPT); return 0; }
b00b6c6834ba92d2f38e78aab9995586ae318423.cu
// matrix multiplication // CA_LAB4 #include<stdio.h> #include<iostream> #include<cstdlib> #include<time.h> #include<cuda.h> #define TILE_WIDTH 32 #define DEBUG 0 using namespace std; void print(float *A, int n, int m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cout << A[n*i+j] << " "; cout<<endl; } void init_matrix (float *mat, float value, int n, int m) { int size = n * m; for (int i = 0; i < size; i++) mat[i] = value; } void multMatrixSeq (float *mA, float *mB, float *mC, int n, int m, int o) { for (int i = 0; i < n; i++) { for (int j = 0; j < o; j++) { float sum = 0; for (int k = 0; k < m; k++) { sum += mA[m*i+k] * mB[o*k+j]; } mC[o*i+j] = sum; } } } __global__ void CU_multMatrixThread (float *mA, float *mB, float *mC, int n, int m, int o) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; if ((row<n) && (col<o)) { float temp = 0; for (int i = 0; i < m; i++) temp += mA[row*m+i] * mB[i*o+col]; mC[row*o+col] = temp; } } __global__ void CU_multMatrixTiled(float *mA, float *mB, float *mC, int n, int m, int o){ __shared__ float tmpM1[TILE_WIDTH][TILE_WIDTH]; __shared__ float tmpM2[TILE_WIDTH][TILE_WIDTH]; int bx = blockIdx.x; int by = blockIdx.y; int tx = threadIdx.x; int ty = threadIdx.y; int row = by * TILE_WIDTH + ty; int col = bx * TILE_WIDTH + tx; float Pvalue = 0; for (int k = 0; k < (m + TILE_WIDTH - 1) / TILE_WIDTH; ++k) { if (k*TILE_WIDTH + tx < m && row < n) tmpM1[ty][tx] = mA[row * m + k*TILE_WIDTH + tx]; else tmpM1[ty][tx] = 0; if (k*TILE_WIDTH + ty < m && col < o) tmpM2[ty][tx] = mB[(k*TILE_WIDTH + ty) * o + col]; else tmpM2[ty][tx] =0; __syncthreads(); for(int k = 0; k < TILE_WIDTH; ++k) Pvalue += tmpM1[ty][k] * tmpM2[k][tx]; __syncthreads(); } if (row < n && col < o) mC[row * o + col] = Pvalue; } void multMatrixTiled(float *A, float *B, float *C, int n, int m, int o) { float blockSize = TILE_WIDTH; float *mA, *mB, *mC; cudaMalloc(&mA, n * m * sizeof(float)); cudaMalloc(&mB, m * o * sizeof(float)); cudaMalloc(&mC, n * o * sizeof(float)); cudaMemcpy(mA, A, n * m * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(mB, B, m * o * sizeof(float), cudaMemcpyHostToDevice); dim3 threads(blockSize,blockSize,1); dim3 blocks(ceil(o/blockSize),ceil(n/blockSize),1); CU_multMatrixThread<<<blocks,threads>>>(mA,mB,mC,n,m,o); cudaMemcpy (C, mC, n * o * sizeof(float), cudaMemcpyDeviceToHost); cudaFree(mA); cudaFree(mB); cudaFree(mC); } void multMatrixThread(float *A, float *B, float *C, int n, int m, int o) { float blockSize = TILE_WIDTH; float *mA, *mB, *mC; cudaMalloc(&mA, n * m * sizeof(float)); cudaMalloc(&mB, m * o * sizeof(float)); cudaMalloc(&mC, n * o * sizeof(float)); cudaMemcpy(mA, A, n * m * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(mB, B, m * o * sizeof(float), cudaMemcpyHostToDevice); dim3 threads(blockSize,blockSize,1); dim3 blocks(ceil(o/blockSize),ceil(n/blockSize),1); CU_multMatrixThread<<<blocks,threads>>>(mA,mB,mC,n,m,o); cudaMemcpy (C, mC, n * o * sizeof(float), cudaMemcpyDeviceToHost); cudaFree(mA); cudaFree(mB); cudaFree(mC); } int compareMatrix (float *A, float *B,int n, int m) { int size = n * m; for (int i = 0; i < size; i++ ) { if (A[i] != B[i]) { cout<<"the sequential result and parallel result are not equal"<<endl; return 0; } } cout<<"the sequential result and parallel result are equal"<<endl; return 0; } int main(int argc, char* argv[]) { clock_t start, finish; double elapsedsequential, elapsedParallel, elapsedParallelTiles, optimizationP, optimizationT; int kkkkk = atoi(argv[1]); int n = kkkkk; int m = kkkkk; int o = kkkkk; float *matA = (float *) malloc(n * m * sizeof(float)); float *matB = (float *) malloc(m * o * sizeof(float)); float *matCS = (float *) malloc(n * o * sizeof(float)); float *matCP = (float *) malloc(n * o * sizeof(float)); float *matCPT = (float *) malloc(n * o * sizeof(float)); init_matrix(matA,1.5,n,m); init_matrix(matB,1.5,m,o); init_matrix(matCS,0,n,o); init_matrix(matCP,0,n,o); init_matrix(matCPT,0,n,o); start = clock(); multMatrixSeq(matA,matB,matCS,n,m,o); finish = clock(); elapsedsequential = (((double) (finish - start)) / CLOCKS_PER_SEC ); cout<< "sequential matrix multiplication: " << elapsedsequential << "sec"<< endl<< endl; start = clock(); multMatrixThread(matA,matB,matCP,n,m,o); finish = clock(); elapsedParallel = (((double) (finish - start)) / CLOCKS_PER_SEC ); cout<< "parallel matrix multiplication without using Tiles: " << elapsedParallel << "sec"<< endl<< endl; start = clock(); multMatrixTiled(matA,matB,matCPT,n,m,o); finish = clock(); elapsedParallelTiles = (((double) (finish - start)) / CLOCKS_PER_SEC ); cout<< "parallel matrix multiplication using Tiles: " << elapsedParallelTiles << "sec"<< endl<< endl; optimizationP = elapsedsequential/elapsedParallel; cout<< "speedup without using Tiles: " << optimizationP <<endl; optimizationT = elapsedsequential/elapsedParallelTiles; cout<< "speedup using Tiles: " << optimizationT <<endl; cout<< "check parallel result without using Tiles: " <<endl; compareMatrix(matCS,matCP,n,o); cout<< "check parallel result using Tiles: " <<endl; compareMatrix(matCS,matCPT,n,o); if (DEBUG) { print(matCS,n,o); cout<<endl; print(matCP,n,o); cout<<endl; print(matCPT,n,o); } free (matA); free (matB); free (matCS); free (matCP); free (matCPT); return 0; }
8a15bc7d1057fba70e589d5b0919f8bb34892197.hip
// !!! This is a file automatically generated by hipify!!! /* * Copyright (c) 2018, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "random/rng.h" #include "stats/cov.h" #include "stats/mean.h" #include "test_utils.h" namespace MLCommon { namespace Stats { template <typename T> struct CovInputs { T tolerance, mean, var; int rows, cols; bool sample, rowMajor, stable; unsigned long long int seed; }; template <typename T> ::std::ostream &operator<<(::std::ostream &os, const CovInputs<T> &dims) { return os; } template <typename T> class CovTest : public ::testing::TestWithParam<CovInputs<T>> { protected: void SetUp() override { CUBLAS_CHECK(hipblasCreate(&handle)); params = ::testing::TestWithParam<CovInputs<T>>::GetParam(); Random::Rng<T> r(params.seed); int rows = params.rows, cols = params.cols; int len = rows * cols; T var = params.var; allocate(data, len); allocate(mean_act, cols); allocate(cov_act, cols * cols); r.normal(data, len, params.mean, var); mean(mean_act, data, cols, rows, params.sample, params.rowMajor); cov(cov_act, data, mean_act, cols, rows, params.sample, params.rowMajor, params.stable, handle); T data_h[6] = {1.0, 2.0, 5.0, 4.0, 2.0, 1.0}; T cov_cm_ref_h[4] = {4.3333, -2.8333, -2.8333, 2.333}; allocate(data_cm, 6); allocate(cov_cm, 4); allocate(cov_cm_ref, 4); allocate(mean_cm, 2); updateDevice(data_cm, data_h, 6); updateDevice(cov_cm_ref, cov_cm_ref_h, 4); mean(mean_cm, data_cm, 2, 3, true, false); cov(cov_cm, data_cm, mean_cm, 2, 3, true, false, true, handle); } void TearDown() override { CUDA_CHECK(hipFree(data)); CUDA_CHECK(hipFree(mean_act)); CUDA_CHECK(hipFree(cov_act)); CUDA_CHECK(hipFree(data_cm)); CUDA_CHECK(hipFree(cov_cm)); CUDA_CHECK(hipFree(cov_cm_ref)); CUDA_CHECK(hipFree(mean_cm)); CUBLAS_CHECK(hipblasDestroy(handle)); } protected: CovInputs<T> params; T *data, *mean_act, *cov_act; hipblasHandle_t handle; T *data_cm, *cov_cm, *cov_cm_ref, *mean_cm; }; ///@todo: add stable=false after it has been implemented const std::vector<CovInputs<float>> inputsf = { {0.03f, 1.f, 2.f, 32 * 1024, 32, true, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 64, true, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 128, true, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 256, true, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 32, false, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 64, false, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 128, false, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 256, false, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 32, true, true, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 64, true, true, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 128, true, true, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 256, true, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 32, false, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 64, false, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 128, false, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 256, false, true, true, 1234ULL}}; const std::vector<CovInputs<double>> inputsd = { {0.03, 1.0, 2.0, 32 * 1024, 32, true, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 64, true, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 128, true, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 256, true, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 32, false, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 64, false, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 128, false, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 256, false, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 32, true, true, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 64, true, true, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 128, true, true, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 256, true, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 32, false, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 64, false, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 128, false, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 256, false, true, true, 1234ULL}}; typedef CovTest<float> CovTestF; TEST_P(CovTestF, Result) { ASSERT_TRUE(diagonalMatch(params.var * params.var, cov_act, params.cols, params.cols, CompareApprox<float>(params.tolerance))); } typedef CovTest<double> CovTestD; TEST_P(CovTestD, Result) { ASSERT_TRUE(diagonalMatch(params.var * params.var, cov_act, params.cols, params.cols, CompareApprox<double>(params.tolerance))); } typedef CovTest<float> CovTestSmallF; TEST_P(CovTestSmallF, Result) { ASSERT_TRUE(devArrMatch(cov_cm_ref, cov_cm, 2, 2, CompareApprox<float>(params.tolerance))); } typedef CovTest<double> CovTestSmallD; TEST_P(CovTestSmallD, Result) { ASSERT_TRUE(devArrMatch(cov_cm_ref, cov_cm, 2, 2, CompareApprox<double>(params.tolerance))); } INSTANTIATE_TEST_CASE_P(CovTests, CovTestF, ::testing::ValuesIn(inputsf)); INSTANTIATE_TEST_CASE_P(CovTests, CovTestD, ::testing::ValuesIn(inputsd)); INSTANTIATE_TEST_CASE_P(CovTests, CovTestSmallF, ::testing::ValuesIn(inputsf)); INSTANTIATE_TEST_CASE_P(CovTests, CovTestSmallD, ::testing::ValuesIn(inputsd)); } // end namespace Stats } // end namespace MLCommon
8a15bc7d1057fba70e589d5b0919f8bb34892197.cu
/* * Copyright (c) 2018, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "random/rng.h" #include "stats/cov.h" #include "stats/mean.h" #include "test_utils.h" namespace MLCommon { namespace Stats { template <typename T> struct CovInputs { T tolerance, mean, var; int rows, cols; bool sample, rowMajor, stable; unsigned long long int seed; }; template <typename T> ::std::ostream &operator<<(::std::ostream &os, const CovInputs<T> &dims) { return os; } template <typename T> class CovTest : public ::testing::TestWithParam<CovInputs<T>> { protected: void SetUp() override { CUBLAS_CHECK(cublasCreate(&handle)); params = ::testing::TestWithParam<CovInputs<T>>::GetParam(); Random::Rng<T> r(params.seed); int rows = params.rows, cols = params.cols; int len = rows * cols; T var = params.var; allocate(data, len); allocate(mean_act, cols); allocate(cov_act, cols * cols); r.normal(data, len, params.mean, var); mean(mean_act, data, cols, rows, params.sample, params.rowMajor); cov(cov_act, data, mean_act, cols, rows, params.sample, params.rowMajor, params.stable, handle); T data_h[6] = {1.0, 2.0, 5.0, 4.0, 2.0, 1.0}; T cov_cm_ref_h[4] = {4.3333, -2.8333, -2.8333, 2.333}; allocate(data_cm, 6); allocate(cov_cm, 4); allocate(cov_cm_ref, 4); allocate(mean_cm, 2); updateDevice(data_cm, data_h, 6); updateDevice(cov_cm_ref, cov_cm_ref_h, 4); mean(mean_cm, data_cm, 2, 3, true, false); cov(cov_cm, data_cm, mean_cm, 2, 3, true, false, true, handle); } void TearDown() override { CUDA_CHECK(cudaFree(data)); CUDA_CHECK(cudaFree(mean_act)); CUDA_CHECK(cudaFree(cov_act)); CUDA_CHECK(cudaFree(data_cm)); CUDA_CHECK(cudaFree(cov_cm)); CUDA_CHECK(cudaFree(cov_cm_ref)); CUDA_CHECK(cudaFree(mean_cm)); CUBLAS_CHECK(cublasDestroy(handle)); } protected: CovInputs<T> params; T *data, *mean_act, *cov_act; cublasHandle_t handle; T *data_cm, *cov_cm, *cov_cm_ref, *mean_cm; }; ///@todo: add stable=false after it has been implemented const std::vector<CovInputs<float>> inputsf = { {0.03f, 1.f, 2.f, 32 * 1024, 32, true, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 64, true, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 128, true, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 256, true, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 32, false, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 64, false, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 128, false, false, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 256, false, false, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 32, true, true, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 64, true, true, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 128, true, true, true, 1234ULL}, {0.03f, 1.f, 2.f, 32 * 1024, 256, true, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 32, false, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 64, false, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 128, false, true, true, 1234ULL}, {0.03f, -1.f, 2.f, 32 * 1024, 256, false, true, true, 1234ULL}}; const std::vector<CovInputs<double>> inputsd = { {0.03, 1.0, 2.0, 32 * 1024, 32, true, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 64, true, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 128, true, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 256, true, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 32, false, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 64, false, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 128, false, false, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 256, false, false, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 32, true, true, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 64, true, true, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 128, true, true, true, 1234ULL}, {0.03, 1.0, 2.0, 32 * 1024, 256, true, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 32, false, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 64, false, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 128, false, true, true, 1234ULL}, {0.03, -1.0, 2.0, 32 * 1024, 256, false, true, true, 1234ULL}}; typedef CovTest<float> CovTestF; TEST_P(CovTestF, Result) { ASSERT_TRUE(diagonalMatch(params.var * params.var, cov_act, params.cols, params.cols, CompareApprox<float>(params.tolerance))); } typedef CovTest<double> CovTestD; TEST_P(CovTestD, Result) { ASSERT_TRUE(diagonalMatch(params.var * params.var, cov_act, params.cols, params.cols, CompareApprox<double>(params.tolerance))); } typedef CovTest<float> CovTestSmallF; TEST_P(CovTestSmallF, Result) { ASSERT_TRUE(devArrMatch(cov_cm_ref, cov_cm, 2, 2, CompareApprox<float>(params.tolerance))); } typedef CovTest<double> CovTestSmallD; TEST_P(CovTestSmallD, Result) { ASSERT_TRUE(devArrMatch(cov_cm_ref, cov_cm, 2, 2, CompareApprox<double>(params.tolerance))); } INSTANTIATE_TEST_CASE_P(CovTests, CovTestF, ::testing::ValuesIn(inputsf)); INSTANTIATE_TEST_CASE_P(CovTests, CovTestD, ::testing::ValuesIn(inputsd)); INSTANTIATE_TEST_CASE_P(CovTests, CovTestSmallF, ::testing::ValuesIn(inputsf)); INSTANTIATE_TEST_CASE_P(CovTests, CovTestSmallD, ::testing::ValuesIn(inputsd)); } // end namespace Stats } // end namespace MLCommon
5a18df9e7f5fea119725afa2213c5462dc6e482d.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "detectNet.h" #include "cudaUtility.h" template<typename T> __global__ void gpuDetectionOverlay( T* input, T* output, int width, int height, detectNet::Detection* detections, int numDetections, float4* colors ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; if( x >= width || y >= height ) return; const T px_in = input[ y * width + x ]; T px_out = px_in; const float fx = x; const float fy = y; for( int n=0; n < numDetections; n++ ) { const detectNet::Detection det = detections[n]; // check if this pixel is inside the bounding box if( fx >= det.Left && fx <= det.Right && fy >= det.Top && fy <= det.Bottom ) { const float4 color = colors[det.ClassID]; const float alpha = color.w / 255.0f; const float ialph = 1.0f - alpha; px_out.x = alpha * color.x + ialph * px_out.x; px_out.y = alpha * color.y + ialph * px_out.y; px_out.z = alpha * color.z + ialph * px_out.z; } } output[y * width + x] = px_out; } template<typename T> __global__ void gpuDetectionOverlayBox( T* input, T* output, int imgWidth, int imgHeight, int x0, int y0, int boxWidth, int boxHeight, const float4 color ) { const int box_x = blockIdx.x * blockDim.x + threadIdx.x; const int box_y = blockIdx.y * blockDim.y + threadIdx.y; if( box_x >= boxWidth || box_y >= boxHeight ) return; const int x = box_x + x0; const int y = box_y + y0; if( x >= imgWidth || y >= imgHeight ) return; T px = input[ y * imgWidth + x ]; const float alpha = color.w / 255.0f; const float ialph = 1.0f - alpha; px.x = alpha * color.x + ialph * px.x; px.y = alpha * color.y + ialph * px.y; px.z = alpha * color.z + ialph * px.z; output[y * imgWidth + x] = px; } template<typename T> hipError_t launchDetectionOverlay( T* input, T* output, uint32_t width, uint32_t height, detectNet::Detection* detections, int numDetections, float4* colors ) { if( !input || !output || width == 0 || height == 0 || !detections || numDetections == 0 || !colors ) return hipErrorInvalidValue; // this assumes that the output already has the input image copied to it, // which if input != output, is done first by detectNet::Detect() for( int n=0; n < numDetections; n++ ) { const int boxWidth = (int)detections[n].Width(); const int boxHeight = (int)detections[n].Height(); // launch kernel const dim3 blockDim(8, 8); const dim3 gridDim(iDivUp(boxWidth,blockDim.x), iDivUp(boxHeight,blockDim.y)); hipLaunchKernelGGL(( gpuDetectionOverlayBox<T>), dim3(gridDim), dim3(blockDim), 0, 0, input, output, width, height, (int)detections[n].Left, (int)detections[n].Top, boxWidth, boxHeight, colors[detections[n].ClassID]); } return hipGetLastError(); } hipError_t cudaDetectionOverlay( void* input, void* output, uint32_t width, uint32_t height, imageFormat format, detectNet::Detection* detections, int numDetections, float4* colors ) { if( format == IMAGE_RGB8 ) return launchDetectionOverlay<uchar3>((uchar3*)input, (uchar3*)output, width, height, detections, numDetections, colors); else if( format == IMAGE_RGBA8 ) return launchDetectionOverlay<uchar4>((uchar4*)input, (uchar4*)output, width, height, detections, numDetections, colors); else if( format == IMAGE_RGB32F ) return launchDetectionOverlay<float3>((float3*)input, (float3*)output, width, height, detections, numDetections, colors); else if( format == IMAGE_RGBA32F ) return launchDetectionOverlay<float4>((float4*)input, (float4*)output, width, height, detections, numDetections, colors); else return hipErrorInvalidValue; }
5a18df9e7f5fea119725afa2213c5462dc6e482d.cu
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "detectNet.h" #include "cudaUtility.h" template<typename T> __global__ void gpuDetectionOverlay( T* input, T* output, int width, int height, detectNet::Detection* detections, int numDetections, float4* colors ) { const int x = blockIdx.x * blockDim.x + threadIdx.x; const int y = blockIdx.y * blockDim.y + threadIdx.y; if( x >= width || y >= height ) return; const T px_in = input[ y * width + x ]; T px_out = px_in; const float fx = x; const float fy = y; for( int n=0; n < numDetections; n++ ) { const detectNet::Detection det = detections[n]; // check if this pixel is inside the bounding box if( fx >= det.Left && fx <= det.Right && fy >= det.Top && fy <= det.Bottom ) { const float4 color = colors[det.ClassID]; const float alpha = color.w / 255.0f; const float ialph = 1.0f - alpha; px_out.x = alpha * color.x + ialph * px_out.x; px_out.y = alpha * color.y + ialph * px_out.y; px_out.z = alpha * color.z + ialph * px_out.z; } } output[y * width + x] = px_out; } template<typename T> __global__ void gpuDetectionOverlayBox( T* input, T* output, int imgWidth, int imgHeight, int x0, int y0, int boxWidth, int boxHeight, const float4 color ) { const int box_x = blockIdx.x * blockDim.x + threadIdx.x; const int box_y = blockIdx.y * blockDim.y + threadIdx.y; if( box_x >= boxWidth || box_y >= boxHeight ) return; const int x = box_x + x0; const int y = box_y + y0; if( x >= imgWidth || y >= imgHeight ) return; T px = input[ y * imgWidth + x ]; const float alpha = color.w / 255.0f; const float ialph = 1.0f - alpha; px.x = alpha * color.x + ialph * px.x; px.y = alpha * color.y + ialph * px.y; px.z = alpha * color.z + ialph * px.z; output[y * imgWidth + x] = px; } template<typename T> cudaError_t launchDetectionOverlay( T* input, T* output, uint32_t width, uint32_t height, detectNet::Detection* detections, int numDetections, float4* colors ) { if( !input || !output || width == 0 || height == 0 || !detections || numDetections == 0 || !colors ) return cudaErrorInvalidValue; // this assumes that the output already has the input image copied to it, // which if input != output, is done first by detectNet::Detect() for( int n=0; n < numDetections; n++ ) { const int boxWidth = (int)detections[n].Width(); const int boxHeight = (int)detections[n].Height(); // launch kernel const dim3 blockDim(8, 8); const dim3 gridDim(iDivUp(boxWidth,blockDim.x), iDivUp(boxHeight,blockDim.y)); gpuDetectionOverlayBox<T><<<gridDim, blockDim>>>(input, output, width, height, (int)detections[n].Left, (int)detections[n].Top, boxWidth, boxHeight, colors[detections[n].ClassID]); } return cudaGetLastError(); } cudaError_t cudaDetectionOverlay( void* input, void* output, uint32_t width, uint32_t height, imageFormat format, detectNet::Detection* detections, int numDetections, float4* colors ) { if( format == IMAGE_RGB8 ) return launchDetectionOverlay<uchar3>((uchar3*)input, (uchar3*)output, width, height, detections, numDetections, colors); else if( format == IMAGE_RGBA8 ) return launchDetectionOverlay<uchar4>((uchar4*)input, (uchar4*)output, width, height, detections, numDetections, colors); else if( format == IMAGE_RGB32F ) return launchDetectionOverlay<float3>((float3*)input, (float3*)output, width, height, detections, numDetections, colors); else if( format == IMAGE_RGBA32F ) return launchDetectionOverlay<float4>((float4*)input, (float4*)output, width, height, detections, numDetections, colors); else return cudaErrorInvalidValue; }
d289a6740fc895b829ff2f44d0dd9e1266bb70fa.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "../knet.h" #include <assert.h> // broadcasting add: c = alpha*a + beta * b // each dim of a is either 1 or matches b. c has the same size as b. template<typename dType> __global__ void _addforw(int ndims, dType alpha, int *adims, dType *a, dType beta, int *bdims, dType *b, dType *c) { int b0, b1, b2, b3, b4, b5, b6, b7, i, j, ai; int bi = threadIdx.x + blockIdx.x * blockDim.x; int bn = 1; for (int n=0; n<ndims; n++) bn *= bdims[n]; while(bi < bn) { j = bi; if (ndims > 0) { i=j; j=i/bdims[0]; b0=i-j*bdims[0]; } if (ndims > 1) { i=j; j=i/bdims[1]; b1=i-j*bdims[1]; } if (ndims > 2) { i=j; j=i/bdims[2]; b2=i-j*bdims[2]; } if (ndims > 3) { i=j; j=i/bdims[3]; b3=i-j*bdims[3]; } if (ndims > 4) { i=j; j=i/bdims[4]; b4=i-j*bdims[4]; } if (ndims > 5) { i=j; j=i/bdims[5]; b5=i-j*bdims[5]; } if (ndims > 6) { i=j; j=i/bdims[6]; b6=i-j*bdims[6]; } if (ndims > 7) { i=j; j=i/bdims[7]; b7=i-j*bdims[7]; } ai = 0; if (ndims > 7) { ai = adims[7]*ai + (adims[7]==1 ? 0 : b7); } if (ndims > 6) { ai = adims[6]*ai + (adims[6]==1 ? 0 : b6); } if (ndims > 5) { ai = adims[5]*ai + (adims[5]==1 ? 0 : b5); } if (ndims > 4) { ai = adims[4]*ai + (adims[4]==1 ? 0 : b4); } if (ndims > 3) { ai = adims[3]*ai + (adims[3]==1 ? 0 : b3); } if (ndims > 2) { ai = adims[2]*ai + (adims[2]==1 ? 0 : b2); } if (ndims > 1) { ai = adims[1]*ai + (adims[1]==1 ? 0 : b1); } if (ndims > 0) { ai = adims[0]*ai + (adims[0]==1 ? 0 : b0); } c[bi] = alpha * a[ai] + beta * b[bi]; bi += blockDim.x * gridDim.x; } } // slightly more optimized 2D version template<typename dType> __global__ void _addforw2d(dType alpha, int *adims, dType *a, dType beta, int *bdims, dType *b, dType *c) { int b0, b1, i, j, ai, A0, A1, B0, B1; B0 = bdims[0]; B1 = bdims[1]; A0 = adims[0]; A1 = adims[1]; int bi = threadIdx.x + blockIdx.x * blockDim.x; int bn = bdims[0]*bdims[1]; while(bi < bn) { j=bi/B0; b0=bi-j*B0; i=j; j=i/B1; b1=i-j*B1; ai = A0*(A1==1 ? 0 : b1) + (A0==1 ? 0 : b0); c[bi] = alpha * a[ai] + beta * b[bi]; /* dType cval = b[bi]; if (beta != 1) cval *= beta; if (alpha != 0) { if (alpha != 1) cval += alpha * a[ai]; else cval += a[ai]; } c[bi] = cval; */ bi += blockDim.x * gridDim.x; } } extern "C" { void addforw32(int ndims, float alpha, int *adims, float *a, float beta, int *bdims, float *b, float *c) { if (ndims==2) { KCALL(_addforw2d,alpha,adims,a,beta,bdims,b,c); } else { KCALL(_addforw,ndims,alpha,adims,a,beta,bdims,b,c); } } void addforw64(int ndims, double alpha, int *adims, double *a, double beta, int *bdims, double *b, double *c) { if (ndims==2) { KCALL(_addforw2d,alpha,adims,a,beta,bdims,b,c); } else { KCALL(_addforw,ndims,alpha,adims,a,beta,bdims,b,c); } } /* #include <stdio.h> void addforw32(int ndims, float alpha, int *adims, float *a, float beta, int *bdims, float *b, float *c) { printf("ndims=%d alpha=%g beta=%g\n", ndims, alpha, beta); int *ad = (int *) calloc(ndims, sizeof(int)); int *bd = (int *) calloc(ndims, sizeof(int)); hipMemcpy(ad, adims, ndims*sizeof(int), hipMemcpyDeviceToHost); hipMemcpy(bd, bdims, ndims*sizeof(int), hipMemcpyDeviceToHost); for (int n=0; n<ndims; n++) printf("a[%d]=%d b[%d]=%d\n", n, ad[n], n, bd[n]); KCALL(_addforw,ndims,alpha,adims,a,beta,bdims,b,c); } */ } template<typename dType> __global__ void _addback(int ndims, int *cdims, dType *c, int *adims, dType *a) { int c0, c1, c2, c3, c4, c5, c6, c7, i, j, ai; int ci = threadIdx.x + blockIdx.x * blockDim.x; int cn = 1; for (int n=0; n<ndims; n++) cn *= cdims[n]; while(ci < cn) { j = ci; if (ndims > 0) { i=j; j=i/cdims[0]; c0=i-j*cdims[0]; } if (ndims > 1) { i=j; j=i/cdims[1]; c1=i-j*cdims[1]; } if (ndims > 2) { i=j; j=i/cdims[2]; c2=i-j*cdims[2]; } if (ndims > 3) { i=j; j=i/cdims[3]; c3=i-j*cdims[3]; } if (ndims > 4) { i=j; j=i/cdims[4]; c4=i-j*cdims[4]; } if (ndims > 5) { i=j; j=i/cdims[5]; c5=i-j*cdims[5]; } if (ndims > 6) { i=j; j=i/cdims[6]; c6=i-j*cdims[6]; } if (ndims > 7) { i=j; j=i/cdims[7]; c7=i-j*cdims[7]; } ai = 0; if (ndims > 7) { ai = adims[7]*ai + (adims[7]==1 ? 0 : c7); } if (ndims > 6) { ai = adims[6]*ai + (adims[6]==1 ? 0 : c6); } if (ndims > 5) { ai = adims[5]*ai + (adims[5]==1 ? 0 : c5); } if (ndims > 4) { ai = adims[4]*ai + (adims[4]==1 ? 0 : c4); } if (ndims > 3) { ai = adims[3]*ai + (adims[3]==1 ? 0 : c3); } if (ndims > 2) { ai = adims[2]*ai + (adims[2]==1 ? 0 : c2); } if (ndims > 1) { ai = adims[1]*ai + (adims[1]==1 ? 0 : c1); } if (ndims > 0) { ai = adims[0]*ai + (adims[0]==1 ? 0 : c0); } atomicAdd(&a[ai], c[ci]); ci += blockDim.x * gridDim.x; } } extern "C" { void addback32(int ndims, int *cdims, float *c, int *adims, float *a) KCALL(_addback,ndims,cdims,c,adims,a); void addback64(int ndims, int *cdims, double *c, int *adims, double *a) KCALL(_addback,ndims,cdims,c,adims,a); }
d289a6740fc895b829ff2f44d0dd9e1266bb70fa.cu
#include "../knet.h" #include <assert.h> // broadcasting add: c = alpha*a + beta * b // each dim of a is either 1 or matches b. c has the same size as b. template<typename dType> __global__ void _addforw(int ndims, dType alpha, int *adims, dType *a, dType beta, int *bdims, dType *b, dType *c) { int b0, b1, b2, b3, b4, b5, b6, b7, i, j, ai; int bi = threadIdx.x + blockIdx.x * blockDim.x; int bn = 1; for (int n=0; n<ndims; n++) bn *= bdims[n]; while(bi < bn) { j = bi; if (ndims > 0) { i=j; j=i/bdims[0]; b0=i-j*bdims[0]; } if (ndims > 1) { i=j; j=i/bdims[1]; b1=i-j*bdims[1]; } if (ndims > 2) { i=j; j=i/bdims[2]; b2=i-j*bdims[2]; } if (ndims > 3) { i=j; j=i/bdims[3]; b3=i-j*bdims[3]; } if (ndims > 4) { i=j; j=i/bdims[4]; b4=i-j*bdims[4]; } if (ndims > 5) { i=j; j=i/bdims[5]; b5=i-j*bdims[5]; } if (ndims > 6) { i=j; j=i/bdims[6]; b6=i-j*bdims[6]; } if (ndims > 7) { i=j; j=i/bdims[7]; b7=i-j*bdims[7]; } ai = 0; if (ndims > 7) { ai = adims[7]*ai + (adims[7]==1 ? 0 : b7); } if (ndims > 6) { ai = adims[6]*ai + (adims[6]==1 ? 0 : b6); } if (ndims > 5) { ai = adims[5]*ai + (adims[5]==1 ? 0 : b5); } if (ndims > 4) { ai = adims[4]*ai + (adims[4]==1 ? 0 : b4); } if (ndims > 3) { ai = adims[3]*ai + (adims[3]==1 ? 0 : b3); } if (ndims > 2) { ai = adims[2]*ai + (adims[2]==1 ? 0 : b2); } if (ndims > 1) { ai = adims[1]*ai + (adims[1]==1 ? 0 : b1); } if (ndims > 0) { ai = adims[0]*ai + (adims[0]==1 ? 0 : b0); } c[bi] = alpha * a[ai] + beta * b[bi]; bi += blockDim.x * gridDim.x; } } // slightly more optimized 2D version template<typename dType> __global__ void _addforw2d(dType alpha, int *adims, dType *a, dType beta, int *bdims, dType *b, dType *c) { int b0, b1, i, j, ai, A0, A1, B0, B1; B0 = bdims[0]; B1 = bdims[1]; A0 = adims[0]; A1 = adims[1]; int bi = threadIdx.x + blockIdx.x * blockDim.x; int bn = bdims[0]*bdims[1]; while(bi < bn) { j=bi/B0; b0=bi-j*B0; i=j; j=i/B1; b1=i-j*B1; ai = A0*(A1==1 ? 0 : b1) + (A0==1 ? 0 : b0); c[bi] = alpha * a[ai] + beta * b[bi]; /* dType cval = b[bi]; if (beta != 1) cval *= beta; if (alpha != 0) { if (alpha != 1) cval += alpha * a[ai]; else cval += a[ai]; } c[bi] = cval; */ bi += blockDim.x * gridDim.x; } } extern "C" { void addforw32(int ndims, float alpha, int *adims, float *a, float beta, int *bdims, float *b, float *c) { if (ndims==2) { KCALL(_addforw2d,alpha,adims,a,beta,bdims,b,c); } else { KCALL(_addforw,ndims,alpha,adims,a,beta,bdims,b,c); } } void addforw64(int ndims, double alpha, int *adims, double *a, double beta, int *bdims, double *b, double *c) { if (ndims==2) { KCALL(_addforw2d,alpha,adims,a,beta,bdims,b,c); } else { KCALL(_addforw,ndims,alpha,adims,a,beta,bdims,b,c); } } /* #include <stdio.h> void addforw32(int ndims, float alpha, int *adims, float *a, float beta, int *bdims, float *b, float *c) { printf("ndims=%d alpha=%g beta=%g\n", ndims, alpha, beta); int *ad = (int *) calloc(ndims, sizeof(int)); int *bd = (int *) calloc(ndims, sizeof(int)); cudaMemcpy(ad, adims, ndims*sizeof(int), cudaMemcpyDeviceToHost); cudaMemcpy(bd, bdims, ndims*sizeof(int), cudaMemcpyDeviceToHost); for (int n=0; n<ndims; n++) printf("a[%d]=%d b[%d]=%d\n", n, ad[n], n, bd[n]); KCALL(_addforw,ndims,alpha,adims,a,beta,bdims,b,c); } */ } template<typename dType> __global__ void _addback(int ndims, int *cdims, dType *c, int *adims, dType *a) { int c0, c1, c2, c3, c4, c5, c6, c7, i, j, ai; int ci = threadIdx.x + blockIdx.x * blockDim.x; int cn = 1; for (int n=0; n<ndims; n++) cn *= cdims[n]; while(ci < cn) { j = ci; if (ndims > 0) { i=j; j=i/cdims[0]; c0=i-j*cdims[0]; } if (ndims > 1) { i=j; j=i/cdims[1]; c1=i-j*cdims[1]; } if (ndims > 2) { i=j; j=i/cdims[2]; c2=i-j*cdims[2]; } if (ndims > 3) { i=j; j=i/cdims[3]; c3=i-j*cdims[3]; } if (ndims > 4) { i=j; j=i/cdims[4]; c4=i-j*cdims[4]; } if (ndims > 5) { i=j; j=i/cdims[5]; c5=i-j*cdims[5]; } if (ndims > 6) { i=j; j=i/cdims[6]; c6=i-j*cdims[6]; } if (ndims > 7) { i=j; j=i/cdims[7]; c7=i-j*cdims[7]; } ai = 0; if (ndims > 7) { ai = adims[7]*ai + (adims[7]==1 ? 0 : c7); } if (ndims > 6) { ai = adims[6]*ai + (adims[6]==1 ? 0 : c6); } if (ndims > 5) { ai = adims[5]*ai + (adims[5]==1 ? 0 : c5); } if (ndims > 4) { ai = adims[4]*ai + (adims[4]==1 ? 0 : c4); } if (ndims > 3) { ai = adims[3]*ai + (adims[3]==1 ? 0 : c3); } if (ndims > 2) { ai = adims[2]*ai + (adims[2]==1 ? 0 : c2); } if (ndims > 1) { ai = adims[1]*ai + (adims[1]==1 ? 0 : c1); } if (ndims > 0) { ai = adims[0]*ai + (adims[0]==1 ? 0 : c0); } atomicAdd(&a[ai], c[ci]); ci += blockDim.x * gridDim.x; } } extern "C" { void addback32(int ndims, int *cdims, float *c, int *adims, float *a) KCALL(_addback,ndims,cdims,c,adims,a); void addback64(int ndims, int *cdims, double *c, int *adims, double *a) KCALL(_addback,ndims,cdims,c,adims,a); }
19d647a353a33d59a6bc023f269db1f3fcddfe31.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" //Udacity HW 6 //Poisson Blending /* Background ========== The goal for this assignment is to take one image (the source) and paste it into another image (the destination) attempting to match the two images so that the pasting is non-obvious. This is known as a "seamless clone". The basic ideas are as follows: 1) Figure out the interior and border of the source image 2) Use the values of the border pixels in the destination image as boundary conditions for solving a Poisson equation that tells us how to blend the images. No pixels from the destination except pixels on the border are used to compute the match. Solving the Poisson Equation ============================ There are multiple ways to solve this equation - we choose an iterative method - specifically the Jacobi method. Iterative methods start with a guess of the solution and then iterate to try and improve the guess until it stops changing. If the problem was well-suited for the method then it will stop and where it stops will be the solution. The Jacobi method is the simplest iterative method and converges slowly - that is we need a lot of iterations to get to the answer, but it is the easiest method to write. Jacobi Iterations ================= Our initial guess is going to be the source image itself. This is a pretty good guess for what the blended image will look like and it means that we won't have to do as many iterations compared to if we had started far from the final solution. ImageGuess_prev (Floating point) ImageGuess_next (Floating point) DestinationImg SourceImg Follow these steps to implement one iteration: 1) For every pixel p in the interior, compute two sums over the four neighboring pixels: Sum1: If the neighbor is in the interior then += ImageGuess_prev[neighbor] else if the neighbor in on the border then += DestinationImg[neighbor] Sum2: += SourceImg[p] - SourceImg[neighbor] (for all four neighbors) 2) Calculate the new pixel value: float newVal= (Sum1 + Sum2) / 4.f <------ Notice that the result is FLOATING POINT ImageGuess_next[p] = min(255, max(0, newVal)); //clamp to [0, 255] In this assignment we will do 800 iterations. */ #include "utils.h" #include <thrust/host_vector.h> __global__ void generate_mask_and_channel_init( const uchar4* d_sourceImg, const uchar4* d_destImg, unsigned char * d_mask, unsigned char * d_red_src, unsigned char * d_blue_src, unsigned char * d_green_src, unsigned char * d_red_dst, unsigned char * d_blue_dst, unsigned char * d_green_dst, unsigned int srcSize) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= srcSize) return; d_mask[myId] = (d_sourceImg[myId].x + d_sourceImg[myId].y + d_sourceImg[myId].z < 3 * 255) ? 1 : 0; d_red_src[myId] = d_sourceImg[myId].x; d_blue_src[myId] = d_sourceImg[myId].y; d_green_src[myId] = d_sourceImg[myId].z; d_red_dst[myId] = d_destImg[myId].x; d_blue_dst[myId] = d_destImg[myId].y; d_green_dst[myId] = d_destImg[myId].z; } __global__ void distinct_pixel_kind( unsigned char * d_mask, unsigned char * d_borderPixels, unsigned char * d_strictInteriorPixels, size_t numRowsSource, size_t numColsSource, unsigned int * d_interior_size) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; int row = myId / numColsSource; int col = myId % numColsSource; if(row ==0 || col ==0 || row == numRowsSource -1 || col == numColsSource -1){ return; } if(d_mask[myId]){ if(d_mask[myId - 1] && d_mask[myId + 1] && d_mask[myId - numColsSource] && d_mask[myId + numColsSource]) { d_strictInteriorPixels[myId] = 1; d_borderPixels[myId] = 0; atomicAdd(&d_interior_size[0],1); }else{ d_strictInteriorPixels[myId] = 0; d_borderPixels[myId] = 1; } }else{ d_strictInteriorPixels[myId] = 0; d_borderPixels[myId] = 0; } } __global__ void compute_g( unsigned char * d_red_src, unsigned char * d_blue_src, unsigned char * d_green_src, float * d_g_red, float * d_g_blue, float * d_g_green, unsigned char * d_strictInteriorPixels, size_t numColsSource, size_t numRowsSource) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; if(d_strictInteriorPixels[myId] == 0) return; float r_sum = 4.f * d_red_src[myId]; float b_sum = 4.f * d_blue_src[myId]; float g_sum = 4.f * d_green_src[myId]; r_sum -= (float)d_red_src[myId -1] + (float)d_red_src[myId +1]; r_sum -= (float)d_red_src[myId - numColsSource] + (float)d_red_src[myId + numColsSource]; b_sum -= (float)d_blue_src[myId -1] + (float)d_blue_src[myId +1]; b_sum -= (float)d_blue_src[myId - numColsSource] + (float)d_blue_src[myId + numColsSource]; g_sum -= (float)d_green_src[myId -1] + (float)d_green_src[myId +1]; g_sum -= (float)d_green_src[myId - numColsSource] + (float)d_green_src[myId + numColsSource]; d_g_red[myId] = r_sum; d_g_blue[myId] = b_sum; d_g_green[myId] = g_sum; } __global__ void init_blended_vals( unsigned char * d_red_src, unsigned char * d_blue_src, unsigned char * d_green_src, float * d_blendedValsRed_1, float *d_blendedValsRed_2, float *d_blendedValsBlue_1, float *d_blendedValsBlue_2, float *d_blendedValsGreen_1, float *d_blendedValsGreen_2, unsigned int srcSize) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= srcSize) return; d_blendedValsRed_1[myId] = d_red_src[myId]; d_blendedValsRed_2[myId] = d_red_src[myId]; d_blendedValsBlue_1[myId] = d_blue_src[myId]; d_blendedValsBlue_2[myId] = d_blue_src[myId]; d_blendedValsGreen_1[myId] = d_green_src[myId]; d_blendedValsGreen_2[myId] = d_green_src[myId]; } __global__ void compute_iteration( unsigned char * d_destImg, unsigned char * d_strictInteriorPixels, unsigned char * d_borderPixels, size_t numColsSource, size_t numRowsSource, float * d_g, float * f, float* f_next) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; if(d_strictInteriorPixels[myId] == 0) return; float blendedSum = 0.f; float borderSum = 0.f; if(d_strictInteriorPixels[myId -1]){ blendedSum +=f[myId - 1]; }else{ borderSum += d_destImg[myId -1]; } if(d_strictInteriorPixels[myId + 1]){ blendedSum += f[myId +1]; }else{ borderSum += d_destImg[myId + 1]; } if(d_strictInteriorPixels[myId - numColsSource]){ blendedSum += f[myId - numColsSource]; }else{ borderSum += d_destImg[myId - numColsSource]; } if(d_strictInteriorPixels[myId + numColsSource]){ blendedSum += f[myId + numColsSource]; }else{ borderSum +=d_destImg[myId + numColsSource]; } float f_next_val = (blendedSum + borderSum + d_g[myId])/4.f; f_next[myId] = min(255.f, max(0.f,f_next_val)); } __global__ void compute_iteration1( unsigned char * d_red_dst, unsigned char * d_blue_dst, unsigned char * d_green_dst, unsigned char * d_strictInteriorPixels, unsigned char * d_borderPixels, size_t numColsSource, size_t numRowsSource, float * d_g_red, float * d_g_blue, float * d_g_green, float * f_r, float* f_next_r, float * f_b, float* f_next_b, float * f_g, float* f_next_g) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; if(d_strictInteriorPixels[myId] == 0) return; float blendedSum_r = 0.f; float blendedSum_b = 0.f; float blendedSum_g = 0.f; float borderSum_r = 0.f; float borderSum_b = 0.f; float borderSum_g = 0.f; if(d_strictInteriorPixels[myId -1]){ blendedSum_r +=f_r[myId - 1]; blendedSum_b +=f_b[myId - 1]; blendedSum_g +=f_g[myId - 1]; }else{ borderSum_r += d_red_dst[myId -1]; borderSum_b += d_blue_dst[myId -1]; borderSum_g += d_green_dst[myId -1]; } if(d_strictInteriorPixels[myId +1]){ blendedSum_r +=f_r[myId + 1]; blendedSum_b +=f_b[myId + 1]; blendedSum_g +=f_g[myId + 1]; }else{ borderSum_r += d_red_dst[myId +1]; borderSum_b += d_blue_dst[myId +1]; borderSum_g += d_green_dst[myId +1]; } if(d_strictInteriorPixels[myId - numColsSource]){ blendedSum_r +=f_r[myId - numColsSource]; blendedSum_b +=f_b[myId - numColsSource]; blendedSum_g +=f_g[myId - numColsSource]; }else{ borderSum_r += d_red_dst[myId - numColsSource]; borderSum_b += d_blue_dst[myId - numColsSource]; borderSum_g += d_green_dst[myId - numColsSource]; } if(d_strictInteriorPixels[myId + numColsSource]){ blendedSum_r +=f_r[myId + numColsSource]; blendedSum_b +=f_b[myId + numColsSource]; blendedSum_g +=f_g[myId + numColsSource]; }else{ borderSum_r += d_red_dst[myId + numColsSource]; borderSum_b += d_blue_dst[myId + numColsSource]; borderSum_g += d_green_dst[myId + numColsSource]; } float f_next_val_r = (blendedSum_r + borderSum_r + d_g_red[myId])/4.f; float f_next_val_b = (blendedSum_b + borderSum_b + d_g_blue[myId])/4.f; float f_next_val_g = (blendedSum_g + borderSum_g + d_g_green[myId])/4.f; f_next_r[myId] = min(255.f, max(0.f,f_next_val_r)); f_next_b[myId] = min(255.f, max(0.f,f_next_val_b)); f_next_g[myId] = min(255.f, max(0.f,f_next_val_g)); } __global__ void gather_result( uchar4 * d_blendedImg, float * d_blendedValsRed, float * d_blendedValsBlue, float * d_blendedValsGreen, unsigned char * d_strictInteriorPixels, unsigned int srcSize) { int myId = blockDim.x *blockIdx.x + threadIdx.x; if(myId >= srcSize) return; if(d_strictInteriorPixels[myId] ==0) return; d_blendedImg[myId].x = d_blendedValsRed[myId]; d_blendedImg[myId].y = d_blendedValsBlue[myId]; d_blendedImg[myId].z = d_blendedValsGreen[myId]; } void your_blend(const uchar4* const h_sourceImg, //IN const size_t numRowsSource, const size_t numColsSource, const uchar4* const h_destImg, //IN uchar4* const h_blendedImg) //OUT { /* To Recap here are the steps you need to implement 1) Compute a mask of the pixels from the source image to be copied The pixels that shouldn't be copied are completely white, they have R=255, G=255, B=255. Any other pixels SHOULD be copied. 2) Compute the interior and border regions of the mask. An interior pixel has all 4 neighbors also inside the mask. A border pixel is in the mask itself, but has at least one neighbor that isn't. 3) Separate out the incoming image into three separate channels 4) Create two float(!) buffers for each color channel that will act as our guesses. Initialize them to the respective color channel of the source image since that will act as our intial guess. 5) For each color channel perform the Jacobi iteration described above 800 times. 6) Create the output image by replacing all the interior pixels in the destination image with the result of the Jacobi iterations. Just cast the floating point values to unsigned chars since we have already made sure to clamp them to the correct range. Since this is final assignment we provide little boilerplate code to help you. Notice that all the input/output pointers are HOST pointers. You will have to allocate all of your own GPU memory and perform your own memcopies to get data in and out of the GPU memory. Remember to wrap all of your calls with checkCudaErrors() to catch any thing that might go wrong. After each kernel call do: hipDeviceSynchronize(); checkCudaErrors(hipGetLastError()); to catch any errors that happened while executing the kernel. */ unsigned int srcSize = numRowsSource * numColsSource; dim3 blockSize(128, 1, 1); dim3 gridSize((srcSize + blockSize.x -1)/ blockSize.x , 1, 1); unsigned char * d_mask ; uchar4 * d_sourceImg; uchar4 * d_destImg; unsigned char * d_red_src; unsigned char * d_blue_src; unsigned char * d_green_src; unsigned char * d_red_dst; unsigned char * d_blue_dst; unsigned char * d_green_dst; checkCudaErrors(hipMalloc(&d_sourceImg, sizeof(uchar4) * srcSize)); checkCudaErrors(hipMalloc(&d_destImg, sizeof(uchar4) * srcSize)); checkCudaErrors(hipMemcpy(d_sourceImg, h_sourceImg, sizeof(uchar4) * srcSize, hipMemcpyHostToDevice)); checkCudaErrors(hipMemcpy(d_destImg, h_destImg, sizeof(uchar4) * srcSize, hipMemcpyHostToDevice)); checkCudaErrors(hipMalloc(&d_red_src, sizeof(unsigned char) * srcSize )); checkCudaErrors(hipMalloc(&d_blue_src, sizeof(unsigned char) * srcSize )); checkCudaErrors(hipMalloc(&d_green_src, sizeof(unsigned char) * srcSize )); checkCudaErrors(hipMalloc(&d_red_dst, sizeof(unsigned char) * srcSize )); checkCudaErrors(hipMalloc(&d_blue_dst, sizeof(unsigned char) * srcSize )); checkCudaErrors(hipMalloc(&d_green_dst, sizeof(unsigned char) * srcSize )); checkCudaErrors(hipMalloc(&d_mask, srcSize * sizeof(unsigned char))); checkCudaErrors(hipMemset(d_mask, 0 , srcSize * sizeof(unsigned char))); hipLaunchKernelGGL(( generate_mask_and_channel_init), dim3(gridSize), dim3(blockSize), 0, 0, d_sourceImg, d_destImg ,d_mask, d_red_src, d_blue_src, d_green_src, d_red_dst, d_blue_dst, d_green_dst,srcSize); unsigned char * d_borderPixels; unsigned char * d_strictInteriorPixels; unsigned int * d_interior_size; unsigned int interior_size = 0; checkCudaErrors(hipMalloc(&d_interior_size, sizeof(unsigned int))); checkCudaErrors(hipMalloc(&d_borderPixels, sizeof(unsigned char) * srcSize)); checkCudaErrors(hipMalloc(&d_strictInteriorPixels, sizeof(unsigned char) * srcSize)); checkCudaErrors(hipMemset(d_interior_size, 0 , sizeof(unsigned int))); checkCudaErrors(hipMemset(d_borderPixels, 0 ,sizeof(unsigned char) * srcSize)); checkCudaErrors(hipMemset(d_strictInteriorPixels, 0 ,sizeof(unsigned char) * srcSize)); hipLaunchKernelGGL(( distinct_pixel_kind), dim3(gridSize), dim3(blockSize), 0, 0, d_mask, d_borderPixels, d_strictInteriorPixels, numRowsSource, numColsSource, d_interior_size); checkCudaErrors(hipMemcpy(&interior_size, d_interior_size, sizeof(unsigned int), hipMemcpyDeviceToHost)); float *g_red = new float[srcSize]; float *g_blue = new float[srcSize]; float *g_green = new float[srcSize]; float * d_g_red; float * d_g_blue; float * d_g_green; checkCudaErrors(hipMalloc(&d_g_red, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_g_blue, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_g_green, sizeof(float) * srcSize)); checkCudaErrors(hipMemset(d_g_red, 0 , sizeof(float)* srcSize)); checkCudaErrors(hipMemset(d_g_blue, 0 , sizeof(float)* srcSize)); checkCudaErrors(hipMemset(d_g_green, 0 , sizeof(float)* srcSize)); hipLaunchKernelGGL(( compute_g), dim3(gridSize), dim3(blockSize), 0, 0, d_red_src, d_blue_src, d_green_src, d_g_red, d_g_blue, d_g_green,d_strictInteriorPixels, numColsSource, numRowsSource); //for each color channel we'll need two buffers and we'll ping-pong between them float * d_blendedValsRed_1; float *d_blendedValsRed_2; float *d_blendedValsBlue_1 ; float *d_blendedValsBlue_2 ; float *d_blendedValsGreen_1; float *d_blendedValsGreen_2 ; checkCudaErrors(hipMalloc(&d_blendedValsRed_1, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_blendedValsRed_2, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_blendedValsBlue_1, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_blendedValsBlue_2, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_blendedValsGreen_1, sizeof(float) * srcSize)); checkCudaErrors(hipMalloc(&d_blendedValsGreen_2, sizeof(float) * srcSize)); hipLaunchKernelGGL(( init_blended_vals), dim3(gridSize), dim3(blockSize), 0, 0, d_red_src, d_blue_src, d_green_src, d_blendedValsRed_1, d_blendedValsRed_2, d_blendedValsBlue_1, d_blendedValsBlue_2, d_blendedValsGreen_1, d_blendedValsGreen_2, srcSize); //Perform the solve on each color channel const size_t numIterations = 800; for (size_t i = 0; i < numIterations; ++i) { // compute_iteration<<<gridSize, blockSize>>>(d_red_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_red, d_blendedValsRed_1, d_blendedValsRed_2); // compute_iteration<<<gridSize, blockSize>>>(d_blue_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_blue, d_blendedValsBlue_1, d_blendedValsBlue_2); // compute_iteration<<<gridSize, blockSize>>>(d_green_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_green, d_blendedValsGreen_1, d_blendedValsGreen_2); hipLaunchKernelGGL(( compute_iteration1), dim3(gridSize), dim3(blockSize), 0, 0, d_red_dst,d_blue_dst,d_green_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_red,d_g_blue,d_g_green, d_blendedValsRed_1, d_blendedValsRed_2, d_blendedValsBlue_1,d_blendedValsBlue_2,d_blendedValsGreen_1, d_blendedValsGreen_2); std::swap(d_blendedValsRed_1, d_blendedValsRed_2); std::swap(d_blendedValsBlue_1, d_blendedValsBlue_2); std::swap(d_blendedValsGreen_1, d_blendedValsGreen_2); } std::swap(d_blendedValsRed_1, d_blendedValsRed_2); //put output into _2 std::swap(d_blendedValsBlue_1, d_blendedValsBlue_2); //put output into _2 std::swap(d_blendedValsGreen_1, d_blendedValsGreen_2); //put output into _2 //copy the destination image to the output memcpy(h_blendedImg, h_destImg, sizeof(uchar4) * srcSize); uchar4 * d_blendedImg; checkCudaErrors(hipMalloc(&d_blendedImg, sizeof(uchar4) * srcSize)); checkCudaErrors(hipMemcpy(d_blendedImg, h_blendedImg, sizeof(uchar4) * srcSize, hipMemcpyHostToDevice)); hipLaunchKernelGGL(( gather_result), dim3(gridSize), dim3(blockSize), 0, 0, d_blendedImg, d_blendedValsRed_2, d_blendedValsBlue_2, d_blendedValsGreen_2, d_strictInteriorPixels, srcSize); checkCudaErrors(hipMemcpy(h_blendedImg, d_blendedImg, sizeof(uchar4)* srcSize, hipMemcpyDeviceToHost)); checkCudaErrors(hipFree(d_mask)); checkCudaErrors(hipFree(d_sourceImg)); checkCudaErrors(hipFree(d_destImg)); checkCudaErrors(hipFree(d_red_src)); checkCudaErrors(hipFree(d_red_dst)); checkCudaErrors(hipFree(d_blue_src)); checkCudaErrors(hipFree(d_blue_dst)); checkCudaErrors(hipFree(d_green_src)); checkCudaErrors(hipFree(d_green_dst)); checkCudaErrors(hipFree(d_borderPixels)); checkCudaErrors(hipFree(d_strictInteriorPixels)); checkCudaErrors(hipFree(d_interior_size)); checkCudaErrors(hipFree(d_g_red)); checkCudaErrors(hipFree(d_g_blue)); checkCudaErrors(hipFree(d_g_green)); checkCudaErrors(hipFree(d_blendedValsRed_1)); checkCudaErrors(hipFree(d_blendedValsRed_2)); checkCudaErrors(hipFree(d_blendedValsBlue_1)); checkCudaErrors(hipFree(d_blendedValsBlue_2)); checkCudaErrors(hipFree(d_blendedValsGreen_1)); checkCudaErrors(hipFree(d_blendedValsGreen_2)); checkCudaErrors(hipFree(d_blendedImg)); }
19d647a353a33d59a6bc023f269db1f3fcddfe31.cu
//Udacity HW 6 //Poisson Blending /* Background ========== The goal for this assignment is to take one image (the source) and paste it into another image (the destination) attempting to match the two images so that the pasting is non-obvious. This is known as a "seamless clone". The basic ideas are as follows: 1) Figure out the interior and border of the source image 2) Use the values of the border pixels in the destination image as boundary conditions for solving a Poisson equation that tells us how to blend the images. No pixels from the destination except pixels on the border are used to compute the match. Solving the Poisson Equation ============================ There are multiple ways to solve this equation - we choose an iterative method - specifically the Jacobi method. Iterative methods start with a guess of the solution and then iterate to try and improve the guess until it stops changing. If the problem was well-suited for the method then it will stop and where it stops will be the solution. The Jacobi method is the simplest iterative method and converges slowly - that is we need a lot of iterations to get to the answer, but it is the easiest method to write. Jacobi Iterations ================= Our initial guess is going to be the source image itself. This is a pretty good guess for what the blended image will look like and it means that we won't have to do as many iterations compared to if we had started far from the final solution. ImageGuess_prev (Floating point) ImageGuess_next (Floating point) DestinationImg SourceImg Follow these steps to implement one iteration: 1) For every pixel p in the interior, compute two sums over the four neighboring pixels: Sum1: If the neighbor is in the interior then += ImageGuess_prev[neighbor] else if the neighbor in on the border then += DestinationImg[neighbor] Sum2: += SourceImg[p] - SourceImg[neighbor] (for all four neighbors) 2) Calculate the new pixel value: float newVal= (Sum1 + Sum2) / 4.f <------ Notice that the result is FLOATING POINT ImageGuess_next[p] = min(255, max(0, newVal)); //clamp to [0, 255] In this assignment we will do 800 iterations. */ #include "utils.h" #include <thrust/host_vector.h> __global__ void generate_mask_and_channel_init( const uchar4* d_sourceImg, const uchar4* d_destImg, unsigned char * d_mask, unsigned char * d_red_src, unsigned char * d_blue_src, unsigned char * d_green_src, unsigned char * d_red_dst, unsigned char * d_blue_dst, unsigned char * d_green_dst, unsigned int srcSize) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= srcSize) return; d_mask[myId] = (d_sourceImg[myId].x + d_sourceImg[myId].y + d_sourceImg[myId].z < 3 * 255) ? 1 : 0; d_red_src[myId] = d_sourceImg[myId].x; d_blue_src[myId] = d_sourceImg[myId].y; d_green_src[myId] = d_sourceImg[myId].z; d_red_dst[myId] = d_destImg[myId].x; d_blue_dst[myId] = d_destImg[myId].y; d_green_dst[myId] = d_destImg[myId].z; } __global__ void distinct_pixel_kind( unsigned char * d_mask, unsigned char * d_borderPixels, unsigned char * d_strictInteriorPixels, size_t numRowsSource, size_t numColsSource, unsigned int * d_interior_size) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; int row = myId / numColsSource; int col = myId % numColsSource; if(row ==0 || col ==0 || row == numRowsSource -1 || col == numColsSource -1){ return; } if(d_mask[myId]){ if(d_mask[myId - 1] && d_mask[myId + 1] && d_mask[myId - numColsSource] && d_mask[myId + numColsSource]) { d_strictInteriorPixels[myId] = 1; d_borderPixels[myId] = 0; atomicAdd(&d_interior_size[0],1); }else{ d_strictInteriorPixels[myId] = 0; d_borderPixels[myId] = 1; } }else{ d_strictInteriorPixels[myId] = 0; d_borderPixels[myId] = 0; } } __global__ void compute_g( unsigned char * d_red_src, unsigned char * d_blue_src, unsigned char * d_green_src, float * d_g_red, float * d_g_blue, float * d_g_green, unsigned char * d_strictInteriorPixels, size_t numColsSource, size_t numRowsSource) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; if(d_strictInteriorPixels[myId] == 0) return; float r_sum = 4.f * d_red_src[myId]; float b_sum = 4.f * d_blue_src[myId]; float g_sum = 4.f * d_green_src[myId]; r_sum -= (float)d_red_src[myId -1] + (float)d_red_src[myId +1]; r_sum -= (float)d_red_src[myId - numColsSource] + (float)d_red_src[myId + numColsSource]; b_sum -= (float)d_blue_src[myId -1] + (float)d_blue_src[myId +1]; b_sum -= (float)d_blue_src[myId - numColsSource] + (float)d_blue_src[myId + numColsSource]; g_sum -= (float)d_green_src[myId -1] + (float)d_green_src[myId +1]; g_sum -= (float)d_green_src[myId - numColsSource] + (float)d_green_src[myId + numColsSource]; d_g_red[myId] = r_sum; d_g_blue[myId] = b_sum; d_g_green[myId] = g_sum; } __global__ void init_blended_vals( unsigned char * d_red_src, unsigned char * d_blue_src, unsigned char * d_green_src, float * d_blendedValsRed_1, float *d_blendedValsRed_2, float *d_blendedValsBlue_1, float *d_blendedValsBlue_2, float *d_blendedValsGreen_1, float *d_blendedValsGreen_2, unsigned int srcSize) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= srcSize) return; d_blendedValsRed_1[myId] = d_red_src[myId]; d_blendedValsRed_2[myId] = d_red_src[myId]; d_blendedValsBlue_1[myId] = d_blue_src[myId]; d_blendedValsBlue_2[myId] = d_blue_src[myId]; d_blendedValsGreen_1[myId] = d_green_src[myId]; d_blendedValsGreen_2[myId] = d_green_src[myId]; } __global__ void compute_iteration( unsigned char * d_destImg, unsigned char * d_strictInteriorPixels, unsigned char * d_borderPixels, size_t numColsSource, size_t numRowsSource, float * d_g, float * f, float* f_next) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; if(d_strictInteriorPixels[myId] == 0) return; float blendedSum = 0.f; float borderSum = 0.f; if(d_strictInteriorPixels[myId -1]){ blendedSum +=f[myId - 1]; }else{ borderSum += d_destImg[myId -1]; } if(d_strictInteriorPixels[myId + 1]){ blendedSum += f[myId +1]; }else{ borderSum += d_destImg[myId + 1]; } if(d_strictInteriorPixels[myId - numColsSource]){ blendedSum += f[myId - numColsSource]; }else{ borderSum += d_destImg[myId - numColsSource]; } if(d_strictInteriorPixels[myId + numColsSource]){ blendedSum += f[myId + numColsSource]; }else{ borderSum +=d_destImg[myId + numColsSource]; } float f_next_val = (blendedSum + borderSum + d_g[myId])/4.f; f_next[myId] = min(255.f, max(0.f,f_next_val)); } __global__ void compute_iteration1( unsigned char * d_red_dst, unsigned char * d_blue_dst, unsigned char * d_green_dst, unsigned char * d_strictInteriorPixels, unsigned char * d_borderPixels, size_t numColsSource, size_t numRowsSource, float * d_g_red, float * d_g_blue, float * d_g_green, float * f_r, float* f_next_r, float * f_b, float* f_next_b, float * f_g, float* f_next_g) { int myId = blockDim.x * blockIdx.x + threadIdx.x; if(myId >= numColsSource * numRowsSource) return; if(d_strictInteriorPixels[myId] == 0) return; float blendedSum_r = 0.f; float blendedSum_b = 0.f; float blendedSum_g = 0.f; float borderSum_r = 0.f; float borderSum_b = 0.f; float borderSum_g = 0.f; if(d_strictInteriorPixels[myId -1]){ blendedSum_r +=f_r[myId - 1]; blendedSum_b +=f_b[myId - 1]; blendedSum_g +=f_g[myId - 1]; }else{ borderSum_r += d_red_dst[myId -1]; borderSum_b += d_blue_dst[myId -1]; borderSum_g += d_green_dst[myId -1]; } if(d_strictInteriorPixels[myId +1]){ blendedSum_r +=f_r[myId + 1]; blendedSum_b +=f_b[myId + 1]; blendedSum_g +=f_g[myId + 1]; }else{ borderSum_r += d_red_dst[myId +1]; borderSum_b += d_blue_dst[myId +1]; borderSum_g += d_green_dst[myId +1]; } if(d_strictInteriorPixels[myId - numColsSource]){ blendedSum_r +=f_r[myId - numColsSource]; blendedSum_b +=f_b[myId - numColsSource]; blendedSum_g +=f_g[myId - numColsSource]; }else{ borderSum_r += d_red_dst[myId - numColsSource]; borderSum_b += d_blue_dst[myId - numColsSource]; borderSum_g += d_green_dst[myId - numColsSource]; } if(d_strictInteriorPixels[myId + numColsSource]){ blendedSum_r +=f_r[myId + numColsSource]; blendedSum_b +=f_b[myId + numColsSource]; blendedSum_g +=f_g[myId + numColsSource]; }else{ borderSum_r += d_red_dst[myId + numColsSource]; borderSum_b += d_blue_dst[myId + numColsSource]; borderSum_g += d_green_dst[myId + numColsSource]; } float f_next_val_r = (blendedSum_r + borderSum_r + d_g_red[myId])/4.f; float f_next_val_b = (blendedSum_b + borderSum_b + d_g_blue[myId])/4.f; float f_next_val_g = (blendedSum_g + borderSum_g + d_g_green[myId])/4.f; f_next_r[myId] = min(255.f, max(0.f,f_next_val_r)); f_next_b[myId] = min(255.f, max(0.f,f_next_val_b)); f_next_g[myId] = min(255.f, max(0.f,f_next_val_g)); } __global__ void gather_result( uchar4 * d_blendedImg, float * d_blendedValsRed, float * d_blendedValsBlue, float * d_blendedValsGreen, unsigned char * d_strictInteriorPixels, unsigned int srcSize) { int myId = blockDim.x *blockIdx.x + threadIdx.x; if(myId >= srcSize) return; if(d_strictInteriorPixels[myId] ==0) return; d_blendedImg[myId].x = d_blendedValsRed[myId]; d_blendedImg[myId].y = d_blendedValsBlue[myId]; d_blendedImg[myId].z = d_blendedValsGreen[myId]; } void your_blend(const uchar4* const h_sourceImg, //IN const size_t numRowsSource, const size_t numColsSource, const uchar4* const h_destImg, //IN uchar4* const h_blendedImg) //OUT { /* To Recap here are the steps you need to implement 1) Compute a mask of the pixels from the source image to be copied The pixels that shouldn't be copied are completely white, they have R=255, G=255, B=255. Any other pixels SHOULD be copied. 2) Compute the interior and border regions of the mask. An interior pixel has all 4 neighbors also inside the mask. A border pixel is in the mask itself, but has at least one neighbor that isn't. 3) Separate out the incoming image into three separate channels 4) Create two float(!) buffers for each color channel that will act as our guesses. Initialize them to the respective color channel of the source image since that will act as our intial guess. 5) For each color channel perform the Jacobi iteration described above 800 times. 6) Create the output image by replacing all the interior pixels in the destination image with the result of the Jacobi iterations. Just cast the floating point values to unsigned chars since we have already made sure to clamp them to the correct range. Since this is final assignment we provide little boilerplate code to help you. Notice that all the input/output pointers are HOST pointers. You will have to allocate all of your own GPU memory and perform your own memcopies to get data in and out of the GPU memory. Remember to wrap all of your calls with checkCudaErrors() to catch any thing that might go wrong. After each kernel call do: cudaDeviceSynchronize(); checkCudaErrors(cudaGetLastError()); to catch any errors that happened while executing the kernel. */ unsigned int srcSize = numRowsSource * numColsSource; dim3 blockSize(128, 1, 1); dim3 gridSize((srcSize + blockSize.x -1)/ blockSize.x , 1, 1); unsigned char * d_mask ; uchar4 * d_sourceImg; uchar4 * d_destImg; unsigned char * d_red_src; unsigned char * d_blue_src; unsigned char * d_green_src; unsigned char * d_red_dst; unsigned char * d_blue_dst; unsigned char * d_green_dst; checkCudaErrors(cudaMalloc(&d_sourceImg, sizeof(uchar4) * srcSize)); checkCudaErrors(cudaMalloc(&d_destImg, sizeof(uchar4) * srcSize)); checkCudaErrors(cudaMemcpy(d_sourceImg, h_sourceImg, sizeof(uchar4) * srcSize, cudaMemcpyHostToDevice)); checkCudaErrors(cudaMemcpy(d_destImg, h_destImg, sizeof(uchar4) * srcSize, cudaMemcpyHostToDevice)); checkCudaErrors(cudaMalloc(&d_red_src, sizeof(unsigned char) * srcSize )); checkCudaErrors(cudaMalloc(&d_blue_src, sizeof(unsigned char) * srcSize )); checkCudaErrors(cudaMalloc(&d_green_src, sizeof(unsigned char) * srcSize )); checkCudaErrors(cudaMalloc(&d_red_dst, sizeof(unsigned char) * srcSize )); checkCudaErrors(cudaMalloc(&d_blue_dst, sizeof(unsigned char) * srcSize )); checkCudaErrors(cudaMalloc(&d_green_dst, sizeof(unsigned char) * srcSize )); checkCudaErrors(cudaMalloc(&d_mask, srcSize * sizeof(unsigned char))); checkCudaErrors(cudaMemset(d_mask, 0 , srcSize * sizeof(unsigned char))); generate_mask_and_channel_init<<<gridSize, blockSize>>>(d_sourceImg, d_destImg ,d_mask, d_red_src, d_blue_src, d_green_src, d_red_dst, d_blue_dst, d_green_dst,srcSize); unsigned char * d_borderPixels; unsigned char * d_strictInteriorPixels; unsigned int * d_interior_size; unsigned int interior_size = 0; checkCudaErrors(cudaMalloc(&d_interior_size, sizeof(unsigned int))); checkCudaErrors(cudaMalloc(&d_borderPixels, sizeof(unsigned char) * srcSize)); checkCudaErrors(cudaMalloc(&d_strictInteriorPixels, sizeof(unsigned char) * srcSize)); checkCudaErrors(cudaMemset(d_interior_size, 0 , sizeof(unsigned int))); checkCudaErrors(cudaMemset(d_borderPixels, 0 ,sizeof(unsigned char) * srcSize)); checkCudaErrors(cudaMemset(d_strictInteriorPixels, 0 ,sizeof(unsigned char) * srcSize)); distinct_pixel_kind<<<gridSize, blockSize>>>(d_mask, d_borderPixels, d_strictInteriorPixels, numRowsSource, numColsSource, d_interior_size); checkCudaErrors(cudaMemcpy(&interior_size, d_interior_size, sizeof(unsigned int), cudaMemcpyDeviceToHost)); float *g_red = new float[srcSize]; float *g_blue = new float[srcSize]; float *g_green = new float[srcSize]; float * d_g_red; float * d_g_blue; float * d_g_green; checkCudaErrors(cudaMalloc(&d_g_red, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_g_blue, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_g_green, sizeof(float) * srcSize)); checkCudaErrors(cudaMemset(d_g_red, 0 , sizeof(float)* srcSize)); checkCudaErrors(cudaMemset(d_g_blue, 0 , sizeof(float)* srcSize)); checkCudaErrors(cudaMemset(d_g_green, 0 , sizeof(float)* srcSize)); compute_g<<<gridSize, blockSize>>>(d_red_src, d_blue_src, d_green_src, d_g_red, d_g_blue, d_g_green,d_strictInteriorPixels, numColsSource, numRowsSource); //for each color channel we'll need two buffers and we'll ping-pong between them float * d_blendedValsRed_1; float *d_blendedValsRed_2; float *d_blendedValsBlue_1 ; float *d_blendedValsBlue_2 ; float *d_blendedValsGreen_1; float *d_blendedValsGreen_2 ; checkCudaErrors(cudaMalloc(&d_blendedValsRed_1, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_blendedValsRed_2, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_blendedValsBlue_1, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_blendedValsBlue_2, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_blendedValsGreen_1, sizeof(float) * srcSize)); checkCudaErrors(cudaMalloc(&d_blendedValsGreen_2, sizeof(float) * srcSize)); init_blended_vals<<<gridSize, blockSize>>>(d_red_src, d_blue_src, d_green_src, d_blendedValsRed_1, d_blendedValsRed_2, d_blendedValsBlue_1, d_blendedValsBlue_2, d_blendedValsGreen_1, d_blendedValsGreen_2, srcSize); //Perform the solve on each color channel const size_t numIterations = 800; for (size_t i = 0; i < numIterations; ++i) { // compute_iteration<<<gridSize, blockSize>>>(d_red_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_red, d_blendedValsRed_1, d_blendedValsRed_2); // compute_iteration<<<gridSize, blockSize>>>(d_blue_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_blue, d_blendedValsBlue_1, d_blendedValsBlue_2); // compute_iteration<<<gridSize, blockSize>>>(d_green_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_green, d_blendedValsGreen_1, d_blendedValsGreen_2); compute_iteration1<<<gridSize, blockSize>>>(d_red_dst,d_blue_dst,d_green_dst, d_strictInteriorPixels,d_borderPixels,numColsSource, numRowsSource, d_g_red,d_g_blue,d_g_green, d_blendedValsRed_1, d_blendedValsRed_2, d_blendedValsBlue_1,d_blendedValsBlue_2,d_blendedValsGreen_1, d_blendedValsGreen_2); std::swap(d_blendedValsRed_1, d_blendedValsRed_2); std::swap(d_blendedValsBlue_1, d_blendedValsBlue_2); std::swap(d_blendedValsGreen_1, d_blendedValsGreen_2); } std::swap(d_blendedValsRed_1, d_blendedValsRed_2); //put output into _2 std::swap(d_blendedValsBlue_1, d_blendedValsBlue_2); //put output into _2 std::swap(d_blendedValsGreen_1, d_blendedValsGreen_2); //put output into _2 //copy the destination image to the output memcpy(h_blendedImg, h_destImg, sizeof(uchar4) * srcSize); uchar4 * d_blendedImg; checkCudaErrors(cudaMalloc(&d_blendedImg, sizeof(uchar4) * srcSize)); checkCudaErrors(cudaMemcpy(d_blendedImg, h_blendedImg, sizeof(uchar4) * srcSize, cudaMemcpyHostToDevice)); gather_result<<<gridSize, blockSize>>>(d_blendedImg, d_blendedValsRed_2, d_blendedValsBlue_2, d_blendedValsGreen_2, d_strictInteriorPixels, srcSize); checkCudaErrors(cudaMemcpy(h_blendedImg, d_blendedImg, sizeof(uchar4)* srcSize, cudaMemcpyDeviceToHost)); checkCudaErrors(cudaFree(d_mask)); checkCudaErrors(cudaFree(d_sourceImg)); checkCudaErrors(cudaFree(d_destImg)); checkCudaErrors(cudaFree(d_red_src)); checkCudaErrors(cudaFree(d_red_dst)); checkCudaErrors(cudaFree(d_blue_src)); checkCudaErrors(cudaFree(d_blue_dst)); checkCudaErrors(cudaFree(d_green_src)); checkCudaErrors(cudaFree(d_green_dst)); checkCudaErrors(cudaFree(d_borderPixels)); checkCudaErrors(cudaFree(d_strictInteriorPixels)); checkCudaErrors(cudaFree(d_interior_size)); checkCudaErrors(cudaFree(d_g_red)); checkCudaErrors(cudaFree(d_g_blue)); checkCudaErrors(cudaFree(d_g_green)); checkCudaErrors(cudaFree(d_blendedValsRed_1)); checkCudaErrors(cudaFree(d_blendedValsRed_2)); checkCudaErrors(cudaFree(d_blendedValsBlue_1)); checkCudaErrors(cudaFree(d_blendedValsBlue_2)); checkCudaErrors(cudaFree(d_blendedValsGreen_1)); checkCudaErrors(cudaFree(d_blendedValsGreen_2)); checkCudaErrors(cudaFree(d_blendedImg)); }
27e812a8742cdf0f38d810edfef98d54f4c5aa0a.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include "omp_repair.h" #include <hip/hip_runtime.h> static long num_steps = 100000000; // 100 millions double step; #if __CUDA_ARCH__ < 600 __device__ double atomicAdd2(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int*)address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __double_as_longlong(val + __longlong_as_double(assumed))); // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN) } while (assumed != old); return __longlong_as_double(old); } #endif __global__ void cal_pi(long num_steps, double step, double *sum) { int i; double x; double local; local=0.0; int idx = blockIdx.x*blockDim.x+threadIdx.x; // index du thread int saut = blockDim.x * gridDim.x; for (i=idx;i<= num_steps; i+=saut){ x = (i-0.5)*step; local += 4.0/(1.0+x*x); } atomicAdd2(sum, local); } int main () { double pi, sum = 0.0; double start_time, run_time; step = 1.0/(double) num_steps; start_time = omp_get_wtime(); double *dev_sum; // capture the start time hipEvent_t start, stop; hipEventCreate( &start ); hipEventCreate( &stop ); hipEventRecord( start, 0 ); // hipMalloc((void **)&dev_sum, sizeof(double)); hipMemset(dev_sum, 0, sizeof(double)); hipLaunchKernelGGL(( cal_pi), dim3(512),dim3(512), 0, 0, num_steps,step,dev_sum); hipMemcpy(&sum, dev_sum, sizeof(double), hipMemcpyDeviceToHost); pi = step * sum; // get stop time, and display the timing results hipEventRecord( stop, 0 ); hipEventSynchronize( stop ); float elapsedTime; hipEventElapsedTime( &elapsedTime, start, stop ); printf( "Time to compute : %3.1f ms\n", elapsedTime ); hipEventDestroy( start ); hipEventDestroy( stop ); run_time = omp_get_wtime() - start_time; printf("\n pi with %ld steps is %lf in %lf seconds\n ",num_steps,pi,run_time); }
27e812a8742cdf0f38d810edfef98d54f4c5aa0a.cu
#include <stdio.h> #include "omp_repair.h" #include <cuda.h> static long num_steps = 100000000; // 100 millions double step; #if __CUDA_ARCH__ < 600 __device__ double atomicAdd2(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int*)address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __double_as_longlong(val + __longlong_as_double(assumed))); // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN) } while (assumed != old); return __longlong_as_double(old); } #endif __global__ void cal_pi(long num_steps, double step, double *sum) { int i; double x; double local; local=0.0; int idx = blockIdx.x*blockDim.x+threadIdx.x; // index du thread int saut = blockDim.x * gridDim.x; for (i=idx;i<= num_steps; i+=saut){ x = (i-0.5)*step; local += 4.0/(1.0+x*x); } atomicAdd2(sum, local); } int main () { double pi, sum = 0.0; double start_time, run_time; step = 1.0/(double) num_steps; start_time = omp_get_wtime(); double *dev_sum; // capture the start time cudaEvent_t start, stop; cudaEventCreate( &start ); cudaEventCreate( &stop ); cudaEventRecord( start, 0 ); // cudaMalloc((void **)&dev_sum, sizeof(double)); cudaMemset(dev_sum, 0, sizeof(double)); cal_pi<<<512,512>>>(num_steps,step,dev_sum); cudaMemcpy(&sum, dev_sum, sizeof(double), cudaMemcpyDeviceToHost); pi = step * sum; // get stop time, and display the timing results cudaEventRecord( stop, 0 ); cudaEventSynchronize( stop ); float elapsedTime; cudaEventElapsedTime( &elapsedTime, start, stop ); printf( "Time to compute : %3.1f ms\n", elapsedTime ); cudaEventDestroy( start ); cudaEventDestroy( stop ); run_time = omp_get_wtime() - start_time; printf("\n pi with %ld steps is %lf in %lf seconds\n ",num_steps,pi,run_time); }
5245332954bd2384081d861f36c638310b7aab21.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <iostream> #include <math.h> const int N_SMM = 22; const int N_SP_PER_SMM = 128; // function to add the elements of two arrays __global__ void add(int n, float *x, float *y) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n; i+=stride) y[i] = x[i] + y[i]; } int main(void) { int N = 1 << 20; // 1M elements. float *x, *y; // Allocate Unified Memory - accessible from both CPU and GPU. hipMallocManaged(&x, N*sizeof(float)); hipMallocManaged(&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; } // Run kernel on 1M elements on the GPU. const int nBlocks = ( N + N_SP_PER_SMM - 1 ) / N_SP_PER_SMM; hipLaunchKernelGGL(( add), dim3(nBlocks), dim3(N_SP_PER_SMM), 0, 0, N, x, y); // Wait for the GPU. hipDeviceSynchronize(); // Check for errors (all values should be 3.0f) 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 hipFree(x); x = NULL; hipFree(y); y = NULL; return 0; }
5245332954bd2384081d861f36c638310b7aab21.cu
#include <iostream> #include <math.h> const int N_SMM = 22; const int N_SP_PER_SMM = 128; // function to add the elements of two arrays __global__ void add(int n, float *x, float *y) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < n; i+=stride) y[i] = x[i] + y[i]; } int main(void) { int N = 1 << 20; // 1M elements. float *x, *y; // Allocate Unified Memory - accessible from both CPU and 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; } // Run kernel on 1M elements on the GPU. const int nBlocks = ( N + N_SP_PER_SMM - 1 ) / N_SP_PER_SMM; add<<<nBlocks, N_SP_PER_SMM>>>(N, x, y); // Wait for the GPU. cudaDeviceSynchronize(); // Check for errors (all values should be 3.0f) 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); x = NULL; cudaFree(y); y = NULL; return 0; }
a7017a7b799ced55344cd3d0d34cfc9e0bd19f81.hip
// !!! This is a file automatically generated by hipify!!! #include <hip/hip_runtime.h> #include <stdio.h> #include <xmalloc.cuh> #include <sys/time.h> #include <stdint.h> #include <getopt.h> #include <errno.h> #include <util.h> #define DEBUG 0 ////////////////////////////// #define INITRANDMULT 0x015A4E35 #define INITRANDINCREMENT 997 #define RANDMULT 214013 #define RANDINCREMENT 2531011 #define TESTRAND 100 #define MAXBLOCKSIZE 512 #define EDGEBATCHSIZE 134217728 #define ACTIONBATCHSIZE 16777216 // Errors ////////////////////////////// typedef enum { NO_ERROR, DELETIONS_OVERRAN_INSERTIONS } graphError_t; const char * graphErrorString[] = { "NO ERROR", "DELETIONS OVERRAN INSERTIONS - RARE RANDOM ERROR, RUN IT AGAIN." }; // Device Function Prototypes ////////////////////////////// __device__ uint32_t cudaRand(uint32_t * randVal); __global__ void cudaRMATEdges(uint32_t * randVals, uint32_t SCALE, uint32_t edgesPerThread, uint32_t numthreads, float pA, float pB, float pC, float pD, uint32_t * edgeArray); __global__ void cudaGenerateActions(uint32_t * randVals, uint32_t edges, uint32_t actions, uint32_t numthreads, float pDelete, uint32_t * edgeArray, uint32_t * generatedEdges, int32_t * actionsEdgeArray, graphError_t * error); #if(DEBUG) __global__ void cudaDebugRand(uint32_t * randOut, uint32_t * randVals); __global__ void cudaDebugEdgeList(uint32_t vertices, uint32_t * edgeList, uint32_t size); #endif // Host Functions Prototypes ///////////////////////////// __host__ void hostParseArgs(int argc, char** argv); __host__ void hostInitCudaRand(); __host__ void hostRMATandFileIO(); __host__ int hostCompareEdges(const void * a, const void * b); __host__ void hostFreeCudaRand(); #if (DEBUG) __host__ void hostDebugTestRand(); #endif // Global Device Variables ///////////////////////////// uint32_t * d_uip_randvals; uint32_t * d_uip_edgelist; uint32_t * h_uip_edgelist; int32_t * d_ip_actionslist; int32_t * h_ip_actionslist; void * d_vp_cudastinger; void * d_vp_cudavertices; graphError_t * d_gep_error; // Global Host Variables //////////////////////////// uint32_t h_ui_scale = 14; uint32_t h_ui_edgefactor = 16; uint32_t h_ui_actions = 512 * 512 * 10; uint32_t h_ui_threads = 512; uint32_t h_ui_blocks = 512; uint32_t h_ui_vertices = 4096; uint32_t h_ui_edges = 32768; const char * h_s_infile = NULL; const char * h_s_outfile = NULL; const char * h_s_dimacsoutfile = NULL; const char * h_s_stinger_outfile = NULL; const char * h_s_stinger_actionsfile = NULL; int h_i_streaming = 0; // Host Functions ///////////////////////////// __host__ int main(int argc, char** argv) { printf("CUDA CP2 Implementation\n"); hostParseArgs(argc, argv); d_gep_error = (graphError_t *)cudaXmalloc(sizeof(graphError_t)); graphError_t hosterror = NO_ERROR; hipMemcpy(d_gep_error, &hosterror, sizeof(graphError_t), hipMemcpyHostToDevice); if(h_ui_threads % 8 != 0 || h_ui_blocks % 8 != 0) { fprintf(stderr, "ERROR: Blocks and Threads must be multiples of 8\n"); exit(-1); } tic_reset(); hostInitCudaRand(); #if(DEBUG) hostDebugTestRand(); #endif hostRMATandFileIO(); hipMemcpy(&hosterror, d_gep_error, sizeof(graphError_t), hipMemcpyDeviceToHost); hostFreeCudaRand(); hipFree(d_gep_error); hipDeviceSynchronize(); printf("\nfree() %f", tic_sincelast()); printf("\nTotalTime %f\n", tic_total()); if(hipPeekAtLastError() != hipSuccess) printf("**********************************" "\nCUDA ERROR OCCURED :\n\t%s\nRESULTS MAY NOT BE VALID\n" "**********************************\n", hipGetErrorString(hipGetLastError())); else if(hosterror != NO_ERROR) printf("************************" "\nGRAPH ERROR OCCURED:" "\n%d - %s" "\n************************\n", hosterror, graphErrorString[hosterror]); else printf("NO ERRORS\n"); return 0; } __host__ void hostParseArgs(int argc, char** argv) { static struct option long_options[] = { {"scale", required_argument, 0, 's'}, {"edgefactor", required_argument, 0, 'e'}, {"actions", required_argument, 0, 'a'}, {"help", no_argument, 0, 'h'}, {"blocks", required_argument, 0, 'b'}, {"threads", required_argument, 0, 't'}, {"outfile", required_argument, 0, 'o'}, {"dimacsoutfile", required_argument, 0, 'd'}, {"STINGERoutputfile", required_argument, 0, 'S'}, {"STINGERactionsfile", required_argument, 0, 'A'}, {"CUDADevice", required_argument, 0, 'c'}, {0, 0, 0, 0} }; int32_t intout; while(1) { int option_index = 0; int c = getopt_long(argc, argv, "s:e:a:h?b:t:o:d:S:A:c:", long_options, &option_index); extern char * optarg; extern int optind, opterr, optopt; if(-1 == c) break; switch(c) { default: printf("Unrecognized option: %c\n\n", c); case '?': case 'h': printf("\nUsage" "\n=====" "\n\t-s --scale=SCALE" "\n\t-e --edgefact=EDGEFACT" "\n\t-a --actions=NUMBEROFACTIONS" "\n\t-o --outfile=OUTPUTEDGELISTFILE" "\n\t-d --dimacsoutfile=DIMACSFORMATOUTPUTFILE" "\n\t-S --STINGERoutputfile=STINGEROUTPUTFILE" "\n\t-A --STINGERactionsfile=STINGERACTIONSFILE" "\n\n\tTUNING" "\n\t-b --blocks=BLOCKS" "\n\t-t --threads=THREADS" "\n\t-d --CUDADevice=DEVICENUMBER - if not specified, default is used" "\n\nEdge list files are binary files containing uint32 scale, edgefactor, and" " edges as ordered pairs of uint32\n"); exit(0); break; case 's': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - Scale = %s\n", optarg); exit(-1); } h_ui_scale = intout; break; case 'e': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - Edgefactor = %s\n", optarg); exit(-1); } h_ui_edgefactor = intout; break; case 'a': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - Actions = %s\n", optarg); exit(-1); } h_ui_actions = intout; break; case 'b': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - BLOCKS = %s\n", optarg); exit(-1); } h_ui_blocks = intout; break; case 't': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - THREADS = %s\n", optarg); exit(-1); } h_ui_threads = intout; break; case 'c': errno =0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - CUDA Device = %s\n", optarg); exit(-1); } hipSetDevice(intout); break; case 'i': if(optarg != NULL) h_s_infile = optarg; break; case 'o': if(optarg != NULL) h_s_outfile = optarg; break; case 'd': if(optarg != NULL) h_s_dimacsoutfile = optarg; break; case 'S': if(optarg != NULL) h_s_stinger_outfile = optarg; break; case 'A': if(optarg != NULL) h_s_stinger_actionsfile = optarg; break; case 'p': h_i_streaming = 1; break; } } h_ui_vertices = (1L << h_ui_scale); h_ui_edges = h_ui_vertices * h_ui_edgefactor; if(h_s_infile == NULL) { printf("<BLOCKS, THREADS> <%u, %u>\n", h_ui_blocks, h_ui_threads); printf("\n\tScale %d\n\tEdgefactor %d\n\tActions %d\n\t<V,E> <%d,%d>\n", h_ui_scale, h_ui_edgefactor, h_ui_actions, h_ui_vertices, h_ui_edges); } } __host__ void hostInitCudaRand() { uint32_t totalThreads = h_ui_blocks * h_ui_threads; uint32_t * hostRandVals = (uint32_t *)xmalloc(totalThreads * sizeof(uint32_t)); d_uip_randvals = (uint32_t *)cudaXmalloc(totalThreads * sizeof(uint32_t)); struct timeval tv; gettimeofday(&tv, NULL); hostRandVals[0] = tv.tv_sec * INITRANDMULT + INITRANDINCREMENT; uint32_t i; for(i = 1; i < totalThreads; ++i) { hostRandVals[i] = hostRandVals[i-1] * INITRANDMULT + INITRANDINCREMENT; } hipMemcpy(d_uip_randvals, hostRandVals, totalThreads * sizeof(uint32_t), hipMemcpyHostToDevice); free(hostRandVals); hipDeviceSynchronize(); printf("\nhostInitCudaRand() %f", tic_sincelast()); } __host__ void hostRMATandFileIO() { if(h_ui_edges % (h_ui_blocks * h_ui_threads) != 0) { printf("ERROR: Edges must divide evenly by blocks * threads.\n"); exit(-1); }; d_uip_edgelist = (uint32_t *)cudaXmalloc(EDGEBATCHSIZE * 4 * sizeof(uint32_t)); h_uip_edgelist = (uint32_t *)xmalloc(h_ui_edges * 4 * sizeof(uint32_t)); d_ip_actionslist = (int32_t *)cudaXmalloc(ACTIONBATCHSIZE * 4 * sizeof(int32_t)); uint32_t * tempactions = (uint32_t *)cudaXmalloc(ACTIONBATCHSIZE * 4 * sizeof(uint32_t)); h_ip_actionslist = (int32_t *)xmalloc(h_ui_actions * 4 * sizeof(int32_t)); hipDeviceSynchronize(); printf("\nedgeListMalloc %f", tic_sincelast()); if(h_ui_actions % (h_ui_blocks * h_ui_threads) != 0) { printf("ERROR: Actions must divide evenly by blocks * threads.\n"); exit(-1); } uint32_t * edgedest = h_uip_edgelist; int32_t * actiondest = h_ip_actionslist; for(uint64_t j = 0, k = 0; j < h_ui_edges || k < h_ui_actions; j += EDGEBATCHSIZE, k += ACTIONBATCHSIZE) { if(j < h_ui_edges) { uint32_t generate = (h_ui_edges - j > EDGEBATCHSIZE ? EDGEBATCHSIZE : h_ui_edges - j); hipLaunchKernelGGL(( cudaRMATEdges), dim3(h_ui_blocks), dim3(h_ui_threads), 0, 0, d_uip_randvals, h_ui_scale, generate / (h_ui_blocks * h_ui_threads), h_ui_blocks * h_ui_threads, 0.55, 0.1, 0.1, 0.25, d_uip_edgelist); hipMemcpy(edgedest, d_uip_edgelist, generate * 4 * sizeof(uint32_t), hipMemcpyDeviceToHost); edgedest += EDGEBATCHSIZE; } if(k < h_ui_actions) { uint32_t generate = (h_ui_actions - k > ACTIONBATCHSIZE ? ACTIONBATCHSIZE : h_ui_actions - k); hipLaunchKernelGGL(( cudaRMATEdges), dim3(h_ui_blocks), dim3(h_ui_threads), 0, 0, d_uip_randvals, h_ui_scale, generate / (h_ui_blocks * h_ui_threads), h_ui_blocks * h_ui_threads, 0.55, 0.1, 0.1, 0.25, tempactions); hipLaunchKernelGGL(( cudaGenerateActions), dim3(h_ui_blocks / 8), dim3(h_ui_threads), 0, 0, d_uip_randvals, h_ui_edges, generate, h_ui_blocks * h_ui_threads / 8, 0.0625, d_uip_edgelist, tempactions, d_ip_actionslist, d_gep_error); hipMemcpy(actiondest, d_ip_actionslist, generate * 4 * sizeof(uint32_t), hipMemcpyDeviceToHost); actiondest += ACTIONBATCHSIZE; } } hipFree(d_uip_edgelist); hipFree(d_ip_actionslist); hipFree(tempactions); hipDeviceSynchronize(); printf("\ncudaRMATEdges() %f", tic_sincelast()); if(h_s_outfile != NULL) { FILE * fp; fp = fopen(h_s_outfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } uint32_t written = 0; written += fwrite(&h_ui_scale, sizeof(uint32_t), 1, fp); written += fwrite(&h_ui_edgefactor, sizeof(uint32_t), 1, fp); if(written != 2) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } written = fwrite(h_uip_edgelist, sizeof(uint32_t), 4 * h_ui_edges, fp); if(written != 4 * h_ui_edges) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } fclose(fp); hipDeviceSynchronize(); printf("\nWriteOutputFile() %f", tic_sincelast()); } if(h_s_dimacsoutfile != NULL) { FILE * fp; fp = fopen(h_s_dimacsoutfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } fprintf(fp, "c graph generated by CUDARMAT\n"); fprintf(fp, "p sp %d %d\n", h_ui_vertices, 2 * h_ui_edges); uint32_t j; for(j = 0; j < h_ui_edges * 4; j += 2) fprintf(fp, "a %d %d 1", h_uip_edgelist[j], h_uip_edgelist[j+1]); fclose(fp); hipDeviceSynchronize(); printf("\nWriteDimacsOutputFile() %f", tic_sincelast()); } if(h_s_stinger_outfile != NULL) { FILE * fp; fp = fopen(h_s_stinger_outfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } uint32_t written = 0; int64_t v64 = h_ui_vertices; int64_t e64 = h_ui_edges * 2; int64_t ec = 0x1234ABCD; written += fwrite(&ec, sizeof(int64_t), 1, fp); written += fwrite(&v64, sizeof(int64_t), 1, fp); written += fwrite(&e64, sizeof(int64_t), 1, fp); if(written != 3) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } qsort(h_uip_edgelist, 2 * h_ui_edges, 2 * sizeof(uint32_t), hostCompareEdges); int64_t * off = (int64_t *)xcalloc((h_ui_vertices + 1), sizeof(int64_t)); int64_t * ind = (int64_t *)xmalloc(h_ui_edges * 2 * sizeof(int64_t)); int64_t * weight = (int64_t *)xmalloc(h_ui_edges * 2 * sizeof(int64_t)); off += 1; uint32_t j, k = 0; for(j = 0; j < h_ui_edges * 4; j += 2) { off[h_uip_edgelist[j]]++; ind[k] = h_uip_edgelist[j+1]; weight[k] = 1; k++; } for(j = 1; j < h_ui_vertices; ++j) off[j] += off[j - 1]; off -= 1; written = fwrite(off, sizeof(int64_t), h_ui_vertices + 1, fp); written += fwrite(ind, sizeof(int64_t), h_ui_edges * 2, fp); written += fwrite(weight, sizeof(int64_t), h_ui_edges * 2, fp); if(written != 4 * h_ui_edges + h_ui_vertices + 1) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } free(off); free(ind); free(weight); fclose(fp); hipDeviceSynchronize(); printf("\nWriteSTINGEROutputFile() %f", tic_sincelast()); } if(h_s_stinger_actionsfile != NULL) { FILE * fp; fp = fopen(h_s_stinger_actionsfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } uint32_t written = 0; int64_t actions = h_ui_actions * 2; uint64_t ec = 0x1234ABCD; written += fwrite(&ec, sizeof(int64_t), 1, fp); written += fwrite(&actions, sizeof(int64_t), 1, fp); if(written != 2) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } int64_t * act = (int64_t *)xmalloc(sizeof(int64_t) * h_ui_actions * 4); for(uint64_t j = 0; j < h_ui_actions * 4; j++) { act[j] = h_ip_actionslist[j]; } written = fwrite(act, sizeof(int64_t), h_ui_actions * 4, fp); if(written != 4 * h_ui_actions) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } free(act); fclose(fp); hipDeviceSynchronize(); printf("\nWriteSTINGEROutputFile() %f", tic_sincelast()); } free(h_uip_edgelist); free(h_ip_actionslist); } __host__ int hostCompareEdges(const void * a, const void * b) { uint32_t * e1 = (uint32_t *)a; uint32_t * e2 = (uint32_t *)b; if(e1[0] == e2[0]) return e1[1] - e2[1]; else return e1[0] - e2[0]; } __host__ void hostFreeCudaRand() { hipFree(d_uip_randvals); } // HOST DEBUGGING FUNCTIONS ///////////////////////////// #if(DEBUG) __host__ void hostDebugTestRand() { uint32_t * randvalstest; uint32_t bins[32] = {0}; uint32_t boundaries [] = { 134217728U, 268435456U, 402653184U, 536870912U, 671088640U, 805306368U, 939524096U, 1073741824U, 1207959552U, 1342177280U, 1476395008U, 1610612736U, 1744830464U, 1879048192U, 2013265920U, 2147483648U, 2281701376U, 2415919104U, 2550136832U, 2684354560U, 2818572288U, 2952790016U, 3087007744U, 3221225472U, 3355443200U, 3489660928U, (uint32_t)3623878656U, (uint32_t)3758096384U, (uint32_t)3892314112U, (uint32_t)4026531840U, (uint32_t)4160749568U, (uint32_t)4294967295U }; uint32_t numrands = h_ui_blocks * h_ui_threads * TESTRAND; randvalstest = (uint32_t *)cudaXmalloc(numrands * sizeof(uint32_t)); hipLaunchKernelGGL(( cudaDebugRand) , dim3(h_ui_blocks), dim3(h_ui_threads), 0, 0, randvalstest, d_uip_randvals); uint32_t * results = (uint32_t *) xmalloc(numrands * sizeof(uint32_t)); hipMemcpy(results, randvalstest, numrands * sizeof(uint32_t), hipMemcpyDeviceToHost); int i,j; //int duplicates = 0; for(i = 0; i < numrands; ++i) { //printf("%u\n", results[i]); for(j = 0; j < 32; ++j) { if(results[i] < boundaries[j]) { bins[j]++; break; } } //for(j = i+1; j < numrands; ++j) { // if(results[i] == results[j]) // duplicates++; //} } free(results); printf("\n\n***BEGIN BINS***\n\n"); for(i = 0; i < 32; ++i) { printf("%u\n", bins[i]); } //printf("\n***DUPLICATES %d***\n", duplicates); hipFree(randvalstest); } #endif // Device Functions ////////////////////////////// __device__ uint32_t cudaRand(uint32_t * randVal) { (*randVal) = ((*randVal) * RANDMULT + RANDINCREMENT); return *randVal; } __global__ void cudaRMATEdges(uint32_t * randVals, uint32_t SCALE, uint32_t edgesPerThread, uint32_t numthreads, float pA, float pB, float pC, float pD, uint32_t * edgeArray) { __shared__ uint32_t aboutToWrite[MAXBLOCKSIZE]; uint32_t thread_id = (blockIdx.x * blockDim.x + threadIdx.x); int swap = thread_id % 2 == 0 ? 1 : -1; uint32_t myRand = randVals[thread_id]; float A, B, C, D; uint32_t iteration; uint32_t step = numthreads * 4; uint32_t stop = numthreads * 4 * edgesPerThread; for(iteration = 0; iteration < stop; iteration += step) { A = pA; B = pB; C = pC; D = pD; uint32_t i = 0; uint32_t j = 0; uint32_t curBit = ((uint32_t) 1) << (SCALE - 1); while(1) { const float rand = ((float)cudaRand(&myRand)) / (4294967295.0f); if(rand > A) { if(rand <= A + B) j |= curBit; else if (rand <= A + B + C) i |= curBit; else { j |= curBit; i |= curBit; } } if(1 == curBit) break; A *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); B *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); C *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); D *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); const float norm = 1.0 / (A + B + C + D); A *= norm; B *= norm; C *= norm; D = 1.0 - (A + B + C); curBit >>= 1; } if(swap == 1) { aboutToWrite[threadIdx.x] = i; } else { aboutToWrite[threadIdx.x] = j; } if(swap == 1) { if(aboutToWrite[threadIdx.x + swap] == j) { j ^= 1; } } else { if(aboutToWrite[threadIdx.x + swap] == i) { i ^= 1; } } __syncthreads(); uint32_t index = thread_id + iteration; edgeArray[index] = i; index += numthreads; edgeArray[index] = j; index += numthreads; edgeArray[index + swap] = j; index += numthreads; edgeArray[index + swap] = i; } } __global__ void cudaGenerateActions(uint32_t * randVals, uint32_t edges, uint32_t actions, uint32_t numthreads, float pDelete, uint32_t * edgeArray, uint32_t * generatedEdges, int32_t * actionsEdgeArray, graphError_t * error) { uint32_t thread_id = (blockIdx.x * blockDim.x + threadIdx.x); uint32_t threadIdx4 = threadIdx.x * 4; __shared__ int32_t sharedActions[2048]; uint32_t myRand = randVals[thread_id]; uint32_t original_del = thread_id * 2; uint32_t new_del = original_del; uint32_t new_ins = original_del; uint32_t stop = 4 * actions; uint32_t step = 4 * numthreads; uint32_t index = thread_id; for(; index < stop; index += step) { const float rand = ((float)cudaRand(&myRand)) / (4294967295.0f); if(rand >= pDelete) { sharedActions[threadIdx4] = generatedEdges[new_ins]; sharedActions[threadIdx4 +1] = generatedEdges[new_ins+1]; new_ins += step; } else { if(original_del < edges * 4) { sharedActions[threadIdx4] = -edgeArray[original_del]; sharedActions[threadIdx4 +1] = -edgeArray[original_del+1]; original_del += step; } else if(new_del < new_ins) { sharedActions[threadIdx4] = -generatedEdges[new_del]; sharedActions[threadIdx4 +1] = -generatedEdges[new_del+1]; new_del += step; } else { // Deletes caught up to insertions // if you are near a window, check for flying pigs *error = DELETIONS_OVERRAN_INSERTIONS; } } //reverse edges sharedActions[threadIdx4 + 2] = sharedActions[threadIdx4 + 1]; sharedActions[threadIdx4 + 3] = sharedActions[threadIdx4]; __syncthreads(); actionsEdgeArray[index] = sharedActions[threadIdx.x]; actionsEdgeArray[index + blockDim.x] = sharedActions[threadIdx.x + blockDim.x]; actionsEdgeArray[index + blockDim.x * 2] = sharedActions[threadIdx.x + blockDim.x * 2]; actionsEdgeArray[index + blockDim.x * 3] = sharedActions[threadIdx.x + blockDim.x * 3]; } } // DEVICE DEBUGGING FUNCTIONS ////////////////////////////// __global__ void cudaDebugRand(uint32_t * randOut, uint32_t * randVals) { int i; int thread_id = (blockIdx.x * blockDim.x + threadIdx.x); int thread_offset = thread_id * TESTRAND; for(i = 0; i < TESTRAND; ++i) { randOut[i + thread_offset] = cudaRand(randVals + thread_id); } } __global__ void cudaDebugEdgeList(uint32_t vertices, uint32_t * edgeList, uint32_t size) { uint32_t i = 0; for(i = 0; i < size; ++i) { if(edgeList[i] > vertices) edgeList[i] = 0xFFFFFFFF - i; } }
a7017a7b799ced55344cd3d0d34cfc9e0bd19f81.cu
#include <cuda.h> #include <stdio.h> #include <xmalloc.cuh> #include <sys/time.h> #include <stdint.h> #include <getopt.h> #include <errno.h> #include <util.h> #define DEBUG 0 ////////////////////////////// #define INITRANDMULT 0x015A4E35 #define INITRANDINCREMENT 997 #define RANDMULT 214013 #define RANDINCREMENT 2531011 #define TESTRAND 100 #define MAXBLOCKSIZE 512 #define EDGEBATCHSIZE 134217728 #define ACTIONBATCHSIZE 16777216 // Errors ////////////////////////////// typedef enum { NO_ERROR, DELETIONS_OVERRAN_INSERTIONS } graphError_t; const char * graphErrorString[] = { "NO ERROR", "DELETIONS OVERRAN INSERTIONS - RARE RANDOM ERROR, RUN IT AGAIN." }; // Device Function Prototypes ////////////////////////////// __device__ uint32_t cudaRand(uint32_t * randVal); __global__ void cudaRMATEdges(uint32_t * randVals, uint32_t SCALE, uint32_t edgesPerThread, uint32_t numthreads, float pA, float pB, float pC, float pD, uint32_t * edgeArray); __global__ void cudaGenerateActions(uint32_t * randVals, uint32_t edges, uint32_t actions, uint32_t numthreads, float pDelete, uint32_t * edgeArray, uint32_t * generatedEdges, int32_t * actionsEdgeArray, graphError_t * error); #if(DEBUG) __global__ void cudaDebugRand(uint32_t * randOut, uint32_t * randVals); __global__ void cudaDebugEdgeList(uint32_t vertices, uint32_t * edgeList, uint32_t size); #endif // Host Functions Prototypes ///////////////////////////// __host__ void hostParseArgs(int argc, char** argv); __host__ void hostInitCudaRand(); __host__ void hostRMATandFileIO(); __host__ int hostCompareEdges(const void * a, const void * b); __host__ void hostFreeCudaRand(); #if (DEBUG) __host__ void hostDebugTestRand(); #endif // Global Device Variables ///////////////////////////// uint32_t * d_uip_randvals; uint32_t * d_uip_edgelist; uint32_t * h_uip_edgelist; int32_t * d_ip_actionslist; int32_t * h_ip_actionslist; void * d_vp_cudastinger; void * d_vp_cudavertices; graphError_t * d_gep_error; // Global Host Variables //////////////////////////// uint32_t h_ui_scale = 14; uint32_t h_ui_edgefactor = 16; uint32_t h_ui_actions = 512 * 512 * 10; uint32_t h_ui_threads = 512; uint32_t h_ui_blocks = 512; uint32_t h_ui_vertices = 4096; uint32_t h_ui_edges = 32768; const char * h_s_infile = NULL; const char * h_s_outfile = NULL; const char * h_s_dimacsoutfile = NULL; const char * h_s_stinger_outfile = NULL; const char * h_s_stinger_actionsfile = NULL; int h_i_streaming = 0; // Host Functions ///////////////////////////// __host__ int main(int argc, char** argv) { printf("CUDA CP2 Implementation\n"); hostParseArgs(argc, argv); d_gep_error = (graphError_t *)cudaXmalloc(sizeof(graphError_t)); graphError_t hosterror = NO_ERROR; cudaMemcpy(d_gep_error, &hosterror, sizeof(graphError_t), cudaMemcpyHostToDevice); if(h_ui_threads % 8 != 0 || h_ui_blocks % 8 != 0) { fprintf(stderr, "ERROR: Blocks and Threads must be multiples of 8\n"); exit(-1); } tic_reset(); hostInitCudaRand(); #if(DEBUG) hostDebugTestRand(); #endif hostRMATandFileIO(); cudaMemcpy(&hosterror, d_gep_error, sizeof(graphError_t), cudaMemcpyDeviceToHost); hostFreeCudaRand(); cudaFree(d_gep_error); cudaThreadSynchronize(); printf("\nfree() %f", tic_sincelast()); printf("\nTotalTime %f\n", tic_total()); if(cudaPeekAtLastError() != cudaSuccess) printf("**********************************" "\nCUDA ERROR OCCURED :\n\t%s\nRESULTS MAY NOT BE VALID\n" "**********************************\n", cudaGetErrorString(cudaGetLastError())); else if(hosterror != NO_ERROR) printf("************************" "\nGRAPH ERROR OCCURED:" "\n%d - %s" "\n************************\n", hosterror, graphErrorString[hosterror]); else printf("NO ERRORS\n"); return 0; } __host__ void hostParseArgs(int argc, char** argv) { static struct option long_options[] = { {"scale", required_argument, 0, 's'}, {"edgefactor", required_argument, 0, 'e'}, {"actions", required_argument, 0, 'a'}, {"help", no_argument, 0, 'h'}, {"blocks", required_argument, 0, 'b'}, {"threads", required_argument, 0, 't'}, {"outfile", required_argument, 0, 'o'}, {"dimacsoutfile", required_argument, 0, 'd'}, {"STINGERoutputfile", required_argument, 0, 'S'}, {"STINGERactionsfile", required_argument, 0, 'A'}, {"CUDADevice", required_argument, 0, 'c'}, {0, 0, 0, 0} }; int32_t intout; while(1) { int option_index = 0; int c = getopt_long(argc, argv, "s:e:a:h?b:t:o:d:S:A:c:", long_options, &option_index); extern char * optarg; extern int optind, opterr, optopt; if(-1 == c) break; switch(c) { default: printf("Unrecognized option: %c\n\n", c); case '?': case 'h': printf("\nUsage" "\n=====" "\n\t-s --scale=SCALE" "\n\t-e --edgefact=EDGEFACT" "\n\t-a --actions=NUMBEROFACTIONS" "\n\t-o --outfile=OUTPUTEDGELISTFILE" "\n\t-d --dimacsoutfile=DIMACSFORMATOUTPUTFILE" "\n\t-S --STINGERoutputfile=STINGEROUTPUTFILE" "\n\t-A --STINGERactionsfile=STINGERACTIONSFILE" "\n\n\tTUNING" "\n\t-b --blocks=BLOCKS" "\n\t-t --threads=THREADS" "\n\t-d --CUDADevice=DEVICENUMBER - if not specified, default is used" "\n\nEdge list files are binary files containing uint32 scale, edgefactor, and" " edges as ordered pairs of uint32\n"); exit(0); break; case 's': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - Scale = %s\n", optarg); exit(-1); } h_ui_scale = intout; break; case 'e': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - Edgefactor = %s\n", optarg); exit(-1); } h_ui_edgefactor = intout; break; case 'a': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - Actions = %s\n", optarg); exit(-1); } h_ui_actions = intout; break; case 'b': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - BLOCKS = %s\n", optarg); exit(-1); } h_ui_blocks = intout; break; case 't': errno = 0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - THREADS = %s\n", optarg); exit(-1); } h_ui_threads = intout; break; case 'c': errno =0; intout = strtol(optarg, NULL, 10); if(errno || intout < 0) { printf("Error - CUDA Device = %s\n", optarg); exit(-1); } cudaSetDevice(intout); break; case 'i': if(optarg != NULL) h_s_infile = optarg; break; case 'o': if(optarg != NULL) h_s_outfile = optarg; break; case 'd': if(optarg != NULL) h_s_dimacsoutfile = optarg; break; case 'S': if(optarg != NULL) h_s_stinger_outfile = optarg; break; case 'A': if(optarg != NULL) h_s_stinger_actionsfile = optarg; break; case 'p': h_i_streaming = 1; break; } } h_ui_vertices = (1L << h_ui_scale); h_ui_edges = h_ui_vertices * h_ui_edgefactor; if(h_s_infile == NULL) { printf("<BLOCKS, THREADS> <%u, %u>\n", h_ui_blocks, h_ui_threads); printf("\n\tScale %d\n\tEdgefactor %d\n\tActions %d\n\t<V,E> <%d,%d>\n", h_ui_scale, h_ui_edgefactor, h_ui_actions, h_ui_vertices, h_ui_edges); } } __host__ void hostInitCudaRand() { uint32_t totalThreads = h_ui_blocks * h_ui_threads; uint32_t * hostRandVals = (uint32_t *)xmalloc(totalThreads * sizeof(uint32_t)); d_uip_randvals = (uint32_t *)cudaXmalloc(totalThreads * sizeof(uint32_t)); struct timeval tv; gettimeofday(&tv, NULL); hostRandVals[0] = tv.tv_sec * INITRANDMULT + INITRANDINCREMENT; uint32_t i; for(i = 1; i < totalThreads; ++i) { hostRandVals[i] = hostRandVals[i-1] * INITRANDMULT + INITRANDINCREMENT; } cudaMemcpy(d_uip_randvals, hostRandVals, totalThreads * sizeof(uint32_t), cudaMemcpyHostToDevice); free(hostRandVals); cudaThreadSynchronize(); printf("\nhostInitCudaRand() %f", tic_sincelast()); } __host__ void hostRMATandFileIO() { if(h_ui_edges % (h_ui_blocks * h_ui_threads) != 0) { printf("ERROR: Edges must divide evenly by blocks * threads.\n"); exit(-1); }; d_uip_edgelist = (uint32_t *)cudaXmalloc(EDGEBATCHSIZE * 4 * sizeof(uint32_t)); h_uip_edgelist = (uint32_t *)xmalloc(h_ui_edges * 4 * sizeof(uint32_t)); d_ip_actionslist = (int32_t *)cudaXmalloc(ACTIONBATCHSIZE * 4 * sizeof(int32_t)); uint32_t * tempactions = (uint32_t *)cudaXmalloc(ACTIONBATCHSIZE * 4 * sizeof(uint32_t)); h_ip_actionslist = (int32_t *)xmalloc(h_ui_actions * 4 * sizeof(int32_t)); cudaThreadSynchronize(); printf("\nedgeListMalloc %f", tic_sincelast()); if(h_ui_actions % (h_ui_blocks * h_ui_threads) != 0) { printf("ERROR: Actions must divide evenly by blocks * threads.\n"); exit(-1); } uint32_t * edgedest = h_uip_edgelist; int32_t * actiondest = h_ip_actionslist; for(uint64_t j = 0, k = 0; j < h_ui_edges || k < h_ui_actions; j += EDGEBATCHSIZE, k += ACTIONBATCHSIZE) { if(j < h_ui_edges) { uint32_t generate = (h_ui_edges - j > EDGEBATCHSIZE ? EDGEBATCHSIZE : h_ui_edges - j); cudaRMATEdges<<<h_ui_blocks, h_ui_threads>>>(d_uip_randvals, h_ui_scale, generate / (h_ui_blocks * h_ui_threads), h_ui_blocks * h_ui_threads, 0.55, 0.1, 0.1, 0.25, d_uip_edgelist); cudaMemcpy(edgedest, d_uip_edgelist, generate * 4 * sizeof(uint32_t), cudaMemcpyDeviceToHost); edgedest += EDGEBATCHSIZE; } if(k < h_ui_actions) { uint32_t generate = (h_ui_actions - k > ACTIONBATCHSIZE ? ACTIONBATCHSIZE : h_ui_actions - k); cudaRMATEdges<<<h_ui_blocks, h_ui_threads>>>(d_uip_randvals, h_ui_scale, generate / (h_ui_blocks * h_ui_threads), h_ui_blocks * h_ui_threads, 0.55, 0.1, 0.1, 0.25, tempactions); cudaGenerateActions<<<h_ui_blocks / 8, h_ui_threads>>>(d_uip_randvals, h_ui_edges, generate, h_ui_blocks * h_ui_threads / 8, 0.0625, d_uip_edgelist, tempactions, d_ip_actionslist, d_gep_error); cudaMemcpy(actiondest, d_ip_actionslist, generate * 4 * sizeof(uint32_t), cudaMemcpyDeviceToHost); actiondest += ACTIONBATCHSIZE; } } cudaFree(d_uip_edgelist); cudaFree(d_ip_actionslist); cudaFree(tempactions); cudaThreadSynchronize(); printf("\ncudaRMATEdges() %f", tic_sincelast()); if(h_s_outfile != NULL) { FILE * fp; fp = fopen(h_s_outfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } uint32_t written = 0; written += fwrite(&h_ui_scale, sizeof(uint32_t), 1, fp); written += fwrite(&h_ui_edgefactor, sizeof(uint32_t), 1, fp); if(written != 2) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } written = fwrite(h_uip_edgelist, sizeof(uint32_t), 4 * h_ui_edges, fp); if(written != 4 * h_ui_edges) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } fclose(fp); cudaThreadSynchronize(); printf("\nWriteOutputFile() %f", tic_sincelast()); } if(h_s_dimacsoutfile != NULL) { FILE * fp; fp = fopen(h_s_dimacsoutfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } fprintf(fp, "c graph generated by CUDARMAT\n"); fprintf(fp, "p sp %d %d\n", h_ui_vertices, 2 * h_ui_edges); uint32_t j; for(j = 0; j < h_ui_edges * 4; j += 2) fprintf(fp, "a %d %d 1", h_uip_edgelist[j], h_uip_edgelist[j+1]); fclose(fp); cudaThreadSynchronize(); printf("\nWriteDimacsOutputFile() %f", tic_sincelast()); } if(h_s_stinger_outfile != NULL) { FILE * fp; fp = fopen(h_s_stinger_outfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } uint32_t written = 0; int64_t v64 = h_ui_vertices; int64_t e64 = h_ui_edges * 2; int64_t ec = 0x1234ABCD; written += fwrite(&ec, sizeof(int64_t), 1, fp); written += fwrite(&v64, sizeof(int64_t), 1, fp); written += fwrite(&e64, sizeof(int64_t), 1, fp); if(written != 3) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } qsort(h_uip_edgelist, 2 * h_ui_edges, 2 * sizeof(uint32_t), hostCompareEdges); int64_t * off = (int64_t *)xcalloc((h_ui_vertices + 1), sizeof(int64_t)); int64_t * ind = (int64_t *)xmalloc(h_ui_edges * 2 * sizeof(int64_t)); int64_t * weight = (int64_t *)xmalloc(h_ui_edges * 2 * sizeof(int64_t)); off += 1; uint32_t j, k = 0; for(j = 0; j < h_ui_edges * 4; j += 2) { off[h_uip_edgelist[j]]++; ind[k] = h_uip_edgelist[j+1]; weight[k] = 1; k++; } for(j = 1; j < h_ui_vertices; ++j) off[j] += off[j - 1]; off -= 1; written = fwrite(off, sizeof(int64_t), h_ui_vertices + 1, fp); written += fwrite(ind, sizeof(int64_t), h_ui_edges * 2, fp); written += fwrite(weight, sizeof(int64_t), h_ui_edges * 2, fp); if(written != 4 * h_ui_edges + h_ui_vertices + 1) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } free(off); free(ind); free(weight); fclose(fp); cudaThreadSynchronize(); printf("\nWriteSTINGEROutputFile() %f", tic_sincelast()); } if(h_s_stinger_actionsfile != NULL) { FILE * fp; fp = fopen(h_s_stinger_actionsfile, "w+"); if(fp == NULL) { fprintf(stderr, "\nERROR: Could not open output file.\n"); exit(-1); } uint32_t written = 0; int64_t actions = h_ui_actions * 2; uint64_t ec = 0x1234ABCD; written += fwrite(&ec, sizeof(int64_t), 1, fp); written += fwrite(&actions, sizeof(int64_t), 1, fp); if(written != 2) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } int64_t * act = (int64_t *)xmalloc(sizeof(int64_t) * h_ui_actions * 4); for(uint64_t j = 0; j < h_ui_actions * 4; j++) { act[j] = h_ip_actionslist[j]; } written = fwrite(act, sizeof(int64_t), h_ui_actions * 4, fp); if(written != 4 * h_ui_actions) { fprintf(stderr, "\nERROR: Opened output file, but could not write to it.\n"); exit(-1); } free(act); fclose(fp); cudaThreadSynchronize(); printf("\nWriteSTINGEROutputFile() %f", tic_sincelast()); } free(h_uip_edgelist); free(h_ip_actionslist); } __host__ int hostCompareEdges(const void * a, const void * b) { uint32_t * e1 = (uint32_t *)a; uint32_t * e2 = (uint32_t *)b; if(e1[0] == e2[0]) return e1[1] - e2[1]; else return e1[0] - e2[0]; } __host__ void hostFreeCudaRand() { cudaFree(d_uip_randvals); } // HOST DEBUGGING FUNCTIONS ///////////////////////////// #if(DEBUG) __host__ void hostDebugTestRand() { uint32_t * randvalstest; uint32_t bins[32] = {0}; uint32_t boundaries [] = { 134217728U, 268435456U, 402653184U, 536870912U, 671088640U, 805306368U, 939524096U, 1073741824U, 1207959552U, 1342177280U, 1476395008U, 1610612736U, 1744830464U, 1879048192U, 2013265920U, 2147483648U, 2281701376U, 2415919104U, 2550136832U, 2684354560U, 2818572288U, 2952790016U, 3087007744U, 3221225472U, 3355443200U, 3489660928U, (uint32_t)3623878656U, (uint32_t)3758096384U, (uint32_t)3892314112U, (uint32_t)4026531840U, (uint32_t)4160749568U, (uint32_t)4294967295U }; uint32_t numrands = h_ui_blocks * h_ui_threads * TESTRAND; randvalstest = (uint32_t *)cudaXmalloc(numrands * sizeof(uint32_t)); cudaDebugRand <<<h_ui_blocks, h_ui_threads>>>(randvalstest, d_uip_randvals); uint32_t * results = (uint32_t *) xmalloc(numrands * sizeof(uint32_t)); cudaMemcpy(results, randvalstest, numrands * sizeof(uint32_t), cudaMemcpyDeviceToHost); int i,j; //int duplicates = 0; for(i = 0; i < numrands; ++i) { //printf("%u\n", results[i]); for(j = 0; j < 32; ++j) { if(results[i] < boundaries[j]) { bins[j]++; break; } } //for(j = i+1; j < numrands; ++j) { // if(results[i] == results[j]) // duplicates++; //} } free(results); printf("\n\n***BEGIN BINS***\n\n"); for(i = 0; i < 32; ++i) { printf("%u\n", bins[i]); } //printf("\n***DUPLICATES %d***\n", duplicates); cudaFree(randvalstest); } #endif // Device Functions ////////////////////////////// __device__ uint32_t cudaRand(uint32_t * randVal) { (*randVal) = ((*randVal) * RANDMULT + RANDINCREMENT); return *randVal; } __global__ void cudaRMATEdges(uint32_t * randVals, uint32_t SCALE, uint32_t edgesPerThread, uint32_t numthreads, float pA, float pB, float pC, float pD, uint32_t * edgeArray) { __shared__ uint32_t aboutToWrite[MAXBLOCKSIZE]; uint32_t thread_id = (blockIdx.x * blockDim.x + threadIdx.x); int swap = thread_id % 2 == 0 ? 1 : -1; uint32_t myRand = randVals[thread_id]; float A, B, C, D; uint32_t iteration; uint32_t step = numthreads * 4; uint32_t stop = numthreads * 4 * edgesPerThread; for(iteration = 0; iteration < stop; iteration += step) { A = pA; B = pB; C = pC; D = pD; uint32_t i = 0; uint32_t j = 0; uint32_t curBit = ((uint32_t) 1) << (SCALE - 1); while(1) { const float rand = ((float)cudaRand(&myRand)) / (4294967295.0f); if(rand > A) { if(rand <= A + B) j |= curBit; else if (rand <= A + B + C) i |= curBit; else { j |= curBit; i |= curBit; } } if(1 == curBit) break; A *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); B *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); C *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); D *= (0.95 + (((float)cudaRand(&myRand)) / (42949672950.0f))); const float norm = 1.0 / (A + B + C + D); A *= norm; B *= norm; C *= norm; D = 1.0 - (A + B + C); curBit >>= 1; } if(swap == 1) { aboutToWrite[threadIdx.x] = i; } else { aboutToWrite[threadIdx.x] = j; } if(swap == 1) { if(aboutToWrite[threadIdx.x + swap] == j) { j ^= 1; } } else { if(aboutToWrite[threadIdx.x + swap] == i) { i ^= 1; } } __syncthreads(); uint32_t index = thread_id + iteration; edgeArray[index] = i; index += numthreads; edgeArray[index] = j; index += numthreads; edgeArray[index + swap] = j; index += numthreads; edgeArray[index + swap] = i; } } __global__ void cudaGenerateActions(uint32_t * randVals, uint32_t edges, uint32_t actions, uint32_t numthreads, float pDelete, uint32_t * edgeArray, uint32_t * generatedEdges, int32_t * actionsEdgeArray, graphError_t * error) { uint32_t thread_id = (blockIdx.x * blockDim.x + threadIdx.x); uint32_t threadIdx4 = threadIdx.x * 4; __shared__ int32_t sharedActions[2048]; uint32_t myRand = randVals[thread_id]; uint32_t original_del = thread_id * 2; uint32_t new_del = original_del; uint32_t new_ins = original_del; uint32_t stop = 4 * actions; uint32_t step = 4 * numthreads; uint32_t index = thread_id; for(; index < stop; index += step) { const float rand = ((float)cudaRand(&myRand)) / (4294967295.0f); if(rand >= pDelete) { sharedActions[threadIdx4] = generatedEdges[new_ins]; sharedActions[threadIdx4 +1] = generatedEdges[new_ins+1]; new_ins += step; } else { if(original_del < edges * 4) { sharedActions[threadIdx4] = -edgeArray[original_del]; sharedActions[threadIdx4 +1] = -edgeArray[original_del+1]; original_del += step; } else if(new_del < new_ins) { sharedActions[threadIdx4] = -generatedEdges[new_del]; sharedActions[threadIdx4 +1] = -generatedEdges[new_del+1]; new_del += step; } else { // Deletes caught up to insertions // if you are near a window, check for flying pigs *error = DELETIONS_OVERRAN_INSERTIONS; } } //reverse edges sharedActions[threadIdx4 + 2] = sharedActions[threadIdx4 + 1]; sharedActions[threadIdx4 + 3] = sharedActions[threadIdx4]; __syncthreads(); actionsEdgeArray[index] = sharedActions[threadIdx.x]; actionsEdgeArray[index + blockDim.x] = sharedActions[threadIdx.x + blockDim.x]; actionsEdgeArray[index + blockDim.x * 2] = sharedActions[threadIdx.x + blockDim.x * 2]; actionsEdgeArray[index + blockDim.x * 3] = sharedActions[threadIdx.x + blockDim.x * 3]; } } // DEVICE DEBUGGING FUNCTIONS ////////////////////////////// __global__ void cudaDebugRand(uint32_t * randOut, uint32_t * randVals) { int i; int thread_id = (blockIdx.x * blockDim.x + threadIdx.x); int thread_offset = thread_id * TESTRAND; for(i = 0; i < TESTRAND; ++i) { randOut[i + thread_offset] = cudaRand(randVals + thread_id); } } __global__ void cudaDebugEdgeList(uint32_t vertices, uint32_t * edgeList, uint32_t size) { uint32_t i = 0; for(i = 0; i < size; ++i) { if(edgeList[i] > vertices) edgeList[i] = 0xFFFFFFFF - i; } }
2c8987f55c75f129056bde94db7403d7a476ab52.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright 1993-2012 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ /* Vector addition: C = A + B. * * This sample is a very basic sample that implements element by element * vector addition. It is the same as the sample illustrating Chapter 3 * of the programming guide with some additions like error checking. * */ #include <stdio.h> #include <hip/hip_fp16.h> ///////////////////////////////////////////////////////////////////////////////////////////////////////// __global__ void ADMM_ScaleLLRs(float* LLRs, int N) { const int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < N) { const float mu = 3.0f; LLRs[i] = LLRs[i] / mu; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// __global__ void ADMM_HardDecision( float* OutputFromDecoder, int* HardDecision, int N ) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < N) { HardDecision[i] = floorf(OutputFromDecoder[i] + 0.50f); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// __shared__ int sdata[128*6]; // > 512 __global__ void reduce(int *g_idata, unsigned int n) { // perform first level of reduction, // reading from global memory, writing to shared memory unsigned int tid = threadIdx.x; unsigned int i = blockIdx.x * blockDim.x * 2 + threadIdx.x; unsigned int gridSize = blockDim.x * 2 * gridDim.x; int mySum = 0; // we reduce multiple elements per thread. The number is determined by the // number of active thread blocks (via gridDim). More blocks will result // in a larger gridSize and therefore fewer elements per thread while (i < n) { mySum += g_idata[i]; // ensure we don't read out of bounds if (i + blockDim.x < n) mySum += g_idata[i+blockDim.x]; i += gridSize; } // each thread puts its local sum into shared memory sdata[tid] = mySum; __syncthreads(); // do reduction in shared mem if (blockDim.x >= 1024) { if (tid < 512) { sdata[tid] = mySum = mySum + sdata[tid + 512]; } __syncthreads(); } if (blockDim.x >= 512) { if (tid < 256) { sdata[tid] = mySum = mySum + sdata[tid + 256]; } __syncthreads(); } if (blockDim.x >= 256) { if (tid < 128) { sdata[tid] = mySum = mySum + sdata[tid + 128]; } __syncthreads(); } if (blockDim.x >= 128) { if (tid < 64) { sdata[tid] = mySum = mySum + sdata[tid + 64]; } __syncthreads(); } // avoid bank conflict if (tid < 32) { // now that we are using warp-synchronous programming (below) // we need to declare our shared memory volatile so that the compiler // doesn't reorder stores to it and induce incorrect behavior. volatile int* smem = sdata; if (blockDim.x >= 64) { smem[tid] = mySum = mySum + smem[tid + 32]; } if (blockDim.x >= 32) { smem[tid] = mySum = mySum + smem[tid + 16]; } if (blockDim.x >= 16) { smem[tid] = mySum = mySum + smem[tid + 8]; } if (blockDim.x >= 8) { smem[tid] = mySum = mySum + smem[tid + 4]; } if (blockDim.x >= 4) { smem[tid] = mySum = mySum + smem[tid + 2]; } if (blockDim.x >= 2) { smem[tid] = mySum = mySum + smem[tid + 1]; } } // write result for this block to global mem if (tid == 0) g_idata[blockIdx.x] = sdata[0]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2c8987f55c75f129056bde94db7403d7a476ab52.cu
/* * Copyright 1993-2012 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ /* Vector addition: C = A + B. * * This sample is a very basic sample that implements element by element * vector addition. It is the same as the sample illustrating Chapter 3 * of the programming guide with some additions like error checking. * */ #include <stdio.h> #include <cuda_fp16.h> ///////////////////////////////////////////////////////////////////////////////////////////////////////// __global__ void ADMM_ScaleLLRs(float* LLRs, int N) { const int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < N) { const float mu = 3.0f; LLRs[i] = LLRs[i] / mu; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// __global__ void ADMM_HardDecision( float* OutputFromDecoder, int* HardDecision, int N ) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < N) { HardDecision[i] = floorf(OutputFromDecoder[i] + 0.50f); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// __shared__ int sdata[128*6]; // > 512 __global__ void reduce(int *g_idata, unsigned int n) { // perform first level of reduction, // reading from global memory, writing to shared memory unsigned int tid = threadIdx.x; unsigned int i = blockIdx.x * blockDim.x * 2 + threadIdx.x; unsigned int gridSize = blockDim.x * 2 * gridDim.x; int mySum = 0; // we reduce multiple elements per thread. The number is determined by the // number of active thread blocks (via gridDim). More blocks will result // in a larger gridSize and therefore fewer elements per thread while (i < n) { mySum += g_idata[i]; // ensure we don't read out of bounds if (i + blockDim.x < n) mySum += g_idata[i+blockDim.x]; i += gridSize; } // each thread puts its local sum into shared memory sdata[tid] = mySum; __syncthreads(); // do reduction in shared mem if (blockDim.x >= 1024) { if (tid < 512) { sdata[tid] = mySum = mySum + sdata[tid + 512]; } __syncthreads(); } if (blockDim.x >= 512) { if (tid < 256) { sdata[tid] = mySum = mySum + sdata[tid + 256]; } __syncthreads(); } if (blockDim.x >= 256) { if (tid < 128) { sdata[tid] = mySum = mySum + sdata[tid + 128]; } __syncthreads(); } if (blockDim.x >= 128) { if (tid < 64) { sdata[tid] = mySum = mySum + sdata[tid + 64]; } __syncthreads(); } // avoid bank conflict if (tid < 32) { // now that we are using warp-synchronous programming (below) // we need to declare our shared memory volatile so that the compiler // doesn't reorder stores to it and induce incorrect behavior. volatile int* smem = sdata; if (blockDim.x >= 64) { smem[tid] = mySum = mySum + smem[tid + 32]; } if (blockDim.x >= 32) { smem[tid] = mySum = mySum + smem[tid + 16]; } if (blockDim.x >= 16) { smem[tid] = mySum = mySum + smem[tid + 8]; } if (blockDim.x >= 8) { smem[tid] = mySum = mySum + smem[tid + 4]; } if (blockDim.x >= 4) { smem[tid] = mySum = mySum + smem[tid + 2]; } if (blockDim.x >= 2) { smem[tid] = mySum = mySum + smem[tid + 1]; } } // write result for this block to global mem if (tid == 0) g_idata[blockIdx.x] = sdata[0]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
a12a901978c06611b99445bfef59ecf333dd6947.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "orc_common.h" #include "orc_gpu.h" #include <io/utilities/block_utils.cuh> namespace cudf { namespace io { namespace orc { namespace gpu { struct compressed_stream_s { CompressedStreamInfo info; gpu_inflate_input_s ctl; }; // blockDim {128,1,1} extern "C" __global__ void __launch_bounds__(128, 8) gpuParseCompressedStripeData(CompressedStreamInfo *strm_info, int32_t num_streams, uint32_t block_size, uint32_t log2maxcr) { __shared__ compressed_stream_s strm_g[4]; volatile compressed_stream_s * const s = &strm_g[threadIdx.x >> 5]; int strm_id = blockIdx.x * 4 + (threadIdx.x >> 5); int t = threadIdx.x & 0x1f; if (strm_id < num_streams && t < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(CompressedStreamInfo) <= 128 ((uint32_t *)&s->info)[t] = ((const uint32_t *)&strm_info[strm_id])[t]; } __syncthreads(); if (strm_id < num_streams) { // Walk through the compressed blocks const uint8_t *cur = s->info.compressed_data; const uint8_t *end = cur + s->info.compressed_data_size; uint8_t *uncompressed = s->info.uncompressed_data; size_t max_uncompressed_size = 0; uint32_t num_compressed_blocks = 0; uint32_t num_uncompressed_blocks = 0; while (cur + 3 < end) { uint32_t block_len = SHFL0((t == 0) ? cur[0] | (cur[1] << 8) | (cur[2] << 16) : 0); uint32_t is_uncompressed = block_len & 1; uint32_t uncompressed_size; gpu_inflate_input_s *init_ctl; block_len >>= 1; cur += 3; if (block_len > block_size || cur + block_len > end) { // Fatal num_compressed_blocks = 0; max_uncompressed_size = 0; break; } // TBD: For some codecs like snappy, it wouldn't be too difficult to get the actual uncompressed size and avoid waste due to block size alignment // For now, rely on the max compression ratio to limit waste for the most extreme cases (small single-block streams) uncompressed_size = (is_uncompressed) ? block_len : (block_len < (block_size >> log2maxcr)) ? block_len << log2maxcr : block_size; if (is_uncompressed) { if (uncompressed_size <= 32) { // For short blocks, copy the uncompressed data to output init_ctl = 0; if (uncompressed && max_uncompressed_size + uncompressed_size <= s->info.max_uncompressed_size && t < uncompressed_size) { uncompressed[max_uncompressed_size + t] = cur[t]; } } else { init_ctl = s->info.copyctl; init_ctl = (init_ctl && num_uncompressed_blocks < s->info.num_uncompressed_blocks) ? &init_ctl[num_uncompressed_blocks] : 0; num_uncompressed_blocks++; } } else { init_ctl = s->info.decctl; init_ctl = (init_ctl && num_compressed_blocks < s->info.num_compressed_blocks) ? &init_ctl[num_compressed_blocks] : 0; num_compressed_blocks++; } if (!t && init_ctl) { s->ctl.srcDevice = const_cast<uint8_t *>(cur); s->ctl.srcSize = block_len; s->ctl.dstDevice = uncompressed + max_uncompressed_size; s->ctl.dstSize = uncompressed_size; } SYNCWARP(); if (init_ctl && t < sizeof(gpu_inflate_input_s) / sizeof(uint32_t)) { reinterpret_cast<uint32_t *>(init_ctl)[t] = reinterpret_cast<volatile uint32_t *>(&s->ctl)[t]; } cur += block_len; max_uncompressed_size += uncompressed_size; } SYNCWARP(); if (!t) { s->info.num_compressed_blocks = num_compressed_blocks; s->info.num_uncompressed_blocks = num_uncompressed_blocks; s->info.max_uncompressed_size = max_uncompressed_size; } } __syncthreads(); if (strm_id < num_streams && t < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(CompressedStreamInfo) <= 128 ((uint32_t *)&strm_info[strm_id])[t] = ((uint32_t *)&s->info)[t]; } } // blockDim {128,1,1} extern "C" __global__ void __launch_bounds__(128, 8) gpuPostDecompressionReassemble(CompressedStreamInfo *strm_info, int32_t num_streams) { __shared__ compressed_stream_s strm_g[4]; volatile compressed_stream_s * const s = &strm_g[threadIdx.x >> 5]; int strm_id = blockIdx.x * 4 + (threadIdx.x >> 5); int t = threadIdx.x & 0x1f; if (strm_id < num_streams && t < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(CompressedStreamInfo) <= 128 ((uint32_t *)&s->info)[t] = ((const uint32_t *)&strm_info[strm_id])[t]; } __syncthreads(); if (strm_id < num_streams && s->info.num_compressed_blocks + s->info.num_uncompressed_blocks > 0 && s->info.max_uncompressed_size > 0) { // Walk through the compressed blocks const uint8_t *cur = s->info.compressed_data; const uint8_t *end = cur + s->info.compressed_data_size; const gpu_inflate_input_s *dec_in = s->info.decctl; const gpu_inflate_status_s *dec_out = s->info.decstatus; uint8_t *uncompressed_actual = s->info.uncompressed_data; uint8_t *uncompressed_estimated = uncompressed_actual; uint32_t num_compressed_blocks = 0; uint32_t max_compressed_blocks = s->info.num_compressed_blocks; while (cur + 3 < end) { uint32_t block_len = SHFL0((t == 0) ? cur[0] | (cur[1] << 8) | (cur[2] << 16) : 0); uint32_t is_uncompressed = block_len & 1; uint32_t uncompressed_size_est, uncompressed_size_actual; block_len >>= 1; cur += 3; if (cur + block_len > end) { break; } if (is_uncompressed) { uncompressed_size_est = block_len; uncompressed_size_actual = block_len; } else { if (num_compressed_blocks > max_compressed_blocks) { break; } if (SHFL0((t == 0) ? dec_out[num_compressed_blocks].status : 0) != 0) { // Decompression failed, not much point in doing anything else break; } uncompressed_size_est = SHFL0((t == 0) ? *(const uint32_t *)&dec_in[num_compressed_blocks].dstSize : 0); uncompressed_size_actual = SHFL0((t == 0) ? *(const uint32_t *)&dec_out[num_compressed_blocks].bytes_written : 0); } // In practice, this should never happen with a well-behaved writer, as we would expect the uncompressed size to always be equal to // the compression block size except for the last block if (uncompressed_actual < uncompressed_estimated) { // warp-level memmove for (int i = t; i < (int)uncompressed_size_actual; i += 32) { uncompressed_actual[i] = uncompressed_estimated[i]; } } cur += block_len; num_compressed_blocks += 1 - is_uncompressed; uncompressed_estimated += uncompressed_size_est; uncompressed_actual += uncompressed_size_actual; } // Update info with actual uncompressed size if (!t) { size_t total_uncompressed_size = uncompressed_actual - s->info.uncompressed_data; // Set uncompressed size to zero if there were any errors strm_info[strm_id].max_uncompressed_size = (num_compressed_blocks == s->info.num_compressed_blocks) ? total_uncompressed_size : 0; } } } /** * @brief Shared mem state for gpuParseRowGroupIndex * */ struct rowindex_state_s { ColumnDesc chunk; uint32_t rowgroup_start; uint32_t rowgroup_end; int is_compressed; uint32_t row_index_entry[3][CI_PRESENT]; // NOTE: Assumes CI_PRESENT follows CI_DATA and CI_DATA2 CompressedStreamInfo strm_info[2]; RowGroup rowgroups[128]; uint32_t compressed_offset[128][2]; }; #define PB_ROWINDEXENTRY_ID ((1*8) + PB_TYPE_FIXEDLEN) enum row_entry_state_e { NOT_FOUND = 0, GET_LENGTH, SKIP_VARINT, SKIP_FIXEDLEN, STORE_INDEX0, STORE_INDEX1, STORE_INDEX2, }; /** * @brief Decode a single row group index entry * * @param[in,out] s row group index state * @param[in] start start position in byte stream * @param[in] end end of byte stream * @return bytes consumed * **/ static uint32_t __device__ ProtobufParseRowIndexEntry(rowindex_state_s *s, const uint8_t *start, const uint8_t *end) { const uint8_t *cur = start; row_entry_state_e state = NOT_FOUND; uint32_t length = 0, strm_idx_id = s->chunk.skip_count >> 8, idx_id = 1, ci_id = CI_PRESENT, pos_end = 0; while (cur < end) { uint32_t v = 0; for (uint32_t l = 0; l <= 28; l += 7) { uint32_t c = (cur < end) ? *cur++ : 0; v |= (c & 0x7f) << l; if (c <= 0x7f) break; } switch (state) { case NOT_FOUND: if (v == PB_ROWINDEXENTRY_ID) { state = GET_LENGTH; } else { v &= 7; if (v == PB_TYPE_FIXED64) cur += 8; else if (v == PB_TYPE_FIXED32) cur += 4; else if (v == PB_TYPE_VARINT) state = SKIP_VARINT; else if (v == PB_TYPE_FIXEDLEN) state = SKIP_FIXEDLEN; } break; case SKIP_VARINT: state = NOT_FOUND; break; case SKIP_FIXEDLEN: cur += v; state = NOT_FOUND; break; case GET_LENGTH: if (length == 0) { length = (uint32_t)(cur + v - start); state = NOT_FOUND; // Scan for positions (same field id & low-level type as RowIndexEntry entry) } else { pos_end = min((uint32_t)(cur + v - start), length); state = STORE_INDEX0; } break; case STORE_INDEX0: ci_id = (idx_id == (strm_idx_id & 0xff)) ? CI_DATA : (idx_id == ((strm_idx_id >> 8) & 0xff)) ? CI_DATA2 : CI_PRESENT; idx_id++; if (s->is_compressed) { if (ci_id < CI_PRESENT) s->row_index_entry[0][ci_id] = v; if (cur >= start + pos_end) return length; state = STORE_INDEX1; break; } else { if (ci_id < CI_PRESENT) s->row_index_entry[0][ci_id] = 0; // Fall through to STORE_INDEX1 for uncompressed (always block0) } case STORE_INDEX1: if (ci_id < CI_PRESENT) s->row_index_entry[1][ci_id] = v; if (cur >= start + pos_end) return length; state = (ci_id == CI_DATA && s->chunk.encoding_kind != DICTIONARY && s->chunk.encoding_kind != DICTIONARY_V2 && (s->chunk.type_kind == STRING || s->chunk.type_kind == BINARY || s->chunk.type_kind == VARCHAR || s->chunk.type_kind == CHAR || s->chunk.type_kind == DECIMAL || s->chunk.type_kind == FLOAT || s->chunk.type_kind == DOUBLE)) ? STORE_INDEX0 : STORE_INDEX2; break; case STORE_INDEX2: if (ci_id < CI_PRESENT) s->row_index_entry[2][ci_id] = v; // Boolean columns have an extra byte to indicate the position of the bit within the byte // TODO: Currently assuming rowIndexStride is a multiple of 8 and ignoring this value if (ci_id == CI_PRESENT || s->chunk.type_kind == BOOLEAN) cur++; if (cur >= start + pos_end) return length; state = STORE_INDEX0; break; } } return (uint32_t)(end - start); } /** * @brief Decode row group index entries * * @param[in,out] s row group index state * @param[in] num_rowgroups Number of index entries to read * **/ static __device__ void gpuReadRowGroupIndexEntries(rowindex_state_s *s, int num_rowgroups) { const uint8_t *index_data = s->chunk.streams[CI_INDEX]; int index_data_len = s->chunk.strm_len[CI_INDEX]; for (int i = 0; i < num_rowgroups; i++) { s->row_index_entry[0][0] = 0; s->row_index_entry[0][1] = 0; s->row_index_entry[1][0] = 0; s->row_index_entry[1][1] = 0; s->row_index_entry[2][0] = 0; s->row_index_entry[2][1] = 0; if (index_data_len > 0) { int len = ProtobufParseRowIndexEntry(s, index_data, index_data + index_data_len); index_data += len; index_data_len = max(index_data_len - len, 0); for (int j = 0; j < 2; j++) { s->rowgroups[i].strm_offset[j] = s->row_index_entry[1][j]; s->rowgroups[i].run_pos[j] = s->row_index_entry[2][j]; s->compressed_offset[i][j] = s->row_index_entry[0][j]; } } } s->chunk.streams[CI_INDEX] = index_data; s->chunk.strm_len[CI_INDEX] = index_data_len; } /** * @brief Translate block+offset compressed position into an uncompressed offset * * @param[in,out] s row group index state * @param[in] ci_id index to convert (CI_DATA or CI_DATA2) * @param[in] num_rowgroups Number of index entries * @param[in] t thread id * **/ static __device__ void gpuMapRowIndexToUncompressed(rowindex_state_s *s, int ci_id, int num_rowgroups, int t) { int32_t strm_len = s->chunk.strm_len[ci_id]; if (strm_len > 0) { int32_t compressed_offset = (t < num_rowgroups) ? s->compressed_offset[t][ci_id] : 0; if (compressed_offset > 0) { const uint8_t *start = s->strm_info[ci_id].compressed_data; const uint8_t *cur = start; const uint8_t *end = cur + s->strm_info[ci_id].compressed_data_size; gpu_inflate_status_s *decstatus = s->strm_info[ci_id].decstatus; uint32_t uncomp_offset = 0; for (;;) { uint32_t block_len, is_uncompressed; if (cur + 3 > end || cur + 3 >= start + compressed_offset) { break; } block_len = cur[0] | (cur[1] << 8) | (cur[2] << 16); cur += 3; is_uncompressed = block_len & 1; block_len >>= 1; cur += block_len; if (cur > end) { break; } if (is_uncompressed) { uncomp_offset += block_len; } else { uncomp_offset += decstatus->bytes_written; decstatus++; } } s->rowgroups[t].strm_offset[ci_id] += uncomp_offset; } } } /** * @brief Decode index streams * * @param[out] row_groups RowGroup device array [rowgroup][column] * @param[in] strm_info List of compressed streams (or NULL if uncompressed) * @param[in] chunks ColumnDesc device array [stripe][column] * @param[in] num_columns Number of columns * @param[in] num_stripes Number of stripes * @param[in] num_rowgroups Number of row groups * **/ // blockDim {128,1,1} extern "C" __global__ void __launch_bounds__(128, 8) gpuParseRowGroupIndex(RowGroup *row_groups, CompressedStreamInfo *strm_info, ColumnDesc *chunks, uint32_t num_columns, uint32_t num_stripes, uint32_t num_rowgroups, uint32_t rowidx_stride) { __shared__ __align__(16) rowindex_state_s state_g; rowindex_state_s * const s = &state_g; uint32_t chunk_id = blockIdx.y * num_columns + blockIdx.x; int t = threadIdx.x; if (t < sizeof(ColumnDesc) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(ColumnDesc) <= 128x4 ((volatile uint32_t *)&s->chunk)[t] = ((const uint32_t *)&chunks[chunk_id])[t]; } __syncthreads(); if (strm_info) { int strm_len = s->chunk.strm_len[t >> 6]; int strm_id = s->chunk.strm_id[t >> 6]; int t6 = t & 0x3f; if (strm_len > 0 && t6 < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { ((volatile uint32_t *)&s->strm_info[t >> 6])[t6] = ((const uint32_t *)&strm_info[strm_id])[t6]; } } if (t == 0) { uint32_t rowgroups_in_chunk = (rowidx_stride > 0) ? (s->chunk.num_rows + rowidx_stride - 1) / rowidx_stride : 1; s->rowgroup_start = s->chunk.rowgroup_id; s->rowgroup_end = s->rowgroup_start + rowgroups_in_chunk; s->is_compressed = (strm_info != NULL); } __syncthreads(); while (s->rowgroup_start < s->rowgroup_end) { int num_rowgroups = min(s->rowgroup_end - s->rowgroup_start, 128); int rowgroup_size4, t4, t32; s->rowgroups[t].chunk_id = chunk_id; if (t == 0) { gpuReadRowGroupIndexEntries(s, num_rowgroups); } __syncthreads(); if (s->is_compressed) { // Convert the block + blk_offset pair into a raw offset into the decompressed stream if (s->chunk.strm_len[CI_DATA] > 0) { gpuMapRowIndexToUncompressed(s, CI_DATA, num_rowgroups, t); } if (s->chunk.strm_len[CI_DATA2] > 0) { gpuMapRowIndexToUncompressed(s, CI_DATA2, num_rowgroups, t); } __syncthreads(); } rowgroup_size4 = sizeof(RowGroup) / sizeof(uint32_t); t4 = t & 3; t32 = t >> 2; for (int i = t32; i < num_rowgroups; i += 32) { for (int j = t4; j < rowgroup_size4; j += 4) { ((uint32_t *)&row_groups[(s->rowgroup_start + i) * num_columns + blockIdx.x])[j] = ((volatile uint32_t *)&s->rowgroups[i])[j]; } } __syncthreads(); if (t == 0) { s->rowgroup_start += num_rowgroups; } __syncthreads(); } } hipError_t __host__ ParseCompressedStripeData(CompressedStreamInfo *strm_info, int32_t num_streams, uint32_t compression_block_size, uint32_t log2maxcr, hipStream_t stream) { dim3 dim_block(128, 1); dim3 dim_grid((num_streams + 3) >> 2, 1); // 1 stream per warp, 4 warps per block hipLaunchKernelGGL(( gpuParseCompressedStripeData) , dim3(dim_grid), dim3(dim_block), 0, stream , strm_info, num_streams, compression_block_size, log2maxcr); return hipSuccess; } hipError_t __host__ PostDecompressionReassemble(CompressedStreamInfo *strm_info, int32_t num_streams, hipStream_t stream) { dim3 dim_block(128, 1); dim3 dim_grid((num_streams + 3) >> 2, 1); // 1 stream per warp, 4 warps per block hipLaunchKernelGGL(( gpuPostDecompressionReassemble) , dim3(dim_grid), dim3(dim_block), 0, stream , strm_info, num_streams); return hipSuccess; } /** * @brief Launches kernel for constructing rowgroup from index streams * * @param[out] row_groups RowGroup device array [rowgroup][column] * @param[in] strm_info List of compressed streams (or NULL if uncompressed) * @param[in] chunks ColumnDesc device array [stripe][column] * @param[in] num_columns Number of columns * @param[in] num_stripes Number of stripes * @param[in] num_rowgroups Number of row groups * @param[in] stream CUDA stream to use, default 0 * * @return hipSuccess if successful, a CUDA error code otherwise **/ hipError_t __host__ ParseRowGroupIndex(RowGroup *row_groups, CompressedStreamInfo *strm_info, ColumnDesc *chunks, uint32_t num_columns, uint32_t num_stripes, uint32_t num_rowgroups, uint32_t rowidx_stride, hipStream_t stream) { dim3 dim_block(128, 1); dim3 dim_grid(num_columns, num_stripes); // 1 column chunk per block hipLaunchKernelGGL(( gpuParseRowGroupIndex) , dim3(dim_grid), dim3(dim_block), 0, stream , row_groups, strm_info, chunks, num_columns, num_stripes, num_rowgroups, rowidx_stride); return hipSuccess; } } // namespace gpu } // namespace orc } // namespace io } // namespace cudf
a12a901978c06611b99445bfef59ecf333dd6947.cu
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "orc_common.h" #include "orc_gpu.h" #include <io/utilities/block_utils.cuh> namespace cudf { namespace io { namespace orc { namespace gpu { struct compressed_stream_s { CompressedStreamInfo info; gpu_inflate_input_s ctl; }; // blockDim {128,1,1} extern "C" __global__ void __launch_bounds__(128, 8) gpuParseCompressedStripeData(CompressedStreamInfo *strm_info, int32_t num_streams, uint32_t block_size, uint32_t log2maxcr) { __shared__ compressed_stream_s strm_g[4]; volatile compressed_stream_s * const s = &strm_g[threadIdx.x >> 5]; int strm_id = blockIdx.x * 4 + (threadIdx.x >> 5); int t = threadIdx.x & 0x1f; if (strm_id < num_streams && t < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(CompressedStreamInfo) <= 128 ((uint32_t *)&s->info)[t] = ((const uint32_t *)&strm_info[strm_id])[t]; } __syncthreads(); if (strm_id < num_streams) { // Walk through the compressed blocks const uint8_t *cur = s->info.compressed_data; const uint8_t *end = cur + s->info.compressed_data_size; uint8_t *uncompressed = s->info.uncompressed_data; size_t max_uncompressed_size = 0; uint32_t num_compressed_blocks = 0; uint32_t num_uncompressed_blocks = 0; while (cur + 3 < end) { uint32_t block_len = SHFL0((t == 0) ? cur[0] | (cur[1] << 8) | (cur[2] << 16) : 0); uint32_t is_uncompressed = block_len & 1; uint32_t uncompressed_size; gpu_inflate_input_s *init_ctl; block_len >>= 1; cur += 3; if (block_len > block_size || cur + block_len > end) { // Fatal num_compressed_blocks = 0; max_uncompressed_size = 0; break; } // TBD: For some codecs like snappy, it wouldn't be too difficult to get the actual uncompressed size and avoid waste due to block size alignment // For now, rely on the max compression ratio to limit waste for the most extreme cases (small single-block streams) uncompressed_size = (is_uncompressed) ? block_len : (block_len < (block_size >> log2maxcr)) ? block_len << log2maxcr : block_size; if (is_uncompressed) { if (uncompressed_size <= 32) { // For short blocks, copy the uncompressed data to output init_ctl = 0; if (uncompressed && max_uncompressed_size + uncompressed_size <= s->info.max_uncompressed_size && t < uncompressed_size) { uncompressed[max_uncompressed_size + t] = cur[t]; } } else { init_ctl = s->info.copyctl; init_ctl = (init_ctl && num_uncompressed_blocks < s->info.num_uncompressed_blocks) ? &init_ctl[num_uncompressed_blocks] : 0; num_uncompressed_blocks++; } } else { init_ctl = s->info.decctl; init_ctl = (init_ctl && num_compressed_blocks < s->info.num_compressed_blocks) ? &init_ctl[num_compressed_blocks] : 0; num_compressed_blocks++; } if (!t && init_ctl) { s->ctl.srcDevice = const_cast<uint8_t *>(cur); s->ctl.srcSize = block_len; s->ctl.dstDevice = uncompressed + max_uncompressed_size; s->ctl.dstSize = uncompressed_size; } SYNCWARP(); if (init_ctl && t < sizeof(gpu_inflate_input_s) / sizeof(uint32_t)) { reinterpret_cast<uint32_t *>(init_ctl)[t] = reinterpret_cast<volatile uint32_t *>(&s->ctl)[t]; } cur += block_len; max_uncompressed_size += uncompressed_size; } SYNCWARP(); if (!t) { s->info.num_compressed_blocks = num_compressed_blocks; s->info.num_uncompressed_blocks = num_uncompressed_blocks; s->info.max_uncompressed_size = max_uncompressed_size; } } __syncthreads(); if (strm_id < num_streams && t < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(CompressedStreamInfo) <= 128 ((uint32_t *)&strm_info[strm_id])[t] = ((uint32_t *)&s->info)[t]; } } // blockDim {128,1,1} extern "C" __global__ void __launch_bounds__(128, 8) gpuPostDecompressionReassemble(CompressedStreamInfo *strm_info, int32_t num_streams) { __shared__ compressed_stream_s strm_g[4]; volatile compressed_stream_s * const s = &strm_g[threadIdx.x >> 5]; int strm_id = blockIdx.x * 4 + (threadIdx.x >> 5); int t = threadIdx.x & 0x1f; if (strm_id < num_streams && t < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(CompressedStreamInfo) <= 128 ((uint32_t *)&s->info)[t] = ((const uint32_t *)&strm_info[strm_id])[t]; } __syncthreads(); if (strm_id < num_streams && s->info.num_compressed_blocks + s->info.num_uncompressed_blocks > 0 && s->info.max_uncompressed_size > 0) { // Walk through the compressed blocks const uint8_t *cur = s->info.compressed_data; const uint8_t *end = cur + s->info.compressed_data_size; const gpu_inflate_input_s *dec_in = s->info.decctl; const gpu_inflate_status_s *dec_out = s->info.decstatus; uint8_t *uncompressed_actual = s->info.uncompressed_data; uint8_t *uncompressed_estimated = uncompressed_actual; uint32_t num_compressed_blocks = 0; uint32_t max_compressed_blocks = s->info.num_compressed_blocks; while (cur + 3 < end) { uint32_t block_len = SHFL0((t == 0) ? cur[0] | (cur[1] << 8) | (cur[2] << 16) : 0); uint32_t is_uncompressed = block_len & 1; uint32_t uncompressed_size_est, uncompressed_size_actual; block_len >>= 1; cur += 3; if (cur + block_len > end) { break; } if (is_uncompressed) { uncompressed_size_est = block_len; uncompressed_size_actual = block_len; } else { if (num_compressed_blocks > max_compressed_blocks) { break; } if (SHFL0((t == 0) ? dec_out[num_compressed_blocks].status : 0) != 0) { // Decompression failed, not much point in doing anything else break; } uncompressed_size_est = SHFL0((t == 0) ? *(const uint32_t *)&dec_in[num_compressed_blocks].dstSize : 0); uncompressed_size_actual = SHFL0((t == 0) ? *(const uint32_t *)&dec_out[num_compressed_blocks].bytes_written : 0); } // In practice, this should never happen with a well-behaved writer, as we would expect the uncompressed size to always be equal to // the compression block size except for the last block if (uncompressed_actual < uncompressed_estimated) { // warp-level memmove for (int i = t; i < (int)uncompressed_size_actual; i += 32) { uncompressed_actual[i] = uncompressed_estimated[i]; } } cur += block_len; num_compressed_blocks += 1 - is_uncompressed; uncompressed_estimated += uncompressed_size_est; uncompressed_actual += uncompressed_size_actual; } // Update info with actual uncompressed size if (!t) { size_t total_uncompressed_size = uncompressed_actual - s->info.uncompressed_data; // Set uncompressed size to zero if there were any errors strm_info[strm_id].max_uncompressed_size = (num_compressed_blocks == s->info.num_compressed_blocks) ? total_uncompressed_size : 0; } } } /** * @brief Shared mem state for gpuParseRowGroupIndex * */ struct rowindex_state_s { ColumnDesc chunk; uint32_t rowgroup_start; uint32_t rowgroup_end; int is_compressed; uint32_t row_index_entry[3][CI_PRESENT]; // NOTE: Assumes CI_PRESENT follows CI_DATA and CI_DATA2 CompressedStreamInfo strm_info[2]; RowGroup rowgroups[128]; uint32_t compressed_offset[128][2]; }; #define PB_ROWINDEXENTRY_ID ((1*8) + PB_TYPE_FIXEDLEN) enum row_entry_state_e { NOT_FOUND = 0, GET_LENGTH, SKIP_VARINT, SKIP_FIXEDLEN, STORE_INDEX0, STORE_INDEX1, STORE_INDEX2, }; /** * @brief Decode a single row group index entry * * @param[in,out] s row group index state * @param[in] start start position in byte stream * @param[in] end end of byte stream * @return bytes consumed * **/ static uint32_t __device__ ProtobufParseRowIndexEntry(rowindex_state_s *s, const uint8_t *start, const uint8_t *end) { const uint8_t *cur = start; row_entry_state_e state = NOT_FOUND; uint32_t length = 0, strm_idx_id = s->chunk.skip_count >> 8, idx_id = 1, ci_id = CI_PRESENT, pos_end = 0; while (cur < end) { uint32_t v = 0; for (uint32_t l = 0; l <= 28; l += 7) { uint32_t c = (cur < end) ? *cur++ : 0; v |= (c & 0x7f) << l; if (c <= 0x7f) break; } switch (state) { case NOT_FOUND: if (v == PB_ROWINDEXENTRY_ID) { state = GET_LENGTH; } else { v &= 7; if (v == PB_TYPE_FIXED64) cur += 8; else if (v == PB_TYPE_FIXED32) cur += 4; else if (v == PB_TYPE_VARINT) state = SKIP_VARINT; else if (v == PB_TYPE_FIXEDLEN) state = SKIP_FIXEDLEN; } break; case SKIP_VARINT: state = NOT_FOUND; break; case SKIP_FIXEDLEN: cur += v; state = NOT_FOUND; break; case GET_LENGTH: if (length == 0) { length = (uint32_t)(cur + v - start); state = NOT_FOUND; // Scan for positions (same field id & low-level type as RowIndexEntry entry) } else { pos_end = min((uint32_t)(cur + v - start), length); state = STORE_INDEX0; } break; case STORE_INDEX0: ci_id = (idx_id == (strm_idx_id & 0xff)) ? CI_DATA : (idx_id == ((strm_idx_id >> 8) & 0xff)) ? CI_DATA2 : CI_PRESENT; idx_id++; if (s->is_compressed) { if (ci_id < CI_PRESENT) s->row_index_entry[0][ci_id] = v; if (cur >= start + pos_end) return length; state = STORE_INDEX1; break; } else { if (ci_id < CI_PRESENT) s->row_index_entry[0][ci_id] = 0; // Fall through to STORE_INDEX1 for uncompressed (always block0) } case STORE_INDEX1: if (ci_id < CI_PRESENT) s->row_index_entry[1][ci_id] = v; if (cur >= start + pos_end) return length; state = (ci_id == CI_DATA && s->chunk.encoding_kind != DICTIONARY && s->chunk.encoding_kind != DICTIONARY_V2 && (s->chunk.type_kind == STRING || s->chunk.type_kind == BINARY || s->chunk.type_kind == VARCHAR || s->chunk.type_kind == CHAR || s->chunk.type_kind == DECIMAL || s->chunk.type_kind == FLOAT || s->chunk.type_kind == DOUBLE)) ? STORE_INDEX0 : STORE_INDEX2; break; case STORE_INDEX2: if (ci_id < CI_PRESENT) s->row_index_entry[2][ci_id] = v; // Boolean columns have an extra byte to indicate the position of the bit within the byte // TODO: Currently assuming rowIndexStride is a multiple of 8 and ignoring this value if (ci_id == CI_PRESENT || s->chunk.type_kind == BOOLEAN) cur++; if (cur >= start + pos_end) return length; state = STORE_INDEX0; break; } } return (uint32_t)(end - start); } /** * @brief Decode row group index entries * * @param[in,out] s row group index state * @param[in] num_rowgroups Number of index entries to read * **/ static __device__ void gpuReadRowGroupIndexEntries(rowindex_state_s *s, int num_rowgroups) { const uint8_t *index_data = s->chunk.streams[CI_INDEX]; int index_data_len = s->chunk.strm_len[CI_INDEX]; for (int i = 0; i < num_rowgroups; i++) { s->row_index_entry[0][0] = 0; s->row_index_entry[0][1] = 0; s->row_index_entry[1][0] = 0; s->row_index_entry[1][1] = 0; s->row_index_entry[2][0] = 0; s->row_index_entry[2][1] = 0; if (index_data_len > 0) { int len = ProtobufParseRowIndexEntry(s, index_data, index_data + index_data_len); index_data += len; index_data_len = max(index_data_len - len, 0); for (int j = 0; j < 2; j++) { s->rowgroups[i].strm_offset[j] = s->row_index_entry[1][j]; s->rowgroups[i].run_pos[j] = s->row_index_entry[2][j]; s->compressed_offset[i][j] = s->row_index_entry[0][j]; } } } s->chunk.streams[CI_INDEX] = index_data; s->chunk.strm_len[CI_INDEX] = index_data_len; } /** * @brief Translate block+offset compressed position into an uncompressed offset * * @param[in,out] s row group index state * @param[in] ci_id index to convert (CI_DATA or CI_DATA2) * @param[in] num_rowgroups Number of index entries * @param[in] t thread id * **/ static __device__ void gpuMapRowIndexToUncompressed(rowindex_state_s *s, int ci_id, int num_rowgroups, int t) { int32_t strm_len = s->chunk.strm_len[ci_id]; if (strm_len > 0) { int32_t compressed_offset = (t < num_rowgroups) ? s->compressed_offset[t][ci_id] : 0; if (compressed_offset > 0) { const uint8_t *start = s->strm_info[ci_id].compressed_data; const uint8_t *cur = start; const uint8_t *end = cur + s->strm_info[ci_id].compressed_data_size; gpu_inflate_status_s *decstatus = s->strm_info[ci_id].decstatus; uint32_t uncomp_offset = 0; for (;;) { uint32_t block_len, is_uncompressed; if (cur + 3 > end || cur + 3 >= start + compressed_offset) { break; } block_len = cur[0] | (cur[1] << 8) | (cur[2] << 16); cur += 3; is_uncompressed = block_len & 1; block_len >>= 1; cur += block_len; if (cur > end) { break; } if (is_uncompressed) { uncomp_offset += block_len; } else { uncomp_offset += decstatus->bytes_written; decstatus++; } } s->rowgroups[t].strm_offset[ci_id] += uncomp_offset; } } } /** * @brief Decode index streams * * @param[out] row_groups RowGroup device array [rowgroup][column] * @param[in] strm_info List of compressed streams (or NULL if uncompressed) * @param[in] chunks ColumnDesc device array [stripe][column] * @param[in] num_columns Number of columns * @param[in] num_stripes Number of stripes * @param[in] num_rowgroups Number of row groups * **/ // blockDim {128,1,1} extern "C" __global__ void __launch_bounds__(128, 8) gpuParseRowGroupIndex(RowGroup *row_groups, CompressedStreamInfo *strm_info, ColumnDesc *chunks, uint32_t num_columns, uint32_t num_stripes, uint32_t num_rowgroups, uint32_t rowidx_stride) { __shared__ __align__(16) rowindex_state_s state_g; rowindex_state_s * const s = &state_g; uint32_t chunk_id = blockIdx.y * num_columns + blockIdx.x; int t = threadIdx.x; if (t < sizeof(ColumnDesc) / sizeof(uint32_t)) { // NOTE: Assumes that sizeof(ColumnDesc) <= 128x4 ((volatile uint32_t *)&s->chunk)[t] = ((const uint32_t *)&chunks[chunk_id])[t]; } __syncthreads(); if (strm_info) { int strm_len = s->chunk.strm_len[t >> 6]; int strm_id = s->chunk.strm_id[t >> 6]; int t6 = t & 0x3f; if (strm_len > 0 && t6 < sizeof(CompressedStreamInfo) / sizeof(uint32_t)) { ((volatile uint32_t *)&s->strm_info[t >> 6])[t6] = ((const uint32_t *)&strm_info[strm_id])[t6]; } } if (t == 0) { uint32_t rowgroups_in_chunk = (rowidx_stride > 0) ? (s->chunk.num_rows + rowidx_stride - 1) / rowidx_stride : 1; s->rowgroup_start = s->chunk.rowgroup_id; s->rowgroup_end = s->rowgroup_start + rowgroups_in_chunk; s->is_compressed = (strm_info != NULL); } __syncthreads(); while (s->rowgroup_start < s->rowgroup_end) { int num_rowgroups = min(s->rowgroup_end - s->rowgroup_start, 128); int rowgroup_size4, t4, t32; s->rowgroups[t].chunk_id = chunk_id; if (t == 0) { gpuReadRowGroupIndexEntries(s, num_rowgroups); } __syncthreads(); if (s->is_compressed) { // Convert the block + blk_offset pair into a raw offset into the decompressed stream if (s->chunk.strm_len[CI_DATA] > 0) { gpuMapRowIndexToUncompressed(s, CI_DATA, num_rowgroups, t); } if (s->chunk.strm_len[CI_DATA2] > 0) { gpuMapRowIndexToUncompressed(s, CI_DATA2, num_rowgroups, t); } __syncthreads(); } rowgroup_size4 = sizeof(RowGroup) / sizeof(uint32_t); t4 = t & 3; t32 = t >> 2; for (int i = t32; i < num_rowgroups; i += 32) { for (int j = t4; j < rowgroup_size4; j += 4) { ((uint32_t *)&row_groups[(s->rowgroup_start + i) * num_columns + blockIdx.x])[j] = ((volatile uint32_t *)&s->rowgroups[i])[j]; } } __syncthreads(); if (t == 0) { s->rowgroup_start += num_rowgroups; } __syncthreads(); } } cudaError_t __host__ ParseCompressedStripeData(CompressedStreamInfo *strm_info, int32_t num_streams, uint32_t compression_block_size, uint32_t log2maxcr, cudaStream_t stream) { dim3 dim_block(128, 1); dim3 dim_grid((num_streams + 3) >> 2, 1); // 1 stream per warp, 4 warps per block gpuParseCompressedStripeData <<< dim_grid, dim_block, 0, stream >>>(strm_info, num_streams, compression_block_size, log2maxcr); return cudaSuccess; } cudaError_t __host__ PostDecompressionReassemble(CompressedStreamInfo *strm_info, int32_t num_streams, cudaStream_t stream) { dim3 dim_block(128, 1); dim3 dim_grid((num_streams + 3) >> 2, 1); // 1 stream per warp, 4 warps per block gpuPostDecompressionReassemble <<< dim_grid, dim_block, 0, stream >>>(strm_info, num_streams); return cudaSuccess; } /** * @brief Launches kernel for constructing rowgroup from index streams * * @param[out] row_groups RowGroup device array [rowgroup][column] * @param[in] strm_info List of compressed streams (or NULL if uncompressed) * @param[in] chunks ColumnDesc device array [stripe][column] * @param[in] num_columns Number of columns * @param[in] num_stripes Number of stripes * @param[in] num_rowgroups Number of row groups * @param[in] stream CUDA stream to use, default 0 * * @return cudaSuccess if successful, a CUDA error code otherwise **/ cudaError_t __host__ ParseRowGroupIndex(RowGroup *row_groups, CompressedStreamInfo *strm_info, ColumnDesc *chunks, uint32_t num_columns, uint32_t num_stripes, uint32_t num_rowgroups, uint32_t rowidx_stride, cudaStream_t stream) { dim3 dim_block(128, 1); dim3 dim_grid(num_columns, num_stripes); // 1 column chunk per block gpuParseRowGroupIndex <<< dim_grid, dim_block, 0, stream >>>(row_groups, strm_info, chunks, num_columns, num_stripes, num_rowgroups, rowidx_stride); return cudaSuccess; } } // namespace gpu } // namespace orc } // namespace io } // namespace cudf
5e96705a6f4214990377e9f2eccb8ed07cc6cd7e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DCNv2Plugin.h" #include <hip/hip_fp16.h> #include <rocblas.h> #define KERNEL_POSITION \ int position = (blockDim.x * blockIdx.x + threadIdx.x); \ if (position >= (edge)) return; #define cublasCheck(op) \ do { \ auto ret = (op); \ if (ret != HIPBLAS_STATUS_SUCCESS) { \ INFO("%s fail, %d != %d", #op, ret, HIPBLAS_STATUS_SUCCESS); \ abort(); \ } \ } while (0); template <typename T> static __global__ void sigmoidKernel(const T* input, T* output, int edge); template <> __global__ void sigmoidKernel(const float* input, float* output, int edge) { KERNEL_POSITION; output[position] = 1 / (1 + exp(-input[position])); } template<> __global__ void sigmoidKernel(const half* input, half* output, int edge) { KERNEL_POSITION; half one = 1.0f; output[position] = one / (one + hexp(-input[position])); } static __device__ float dmcnIm2colBilinearFP32(const float *bottom_data, const int data_width, const int height, const int width, float h, float w) { int h_low = floor(h); int w_low = floor(w); int h_high = h_low + 1; int w_high = w_low + 1; float lh = h - h_low; float lw = w - w_low; float hh = 1 - lh, hw = 1 - lw; float v1 = 0; float v2 = 0; float v3 = 0; float v4 = 0; if (h_low >= 0 && w_low >= 0) v1 = bottom_data[h_low * data_width + w_low]; if (h_low >= 0 && w_high <= width - 1) v2 = bottom_data[h_low * data_width + w_high]; if (h_high <= height - 1 && w_low >= 0) v3 = bottom_data[h_high * data_width + w_low]; if (h_high <= height - 1 && w_high <= width - 1) v4 = bottom_data[h_high * data_width + w_high]; float w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw; float val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } static __device__ half dmcnIm2colBilinearFP16(const half *bottom_data, const int data_width, const int height, const int width, const half& h, const half& w) { int h_low = hfloor(h); int w_low = hfloor(w); int h_high = h_low + 1; int w_high = w_low + 1; half one = 1.0f; half h_low_hf = h_low; half w_low_hf = w_low; half lh = h - h_low_hf; half lw = w - w_low_hf; half hh = one - lh, hw = one - lw; half zero = 0.0f; half v1 = zero; half v2 = zero; half v3 = zero; half v4 = zero; if (h_low >= 0 && w_low >= 0) v1 = bottom_data[h_low * data_width + w_low]; if (h_low >= 0 && w_high <= width - 1) v2 = bottom_data[h_low * data_width + w_high]; if (h_high <= height - 1 && w_low >= 0) v3 = bottom_data[h_high * data_width + w_low]; if (h_high <= height - 1 && w_high <= width - 1) v4 = bottom_data[h_high * data_width + w_high]; half w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw; return (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); } template <typename T> static __global__ void DCNIm2colKernel( const T *data_input, const T *data_offset, const T *data_mask, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_output, const int width_output, T *data_output, int edge); template <> __global__ void DCNIm2colKernel( const float *data_input, const float *data_offset, const float *data_mask, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_output, const int width_output, float *data_output, int edge) { KERNEL_POSITION; const int f_area_input = width_input * height_input; const int f_area_output = width_output * height_output; // index index of output matrix const int w_output = position % width_output; const int h_output = (position / width_output) % height_output; const int c_input = (position / width_output / height_output) % num_channels; const int c_output = c_input * kernel_h * kernel_w; const int deformable_group_index = c_input / channel_per_deformable_group; const int h_input = h_output * stride_h - pad_h; const int w_input = w_output * stride_w - pad_w; int data_output_offset = c_input * kernel_h * kernel_w * f_area_output + h_output * width_output + w_output; float *data_output_ptr = data_output + data_output_offset; const float *data_input_ptr = data_input + c_input * f_area_input; const float *data_offset_ptr = data_offset + deformable_group_index * 2 * kernel_h * kernel_w * f_area_output; const float *data_mask_ptr = data_mask + deformable_group_index * kernel_h * kernel_w * f_area_output; for (int i = 0; i < kernel_h; ++i) { for (int j = 0; j < kernel_w; ++j) { const int row = i + h_input; const int col = j + w_input; const int kernel_index = i * kernel_w + j; const int offset_h_offset = 2 * kernel_index * f_area_output + h_output * width_output + w_output; const int offset_w_offset = (2 * kernel_index + 1) * f_area_output + h_output * width_output + w_output; const int mask_offset = kernel_index * f_area_output + h_output * width_output + w_output; const float offset_h = data_offset_ptr[offset_h_offset]; const float offset_w = data_offset_ptr[offset_w_offset]; const float mask = data_mask_ptr[mask_offset]; float val = 0; const float h_im = h_input + i * dilation_h + offset_h; const float w_im = w_input + j * dilation_w + offset_w; if (h_im > -1 && w_im > -1 && h_im < height_input && w_im < width_input) { val = dmcnIm2colBilinearFP32(data_input_ptr, width_input, height_input, width_input, h_im, w_im); } *data_output_ptr = val * mask; data_output_ptr += f_area_output; } } } template <> __global__ void DCNIm2colKernel( const half *data_input, const half *data_offset, const half *data_mask, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_output, const int width_output, half *data_output, int edge) { KERNEL_POSITION; const int f_area_input = width_input * height_input; const int f_area_output = width_output * height_output; // index index of output matrix const int w_output = position % width_output; const int h_output = (position / width_output) % height_output; const int c_input = (position / width_output / height_output) % num_channels; const int c_output = c_input * kernel_h * kernel_w; const int deformable_group_index = c_input / channel_per_deformable_group; const int h_input = h_output * stride_h - pad_h; const int w_input = w_output * stride_w - pad_w; half width_input_hf = __float2half(width_input); half height_input_hf = __float2half(height_input); half h_input_hf = __float2half(h_input); half w_input_hf = __float2half(w_input); half dilation_h_hf = __float2half(dilation_h); half dilation_w_hf = __float2half(dilation_w); int data_output_offset = c_input * kernel_h * kernel_w * f_area_output + h_output * width_output + w_output; half *data_output_ptr = data_output + data_output_offset; const half *data_input_ptr = data_input + c_input * f_area_input; const half *data_offset_ptr = data_offset + deformable_group_index * 2 * kernel_h * kernel_w * f_area_output; const half *data_mask_ptr = data_mask + deformable_group_index * kernel_h * kernel_w * f_area_output; half n_one = -1.0f; half zero = 0.0f; for (int i = 0; i < kernel_h; ++i) { for (int j = 0; j < kernel_w; ++j) { half i_hf = __float2half(i); half j_hf = __float2half(j); const int row = i + h_input; const int col = j + w_input; const int kernel_index = i * kernel_w + j; const int offset_h_offset = 2 * kernel_index * f_area_output + h_output * width_output + w_output; const int offset_w_offset = (2 * kernel_index + 1) * f_area_output + h_output * width_output + w_output; const int mask_offset = kernel_index * f_area_output + h_output * width_output + w_output; const half offset_h = data_offset_ptr[offset_h_offset]; const half offset_w = data_offset_ptr[offset_w_offset]; const half mask = data_mask_ptr[mask_offset]; half val = zero; half h_im = h_input_hf + i_hf * dilation_h_hf + offset_h; half w_im = w_input_hf + j_hf * dilation_w_hf + offset_w; if (h_im > n_one && w_im > n_one && h_im < height_input_hf && w_im < width_input_hf) { val = dmcnIm2colBilinearFP16(data_input_ptr, width_input_hf, height_input_hf, width_input_hf, h_im, w_im); } *data_output_ptr = val * mask; data_output_ptr += f_area_output; } } } template <typename T> static __global__ void biasKernel(T* data_input, const T* bias, const int f_area, int edge) { KERNEL_POSITION; int bias_index = position / f_area; data_input[position] += bias[bias_index]; } template <typename T> inline void segemm_native(hipblasHandle_t handle, hipblasOperation_t transa, hipblasOperation_t transb, int m, int n, int k, float alpha, /* host or device pointer */ const T *A, int lda, const T *B, int ldb, float beta, /* host or device pointer */ T *C, int ldc); template <> inline void segemm_native<float>(hipblasHandle_t handle, hipblasOperation_t transa, hipblasOperation_t transb, int m, int n, int k, float alpha, /* host or device pointer */ const float *A, int lda, const float *B, int ldb, float beta, /* host or device pointer */ float *C, int ldc) { hipblasSgemm(handle, transa, transb, m, n, k, &alpha, A, lda, B, ldb, &beta, C, ldc); } template <> inline void segemm_native<half>(hipblasHandle_t handle, hipblasOperation_t transa, hipblasOperation_t transb, int m, int n, int k, float alpha, const half *A, int lda, const half *B, int ldb, float beta, half *C, int ldc) { auto halpha = half(alpha); auto hbeta = half(beta); hipblasGemmEx(handle, transa, transb, m, n, k, &halpha, A, HIP_R_16F, lda, B, HIP_R_16F, ldb, &hbeta, C, HIP_R_16F, ldc, HIP_R_16F, CUBLAS_GEMM_DFALT); } namespace nvinfer1 { namespace dcnv2 { template <typename T> void enqueue_native(hipblasHandle_t handle, const T* input1, const T* input2, const T* weights, const T* bias, T* output, const Dims& input1_shape, const Dims& input2_shape, const Dims& weights_shape, const Dims& output_shape, const int deformable_groups, void* workspace, hipStream_t stream) { int kernel_size = weights_shape.d[W_DIM]; size_t maskSize = static_cast<size_t>(input1_shape.d[H_DIM] * input1_shape.d[W_DIM] * kernel_size * kernel_size * deformable_groups); size_t im2colSize = static_cast<size_t>(input1_shape.d[C_DIM] * kernel_size * kernel_size * output_shape.d[H_DIM] * output_shape.d[W_DIM]); const int m = output_shape.d[C_DIM]; const int n = output_shape.d[H_DIM] * output_shape.d[W_DIM]; const int k = input1_shape.d[C_DIM] * kernel_size * kernel_size; float alpha = 1.0; float beta = 0.0; for (int ibatch = 0 ; ibatch < input2_shape.d[N_DIM]; ++ibatch) { T* maskWorkspacePtr = static_cast<T*>(workspace) + (maskSize + im2colSize) * ibatch; T* im2colWorkspacePtr = static_cast<T*>(workspace) + (maskSize + im2colSize) * ibatch + maskSize; const T* inputMask = static_cast<const T*>(input2) + (ibatch, input2_shape.d[C_DIM] / 3 * 2); dim3 sigmoidGrid(maskSize); dim3 sigmoidBlock(maskSize); hipLaunchKernelGGL(( sigmoidKernel), dim3(sigmoidGrid), dim3(sigmoidBlock), 0, stream, inputMask, maskWorkspacePtr, maskSize); const int INPUT1_ELEMS_PER_BATCH = input1_shape.d[C_DIM] * input1_shape.d[H_DIM] * input1_shape.d[W_DIM]; const T* datainput = static_cast<const T*>(input1) + (ibatch * INPUT1_ELEMS_PER_BATCH); const int INPUT2_ELEMS_PER_BATCH = input2_shape.d[C_DIM] * input2_shape.d[H_DIM] * input2_shape.d[W_DIM]; const T* offset = static_cast<const T*>(input2) + (ibatch * INPUT2_ELEMS_PER_BATCH); dim3 im2colGrid(im2colSize); dim3 im2colBlock(im2colSize); hipLaunchKernelGGL(( DCNIm2colKernel), dim3(im2colGrid), dim3(im2colBlock), 0, stream, datainput, offset, maskWorkspacePtr, input1_shape.d[H_DIM], input1_shape.d[W_DIM], kernel_size, kernel_size, 1, 1, 1, 1, 1, 1, input1_shape.d[C_DIM], input1_shape.d[N_DIM], input1_shape.d[C_DIM], deformable_groups, output_shape.d[H_DIM], output_shape.d[W_DIM], im2colWorkspacePtr, im2colSize); const T* weightKernel = static_cast<const T*>(weights); const int OUTPUT_ELEMS_PER_BATCH = output_shape.d[C_DIM] * output_shape.d[H_DIM] * output_shape.d[W_DIM]; T* batch_output = static_cast<T*>(output) + (ibatch * OUTPUT_ELEMS_PER_BATCH); segemm_native(handle, HIPBLAS_OP_N, HIPBLAS_OP_N, n, m, k, alpha, im2colWorkspacePtr, n, weightKernel, k, beta, batch_output, n); if (bias) { const T* weightBias = static_cast<const T*>(bias); size_t edge = output_shape.d[C_DIM] * output_shape.d[H_DIM] * output_shape.d[W_DIM]; size_t area = output_shape.d[H_DIM] * output_shape.d[W_DIM]; dim3 biasGrid(edge); dim3 biasBlock(edge); hipLaunchKernelGGL(( biasKernel), dim3(biasGrid), dim3(biasBlock), 0, stream, batch_output, weightBias, area, edge); } } } void enqueue_call(const void* const* inputs, void* const* outputs, void* workspace, hipStream_t stream, const DataType& iType, const Dims& input_shape, const Dims& input_shape1, const Dims& weights_shape, const Dims& output_shape, DataType mType, hipblasHandle_t cublasHandle_, const DCNv2Parameters& mParam) { if (mType == nvinfer1::DataType::kFLOAT) { enqueue_native<float>(cublasHandle_, static_cast<const float*>(inputs[0]), static_cast<const float*>(inputs[1]), static_cast<const float*>(inputs[2]), static_cast<const float*>(inputs[3]), static_cast<float*>(outputs[0]), input_shape, input_shape1, weights_shape, output_shape, mParam.deformable_groups, workspace, stream); } else if (mType == nvinfer1::DataType::kHALF) { enqueue_native<half>(cublasHandle_, static_cast<const half*>(inputs[0]), static_cast<const half*>(inputs[1]), static_cast<const half*>(inputs[2]), static_cast<const half*>(inputs[3]), static_cast<half*>(outputs[0]), input_shape, input_shape1, weights_shape, output_shape, mParam.deformable_groups, workspace, stream); } } } // namespace nvinfer1 } // namespace dcnv2
5e96705a6f4214990377e9f2eccb8ed07cc6cd7e.cu
/* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DCNv2Plugin.h" #include <cuda_fp16.h> #include <cublas_v2.h> #define KERNEL_POSITION \ int position = (blockDim.x * blockIdx.x + threadIdx.x); \ if (position >= (edge)) return; #define cublasCheck(op) \ do { \ auto ret = (op); \ if (ret != CUBLAS_STATUS_SUCCESS) { \ INFO("%s fail, %d != %d", #op, ret, CUBLAS_STATUS_SUCCESS); \ abort(); \ } \ } while (0); template <typename T> static __global__ void sigmoidKernel(const T* input, T* output, int edge); template <> __global__ void sigmoidKernel(const float* input, float* output, int edge) { KERNEL_POSITION; output[position] = 1 / (1 + exp(-input[position])); } template<> __global__ void sigmoidKernel(const half* input, half* output, int edge) { KERNEL_POSITION; half one = 1.0f; output[position] = one / (one + hexp(-input[position])); } static __device__ float dmcnIm2colBilinearFP32(const float *bottom_data, const int data_width, const int height, const int width, float h, float w) { int h_low = floor(h); int w_low = floor(w); int h_high = h_low + 1; int w_high = w_low + 1; float lh = h - h_low; float lw = w - w_low; float hh = 1 - lh, hw = 1 - lw; float v1 = 0; float v2 = 0; float v3 = 0; float v4 = 0; if (h_low >= 0 && w_low >= 0) v1 = bottom_data[h_low * data_width + w_low]; if (h_low >= 0 && w_high <= width - 1) v2 = bottom_data[h_low * data_width + w_high]; if (h_high <= height - 1 && w_low >= 0) v3 = bottom_data[h_high * data_width + w_low]; if (h_high <= height - 1 && w_high <= width - 1) v4 = bottom_data[h_high * data_width + w_high]; float w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw; float val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } static __device__ half dmcnIm2colBilinearFP16(const half *bottom_data, const int data_width, const int height, const int width, const half& h, const half& w) { int h_low = hfloor(h); int w_low = hfloor(w); int h_high = h_low + 1; int w_high = w_low + 1; half one = 1.0f; half h_low_hf = h_low; half w_low_hf = w_low; half lh = h - h_low_hf; half lw = w - w_low_hf; half hh = one - lh, hw = one - lw; half zero = 0.0f; half v1 = zero; half v2 = zero; half v3 = zero; half v4 = zero; if (h_low >= 0 && w_low >= 0) v1 = bottom_data[h_low * data_width + w_low]; if (h_low >= 0 && w_high <= width - 1) v2 = bottom_data[h_low * data_width + w_high]; if (h_high <= height - 1 && w_low >= 0) v3 = bottom_data[h_high * data_width + w_low]; if (h_high <= height - 1 && w_high <= width - 1) v4 = bottom_data[h_high * data_width + w_high]; half w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw; return (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); } template <typename T> static __global__ void DCNIm2colKernel( const T *data_input, const T *data_offset, const T *data_mask, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_output, const int width_output, T *data_output, int edge); template <> __global__ void DCNIm2colKernel( const float *data_input, const float *data_offset, const float *data_mask, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_output, const int width_output, float *data_output, int edge) { KERNEL_POSITION; const int f_area_input = width_input * height_input; const int f_area_output = width_output * height_output; // index index of output matrix const int w_output = position % width_output; const int h_output = (position / width_output) % height_output; const int c_input = (position / width_output / height_output) % num_channels; const int c_output = c_input * kernel_h * kernel_w; const int deformable_group_index = c_input / channel_per_deformable_group; const int h_input = h_output * stride_h - pad_h; const int w_input = w_output * stride_w - pad_w; int data_output_offset = c_input * kernel_h * kernel_w * f_area_output + h_output * width_output + w_output; float *data_output_ptr = data_output + data_output_offset; const float *data_input_ptr = data_input + c_input * f_area_input; const float *data_offset_ptr = data_offset + deformable_group_index * 2 * kernel_h * kernel_w * f_area_output; const float *data_mask_ptr = data_mask + deformable_group_index * kernel_h * kernel_w * f_area_output; for (int i = 0; i < kernel_h; ++i) { for (int j = 0; j < kernel_w; ++j) { const int row = i + h_input; const int col = j + w_input; const int kernel_index = i * kernel_w + j; const int offset_h_offset = 2 * kernel_index * f_area_output + h_output * width_output + w_output; const int offset_w_offset = (2 * kernel_index + 1) * f_area_output + h_output * width_output + w_output; const int mask_offset = kernel_index * f_area_output + h_output * width_output + w_output; const float offset_h = data_offset_ptr[offset_h_offset]; const float offset_w = data_offset_ptr[offset_w_offset]; const float mask = data_mask_ptr[mask_offset]; float val = 0; const float h_im = h_input + i * dilation_h + offset_h; const float w_im = w_input + j * dilation_w + offset_w; if (h_im > -1 && w_im > -1 && h_im < height_input && w_im < width_input) { val = dmcnIm2colBilinearFP32(data_input_ptr, width_input, height_input, width_input, h_im, w_im); } *data_output_ptr = val * mask; data_output_ptr += f_area_output; } } } template <> __global__ void DCNIm2colKernel( const half *data_input, const half *data_offset, const half *data_mask, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_output, const int width_output, half *data_output, int edge) { KERNEL_POSITION; const int f_area_input = width_input * height_input; const int f_area_output = width_output * height_output; // index index of output matrix const int w_output = position % width_output; const int h_output = (position / width_output) % height_output; const int c_input = (position / width_output / height_output) % num_channels; const int c_output = c_input * kernel_h * kernel_w; const int deformable_group_index = c_input / channel_per_deformable_group; const int h_input = h_output * stride_h - pad_h; const int w_input = w_output * stride_w - pad_w; half width_input_hf = __float2half(width_input); half height_input_hf = __float2half(height_input); half h_input_hf = __float2half(h_input); half w_input_hf = __float2half(w_input); half dilation_h_hf = __float2half(dilation_h); half dilation_w_hf = __float2half(dilation_w); int data_output_offset = c_input * kernel_h * kernel_w * f_area_output + h_output * width_output + w_output; half *data_output_ptr = data_output + data_output_offset; const half *data_input_ptr = data_input + c_input * f_area_input; const half *data_offset_ptr = data_offset + deformable_group_index * 2 * kernel_h * kernel_w * f_area_output; const half *data_mask_ptr = data_mask + deformable_group_index * kernel_h * kernel_w * f_area_output; half n_one = -1.0f; half zero = 0.0f; for (int i = 0; i < kernel_h; ++i) { for (int j = 0; j < kernel_w; ++j) { half i_hf = __float2half(i); half j_hf = __float2half(j); const int row = i + h_input; const int col = j + w_input; const int kernel_index = i * kernel_w + j; const int offset_h_offset = 2 * kernel_index * f_area_output + h_output * width_output + w_output; const int offset_w_offset = (2 * kernel_index + 1) * f_area_output + h_output * width_output + w_output; const int mask_offset = kernel_index * f_area_output + h_output * width_output + w_output; const half offset_h = data_offset_ptr[offset_h_offset]; const half offset_w = data_offset_ptr[offset_w_offset]; const half mask = data_mask_ptr[mask_offset]; half val = zero; half h_im = h_input_hf + i_hf * dilation_h_hf + offset_h; half w_im = w_input_hf + j_hf * dilation_w_hf + offset_w; if (h_im > n_one && w_im > n_one && h_im < height_input_hf && w_im < width_input_hf) { val = dmcnIm2colBilinearFP16(data_input_ptr, width_input_hf, height_input_hf, width_input_hf, h_im, w_im); } *data_output_ptr = val * mask; data_output_ptr += f_area_output; } } } template <typename T> static __global__ void biasKernel(T* data_input, const T* bias, const int f_area, int edge) { KERNEL_POSITION; int bias_index = position / f_area; data_input[position] += bias[bias_index]; } template <typename T> inline void segemm_native(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float alpha, /* host or device pointer */ const T *A, int lda, const T *B, int ldb, float beta, /* host or device pointer */ T *C, int ldc); template <> inline void segemm_native<float>(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float alpha, /* host or device pointer */ const float *A, int lda, const float *B, int ldb, float beta, /* host or device pointer */ float *C, int ldc) { cublasSgemm(handle, transa, transb, m, n, k, &alpha, A, lda, B, ldb, &beta, C, ldc); } template <> inline void segemm_native<half>(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float alpha, const half *A, int lda, const half *B, int ldb, float beta, half *C, int ldc) { auto halpha = half(alpha); auto hbeta = half(beta); cublasGemmEx(handle, transa, transb, m, n, k, &halpha, A, CUDA_R_16F, lda, B, CUDA_R_16F, ldb, &hbeta, C, CUDA_R_16F, ldc, CUDA_R_16F, CUBLAS_GEMM_DFALT); } namespace nvinfer1 { namespace dcnv2 { template <typename T> void enqueue_native(cublasHandle_t handle, const T* input1, const T* input2, const T* weights, const T* bias, T* output, const Dims& input1_shape, const Dims& input2_shape, const Dims& weights_shape, const Dims& output_shape, const int deformable_groups, void* workspace, cudaStream_t stream) { int kernel_size = weights_shape.d[W_DIM]; size_t maskSize = static_cast<size_t>(input1_shape.d[H_DIM] * input1_shape.d[W_DIM] * kernel_size * kernel_size * deformable_groups); size_t im2colSize = static_cast<size_t>(input1_shape.d[C_DIM] * kernel_size * kernel_size * output_shape.d[H_DIM] * output_shape.d[W_DIM]); const int m = output_shape.d[C_DIM]; const int n = output_shape.d[H_DIM] * output_shape.d[W_DIM]; const int k = input1_shape.d[C_DIM] * kernel_size * kernel_size; float alpha = 1.0; float beta = 0.0; for (int ibatch = 0 ; ibatch < input2_shape.d[N_DIM]; ++ibatch) { T* maskWorkspacePtr = static_cast<T*>(workspace) + (maskSize + im2colSize) * ibatch; T* im2colWorkspacePtr = static_cast<T*>(workspace) + (maskSize + im2colSize) * ibatch + maskSize; const T* inputMask = static_cast<const T*>(input2) + (ibatch, input2_shape.d[C_DIM] / 3 * 2); dim3 sigmoidGrid(maskSize); dim3 sigmoidBlock(maskSize); sigmoidKernel<<<sigmoidGrid, sigmoidBlock, 0, stream>>> ( inputMask, maskWorkspacePtr, maskSize); const int INPUT1_ELEMS_PER_BATCH = input1_shape.d[C_DIM] * input1_shape.d[H_DIM] * input1_shape.d[W_DIM]; const T* datainput = static_cast<const T*>(input1) + (ibatch * INPUT1_ELEMS_PER_BATCH); const int INPUT2_ELEMS_PER_BATCH = input2_shape.d[C_DIM] * input2_shape.d[H_DIM] * input2_shape.d[W_DIM]; const T* offset = static_cast<const T*>(input2) + (ibatch * INPUT2_ELEMS_PER_BATCH); dim3 im2colGrid(im2colSize); dim3 im2colBlock(im2colSize); DCNIm2colKernel<<<im2colGrid, im2colBlock, 0, stream>>>( datainput, offset, maskWorkspacePtr, input1_shape.d[H_DIM], input1_shape.d[W_DIM], kernel_size, kernel_size, 1, 1, 1, 1, 1, 1, input1_shape.d[C_DIM], input1_shape.d[N_DIM], input1_shape.d[C_DIM], deformable_groups, output_shape.d[H_DIM], output_shape.d[W_DIM], im2colWorkspacePtr, im2colSize); const T* weightKernel = static_cast<const T*>(weights); const int OUTPUT_ELEMS_PER_BATCH = output_shape.d[C_DIM] * output_shape.d[H_DIM] * output_shape.d[W_DIM]; T* batch_output = static_cast<T*>(output) + (ibatch * OUTPUT_ELEMS_PER_BATCH); segemm_native(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, alpha, im2colWorkspacePtr, n, weightKernel, k, beta, batch_output, n); if (bias) { const T* weightBias = static_cast<const T*>(bias); size_t edge = output_shape.d[C_DIM] * output_shape.d[H_DIM] * output_shape.d[W_DIM]; size_t area = output_shape.d[H_DIM] * output_shape.d[W_DIM]; dim3 biasGrid(edge); dim3 biasBlock(edge); biasKernel<<<biasGrid, biasBlock, 0, stream>>>(batch_output, weightBias, area, edge); } } } void enqueue_call(const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream, const DataType& iType, const Dims& input_shape, const Dims& input_shape1, const Dims& weights_shape, const Dims& output_shape, DataType mType, cublasHandle_t cublasHandle_, const DCNv2Parameters& mParam) { if (mType == nvinfer1::DataType::kFLOAT) { enqueue_native<float>(cublasHandle_, static_cast<const float*>(inputs[0]), static_cast<const float*>(inputs[1]), static_cast<const float*>(inputs[2]), static_cast<const float*>(inputs[3]), static_cast<float*>(outputs[0]), input_shape, input_shape1, weights_shape, output_shape, mParam.deformable_groups, workspace, stream); } else if (mType == nvinfer1::DataType::kHALF) { enqueue_native<half>(cublasHandle_, static_cast<const half*>(inputs[0]), static_cast<const half*>(inputs[1]), static_cast<const half*>(inputs[2]), static_cast<const half*>(inputs[3]), static_cast<half*>(outputs[0]), input_shape, input_shape1, weights_shape, output_shape, mParam.deformable_groups, workspace, stream); } } } // namespace nvinfer1 } // namespace dcnv2
db55c998724651e2bb6c9ad1b494d091e6614dd9.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "util.cuh" #include <hip/hip_fp16.h> #include <helper_timer.h> #include <hip/hip_cooperative_groups.h> #include <cstdio> using namespace cooperative_groups; // FMA numerical arithmetic function in GPU @FP32 // y = x * y + z // in this kernel, assuming we have transposed matrix y __global__ void fmaf_kernel(float *d_x, float *d_y, float *d_z, int size) { int idx_x = blockIdx.x * blockDim.x + threadIdx.x; int stride = gridDim.x * blockDim.x; for (int i = idx_x; i < size; i += stride) { d_z[i] = fmaf(d_x[i], d_y[i], 0.f); } } void fmaf_host(float *h_x, float *h_y, float *h_z, int size) { #pragma omp parallel { #pragma omp for for (int i = 0; i < size; i++) h_z[i] = h_x[i] * h_y[i] + 0.f; } } int main() { CBuffer<float> X, Y, Z; int size = 1 << 26; srand(2019); // initialize host buffers X.init(size, true); Y.init(size, true); Z.init(size, true); // initalize gpu buffers X.cuda(); Y.cuda(); Z.cuda(); // getting number of blocks for stride-loop int n_threads = 256; int num_sms; int num_blocks_per_sm; hipDeviceGetAttribute(&num_sms, hipDeviceAttributeMultiprocessorCount, 0); hipOccupancyMaxActiveBlocksPerMultiprocessor(&num_blocks_per_sm, fmaf_kernel, n_threads, n_threads*sizeof(float2)); int n_blocks = min(num_blocks_per_sm * num_sms, (size/2 + n_threads - 1) / n_threads); // initialize timer StopWatchInterface *timer; sdkCreateTimer(&timer); sdkStartTimer(&timer); hipLaunchKernelGGL(( fmaf_kernel), dim3(n_blocks), dim3(n_threads), n_threads * sizeof(float) , 0, X.d_ptr_, Y.d_ptr_, Z.d_ptr_, size); hipDeviceSynchronize(); sdkStopTimer(&timer); float elapsedTimeMs = sdkGetTimerValue(&timer); float ops = size / elapsedTimeMs * 1e-6; printf("FMA, FLOPS = %.3f GFlops, Operation Time= %.3f msec\n", ops, elapsedTimeMs); fmaf_host(X.h_ptr_, Y.h_ptr_, Z.h_ptr_, size); int diff_count = Z.diff_count(); (diff_count == 0) ? printf("Success!!\n") : printf("Counted diff!! (%d times)\n", diff_count); // cleanup sdkDeleteTimer(&timer); return 0; }
db55c998724651e2bb6c9ad1b494d091e6614dd9.cu
#include "util.cuh" #include <cuda_fp16.h> #include <helper_timer.h> #include <cooperative_groups.h> #include <cstdio> using namespace cooperative_groups; // FMA numerical arithmetic function in GPU @FP32 // y = x * y + z // in this kernel, assuming we have transposed matrix y __global__ void fmaf_kernel(float *d_x, float *d_y, float *d_z, int size) { int idx_x = blockIdx.x * blockDim.x + threadIdx.x; int stride = gridDim.x * blockDim.x; for (int i = idx_x; i < size; i += stride) { d_z[i] = fmaf(d_x[i], d_y[i], 0.f); } } void fmaf_host(float *h_x, float *h_y, float *h_z, int size) { #pragma omp parallel { #pragma omp for for (int i = 0; i < size; i++) h_z[i] = h_x[i] * h_y[i] + 0.f; } } int main() { CBuffer<float> X, Y, Z; int size = 1 << 26; srand(2019); // initialize host buffers X.init(size, true); Y.init(size, true); Z.init(size, true); // initalize gpu buffers X.cuda(); Y.cuda(); Z.cuda(); // getting number of blocks for stride-loop int n_threads = 256; int num_sms; int num_blocks_per_sm; cudaDeviceGetAttribute(&num_sms, cudaDevAttrMultiProcessorCount, 0); cudaOccupancyMaxActiveBlocksPerMultiprocessor(&num_blocks_per_sm, fmaf_kernel, n_threads, n_threads*sizeof(float2)); int n_blocks = min(num_blocks_per_sm * num_sms, (size/2 + n_threads - 1) / n_threads); // initialize timer StopWatchInterface *timer; sdkCreateTimer(&timer); sdkStartTimer(&timer); fmaf_kernel<<< n_blocks, n_threads, n_threads * sizeof(float) >>>(X.d_ptr_, Y.d_ptr_, Z.d_ptr_, size); cudaDeviceSynchronize(); sdkStopTimer(&timer); float elapsedTimeMs = sdkGetTimerValue(&timer); float ops = size / elapsedTimeMs * 1e-6; printf("FMA, FLOPS = %.3f GFlops, Operation Time= %.3f msec\n", ops, elapsedTimeMs); fmaf_host(X.h_ptr_, Y.h_ptr_, Z.h_ptr_, size); int diff_count = Z.diff_count(); (diff_count == 0) ? printf("Success!!\n") : printf("Counted diff!! (%d times)\n", diff_count); // cleanup sdkDeleteTimer(&timer); return 0; }
8b31c06471b5c77bbba66e52c289b6e719a5fd55.hip
// !!! This is a file automatically generated by hipify!!! #include<stdio.h> #include<stdlib.h> #include "hip/hip_runtime.h" #include "device_launch_parameters.h" int main() { int nDevice; hipGetDeviceCount(&nDevice); for (int i = 0; i < nDevice; i++) { hipDeviceProp_t prop; hipGetDeviceProperties(&prop, i); printf("Dispositivo : %d\n", i); printf(" Nombre : %s\n", prop.name); printf(" Frecuencia Reloj : %d KHz\n", prop.memoryClockRate); printf(" Ancho del Bus de Memoria : %d bits\n", prop.memoryBusWidth); printf(" Ancho de Banda : %f GB/s\n\n", 2.0*prop.memoryClockRate*(prop.memoryBusWidth/8)/1.0e6); } }
8b31c06471b5c77bbba66e52c289b6e719a5fd55.cu
#include<stdio.h> #include<stdlib.h> #include "cuda_runtime.h" #include "device_launch_parameters.h" int main() { int nDevice; cudaGetDeviceCount(&nDevice); for (int i = 0; i < nDevice; i++) { cudaDeviceProp prop; cudaGetDeviceProperties(&prop, i); printf("Dispositivo : %d\n", i); printf(" Nombre : %s\n", prop.name); printf(" Frecuencia Reloj : %d KHz\n", prop.memoryClockRate); printf(" Ancho del Bus de Memoria : %d bits\n", prop.memoryBusWidth); printf(" Ancho de Banda : %f GB/s\n\n", 2.0*prop.memoryClockRate*(prop.memoryBusWidth/8)/1.0e6); } }
fe951879d0e02ded8c0d34fd9faf0e9644ff91c1.hip
// !!! This is a file automatically generated by hipify!!! #include <hip/hip_runtime.h> #include <helper_cuda.h> #include <iostream> #include <iomanip> #include <hip/hip_complex.h> #include "deconvolve.h" using namespace std; /* Kernel for copying fw to fk with amplication by prefac/ker */ // Note: assume modeord=0: CMCL-compatible mode ordering in fk (from -N/2 up // to N/2-1) __global__ void Deconvolve_2d(int ms, int mt, int nf1, int nf2, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt; i+=blockDim.x*gridDim.x){ int k1 = i % ms; int k2 = i / ms; int outidx = k1 + k2*ms; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int inidx = w1 + w2*nf1; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]; fk[outidx].x = fw[inidx].x/kervalue; fk[outidx].y = fw[inidx].y/kervalue; } } __global__ void Deconvolve_3d(int ms, int mt, int mu, int nf1, int nf2, int nf3, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2, FLT *fwkerhalf3) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt*mu; i+=blockDim.x* gridDim.x){ int k1 = i % ms; int k2 = (i / ms) % mt; int k3 = (i / ms / mt); int outidx = k1 + k2*ms + k3*ms*mt; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int w3 = k3-mu/2 >= 0 ? k3-mu/2 : nf3+k3-mu/2; int inidx = w1 + w2*nf1 + w3*nf1*nf2; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]* fwkerhalf3[abs(k3-mu/2)]; fk[outidx].x = fw[inidx].x/kervalue; fk[outidx].y = fw[inidx].y/kervalue; //fk[outidx].x = kervalue; //fk[outidx].y = kervalue; } } /* Kernel for copying fk to fw with same amplication */ __global__ void Amplify_2d(int ms, int mt, int nf1, int nf2, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt; i+=blockDim.x*gridDim.x){ int k1 = i % ms; int k2 = i / ms; int inidx = k1 + k2*ms; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int outidx = w1 + w2*nf1; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]; fw[outidx].x = fk[inidx].x/kervalue; fw[outidx].y = fk[inidx].y/kervalue; } } __global__ void Amplify_3d(int ms, int mt, int mu, int nf1, int nf2, int nf3, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2, FLT *fwkerhalf3) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt*mu; i+=blockDim.x*gridDim.x){ int k1 = i % ms; int k2 = (i / ms) % mt; int k3 = (i / ms / mt); int inidx = k1 + k2*ms + k3*ms*mt; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int w3 = k3-mu/2 >= 0 ? k3-mu/2 : nf3+k3-mu/2; int outidx = w1 + w2*nf1 + w3*nf1*nf2; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]* fwkerhalf3[abs(k3-mu/2)]; fw[outidx].x = fk[inidx].x/kervalue; fw[outidx].y = fk[inidx].y/kervalue; //fw[outidx].x = fk[inidx].x; //fw[outidx].y = fk[inidx].y; } } int cudeconvolve2d(cufinufft_plan *d_plan, int blksize) /* wrapper for deconvolution & amplication in 2D. Melody Shih 07/25/19 */ { int ms=d_plan->ms; int mt=d_plan->mt; int nf1=d_plan->nf1; int nf2=d_plan->nf2; int nmodes=ms*mt; int ntransfcufftplan=d_plan->ntransfcufftplan; if(d_plan->spopts.spread_direction == 1){ for(int t=0; t<blksize; t++){ hipLaunchKernelGGL(( Deconvolve_2d), dim3((nmodes+256-1)/256), dim3(256), 0, 0, ms, mt, nf1, nf2, d_plan->fw+t*nf1*nf2,d_plan->fk+t*nmodes,d_plan->fwkerhalf1, d_plan->fwkerhalf2); } }else{ checkCudaErrors(hipMemset(d_plan->fw,0,ntransfcufftplan*nf1*nf2* sizeof(CUCPX))); for(int t=0; t<blksize; t++){ hipLaunchKernelGGL(( Amplify_2d), dim3((nmodes+256-1)/256), dim3(256), 0, 0, ms, mt, nf1, nf2, d_plan->fw+t*nf1*nf2, d_plan->fk+t*nmodes, d_plan->fwkerhalf1, d_plan->fwkerhalf2); #ifdef DEBUG CPX* h_fw; h_fw = (CPX*) malloc(nf1*nf2*sizeof(CPX)); checkCudaErrors(hipMemcpy2D(h_fw,nf1*sizeof(CUCPX),d_plan->fw, nf1*sizeof(CUCPX),nf1*sizeof(CUCPX),nf2, hipMemcpyDeviceToHost)); for(int j=0; j<nf2; j++){ for(int i=0; i<nf1; i++){ printf("(%g,%g)",h_fw[i+j*nf1].real(),h_fw[i+j*nf1].imag()); } printf("\n"); } free(h_fw); #endif } } return 0; } int cudeconvolve3d(cufinufft_plan *d_plan, int blksize) /* wrapper for deconvolution & amplication in 3D. Melody Shih 07/25/19 */ { int ms=d_plan->ms; int mt=d_plan->mt; int mu=d_plan->mu; int nf1=d_plan->nf1; int nf2=d_plan->nf2; int nf3=d_plan->nf3; int nmodes=ms*mt*mu; int ntransfcufftplan=d_plan->ntransfcufftplan; if(d_plan->spopts.spread_direction == 1){ for(int t=0; t<blksize; t++){ hipLaunchKernelGGL(( Deconvolve_3d), dim3((nmodes+256-1)/256), dim3(256), 0, 0, ms, mt, mu, nf1, nf2, nf3, d_plan->fw+t*nf1*nf2*nf3, d_plan->fk+t*nmodes, d_plan->fwkerhalf1, d_plan->fwkerhalf2, d_plan->fwkerhalf3); } }else{ checkCudaErrors(hipMemset(d_plan->fw,0,ntransfcufftplan*nf1*nf2*nf3* sizeof(CUCPX))); for(int t=0; t<blksize; t++){ hipLaunchKernelGGL(( Amplify_3d), dim3((nmodes+256-1)/256), dim3(256), 0, 0, ms, mt, mu, nf1, nf2, nf3, d_plan->fw+t*nf1*nf2*nf3, d_plan->fk+t*nmodes, d_plan->fwkerhalf1, d_plan->fwkerhalf2, d_plan->fwkerhalf3); #if 0 CPX* h_fw; h_fw = (CPX*) malloc(nf1*nf2*nf3*sizeof(CPX)); checkCudaErrors(hipMemcpy(h_fw,d_plan->fw,nf1*nf2*nf3*sizeof(CUCPX), hipMemcpyDeviceToHost)); for(int k=0; k<nf3; k++){ for(int j=0; j<nf2; j++){ for(int i=0; i<nf1; i++){ printf("(%g,%g,%g)",h_fw[i+j*nf1+k*nf1*nf2].real(), h_fw[i+j*nf1+k*nf1*nf2].imag()); } printf("\n"); } printf("\n"); } free(h_fw); #endif } } return 0; }
fe951879d0e02ded8c0d34fd9faf0e9644ff91c1.cu
#include <cuda.h> #include <helper_cuda.h> #include <iostream> #include <iomanip> #include <cuComplex.h> #include "deconvolve.h" using namespace std; /* Kernel for copying fw to fk with amplication by prefac/ker */ // Note: assume modeord=0: CMCL-compatible mode ordering in fk (from -N/2 up // to N/2-1) __global__ void Deconvolve_2d(int ms, int mt, int nf1, int nf2, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt; i+=blockDim.x*gridDim.x){ int k1 = i % ms; int k2 = i / ms; int outidx = k1 + k2*ms; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int inidx = w1 + w2*nf1; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]; fk[outidx].x = fw[inidx].x/kervalue; fk[outidx].y = fw[inidx].y/kervalue; } } __global__ void Deconvolve_3d(int ms, int mt, int mu, int nf1, int nf2, int nf3, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2, FLT *fwkerhalf3) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt*mu; i+=blockDim.x* gridDim.x){ int k1 = i % ms; int k2 = (i / ms) % mt; int k3 = (i / ms / mt); int outidx = k1 + k2*ms + k3*ms*mt; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int w3 = k3-mu/2 >= 0 ? k3-mu/2 : nf3+k3-mu/2; int inidx = w1 + w2*nf1 + w3*nf1*nf2; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]* fwkerhalf3[abs(k3-mu/2)]; fk[outidx].x = fw[inidx].x/kervalue; fk[outidx].y = fw[inidx].y/kervalue; //fk[outidx].x = kervalue; //fk[outidx].y = kervalue; } } /* Kernel for copying fk to fw with same amplication */ __global__ void Amplify_2d(int ms, int mt, int nf1, int nf2, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt; i+=blockDim.x*gridDim.x){ int k1 = i % ms; int k2 = i / ms; int inidx = k1 + k2*ms; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int outidx = w1 + w2*nf1; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]; fw[outidx].x = fk[inidx].x/kervalue; fw[outidx].y = fk[inidx].y/kervalue; } } __global__ void Amplify_3d(int ms, int mt, int mu, int nf1, int nf2, int nf3, CUCPX* fw, CUCPX *fk, FLT *fwkerhalf1, FLT *fwkerhalf2, FLT *fwkerhalf3) { for(int i=blockDim.x*blockIdx.x+threadIdx.x; i<ms*mt*mu; i+=blockDim.x*gridDim.x){ int k1 = i % ms; int k2 = (i / ms) % mt; int k3 = (i / ms / mt); int inidx = k1 + k2*ms + k3*ms*mt; int w1 = k1-ms/2 >= 0 ? k1-ms/2 : nf1+k1-ms/2; int w2 = k2-mt/2 >= 0 ? k2-mt/2 : nf2+k2-mt/2; int w3 = k3-mu/2 >= 0 ? k3-mu/2 : nf3+k3-mu/2; int outidx = w1 + w2*nf1 + w3*nf1*nf2; FLT kervalue = fwkerhalf1[abs(k1-ms/2)]*fwkerhalf2[abs(k2-mt/2)]* fwkerhalf3[abs(k3-mu/2)]; fw[outidx].x = fk[inidx].x/kervalue; fw[outidx].y = fk[inidx].y/kervalue; //fw[outidx].x = fk[inidx].x; //fw[outidx].y = fk[inidx].y; } } int cudeconvolve2d(cufinufft_plan *d_plan, int blksize) /* wrapper for deconvolution & amplication in 2D. Melody Shih 07/25/19 */ { int ms=d_plan->ms; int mt=d_plan->mt; int nf1=d_plan->nf1; int nf2=d_plan->nf2; int nmodes=ms*mt; int ntransfcufftplan=d_plan->ntransfcufftplan; if(d_plan->spopts.spread_direction == 1){ for(int t=0; t<blksize; t++){ Deconvolve_2d<<<(nmodes+256-1)/256, 256>>>(ms, mt, nf1, nf2, d_plan->fw+t*nf1*nf2,d_plan->fk+t*nmodes,d_plan->fwkerhalf1, d_plan->fwkerhalf2); } }else{ checkCudaErrors(cudaMemset(d_plan->fw,0,ntransfcufftplan*nf1*nf2* sizeof(CUCPX))); for(int t=0; t<blksize; t++){ Amplify_2d<<<(nmodes+256-1)/256, 256>>>(ms, mt, nf1, nf2, d_plan->fw+t*nf1*nf2, d_plan->fk+t*nmodes, d_plan->fwkerhalf1, d_plan->fwkerhalf2); #ifdef DEBUG CPX* h_fw; h_fw = (CPX*) malloc(nf1*nf2*sizeof(CPX)); checkCudaErrors(cudaMemcpy2D(h_fw,nf1*sizeof(CUCPX),d_plan->fw, nf1*sizeof(CUCPX),nf1*sizeof(CUCPX),nf2, cudaMemcpyDeviceToHost)); for(int j=0; j<nf2; j++){ for(int i=0; i<nf1; i++){ printf("(%g,%g)",h_fw[i+j*nf1].real(),h_fw[i+j*nf1].imag()); } printf("\n"); } free(h_fw); #endif } } return 0; } int cudeconvolve3d(cufinufft_plan *d_plan, int blksize) /* wrapper for deconvolution & amplication in 3D. Melody Shih 07/25/19 */ { int ms=d_plan->ms; int mt=d_plan->mt; int mu=d_plan->mu; int nf1=d_plan->nf1; int nf2=d_plan->nf2; int nf3=d_plan->nf3; int nmodes=ms*mt*mu; int ntransfcufftplan=d_plan->ntransfcufftplan; if(d_plan->spopts.spread_direction == 1){ for(int t=0; t<blksize; t++){ Deconvolve_3d<<<(nmodes+256-1)/256, 256>>>(ms, mt, mu, nf1, nf2, nf3, d_plan->fw+t*nf1*nf2*nf3, d_plan->fk+t*nmodes, d_plan->fwkerhalf1, d_plan->fwkerhalf2, d_plan->fwkerhalf3); } }else{ checkCudaErrors(cudaMemset(d_plan->fw,0,ntransfcufftplan*nf1*nf2*nf3* sizeof(CUCPX))); for(int t=0; t<blksize; t++){ Amplify_3d<<<(nmodes+256-1)/256, 256>>>(ms, mt, mu, nf1, nf2, nf3, d_plan->fw+t*nf1*nf2*nf3, d_plan->fk+t*nmodes, d_plan->fwkerhalf1, d_plan->fwkerhalf2, d_plan->fwkerhalf3); #if 0 CPX* h_fw; h_fw = (CPX*) malloc(nf1*nf2*nf3*sizeof(CPX)); checkCudaErrors(cudaMemcpy(h_fw,d_plan->fw,nf1*nf2*nf3*sizeof(CUCPX), cudaMemcpyDeviceToHost)); for(int k=0; k<nf3; k++){ for(int j=0; j<nf2; j++){ for(int i=0; i<nf1; i++){ printf("(%g,%g,%g)",h_fw[i+j*nf1+k*nf1*nf2].real(), h_fw[i+j*nf1+k*nf1*nf2].imag()); } printf("\n"); } printf("\n"); } free(h_fw); #endif } } return 0; }
d6f10f3b7565255eb0bad1696aaa8645ee904f16.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <algorithm> #include "CUDA_func.h" namespace NN { namespace CUDA { __global__ void compute_dense_layer(float* input, float* parameters, float* output, int input_size, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < output_size; c += stride) { output[c] = 0; for (int i = 0; i < input_size; i++) { output[c] += input[i] * parameters[c * (input_size + 1) + i]; } output[c] += parameters[c * (input_size + 1) + input_size]; } } __global__ void backprop_dense_layer_input_gradient(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_size, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < input_size; c += stride) { for (int i = 0; i < output_size; i++) { input_gradient[c] += parameters[i * (input_size + 1) + c] * output_gradient[i]; gradient[i * (input_size + 1) + c] += input[c] * output_gradient[i]; } } } __global__ void backprop_dense_layer_bias(float* gradient, float* output_gradient, int input_size, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < output_size; c += stride) { gradient[c * (input_size + 1) + input_size] += output_gradient[c]; } } //------------------------------------------------------------------------------------------- __global__ void compute_conv_layer(float* input, float* parameters, float* output, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int weights_offset; int input_pos; int x, y, z; for (int c = index; c < output_size; c += stride) { output[c] = 0.0f; x = c % layer_width; y = (c / layer_width) % layer_height; z = c / (layer_width * layer_height); weights_offset = z * (neuron_size + 1); for (int k = 0; k < input_depth; k++) { for (int j = 0; j < neuron_height; j++) { for (int i = 0; i < neuron_width; i++) { input_pos = ((k * input_height) + (y+j))*input_width + (x+i); output[c] += input[input_pos] * parameters[weights_offset + (((k * neuron_height) + j) * neuron_width) + i]; } } } output[c] += parameters[weights_offset + neuron_size]; } } __global__ void backprop_conv_layer_input(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int weights_offset; int output_pos; int x, y, z; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = (c / (input_width * input_height)) % input_depth; weights_offset = z * (neuron_width * neuron_height); for (int k = 0; k < layer_depth; k++) { for (int j = 0; j < neuron_height && y-j >= 0; j++) { for (int i = 0; i < neuron_width && x-i >= 0; i++) { output_pos = ((k * layer_height) + (y - j)) * layer_width + (x - i); input_gradient[c] += output_gradient[output_pos] * parameters[weights_offset + k*(neuron_size + 1) + j*neuron_width + i]; } } } } } __global__ void backprop_conv_layer_weights(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int weights_offset; int input_pos; int x, y; for (int c = index; c < layer_depth*input_depth; c += stride) { x = c % input_depth; y = c / input_depth; weights_offset = (y * (neuron_size+1)) + (x * neuron_height * neuron_width); for (int j = 0; j < layer_height; j++) { for (int i = 0; i < layer_width; i++) { for (int jn = 0; jn < neuron_height; jn++) { for (int in = 0; in < neuron_width; in++) { input_pos = ((x * input_height) + (j + jn)) * input_width + (i + in); gradient[weights_offset + jn * neuron_width + in] += output_gradient[((y * layer_height) + j) * layer_width + i] * input[input_pos]; } } } } } } __global__ void backprop_conv_layer_bias(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < layer_depth; c += stride) { for (int j = 0; j < layer_height; j++) { for (int i = 0; i < layer_width; i++) { gradient[c * (neuron_size + 1) + neuron_size] += output_gradient[(c * layer_height + j) * layer_width + i]; } } } } //------------------------------------------------------------------------------------------- __global__ void compute_padding_layer(float* input, float* output, int input_width, int input_height, int input_depth, int output_width, int output_height, int output_depth, int offset_width, int offset_height, int offset_depth, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z, output_pos; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); output_pos = (((offset_depth + z) * output_height) + (offset_height + y)) * output_width + (offset_width + x); output[output_pos] = input[c]; } } __global__ void backprop_padding_layer(float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int output_width, int output_height, int output_depth, int offset_width, int offset_height, int offset_depth, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z, output_pos; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); output_pos = (((offset_depth + z) * output_height) + (offset_height + y)) * output_width + (offset_width + x); input_gradient[c] += output_gradient[output_pos]; } } //------------------------------------------------------------------------------------------- __global__ void set_input_layer(float* input, float* output, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < input_size; i += stride) { output[i] = input[i]; } } //------------------------------------------------------------------------------------------- __global__ void compute_pool_max_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int input_id; float max_input = -1e38f; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x *= filter_width; y *= filter_height; z *= filter_depth; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { input_id = ((k * input_height) + j) * input_width + i; max_input = max(max_input, input[input_id]); } } } output[c] = max_input; } } __global__ void backprop_pool_max_layer(float* input, float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int input_id, mx_in_id; float max_input = -1e38f; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x *= filter_width; y *= filter_height; z *= filter_depth; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { input_id = ((k * input_height) + j) * input_width + i; if (input[input_id] > max_input) { max_input = input[input_id]; mx_in_id = input_id; } } } } input_gradient[mx_in_id] += output_gradient[c]; } } //------------------------------------------------------------------------------------ __global__ void compute_pool_avg_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size, float filter_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int input_id; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x *= filter_width; y *= filter_height; z *= filter_depth; output[c] = 0.0f; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { input_id = ((k * input_height) + j) * input_width + i; output[c] += input[input_id]; } } } output[c] /= filter_size; } } __global__ void backprop_pool_avg_layer(float* input, float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int input_size, float filter_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); x /= filter_width; y /= filter_height; z /= filter_depth; input_gradient[c] += output_gradient[((z * output_height) + y) * output_width + x]/filter_size; } } //------------------------------------------------------------------------------------ __global__ void compute_upscale_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x /= filter_width; y /= filter_height; z /= filter_depth; output[c] = input[((z*input_height) + y)*input_width + x]; } } __global__ void backprop_upscale_layer(float* input, float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int output_id; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); x *= filter_width; y *= filter_height; z *= filter_depth; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { output_id = ((k * output_height) + j) * output_width + i; input_gradient[c] += output_gradient[output_id]; } } } } } //------------------------------------------------------------------------------------ __global__ void compute_gram_layer(float* input, float* output, int input_size, int output_size, int vectors, int vector_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y; for (int c = index; c < output_size; c += stride) { x = c % vectors; y = c / vectors; output[c] = 0.0f; for (int i = 0; i < vector_size; i++) { output[c] += input[x * vector_size + i] * input[y * vector_size + i];// / vector_size; } } } __global__ void backprop_gram_layer(float* input, float* input_gradient, float* output_gradient, int input_size, int output_size, int vectors, int vector_size, float denominator) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y; for (int c = index; c < input_size; c += stride) { x = c % vector_size; y = c / vector_size; for (int i = 0; i < vectors; i++) { input_gradient[c] += input[i * vector_size + x] * output_gradient[y * vectors + i];// / vector_size; } } } //------------------------------------------------------------------------------------ __global__ void compute_rearrange_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_size, int sample_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int offset, pos; int x, y, z; int x_offset, y_offset, z_offset; for (int c = index; c < output_size; c += stride) { offset = c / sample_size; pos = c % sample_size; x_offset = offset % filter_width; y_offset = (offset / filter_width) % filter_height; z_offset = offset / (filter_width * filter_height); pos *= filter_width; x = (pos % input_width) + x_offset; pos /= input_width; pos *= filter_height; y = (pos % input_height) + y_offset; pos /= input_height; pos *= filter_depth; z = pos + z_offset; pos = (z * input_height + y) * input_width + x; output[c] = input[pos]; } } __global__ void backprop_rearrange_layer(float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_size, int sample_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int offset, pos; int x, y, z; int x_offset, y_offset, z_offset; for (int c = index; c < output_size; c += stride) { offset = c / sample_size; pos = c % sample_size; x_offset = offset % filter_width; y_offset = (offset / filter_width) % filter_height; z_offset = offset / (filter_width * filter_height); pos *= filter_width; x = (pos % input_width) + x_offset; pos /= input_width; pos *= filter_height; y = (pos % input_height) + y_offset; pos /= input_height; pos *= filter_depth; z = pos + z_offset; pos = (z * input_height + y) * input_width + x; input_gradient[pos] += output_gradient[c]; } } //------------------------------------------------------------------------------------------- __global__ void adam_optimize(float* parameters, float* gradient, float* mean_gradient, float* mean_squared_gradient, float learning_rate, float batch_size, int parameters_size, float beta1, float beta2, float epsilon, float mean_gradient_adjust, float mean_squared_gradient_adjust) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < parameters_size; i+= stride) { gradient[i] /= batch_size; mean_gradient[i] = beta1 * mean_gradient[i] + (1.0 - beta1) * gradient[i]; mean_squared_gradient[i] = beta2 * mean_squared_gradient[i] + (1.0 - beta2) * gradient[i] * gradient[i]; parameters[i] -= mean_gradient[i] * learning_rate * mean_gradient_adjust / (sqrt(mean_squared_gradient[i] * mean_squared_gradient_adjust) + epsilon); gradient[i] = 0.0f; } } //------------------------------------------------------------------------------------------- __global__ void sgd_optimize(float* parameters, float* gradient, float learning_rate, float batch_size, int parameters_size, float momentum) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < parameters_size; i += stride) { gradient[i] /= batch_size; parameters[i] -= gradient[i] * learning_rate; gradient[i] *= batch_size * momentum; } } //------------------------------------------------------------------------------------ __global__ void add_arrays(float* input_1, float* input_2, float* output, int size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < size; i += stride) { output[i] = input_1[i] + input_2[i]; } } } }
d6f10f3b7565255eb0bad1696aaa8645ee904f16.cu
#include <algorithm> #include "CUDA_func.h" namespace NN { namespace CUDA { __global__ void compute_dense_layer(float* input, float* parameters, float* output, int input_size, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < output_size; c += stride) { output[c] = 0; for (int i = 0; i < input_size; i++) { output[c] += input[i] * parameters[c * (input_size + 1) + i]; } output[c] += parameters[c * (input_size + 1) + input_size]; } } __global__ void backprop_dense_layer_input_gradient(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_size, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < input_size; c += stride) { for (int i = 0; i < output_size; i++) { input_gradient[c] += parameters[i * (input_size + 1) + c] * output_gradient[i]; gradient[i * (input_size + 1) + c] += input[c] * output_gradient[i]; } } } __global__ void backprop_dense_layer_bias(float* gradient, float* output_gradient, int input_size, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < output_size; c += stride) { gradient[c * (input_size + 1) + input_size] += output_gradient[c]; } } //------------------------------------------------------------------------------------------- __global__ void compute_conv_layer(float* input, float* parameters, float* output, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int weights_offset; int input_pos; int x, y, z; for (int c = index; c < output_size; c += stride) { output[c] = 0.0f; x = c % layer_width; y = (c / layer_width) % layer_height; z = c / (layer_width * layer_height); weights_offset = z * (neuron_size + 1); for (int k = 0; k < input_depth; k++) { for (int j = 0; j < neuron_height; j++) { for (int i = 0; i < neuron_width; i++) { input_pos = ((k * input_height) + (y+j))*input_width + (x+i); output[c] += input[input_pos] * parameters[weights_offset + (((k * neuron_height) + j) * neuron_width) + i]; } } } output[c] += parameters[weights_offset + neuron_size]; } } __global__ void backprop_conv_layer_input(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int weights_offset; int output_pos; int x, y, z; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = (c / (input_width * input_height)) % input_depth; weights_offset = z * (neuron_width * neuron_height); for (int k = 0; k < layer_depth; k++) { for (int j = 0; j < neuron_height && y-j >= 0; j++) { for (int i = 0; i < neuron_width && x-i >= 0; i++) { output_pos = ((k * layer_height) + (y - j)) * layer_width + (x - i); input_gradient[c] += output_gradient[output_pos] * parameters[weights_offset + k*(neuron_size + 1) + j*neuron_width + i]; } } } } } __global__ void backprop_conv_layer_weights(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int weights_offset; int input_pos; int x, y; for (int c = index; c < layer_depth*input_depth; c += stride) { x = c % input_depth; y = c / input_depth; weights_offset = (y * (neuron_size+1)) + (x * neuron_height * neuron_width); for (int j = 0; j < layer_height; j++) { for (int i = 0; i < layer_width; i++) { for (int jn = 0; jn < neuron_height; jn++) { for (int in = 0; in < neuron_width; in++) { input_pos = ((x * input_height) + (j + jn)) * input_width + (i + in); gradient[weights_offset + jn * neuron_width + in] += output_gradient[((y * layer_height) + j) * layer_width + i] * input[input_pos]; } } } } } } __global__ void backprop_conv_layer_bias(float* input, float* input_gradient, float* parameters, float* gradient, float* output_gradient, int input_width, int input_height, int input_depth, int layer_width, int layer_height, int layer_depth, int neuron_width, int neuron_height, int input_size, int output_size, int layer_size, int neuron_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int c = index; c < layer_depth; c += stride) { for (int j = 0; j < layer_height; j++) { for (int i = 0; i < layer_width; i++) { gradient[c * (neuron_size + 1) + neuron_size] += output_gradient[(c * layer_height + j) * layer_width + i]; } } } } //------------------------------------------------------------------------------------------- __global__ void compute_padding_layer(float* input, float* output, int input_width, int input_height, int input_depth, int output_width, int output_height, int output_depth, int offset_width, int offset_height, int offset_depth, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z, output_pos; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); output_pos = (((offset_depth + z) * output_height) + (offset_height + y)) * output_width + (offset_width + x); output[output_pos] = input[c]; } } __global__ void backprop_padding_layer(float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int output_width, int output_height, int output_depth, int offset_width, int offset_height, int offset_depth, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z, output_pos; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); output_pos = (((offset_depth + z) * output_height) + (offset_height + y)) * output_width + (offset_width + x); input_gradient[c] += output_gradient[output_pos]; } } //------------------------------------------------------------------------------------------- __global__ void set_input_layer(float* input, float* output, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < input_size; i += stride) { output[i] = input[i]; } } //------------------------------------------------------------------------------------------- __global__ void compute_pool_max_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int input_id; float max_input = -1e38f; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x *= filter_width; y *= filter_height; z *= filter_depth; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { input_id = ((k * input_height) + j) * input_width + i; max_input = max(max_input, input[input_id]); } } } output[c] = max_input; } } __global__ void backprop_pool_max_layer(float* input, float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int input_id, mx_in_id; float max_input = -1e38f; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x *= filter_width; y *= filter_height; z *= filter_depth; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { input_id = ((k * input_height) + j) * input_width + i; if (input[input_id] > max_input) { max_input = input[input_id]; mx_in_id = input_id; } } } } input_gradient[mx_in_id] += output_gradient[c]; } } //------------------------------------------------------------------------------------ __global__ void compute_pool_avg_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size, float filter_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int input_id; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x *= filter_width; y *= filter_height; z *= filter_depth; output[c] = 0.0f; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { input_id = ((k * input_height) + j) * input_width + i; output[c] += input[input_id]; } } } output[c] /= filter_size; } } __global__ void backprop_pool_avg_layer(float* input, float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int input_size, float filter_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); x /= filter_width; y /= filter_height; z /= filter_depth; input_gradient[c] += output_gradient[((z * output_height) + y) * output_width + x]/filter_size; } } //------------------------------------------------------------------------------------ __global__ void compute_upscale_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int output_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; for (int c = index; c < output_size; c += stride) { x = c % output_width; y = (c / output_width) % output_height; z = c / (output_width * output_height); x /= filter_width; y /= filter_height; z /= filter_depth; output[c] = input[((z*input_height) + y)*input_width + x]; } } __global__ void backprop_upscale_layer(float* input, float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_width, int output_height, int output_depth, int input_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y, z; int output_id; for (int c = index; c < input_size; c += stride) { x = c % input_width; y = (c / input_width) % input_height; z = c / (input_width * input_height); x *= filter_width; y *= filter_height; z *= filter_depth; for (int k = z; k < z + filter_depth; k++) { for (int j = y; j < y + filter_height; j++) { for (int i = x; i < x + filter_width; i++) { output_id = ((k * output_height) + j) * output_width + i; input_gradient[c] += output_gradient[output_id]; } } } } } //------------------------------------------------------------------------------------ __global__ void compute_gram_layer(float* input, float* output, int input_size, int output_size, int vectors, int vector_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y; for (int c = index; c < output_size; c += stride) { x = c % vectors; y = c / vectors; output[c] = 0.0f; for (int i = 0; i < vector_size; i++) { output[c] += input[x * vector_size + i] * input[y * vector_size + i];// / vector_size; } } } __global__ void backprop_gram_layer(float* input, float* input_gradient, float* output_gradient, int input_size, int output_size, int vectors, int vector_size, float denominator) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int x, y; for (int c = index; c < input_size; c += stride) { x = c % vector_size; y = c / vector_size; for (int i = 0; i < vectors; i++) { input_gradient[c] += input[i * vector_size + x] * output_gradient[y * vectors + i];// / vector_size; } } } //------------------------------------------------------------------------------------ __global__ void compute_rearrange_layer(float* input, float* output, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_size, int sample_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int offset, pos; int x, y, z; int x_offset, y_offset, z_offset; for (int c = index; c < output_size; c += stride) { offset = c / sample_size; pos = c % sample_size; x_offset = offset % filter_width; y_offset = (offset / filter_width) % filter_height; z_offset = offset / (filter_width * filter_height); pos *= filter_width; x = (pos % input_width) + x_offset; pos /= input_width; pos *= filter_height; y = (pos % input_height) + y_offset; pos /= input_height; pos *= filter_depth; z = pos + z_offset; pos = (z * input_height + y) * input_width + x; output[c] = input[pos]; } } __global__ void backprop_rearrange_layer(float* input_gradient, float* output_gradient, int input_width, int input_height, int input_depth, int filter_width, int filter_height, int filter_depth, int output_size, int sample_size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int offset, pos; int x, y, z; int x_offset, y_offset, z_offset; for (int c = index; c < output_size; c += stride) { offset = c / sample_size; pos = c % sample_size; x_offset = offset % filter_width; y_offset = (offset / filter_width) % filter_height; z_offset = offset / (filter_width * filter_height); pos *= filter_width; x = (pos % input_width) + x_offset; pos /= input_width; pos *= filter_height; y = (pos % input_height) + y_offset; pos /= input_height; pos *= filter_depth; z = pos + z_offset; pos = (z * input_height + y) * input_width + x; input_gradient[pos] += output_gradient[c]; } } //------------------------------------------------------------------------------------------- __global__ void adam_optimize(float* parameters, float* gradient, float* mean_gradient, float* mean_squared_gradient, float learning_rate, float batch_size, int parameters_size, float beta1, float beta2, float epsilon, float mean_gradient_adjust, float mean_squared_gradient_adjust) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < parameters_size; i+= stride) { gradient[i] /= batch_size; mean_gradient[i] = beta1 * mean_gradient[i] + (1.0 - beta1) * gradient[i]; mean_squared_gradient[i] = beta2 * mean_squared_gradient[i] + (1.0 - beta2) * gradient[i] * gradient[i]; parameters[i] -= mean_gradient[i] * learning_rate * mean_gradient_adjust / (sqrt(mean_squared_gradient[i] * mean_squared_gradient_adjust) + epsilon); gradient[i] = 0.0f; } } //------------------------------------------------------------------------------------------- __global__ void sgd_optimize(float* parameters, float* gradient, float learning_rate, float batch_size, int parameters_size, float momentum) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < parameters_size; i += stride) { gradient[i] /= batch_size; parameters[i] -= gradient[i] * learning_rate; gradient[i] *= batch_size * momentum; } } //------------------------------------------------------------------------------------ __global__ void add_arrays(float* input_1, float* input_2, float* output, int size) { int index = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; for (int i = index; i < size; i += stride) { output[i] = input_1[i] + input_2[i]; } } } }
901b61c2382ba0df9efdc46e01e950779f820701.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /// /// Copyright (c) 2018, Intel Corporation /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// * Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above /// copyright notice, this list of conditions and the following /// disclaimer in the documentation and/or other materials provided /// with the distribution. /// * Neither the name of Intel Corporation nor the names of its /// contributors may be used to endorse or promote products /// derived from this software without specific prior written /// permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS /// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT /// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE /// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, /// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, /// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; /// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT /// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN /// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////// /// /// NAME: dgemm /// /// PURPOSE: This program tests the efficiency with which a dense matrix /// dense multiplication is carried out /// /// USAGE: The program takes as input the matrix order, /// the number of times the matrix-matrix multiplication /// is carried out, and, optionally, a tile size for matrix /// blocking /// /// <progname> <# iterations> <matrix order> [<batches>] /// /// The output consists of diagnostics to make sure the /// algorithm worked, and of timing statistics. /// /// FUNCTIONS CALLED: /// /// Other than OpenMP or standard C functions, the following /// functions are used in this program: /// /// cblasDgemm() /// hipblasDgemmStridedBatched() /// /// HISTORY: Written by Rob Van der Wijngaart, February 2009. /// Converted to C++11 by Jeff Hammond, December, 2017. /// ////////////////////////////////////////////////////////////////////// #include "prk_util.h" #include "prk_cuda.h" __global__ void init(int order, const int matrices, double * A, double * B, double * C) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; for (int b=0; b<matrices; ++b) { if ((i<order) && (j<order)) { A[b*order*order+i*order+j] = i; B[b*order*order+i*order+j] = i; C[b*order*order+i*order+j] = 0; } } } __global__ void init(int order, const int matrices, double * C) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; for (int b=0; b<matrices; ++b) { if ((i<order) && (j<order)) { C[b*order*order+i*order+j] = 0; } } } void prk_dgemm(const hipblasHandle_t & h, const int order, const int batches, double * A, double * B, double * C) { const double alpha = 1.0; const double beta = 1.0; for (int b=0; b<batches; ++b) { double * pA = &(A[b*order*order]); double * pB = &(B[b*order*order]); double * pC = &(C[b*order*order]); prk::CUDA::check( hipblasDgemm(h, HIPBLAS_OP_N, HIPBLAS_OP_N, // opA, opB order, order, order, // m, n, k &alpha, // alpha pA, order, // A, lda pB, order, // B, ldb &beta, // beta pC, order) ); // C, ldc } } void prk_bgemm(const hipblasHandle_t & h, const int order, const int batches, double * A, double * B, double * C) { const double alpha = 1.0; const double beta = 1.0; prk::CUDA::check( hipblasDgemmStridedBatched(h, HIPBLAS_OP_N, HIPBLAS_OP_N, order, order, order, &alpha, (const double *)A, order, order*order, (const double *)B, order, order*order, &beta, C, order, order*order, batches) ); // hipblasStatus_t hipblasDgemmBatched(hipblasHandle_t handle, // hipblasOperation_t transa, // hipblasOperation_t transb, // int m, int n, int k, // const double *alpha, // const double *Aarray[], int lda, // const double *Barray[], int ldb, // const double *beta, // double *Carray[], int ldc, // int batchCount) } int main(int argc, char * argv[]) { std::cout << "Parallel Research Kernels version " << PRKVERSION << std::endl; std::cout << "C++11/CUBLAS Dense matrix-matrix multiplication: C += A x B" << std::endl; prk::CUDA::info info; info.print(); ////////////////////////////////////////////////////////////////////// /// Read and test input parameters ////////////////////////////////////////////////////////////////////// int iterations; int order; int batches = 0; int use_ngpu = 1; try { if (argc < 2) { throw "Usage: <# iterations> <matrix order> [<batches>] [<use_ngpu>]"; } iterations = std::atoi(argv[1]); if (iterations < 1) { throw "ERROR: iterations must be >= 1"; } order = std::atoi(argv[2]); if (order <= 0) { throw "ERROR: Matrix Order must be greater than 0"; } else if (order > ::floor(std::sqrt(INT_MAX))) { throw "ERROR: matrix dimension too large - overflow risk"; } if (argc>3) { batches = std::atoi(argv[3]); } if (argc>4) { use_ngpu = std::atoi(argv[4]); } } catch (const char * e) { std::cout << e << std::endl; return 1; } std::cout << "Number of iterations = " << iterations << std::endl; std::cout << "Matrix order = " << order << std::endl; if (batches == 0) { std::cout << "No batching" << std::endl; } else if (batches < 0) { std::cout << "Batch size = " << -batches << " (loop over legacy BLAS)" << std::endl; } else if (batches > 0) { std::cout << "Batch size = " << batches << " (batched BLAS)" << std::endl; } std::cout << "Number of GPUs to use = " << use_ngpu << std::endl; int haz_ngpu = info.num_gpus(); std::cout << "Number of GPUs found = " << haz_ngpu << std::endl; if (use_ngpu > haz_ngpu) { std::cout << "You cannot use more GPUs (" << use_ngpu << ") than you have (" << haz_ngpu << ")" << std::endl; } int ngpus = use_ngpu; std::vector<hipblasHandle_t> contexts(ngpus); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); prk::CUDA::check( hipblasCreate(&contexts[i]) ); } const int tile_size = 32; dim3 dimGrid(prk::divceil(order,tile_size),prk::divceil(order,tile_size),1); dim3 dimBlock(tile_size, tile_size, 1); info.checkDims(dimBlock, dimGrid); ////////////////////////////////////////////////////////////////////// // Allocate space for matrices ////////////////////////////////////////////////////////////////////// double dgemm_time(0); const int matrices = (batches==0 ? 1 : abs(batches)); const size_t nelems = (size_t)order * (size_t)order; const size_t bytes = nelems * sizeof(double); // host buffers std::vector<double*> h_c(ngpus,nullptr); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipHostMalloc((void**)&h_c[i], matrices*bytes) ); } // device buffers std::vector<double*> d_a(ngpus,nullptr); std::vector<double*> d_b(ngpus,nullptr); std::vector<double*> d_c(ngpus,nullptr); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); prk::CUDA::check( hipMalloc((void**)&d_a[i], matrices*bytes) ); prk::CUDA::check( hipMalloc((void**)&d_b[i], matrices*bytes) ); prk::CUDA::check( hipMalloc((void**)&d_c[i], matrices*bytes) ); hipLaunchKernelGGL(( init), dim3(dimGrid), dim3(dimBlock), 0, 0, order, matrices, d_a[i], d_b[i], d_c[i]); } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); prk::CUDA::check( hipDeviceSynchronize() ); } for (int iter = 0; iter<=iterations; iter++) { if (iter==1) dgemm_time = prk::wtime(); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); if (batches == 0) { prk_dgemm(contexts[i], order, matrices, d_a[i], d_b[i], d_c[i]); } else if (batches < 0) { prk_dgemm(contexts[i], order, matrices, d_a[i], d_b[i], d_c[i]); } else if (batches > 0) { prk_bgemm(contexts[i], order, matrices, d_a[i], d_b[i], d_c[i]); } } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); prk::CUDA::check( hipDeviceSynchronize() ); } } dgemm_time = prk::wtime() - dgemm_time; // copy output back to host for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); prk::CUDA::check( hipMemcpyAsync(h_c[i], d_c[i], matrices*bytes, hipMemcpyDeviceToHost) ); } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipSetDevice(i) ); prk::CUDA::check( hipDeviceSynchronize() ); prk::CUDA::check( hipFree(d_c[i]) ); prk::CUDA::check( hipFree(d_b[i]) ); prk::CUDA::check( hipFree(d_a[i]) ); prk::CUDA::check( hipblasDestroy(contexts[i]) ); } ////////////////////////////////////////////////////////////////////// /// Analyze and output results ////////////////////////////////////////////////////////////////////// const double epsilon = 1.0e-8; const double forder = static_cast<double>(order); const double reference = 0.25 * ::pow(forder,3) * ::pow(forder-1.0,2) * (iterations+1); double residuum(0); for (int i=0; i<ngpus; ++i) { for (int b=0; b<matrices; ++b) { const auto checksum = prk::reduce( &(h_c[i][b*order*order+0]), &(h_c[i][b*order*order+nelems]), 0.0); residuum += std::abs(checksum-reference)/reference; } } residuum/=matrices; residuum/=ngpus; if (residuum < epsilon) { #if VERBOSE std::cout << "Reference checksum = " << reference << "\n" << "Actual checksum = " << checksum << std::endl; #endif std::cout << "Solution validates" << std::endl; auto avgtime = dgemm_time/iterations/matrices; auto nflops = 2.0 * ::pow(forder,3) * ngpus; std::cout << "Rate (MF/s): " << 1.0e-6 * nflops/avgtime << " Avg time (s): " << avgtime << std::endl; } else { std::cout << "Reference checksum = " << reference << "\n" << "Residuum = " << residuum << std::endl; return 1; } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( hipHostFree(h_c[i]) ); } return 0; }
901b61c2382ba0df9efdc46e01e950779f820701.cu
/// /// Copyright (c) 2018, Intel Corporation /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// * Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above /// copyright notice, this list of conditions and the following /// disclaimer in the documentation and/or other materials provided /// with the distribution. /// * Neither the name of Intel Corporation nor the names of its /// contributors may be used to endorse or promote products /// derived from this software without specific prior written /// permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS /// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT /// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE /// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, /// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, /// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; /// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT /// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN /// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////// /// /// NAME: dgemm /// /// PURPOSE: This program tests the efficiency with which a dense matrix /// dense multiplication is carried out /// /// USAGE: The program takes as input the matrix order, /// the number of times the matrix-matrix multiplication /// is carried out, and, optionally, a tile size for matrix /// blocking /// /// <progname> <# iterations> <matrix order> [<batches>] /// /// The output consists of diagnostics to make sure the /// algorithm worked, and of timing statistics. /// /// FUNCTIONS CALLED: /// /// Other than OpenMP or standard C functions, the following /// functions are used in this program: /// /// cblasDgemm() /// cublasDgemmStridedBatched() /// /// HISTORY: Written by Rob Van der Wijngaart, February 2009. /// Converted to C++11 by Jeff Hammond, December, 2017. /// ////////////////////////////////////////////////////////////////////// #include "prk_util.h" #include "prk_cuda.h" __global__ void init(int order, const int matrices, double * A, double * B, double * C) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; for (int b=0; b<matrices; ++b) { if ((i<order) && (j<order)) { A[b*order*order+i*order+j] = i; B[b*order*order+i*order+j] = i; C[b*order*order+i*order+j] = 0; } } } __global__ void init(int order, const int matrices, double * C) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y; for (int b=0; b<matrices; ++b) { if ((i<order) && (j<order)) { C[b*order*order+i*order+j] = 0; } } } void prk_dgemm(const cublasHandle_t & h, const int order, const int batches, double * A, double * B, double * C) { const double alpha = 1.0; const double beta = 1.0; for (int b=0; b<batches; ++b) { double * pA = &(A[b*order*order]); double * pB = &(B[b*order*order]); double * pC = &(C[b*order*order]); prk::CUDA::check( cublasDgemm(h, CUBLAS_OP_N, CUBLAS_OP_N, // opA, opB order, order, order, // m, n, k &alpha, // alpha pA, order, // A, lda pB, order, // B, ldb &beta, // beta pC, order) ); // C, ldc } } void prk_bgemm(const cublasHandle_t & h, const int order, const int batches, double * A, double * B, double * C) { const double alpha = 1.0; const double beta = 1.0; prk::CUDA::check( cublasDgemmStridedBatched(h, CUBLAS_OP_N, CUBLAS_OP_N, order, order, order, &alpha, (const double *)A, order, order*order, (const double *)B, order, order*order, &beta, C, order, order*order, batches) ); // cublasStatus_t cublasDgemmBatched(cublasHandle_t handle, // cublasOperation_t transa, // cublasOperation_t transb, // int m, int n, int k, // const double *alpha, // const double *Aarray[], int lda, // const double *Barray[], int ldb, // const double *beta, // double *Carray[], int ldc, // int batchCount) } int main(int argc, char * argv[]) { std::cout << "Parallel Research Kernels version " << PRKVERSION << std::endl; std::cout << "C++11/CUBLAS Dense matrix-matrix multiplication: C += A x B" << std::endl; prk::CUDA::info info; info.print(); ////////////////////////////////////////////////////////////////////// /// Read and test input parameters ////////////////////////////////////////////////////////////////////// int iterations; int order; int batches = 0; int use_ngpu = 1; try { if (argc < 2) { throw "Usage: <# iterations> <matrix order> [<batches>] [<use_ngpu>]"; } iterations = std::atoi(argv[1]); if (iterations < 1) { throw "ERROR: iterations must be >= 1"; } order = std::atoi(argv[2]); if (order <= 0) { throw "ERROR: Matrix Order must be greater than 0"; } else if (order > std::floor(std::sqrt(INT_MAX))) { throw "ERROR: matrix dimension too large - overflow risk"; } if (argc>3) { batches = std::atoi(argv[3]); } if (argc>4) { use_ngpu = std::atoi(argv[4]); } } catch (const char * e) { std::cout << e << std::endl; return 1; } std::cout << "Number of iterations = " << iterations << std::endl; std::cout << "Matrix order = " << order << std::endl; if (batches == 0) { std::cout << "No batching" << std::endl; } else if (batches < 0) { std::cout << "Batch size = " << -batches << " (loop over legacy BLAS)" << std::endl; } else if (batches > 0) { std::cout << "Batch size = " << batches << " (batched BLAS)" << std::endl; } std::cout << "Number of GPUs to use = " << use_ngpu << std::endl; int haz_ngpu = info.num_gpus(); std::cout << "Number of GPUs found = " << haz_ngpu << std::endl; if (use_ngpu > haz_ngpu) { std::cout << "You cannot use more GPUs (" << use_ngpu << ") than you have (" << haz_ngpu << ")" << std::endl; } int ngpus = use_ngpu; std::vector<cublasHandle_t> contexts(ngpus); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); prk::CUDA::check( cublasCreate(&contexts[i]) ); } const int tile_size = 32; dim3 dimGrid(prk::divceil(order,tile_size),prk::divceil(order,tile_size),1); dim3 dimBlock(tile_size, tile_size, 1); info.checkDims(dimBlock, dimGrid); ////////////////////////////////////////////////////////////////////// // Allocate space for matrices ////////////////////////////////////////////////////////////////////// double dgemm_time(0); const int matrices = (batches==0 ? 1 : abs(batches)); const size_t nelems = (size_t)order * (size_t)order; const size_t bytes = nelems * sizeof(double); // host buffers std::vector<double*> h_c(ngpus,nullptr); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaMallocHost((void**)&h_c[i], matrices*bytes) ); } // device buffers std::vector<double*> d_a(ngpus,nullptr); std::vector<double*> d_b(ngpus,nullptr); std::vector<double*> d_c(ngpus,nullptr); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); prk::CUDA::check( cudaMalloc((void**)&d_a[i], matrices*bytes) ); prk::CUDA::check( cudaMalloc((void**)&d_b[i], matrices*bytes) ); prk::CUDA::check( cudaMalloc((void**)&d_c[i], matrices*bytes) ); init<<<dimGrid, dimBlock>>>(order, matrices, d_a[i], d_b[i], d_c[i]); } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); prk::CUDA::check( cudaDeviceSynchronize() ); } for (int iter = 0; iter<=iterations; iter++) { if (iter==1) dgemm_time = prk::wtime(); for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); if (batches == 0) { prk_dgemm(contexts[i], order, matrices, d_a[i], d_b[i], d_c[i]); } else if (batches < 0) { prk_dgemm(contexts[i], order, matrices, d_a[i], d_b[i], d_c[i]); } else if (batches > 0) { prk_bgemm(contexts[i], order, matrices, d_a[i], d_b[i], d_c[i]); } } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); prk::CUDA::check( cudaDeviceSynchronize() ); } } dgemm_time = prk::wtime() - dgemm_time; // copy output back to host for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); prk::CUDA::check( cudaMemcpyAsync(h_c[i], d_c[i], matrices*bytes, cudaMemcpyDeviceToHost) ); } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaSetDevice(i) ); prk::CUDA::check( cudaDeviceSynchronize() ); prk::CUDA::check( cudaFree(d_c[i]) ); prk::CUDA::check( cudaFree(d_b[i]) ); prk::CUDA::check( cudaFree(d_a[i]) ); prk::CUDA::check( cublasDestroy(contexts[i]) ); } ////////////////////////////////////////////////////////////////////// /// Analyze and output results ////////////////////////////////////////////////////////////////////// const double epsilon = 1.0e-8; const double forder = static_cast<double>(order); const double reference = 0.25 * std::pow(forder,3) * std::pow(forder-1.0,2) * (iterations+1); double residuum(0); for (int i=0; i<ngpus; ++i) { for (int b=0; b<matrices; ++b) { const auto checksum = prk::reduce( &(h_c[i][b*order*order+0]), &(h_c[i][b*order*order+nelems]), 0.0); residuum += std::abs(checksum-reference)/reference; } } residuum/=matrices; residuum/=ngpus; if (residuum < epsilon) { #if VERBOSE std::cout << "Reference checksum = " << reference << "\n" << "Actual checksum = " << checksum << std::endl; #endif std::cout << "Solution validates" << std::endl; auto avgtime = dgemm_time/iterations/matrices; auto nflops = 2.0 * std::pow(forder,3) * ngpus; std::cout << "Rate (MF/s): " << 1.0e-6 * nflops/avgtime << " Avg time (s): " << avgtime << std::endl; } else { std::cout << "Reference checksum = " << reference << "\n" << "Residuum = " << residuum << std::endl; return 1; } for (int i=0; i<ngpus; ++i) { prk::CUDA::check( cudaFreeHost(h_c[i]) ); } return 0; }
1ac627b382c9158012a70871226578dbb63f1272.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <dcgn/dcgn.h> #include <dcgn/CUDAFunctions.h> #include "samples/Body.cxx" #include <cstdio> #include <cstdlib> #include <sys/time.h> #define BARRIER_BEFORE_BIG_COMM 1 #define CHECK_ERR() \ { \ hipError_t err = hipGetLastError(); \ if (err != hipSuccess) \ { \ fprintf(stderr, "%s.%s.%d: %s\n", __FILE__, __FUNCTION__, __LINE__, hipGetErrorString(err)); \ fflush(stderr); \ exit(1); \ } \ } \ typedef struct _KernelInfo { int n, timeSteps; char * input, * output; float timeDelta; } KernelInfo; __device__ void block_memcpy(void * dstMem, const void * srcMem, const int size); __device__ void block_memcpy2(void * dstMem, const void * srcMem, const int size); __device__ void updateForces(Body * bodies, Body * ubodies, const int startBody, const int endBody, const int n, const float timeDelta); __host__ void runKernel(Body * bodies, Body * gpuBodies, Body * gpuUpdatedBodies, const int n, const int timeSteps, const float timeDelta); __host__ void nbodyWrapper(void * kernelInfo, const dcgn::GPUInitRequest libParam, const uint3 & gridSize, const uint3 & blockSize, const int sharedMemSize, hipStream_t * const stream); void nbodyTimer(void * kernelInfo); __global__ void nbody(dcgn::GPUInitRequest libParam, Body * gpuBodies, Body * gpuUpdatedBodies, volatile int * sbarr, const int size, const int timeSteps, const float timeDelta); __device__ __host__ int getIndexForRank(const int rank, const int size, const int n); __device__ void __syncblocks(volatile int * sbarr); int main(int argc, char ** argv) { int gpus[] = { 0, 1, -1 }; uint3 gs = { 12, 1, 1 }, bs = { 128, 1, 1 }; dcgn::initAll(&argc, &argv, 1, gpus, 1, 0, -1); if (argc != 5) { dcgn::finalize(); return 0; } FILE * fp = fopen(argv[1], "rb"); KernelInfo kinfo; fread(&kinfo.n, sizeof(int), 1, fp); fread(&kinfo.timeSteps, sizeof(int), 1, fp); fclose(fp); kinfo.input = argv[1]; kinfo.output = argv[2]; sscanf(argv[3], "%d", &kinfo.timeSteps); sscanf(argv[4], "%f", &kinfo.timeDelta); dcgn::launchCPUKernel(0, nbodyTimer, reinterpret_cast<void * >(&kinfo)); dcgn::launchGPUKernel(0, nbodyWrapper, 0, reinterpret_cast<void * >(&kinfo), gs, bs); dcgn::launchGPUKernel(1, nbodyWrapper, 0, reinterpret_cast<void * >(&kinfo), gs, bs); dcgn::finalize(); return 0; } __host__ void nbodyWrapper(void * kernelInfo, const dcgn::GPUInitRequest libParam, const uint3 & gridSize, const uint3 & blockSize, const int sharedMemSize, hipStream_t * const stream) { KernelInfo * const kinfo = reinterpret_cast<KernelInfo * >(kernelInfo); Body * gpuBodies, * gpuUpdatedBodies; volatile int * sbarr; hipMalloc(reinterpret_cast<void ** >(const_cast<int ** >(&sbarr)), sizeof(int) * gridSize.x); CHECK_ERR(); hipMalloc(reinterpret_cast<void ** >(&gpuBodies), sizeof(Body) * kinfo->n); CHECK_ERR(); hipMalloc(reinterpret_cast<void ** >(&gpuUpdatedBodies), sizeof(Body) * kinfo->n); CHECK_ERR(); hipMemset(const_cast<int * >(sbarr), 0, sizeof(int) * gridSize.x); CHECK_ERR(); hipLaunchKernelGGL(( nbody), dim3(gridSize), dim3(blockSize), sharedMemSize, *stream, libParam, gpuBodies, gpuUpdatedBodies, sbarr, kinfo->n, kinfo->timeSteps, kinfo->timeDelta); CHECK_ERR(); } void nbodyTimer(void * kernelInfo) { KernelInfo * kinfo = reinterpret_cast<KernelInfo * >(kernelInfo); Body * storage = new Body[kinfo->n]; if (dcgn::getRank() == 0) { int dummy[2]; FILE * fp = fopen(kinfo->input, "rb"); fread(dummy, sizeof(dummy), 1, fp); fread(storage, sizeof(Body) * kinfo->n, 1, fp); fclose(fp); } dcgn::broadcast(0, storage, sizeof(Body) * kinfo->n); dcgn::barrier(); double t = dcgn::wallTime(); for (int i = 0; i < kinfo->timeSteps; ++i) { int sizeIndex = 0, actualSize = dcgn::getSize() * 2 / 3; for (int j = 0; j < dcgn::getSize(); ++j) { if (j % 3 != 0) { const int start = getIndexForRank(sizeIndex, actualSize, kinfo->n); const int end = getIndexForRank(sizeIndex + 1, actualSize, kinfo->n); /* for (int k = 0; k < dcgn::globalGPUCount(); ++k) { int tvar; dcgn::recv(dcgn::getGPUID(k, 0), &tvar, sizeof(int), &stat); // printf("rank 1 - end =%d.\n", tvar); fflush(stdout); } */ // dcgn::barrier(); dcgn::broadcast(j, storage, (end - start) * sizeof(Body)); ++sizeIndex; } } #if BARRIER_BEFORE_BIG_COMM dcgn::barrier(); #endif } dcgn::barrier(); t = dcgn::wallTime() - t; if (dcgn::getRank() == 0) { printf("done, took %.6f seconds.\n", t); } delete [] storage; } __shared__ char mem[16 * 1024 - 256]; // 16k - 256bytes for some system stuff. __device__ int buf; __global__ void nbody(dcgn::GPUInitRequest libParam, Body * gpuBodies, Body * gpuUpdatedBodies, volatile int * sbarr, const int size, const int timeSteps, const float timeDelta) { if (blockIdx.x == 0 && threadIdx.x == 0) { // printf("initting.\n"); fflush(stdout); dcgn::gpu::init(libParam); // printf("%d.%d.%d: broadcasting.\n", dcgn::gpu::getRank(), blockIdx.x, threadIdx.x); fflush(stdout); dcgn::gpu::broadcast(0, 0, gpuBodies, size * sizeof(Body)); // printf("%d.%d.%d: barriering.\n", dcgn::gpu::getRank(), blockIdx.x, threadIdx.x); fflush(stdout); dcgn::gpu::barrier(0); // printf("%d.%d.%d: executing.\n", dcgn::gpu::getRank(), blockIdx.x, threadIdx.x); fflush(stdout); } const int START_BODY = getIndexForRank(dcgn::gpu::getRank(0), dcgn::gpu::getSize(), size); const int END_BODY = getIndexForRank(dcgn::gpu::getRank(0) + 1, dcgn::gpu::getSize(), size); for (int i = 0; i < timeSteps; ++i) { updateForces(gpuBodies, gpuUpdatedBodies, START_BODY, END_BODY, size, timeDelta); __syncblocks(sbarr); if (threadIdx.x == 0 && blockIdx.x == 0) { int sizeIndex = 0, actualSize = dcgn::gpu::getSize() * 2 / 3; for (int j = 0; j < dcgn::gpu::getSize(); ++j) { if (j % 3 != 0) { const int start = getIndexForRank(sizeIndex, actualSize, size); const int end = getIndexForRank(sizeIndex + 1, actualSize, size); // buf = end; dcgn::gpu::send(0, 0, &buf, sizeof(int)); // printf("dcgn::broadcast(slot=%d, root=%d, buf=%p (%p + %d * %d), size=%d( (%d - %d) * %d) )).\n", // 0, j, gpuUpdatedBodies + start, gpuUpdatedBodies, start, (int)sizeof(Body), (end - start) * (int)sizeof(Body), end, start, (int)sizeof(Body)); // fflush(stdout); // dcgn::gpu::barrier(0); dcgn::gpu::broadcast(0, j, gpuUpdatedBodies + start, (end - start) * sizeof(Body)); ++sizeIndex; } } #if BARRIER_BEFORE_BIG_COMM dcgn::gpu::barrier(0); #endif } __syncblocks(sbarr); Body * tmp = gpuBodies; gpuBodies = gpuUpdatedBodies; gpuUpdatedBodies = tmp; } if (blockIdx.x == 0 && threadIdx.x == 0) { dcgn::gpu::barrier(0); } } __device__ void updateForces(Body * bodies, Body * ubodies, const int startBody, const int endBody, const int n, const float timeDelta) { // load up 2 bodies per thread. then load up one body per thread for work. const int BODY_START = startBody + blockDim.x * blockIdx.x; const int BODY_STRIDE = blockDim.x * gridDim.x; for (int i = BODY_START; i < endBody; i += BODY_STRIDE) { const int NUM_BODIES = (i + blockDim.x <= endBody ? blockDim.x : endBody - i); Body * sharedBodies = reinterpret_cast<Body * >(mem); Body * localBodies = reinterpret_cast<Body * >(mem + NUM_BODIES * sizeof(Body)); block_memcpy(sharedBodies, bodies + i, NUM_BODIES * sizeof(Body)); if (threadIdx.x < NUM_BODIES) { for (int j = 0; j < n; j += blockDim.x * 2) { const int NUM_BODIES2 = (j + blockDim.x * 2 <= n ? 2 * blockDim.x : n - j); block_memcpy(localBodies, bodies + j, NUM_BODIES2 * sizeof(Body)); for (int k = 0; k < NUM_BODIES2; ++k) { sharedBodies[threadIdx.x].addForceFrom(localBodies[k]); } } sharedBodies[threadIdx.x].update(timeDelta); } block_memcpy2(ubodies + i, sharedBodies, NUM_BODIES * sizeof(Body)); } } __device__ __host__ int getIndexForRank(const int rank, const int size, const int n) { if (rank == 0) return 0; if (rank == size) return n; float f = static_cast<float>(rank) / static_cast<float>(size) * n; return static_cast<int>(f); } __device__ void block_memcpy(void * dstMem, const void * srcMem, const int size) { char * dst = reinterpret_cast< char * >(dstMem); const char * src = reinterpret_cast<const char * >(srcMem); int rem = size; dst += threadIdx.x * sizeof(float); src += threadIdx.x * sizeof(float); __syncthreads(); while (rem >= blockDim.x * sizeof(float)) { *reinterpret_cast<float * >(dst) = *reinterpret_cast<const float * >(src); dst += blockDim.x * sizeof(float); src += blockDim.x * sizeof(float); rem -= blockDim.x * sizeof(float); } if (rem > 0 && threadIdx.x == 0) { while (rem > sizeof(float)) { reinterpret_cast<float * >(dst)[threadIdx.x] = *reinterpret_cast<const float * >(src); dst += sizeof(float); src += sizeof(float); rem -= sizeof(float); } while (rem > sizeof(char)) { *(dst++) = *(src++); --rem; } } __syncthreads(); } __device__ void block_memcpy2(void * dstMem, const void * srcMem, const int size) { char * dst = reinterpret_cast< char * >(dstMem); const char * src = reinterpret_cast<const char * >(srcMem); int rem = size; dst += threadIdx.x * sizeof(float); src += threadIdx.x * sizeof(float); __syncthreads(); while (rem >= blockDim.x * sizeof(float)) { *reinterpret_cast<float * >(dst) = *reinterpret_cast<const float * >(src); dst += blockDim.x * sizeof(float); src += blockDim.x * sizeof(float); rem -= blockDim.x * sizeof(float); } if (rem > 0 && threadIdx.x == 0) { while (rem > sizeof(float)) { reinterpret_cast<float * >(dst)[threadIdx.x] = *reinterpret_cast<const float * >(src); dst += sizeof(float); src += sizeof(float); rem -= sizeof(float); } while (rem > sizeof(char)) { *(dst++) = *(src++); --rem; } } __syncthreads(); } __device__ void __syncblocks(volatile int * sbarr) { __syncthreads(); if (threadIdx.x == 0) { sbarr[blockIdx.x] = 1; if (blockIdx.x == 0) { for (int i = 1; i < gridDim.x; ++i) while (sbarr[i] == 0) { } for (int i = 0; i < gridDim.x; ++i) sbarr[i] = 0; } while (sbarr[blockIdx.x] == 1) { } } __syncthreads(); }
1ac627b382c9158012a70871226578dbb63f1272.cu
#include <dcgn/dcgn.h> #include <dcgn/CUDAFunctions.h> #include "samples/Body.cxx" #include <cstdio> #include <cstdlib> #include <sys/time.h> #define BARRIER_BEFORE_BIG_COMM 1 #define CHECK_ERR() \ { \ cudaError_t err = cudaGetLastError(); \ if (err != cudaSuccess) \ { \ fprintf(stderr, "%s.%s.%d: %s\n", __FILE__, __FUNCTION__, __LINE__, cudaGetErrorString(err)); \ fflush(stderr); \ exit(1); \ } \ } \ typedef struct _KernelInfo { int n, timeSteps; char * input, * output; float timeDelta; } KernelInfo; __device__ void block_memcpy(void * dstMem, const void * srcMem, const int size); __device__ void block_memcpy2(void * dstMem, const void * srcMem, const int size); __device__ void updateForces(Body * bodies, Body * ubodies, const int startBody, const int endBody, const int n, const float timeDelta); __host__ void runKernel(Body * bodies, Body * gpuBodies, Body * gpuUpdatedBodies, const int n, const int timeSteps, const float timeDelta); __host__ void nbodyWrapper(void * kernelInfo, const dcgn::GPUInitRequest libParam, const uint3 & gridSize, const uint3 & blockSize, const int sharedMemSize, cudaStream_t * const stream); void nbodyTimer(void * kernelInfo); __global__ void nbody(dcgn::GPUInitRequest libParam, Body * gpuBodies, Body * gpuUpdatedBodies, volatile int * sbarr, const int size, const int timeSteps, const float timeDelta); __device__ __host__ int getIndexForRank(const int rank, const int size, const int n); __device__ void __syncblocks(volatile int * sbarr); int main(int argc, char ** argv) { int gpus[] = { 0, 1, -1 }; uint3 gs = { 12, 1, 1 }, bs = { 128, 1, 1 }; dcgn::initAll(&argc, &argv, 1, gpus, 1, 0, -1); if (argc != 5) { dcgn::finalize(); return 0; } FILE * fp = fopen(argv[1], "rb"); KernelInfo kinfo; fread(&kinfo.n, sizeof(int), 1, fp); fread(&kinfo.timeSteps, sizeof(int), 1, fp); fclose(fp); kinfo.input = argv[1]; kinfo.output = argv[2]; sscanf(argv[3], "%d", &kinfo.timeSteps); sscanf(argv[4], "%f", &kinfo.timeDelta); dcgn::launchCPUKernel(0, nbodyTimer, reinterpret_cast<void * >(&kinfo)); dcgn::launchGPUKernel(0, nbodyWrapper, 0, reinterpret_cast<void * >(&kinfo), gs, bs); dcgn::launchGPUKernel(1, nbodyWrapper, 0, reinterpret_cast<void * >(&kinfo), gs, bs); dcgn::finalize(); return 0; } __host__ void nbodyWrapper(void * kernelInfo, const dcgn::GPUInitRequest libParam, const uint3 & gridSize, const uint3 & blockSize, const int sharedMemSize, cudaStream_t * const stream) { KernelInfo * const kinfo = reinterpret_cast<KernelInfo * >(kernelInfo); Body * gpuBodies, * gpuUpdatedBodies; volatile int * sbarr; cudaMalloc(reinterpret_cast<void ** >(const_cast<int ** >(&sbarr)), sizeof(int) * gridSize.x); CHECK_ERR(); cudaMalloc(reinterpret_cast<void ** >(&gpuBodies), sizeof(Body) * kinfo->n); CHECK_ERR(); cudaMalloc(reinterpret_cast<void ** >(&gpuUpdatedBodies), sizeof(Body) * kinfo->n); CHECK_ERR(); cudaMemset(const_cast<int * >(sbarr), 0, sizeof(int) * gridSize.x); CHECK_ERR(); nbody<<<gridSize, blockSize, sharedMemSize, *stream>>>(libParam, gpuBodies, gpuUpdatedBodies, sbarr, kinfo->n, kinfo->timeSteps, kinfo->timeDelta); CHECK_ERR(); } void nbodyTimer(void * kernelInfo) { KernelInfo * kinfo = reinterpret_cast<KernelInfo * >(kernelInfo); Body * storage = new Body[kinfo->n]; if (dcgn::getRank() == 0) { int dummy[2]; FILE * fp = fopen(kinfo->input, "rb"); fread(dummy, sizeof(dummy), 1, fp); fread(storage, sizeof(Body) * kinfo->n, 1, fp); fclose(fp); } dcgn::broadcast(0, storage, sizeof(Body) * kinfo->n); dcgn::barrier(); double t = dcgn::wallTime(); for (int i = 0; i < kinfo->timeSteps; ++i) { int sizeIndex = 0, actualSize = dcgn::getSize() * 2 / 3; for (int j = 0; j < dcgn::getSize(); ++j) { if (j % 3 != 0) { const int start = getIndexForRank(sizeIndex, actualSize, kinfo->n); const int end = getIndexForRank(sizeIndex + 1, actualSize, kinfo->n); /* for (int k = 0; k < dcgn::globalGPUCount(); ++k) { int tvar; dcgn::recv(dcgn::getGPUID(k, 0), &tvar, sizeof(int), &stat); // printf("rank 1 - end =%d.\n", tvar); fflush(stdout); } */ // dcgn::barrier(); dcgn::broadcast(j, storage, (end - start) * sizeof(Body)); ++sizeIndex; } } #if BARRIER_BEFORE_BIG_COMM dcgn::barrier(); #endif } dcgn::barrier(); t = dcgn::wallTime() - t; if (dcgn::getRank() == 0) { printf("done, took %.6f seconds.\n", t); } delete [] storage; } __shared__ char mem[16 * 1024 - 256]; // 16k - 256bytes for some system stuff. __device__ int buf; __global__ void nbody(dcgn::GPUInitRequest libParam, Body * gpuBodies, Body * gpuUpdatedBodies, volatile int * sbarr, const int size, const int timeSteps, const float timeDelta) { if (blockIdx.x == 0 && threadIdx.x == 0) { // printf("initting.\n"); fflush(stdout); dcgn::gpu::init(libParam); // printf("%d.%d.%d: broadcasting.\n", dcgn::gpu::getRank(), blockIdx.x, threadIdx.x); fflush(stdout); dcgn::gpu::broadcast(0, 0, gpuBodies, size * sizeof(Body)); // printf("%d.%d.%d: barriering.\n", dcgn::gpu::getRank(), blockIdx.x, threadIdx.x); fflush(stdout); dcgn::gpu::barrier(0); // printf("%d.%d.%d: executing.\n", dcgn::gpu::getRank(), blockIdx.x, threadIdx.x); fflush(stdout); } const int START_BODY = getIndexForRank(dcgn::gpu::getRank(0), dcgn::gpu::getSize(), size); const int END_BODY = getIndexForRank(dcgn::gpu::getRank(0) + 1, dcgn::gpu::getSize(), size); for (int i = 0; i < timeSteps; ++i) { updateForces(gpuBodies, gpuUpdatedBodies, START_BODY, END_BODY, size, timeDelta); __syncblocks(sbarr); if (threadIdx.x == 0 && blockIdx.x == 0) { int sizeIndex = 0, actualSize = dcgn::gpu::getSize() * 2 / 3; for (int j = 0; j < dcgn::gpu::getSize(); ++j) { if (j % 3 != 0) { const int start = getIndexForRank(sizeIndex, actualSize, size); const int end = getIndexForRank(sizeIndex + 1, actualSize, size); // buf = end; dcgn::gpu::send(0, 0, &buf, sizeof(int)); // printf("dcgn::broadcast(slot=%d, root=%d, buf=%p (%p + %d * %d), size=%d( (%d - %d) * %d) )).\n", // 0, j, gpuUpdatedBodies + start, gpuUpdatedBodies, start, (int)sizeof(Body), (end - start) * (int)sizeof(Body), end, start, (int)sizeof(Body)); // fflush(stdout); // dcgn::gpu::barrier(0); dcgn::gpu::broadcast(0, j, gpuUpdatedBodies + start, (end - start) * sizeof(Body)); ++sizeIndex; } } #if BARRIER_BEFORE_BIG_COMM dcgn::gpu::barrier(0); #endif } __syncblocks(sbarr); Body * tmp = gpuBodies; gpuBodies = gpuUpdatedBodies; gpuUpdatedBodies = tmp; } if (blockIdx.x == 0 && threadIdx.x == 0) { dcgn::gpu::barrier(0); } } __device__ void updateForces(Body * bodies, Body * ubodies, const int startBody, const int endBody, const int n, const float timeDelta) { // load up 2 bodies per thread. then load up one body per thread for work. const int BODY_START = startBody + blockDim.x * blockIdx.x; const int BODY_STRIDE = blockDim.x * gridDim.x; for (int i = BODY_START; i < endBody; i += BODY_STRIDE) { const int NUM_BODIES = (i + blockDim.x <= endBody ? blockDim.x : endBody - i); Body * sharedBodies = reinterpret_cast<Body * >(mem); Body * localBodies = reinterpret_cast<Body * >(mem + NUM_BODIES * sizeof(Body)); block_memcpy(sharedBodies, bodies + i, NUM_BODIES * sizeof(Body)); if (threadIdx.x < NUM_BODIES) { for (int j = 0; j < n; j += blockDim.x * 2) { const int NUM_BODIES2 = (j + blockDim.x * 2 <= n ? 2 * blockDim.x : n - j); block_memcpy(localBodies, bodies + j, NUM_BODIES2 * sizeof(Body)); for (int k = 0; k < NUM_BODIES2; ++k) { sharedBodies[threadIdx.x].addForceFrom(localBodies[k]); } } sharedBodies[threadIdx.x].update(timeDelta); } block_memcpy2(ubodies + i, sharedBodies, NUM_BODIES * sizeof(Body)); } } __device__ __host__ int getIndexForRank(const int rank, const int size, const int n) { if (rank == 0) return 0; if (rank == size) return n; float f = static_cast<float>(rank) / static_cast<float>(size) * n; return static_cast<int>(f); } __device__ void block_memcpy(void * dstMem, const void * srcMem, const int size) { char * dst = reinterpret_cast< char * >(dstMem); const char * src = reinterpret_cast<const char * >(srcMem); int rem = size; dst += threadIdx.x * sizeof(float); src += threadIdx.x * sizeof(float); __syncthreads(); while (rem >= blockDim.x * sizeof(float)) { *reinterpret_cast<float * >(dst) = *reinterpret_cast<const float * >(src); dst += blockDim.x * sizeof(float); src += blockDim.x * sizeof(float); rem -= blockDim.x * sizeof(float); } if (rem > 0 && threadIdx.x == 0) { while (rem > sizeof(float)) { reinterpret_cast<float * >(dst)[threadIdx.x] = *reinterpret_cast<const float * >(src); dst += sizeof(float); src += sizeof(float); rem -= sizeof(float); } while (rem > sizeof(char)) { *(dst++) = *(src++); --rem; } } __syncthreads(); } __device__ void block_memcpy2(void * dstMem, const void * srcMem, const int size) { char * dst = reinterpret_cast< char * >(dstMem); const char * src = reinterpret_cast<const char * >(srcMem); int rem = size; dst += threadIdx.x * sizeof(float); src += threadIdx.x * sizeof(float); __syncthreads(); while (rem >= blockDim.x * sizeof(float)) { *reinterpret_cast<float * >(dst) = *reinterpret_cast<const float * >(src); dst += blockDim.x * sizeof(float); src += blockDim.x * sizeof(float); rem -= blockDim.x * sizeof(float); } if (rem > 0 && threadIdx.x == 0) { while (rem > sizeof(float)) { reinterpret_cast<float * >(dst)[threadIdx.x] = *reinterpret_cast<const float * >(src); dst += sizeof(float); src += sizeof(float); rem -= sizeof(float); } while (rem > sizeof(char)) { *(dst++) = *(src++); --rem; } } __syncthreads(); } __device__ void __syncblocks(volatile int * sbarr) { __syncthreads(); if (threadIdx.x == 0) { sbarr[blockIdx.x] = 1; if (blockIdx.x == 0) { for (int i = 1; i < gridDim.x; ++i) while (sbarr[i] == 0) { } for (int i = 0; i < gridDim.x; ++i) sbarr[i] = 0; } while (sbarr[blockIdx.x] == 1) { } } __syncthreads(); }
64f57352130f9c480f2b6b6236527ea0733f4639.hip
// !!! This is a file automatically generated by hipify!!! #include "host_shared_ptr.cuh" #include "cuda_tools/device_buffer.cuh" #include <hip/hip_runtime.h> #include <cstdio> #include "cuda_error_checking.cuh" #include "template_generator.hh" namespace cuda_tools { template_generation(host_shared_ptr); template <typename T> __host__ void host_shared_ptr<T>::allocate(std::size_t size) { cuda_safe_call(hipMalloc((void**)&data_, sizeof(T) * size)); } template <typename T> host_shared_ptr<T>::host_shared_ptr(std::size_t size) : size_(size) { allocate(size); } template <typename T> host_shared_ptr<T>::host_shared_ptr(host_shared_ptr<T>&& ptr) : data_(ptr.data_), size_(ptr.size_), counter_(ptr.counter_ + 1) {} template <typename T> host_shared_ptr<T>::host_shared_ptr(host_shared_ptr<T>& ptr) : data_(ptr.data_), size_(ptr.size_), counter_(ptr.counter_ + 1) {} template <typename T> host_shared_ptr<T>& host_shared_ptr<T>::operator=(host_shared_ptr<T>&& r) { data_ = r.data_; size_ = r.size_; counter_ = r.counter_ + 1; return *this; } template <typename T> host_shared_ptr<T>::~host_shared_ptr() { if (--counter_ == 0) { cuda_safe_call(hipFree(data_)); if (host_data_ != nullptr) delete[] host_data_; } } template <typename T> T* host_shared_ptr<T>::download() { if (data_ != nullptr) { if (host_data_ == nullptr) host_data_ = new T[size_]; cuda_safe_call(hipMemcpy(host_data_, data_, sizeof(T) * size_, hipMemcpyDeviceToHost)); } return host_data_; } template <typename T, typename FUNC> __global__ static void kernel_fill(cuda_tools::device_buffer<T> buffer, FUNC func) { const int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < buffer.size_) buffer[index] = func(); } template <typename T> void host_shared_ptr<T>::fill(const T val) { constexpr int TILE_WIDTH = 64; constexpr int TILE_HEIGHT = 1; cuda_tools::device_buffer<T> device_buffer(*this); auto lambda = [val] __device__ { return val; }; const int gx = (this->size_ + TILE_WIDTH - 1) / TILE_WIDTH; const int gy = 1; const dim3 block(TILE_WIDTH, TILE_HEIGHT); const dim3 grid(gx, gy); hipLaunchKernelGGL(( kernel_fill<T>), dim3(grid), dim3(block), 0, 0, device_buffer, lambda); kernel_check_error(); hipDeviceSynchronize(); } } // namespace cuda_tools
64f57352130f9c480f2b6b6236527ea0733f4639.cu
#include "host_shared_ptr.cuh" #include "cuda_tools/device_buffer.cuh" #include <cuda_runtime.h> #include <cstdio> #include "cuda_error_checking.cuh" #include "template_generator.hh" namespace cuda_tools { template_generation(host_shared_ptr); template <typename T> __host__ void host_shared_ptr<T>::allocate(std::size_t size) { cuda_safe_call(cudaMalloc((void**)&data_, sizeof(T) * size)); } template <typename T> host_shared_ptr<T>::host_shared_ptr(std::size_t size) : size_(size) { allocate(size); } template <typename T> host_shared_ptr<T>::host_shared_ptr(host_shared_ptr<T>&& ptr) : data_(ptr.data_), size_(ptr.size_), counter_(ptr.counter_ + 1) {} template <typename T> host_shared_ptr<T>::host_shared_ptr(host_shared_ptr<T>& ptr) : data_(ptr.data_), size_(ptr.size_), counter_(ptr.counter_ + 1) {} template <typename T> host_shared_ptr<T>& host_shared_ptr<T>::operator=(host_shared_ptr<T>&& r) { data_ = r.data_; size_ = r.size_; counter_ = r.counter_ + 1; return *this; } template <typename T> host_shared_ptr<T>::~host_shared_ptr() { if (--counter_ == 0) { cuda_safe_call(cudaFree(data_)); if (host_data_ != nullptr) delete[] host_data_; } } template <typename T> T* host_shared_ptr<T>::download() { if (data_ != nullptr) { if (host_data_ == nullptr) host_data_ = new T[size_]; cuda_safe_call(cudaMemcpy(host_data_, data_, sizeof(T) * size_, cudaMemcpyDeviceToHost)); } return host_data_; } template <typename T, typename FUNC> __global__ static void kernel_fill(cuda_tools::device_buffer<T> buffer, FUNC func) { const int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < buffer.size_) buffer[index] = func(); } template <typename T> void host_shared_ptr<T>::fill(const T val) { constexpr int TILE_WIDTH = 64; constexpr int TILE_HEIGHT = 1; cuda_tools::device_buffer<T> device_buffer(*this); auto lambda = [val] __device__ { return val; }; const int gx = (this->size_ + TILE_WIDTH - 1) / TILE_WIDTH; const int gy = 1; const dim3 block(TILE_WIDTH, TILE_HEIGHT); const dim3 grid(gx, gy); kernel_fill<T><<<grid, block>>>(device_buffer, lambda); kernel_check_error(); cudaDeviceSynchronize(); } } // namespace cuda_tools
e9c557bc3a9a6779bc0c54a1147e5265c282a5f9.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> __global__ void initWith(float num, float *a, int N) { int index = threadIdx.x + blockIdx.x * blockDim.x; int stride = blockDim.x * gridDim.x; for(int i = index; i < N; i += stride) { a[i] = num; } } __global__ void addVectorsInto(float *result, float *a, float *b, int N) { int index = threadIdx.x + blockIdx.x * blockDim.x; int stride = blockDim.x * gridDim.x; for(int i = index; i < N; i += stride) { result[i] = a[i] + b[i]; } } void checkElementsAre(float target, float *vector, int N) { for(int i = 0; i < N; i++) { if(vector[i] != target) { printf("FAIL: vector[%d] - %0.0f does not equal %0.0f\n", i, vector[i], target); exit(1); } } printf("Success! All values calculated correctly.\n"); } int main() { int deviceId; int numberOfSMs; hipGetDevice(&deviceId); hipDeviceGetAttribute(&numberOfSMs, hipDeviceAttributeMultiprocessorCount, deviceId); const int N = 2<<24; size_t size = N * sizeof(float); float *a; float *b; float *c; hipMallocManaged(&a, size); hipMallocManaged(&b, size); hipMallocManaged(&c, size); hipMemPrefetchAsync(a, size, deviceId); hipMemPrefetchAsync(b, size, deviceId); hipMemPrefetchAsync(c, size, deviceId); size_t threadsPerBlock; size_t numberOfBlocks; threadsPerBlock = 256; numberOfBlocks = 32 * numberOfSMs; hipError_t addVectorsErr; hipError_t asyncErr; hipStream_t stream; hipStreamCreate(&stream); hipLaunchKernelGGL(( initWith), dim3(numberOfBlocks), dim3(threadsPerBlock),0,stream, 3, a, N); hipStreamDestroy(stream); hipStream_t stream_1; hipStreamCreate(&stream_1); hipLaunchKernelGGL(( initWith), dim3(numberOfBlocks), dim3(threadsPerBlock),0,stream_1, 4, b, N); hipStreamDestroy(stream_1); hipStream_t stream_2; hipStreamCreate(&stream_2); hipLaunchKernelGGL(( initWith), dim3(numberOfBlocks), dim3(threadsPerBlock),0,stream_2, 0, c, N); hipStreamDestroy(stream_2); hipLaunchKernelGGL(( addVectorsInto), dim3(numberOfBlocks), dim3(threadsPerBlock), 0, 0, c, a, b, N); addVectorsErr = hipGetLastError(); if(addVectorsErr != hipSuccess) printf("Error: %s\n", hipGetErrorString(addVectorsErr)); asyncErr = hipDeviceSynchronize(); if(asyncErr != hipSuccess) printf("Error: %s\n", hipGetErrorString(asyncErr)); hipMemPrefetchAsync(c, size, hipCpuDeviceId); checkElementsAre(7, c, N); hipFree(a); hipFree(b); hipFree(c); }
e9c557bc3a9a6779bc0c54a1147e5265c282a5f9.cu
#include <stdio.h> __global__ void initWith(float num, float *a, int N) { int index = threadIdx.x + blockIdx.x * blockDim.x; int stride = blockDim.x * gridDim.x; for(int i = index; i < N; i += stride) { a[i] = num; } } __global__ void addVectorsInto(float *result, float *a, float *b, int N) { int index = threadIdx.x + blockIdx.x * blockDim.x; int stride = blockDim.x * gridDim.x; for(int i = index; i < N; i += stride) { result[i] = a[i] + b[i]; } } void checkElementsAre(float target, float *vector, int N) { for(int i = 0; i < N; i++) { if(vector[i] != target) { printf("FAIL: vector[%d] - %0.0f does not equal %0.0f\n", i, vector[i], target); exit(1); } } printf("Success! All values calculated correctly.\n"); } int main() { int deviceId; int numberOfSMs; cudaGetDevice(&deviceId); cudaDeviceGetAttribute(&numberOfSMs, cudaDevAttrMultiProcessorCount, deviceId); const int N = 2<<24; size_t size = N * sizeof(float); float *a; float *b; float *c; cudaMallocManaged(&a, size); cudaMallocManaged(&b, size); cudaMallocManaged(&c, size); cudaMemPrefetchAsync(a, size, deviceId); cudaMemPrefetchAsync(b, size, deviceId); cudaMemPrefetchAsync(c, size, deviceId); size_t threadsPerBlock; size_t numberOfBlocks; threadsPerBlock = 256; numberOfBlocks = 32 * numberOfSMs; cudaError_t addVectorsErr; cudaError_t asyncErr; cudaStream_t stream; cudaStreamCreate(&stream); initWith<<<numberOfBlocks, threadsPerBlock,0,stream>>>(3, a, N); cudaStreamDestroy(stream); cudaStream_t stream_1; cudaStreamCreate(&stream_1); initWith<<<numberOfBlocks, threadsPerBlock,0,stream_1>>>(4, b, N); cudaStreamDestroy(stream_1); cudaStream_t stream_2; cudaStreamCreate(&stream_2); initWith<<<numberOfBlocks, threadsPerBlock,0,stream_2>>>(0, c, N); cudaStreamDestroy(stream_2); addVectorsInto<<<numberOfBlocks, threadsPerBlock>>>(c, a, b, N); addVectorsErr = cudaGetLastError(); if(addVectorsErr != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(addVectorsErr)); asyncErr = cudaDeviceSynchronize(); if(asyncErr != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(asyncErr)); cudaMemPrefetchAsync(c, size, cudaCpuDeviceId); checkElementsAre(7, c, N); cudaFree(a); cudaFree(b); cudaFree(c); }
24b6018a8818b1bff3751856ea966fcf3da2a122.hip
// !!! This is a file automatically generated by hipify!!! #include <stdlib.h> #include <stdio.h> #include <hip/hip_runtime.h> __global__ void helloWorld(){ int threadIndex = threadIdx.x; int blockIndex = blockIdx.x; if(threadIndex%2 == 1) printf("Hello World from thread %d of block %d\n", threadIndex, blockIndex); else{ printf("hello from the other threads\n"); if(threadIndex%3) printf("hi from the multiples of 3\n"); } } int main(int argc, char **argv){ int blocks = 4; int threadsPerBlock = 3; hipLaunchKernelGGL(( helloWorld) , dim3(blocks), dim3(threadsPerBlock) , 0, 0, ); hipDeviceSynchronize(); }
24b6018a8818b1bff3751856ea966fcf3da2a122.cu
#include <stdlib.h> #include <stdio.h> #include <cuda.h> __global__ void helloWorld(){ int threadIndex = threadIdx.x; int blockIndex = blockIdx.x; if(threadIndex%2 == 1) printf("Hello World from thread %d of block %d\n", threadIndex, blockIndex); else{ printf("hello from the other threads\n"); if(threadIndex%3) printf("hi from the multiples of 3\n"); } } int main(int argc, char **argv){ int blocks = 4; int threadsPerBlock = 3; helloWorld <<< blocks, threadsPerBlock >>> (); cudaDeviceSynchronize(); }
48681d8c54ddba67fcbf0ab23a9f7b840c113c26.hip
// !!! This is a file automatically generated by hipify!!! #include <hip/hip_runtime.h> #include <iostream> #include <math.h> #include <ctime> #include <cmath> #include "enum_header.h" #include <unistd.h> #include <stdio.h> /* we need these includes for CUDA's random number stuff */ #include <hiprand/hiprand.h> #include <hiprand/hiprand_kernel.h> // REMEMBER TO PUT __host__ __device__ IN FRONT OF CLASS METHODS #define PI 3.14159265358979323846 #define CHECK(x) do {\ hipError_t err =(x);\ if (err !=hipSuccess){\ fprintf(stderr, "API error"\ "%s:%d Returned:%d\n", \ __FILE__, __LINE__, err);\ exit(1);\ } while(0) //double* two_dim_index(double* vector, int i, int j, double m, int b); double* three_dim_index(double* matrix, int i, int j, int k, double m, int b, int num_assets); __device__ double* two_dim_indexGPU(double* vector, int i, int j, double m, int b){ //int m_int= (int)m; double* p; //specify index layout here p=&vector[b*(i)+(j)]; return p; } __device__ double* three_dim_indexGPU(double* matrix, int i, int j, int k, double m, int b, int num_assets){ int m_int = (int)m; double* p; //specify index layout here //p=&matrix[(m_int)*b*(k)+(m_int)*(j)+(i)]; p=&matrix[i*b*num_assets+j*num_assets+k]; return p; } __device__ double densityGPU(double Xold, double Xnew, double sigma, double r, double delta, double delta_t){ double f=0, x=0; //x=(1/(sigma*sqrt(delta_t)))*(log(Xnew)-log(Xold)-(r-delta-0.5*sigma*sigma)*delta_t); x=(1/(sigma*sqrt(delta_t)))*(Xnew-Xold-(r-delta-0.5*sigma*sigma)*delta_t); //f= (1/(sigma*sqrt(delta_t)*Xnew))*(1/(sqrt(2*PI)))*exp(-0.5*x*x); // this is the transition density f= (1/(sigma*sqrt(delta_t)))*(1/(sqrt(2*PI)))*exp(-0.5*x*x); return f; } /* __global__ void init(unsigned int seed, hiprandState_t* states) { int idx=blockDim.x*blockIdx.x + threadIdx.x; // we have to initialize the state hiprand_init(seed, // the seed can be the same for each core, here we pass the time in from the CPU idx, // the sequence number should be different for each core (unless you want all // cores to get the same sequence of numbers for some reason - use thread id! 0, // the offset is how much extra we advance in the sequence for each call, can be 0 &states[idx]); } */ __device__ double GeometricPayOffCallV(double* X, double m, int b, int num_assets, double Strike){ double h; h=1; for(int l=0; l<num_assets; l++){ // h*=exp(X[i][j][l]); //h*= exp(*two_dim_indexGPU(X, i, l, m, b)); h*=exp(X[l]); } h=pow(h,1.0/(num_assets)); if(h-Strike>0){ h=h-Strike; } else{ h=0; } return h; } __device__ double GeometricPayOffPutV(double* X, double m, int b, int num_assets, double Strike){ double h; h=1; for(int l=0; l<num_assets; l++){ // h*=exp(X[i][j][l]); //h*= exp(*two_dim_indexGPU(X, i, l, m, b)); h*=exp(X[l]); } h=pow(h,1.0/(num_assets)); if(Strike-h>0){ h=Strike-h; } else{ h=0; } return h; } __device__ void S_weights(double* S_Weights, double* X_device, double* S_new, int m, int b, double* sigma_device, double* delta_device, double delta_t, int num_assets, double r , int i, double* weight_denominator_device ){//note: S_new used to be just S //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("Beginning \n");} //double density_product, double sum, w_s; //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("in function m =%i /n",m);} for(int h=0; h<b; h++){ //h=k //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("Outside loop, i=%i \n", h);} sum=0; w_s=1; for(int kk=0; kk<num_assets; kk++){ //w_s*=densityGPU(*two_dim_indexGPU(S, i, kk, m, num_assets), *three_dim_indexGPU(X_device, (i+1), h, kk, m, b), sigma_device[kk], r, delta_device[kk], delta_t); w_s*=densityGPU(S_new[kk], *three_dim_indexGPU(X_device, (i+1), h, kk, m, b, num_assets), sigma_device[kk], r, delta_device[kk], delta_t); } /* clock_t start_time =clock(); clock_t stop_time =clock(); int time=stop_time-start_time; if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("result at i=%i , = %i\n",i, time);} */ /* density_product=1; //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("after first inside loop \n");} for(int g=0; g<b; g++){ //g=l //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("inside second loop i=%i \n", g);} for(int gg=0; gg<num_assets; gg++){ density_product*=densityGPU(*three_dim_indexGPU(X_device, i, g, gg, m, b), *three_dim_indexGPU(X_device, (i+1), h, gg, m, b), sigma_device[gg], r, delta_device[gg], delta_t); } sum+=(1/((double)b))*density_product; } */ sum = *two_dim_indexGPU(weight_denominator_device, i, h, m-1, b); if(sum==0){printf("division by zero in weights function of path estimator");} w_s = (((double)b)*w_s)/sum; //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("w_s=%f \n", w_s);} //*two_dim_indexGPU(S_Weights, i, h, m, b)=w_s; S_Weights[h]=w_s; } //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("End \n");} } __global__ void PathEstimatorKernel(double* X_device, double* weight_denominator_device, double* V_device, double* delta_device, double* sigma_device, double* X0_device, int N, double strike, double r, double delta_t, int b, int m, int num_assets, hiprandState_t* states, double* results_dev, double* asset_amount_device){ int idx =blockDim.x*blockIdx.x + threadIdx.x; //if(blockDim.x*blockIdx.x + threadIdx.x==N+1){printf("n+1 outside \n");} if(idx<N){ //printf("inside \n"); //if(blockDim.x*blockIdx.x + threadIdx.x==N-1){printf("n-1 \n");} //if(blockDim.x*blockIdx.x + threadIdx.x==N+1){printf("n+1 inside \n");} //GeometricPayOffPut thePayOff(strike); //GeometricPayOffPut payoff(strike); //enum Containers { vector, matrix }; //Containers Vector = vector; //Containers Matrix = matrix; double v_0, S_i, Z, C, H, sum, weight; //, w_s, sum_Z; //srand((unsigned)time(NULL)); //std::random_device rd; //std::default_random_engine generator; //generator.seed( rd() ); //std::normal_distribution<double> distribution(0.0,1.0); /// ARRAY CODE //const int S_N=(m)*num_assets; //const int S_W_N=(m)*b; const int S_N= num_assets; const int S_W_N= b; double* S_new; S_new= new double[S_N]; //double s_new[S_new_N]; //S_new=s_new; //double* S_old; //S_old=new double[S_N]; double* S_Weights; S_Weights=new double[S_W_N]; //double s_weights[S_W_new_N]; //S_Weights=s_weights; //double* S_new; //double* S_old; //double* S_Weights; /* double s_new[1]; //double s_old[1]; double s_weights[250]; S_new=s_new; //S_old=s_old; S_Weights=s_weights; */ //S_Weights=new double[250]; //S_new=new double[1]; //if(idx==0){printf("X[0][0][0]= %f \n",*three_dim_indexGPU(X_device,0,0,0,m,b));} //if(idx==0){printf("before the loop");} int i=0; do { if(i==0){ for(int ll=0; ll<num_assets; ll++){ //Z=boxmuller(); // NEED TO CHANGE THE RANDOM NUMBER GENERATOR //Z=distribution(generator); Z=hiprand_normal_double(&states[idx]); //printf("for idx=%i, r=%f",idx,Z); //printf("random number for idx %i is %f",idx,Z); S_i=X0_device[ll] + (r-delta_device[ll]-0.5*pow(sigma_device[ll], 2))*delta_t + sigma_device[ll]*sqrt(delta_t)*Z; //tempnodevector.push_back(S_i); //*two_dim_indexGPU(S, i, ll, m, num_assets)=S_i; S_new[ll]=S_i; } } else{ for(int jj=0; jj<num_assets; jj++){ //Z=boxmuller(); //Z=distribution(generator); Z=hiprand_normal_double(&states[idx]); //if(idx==0){printf("random number=%f /n", Z);} //S_i=(*two_dim_indexGPU(S, (i-1), jj, m, num_assets)) + (r-delta_device[jj]-0.5*pow(sigma_device[jj], 2))*delta_t + sigma_device[jj]*sqrt(delta_t)*Z; S_i=S_new[jj] + (r-delta_device[jj]-0.5*pow(sigma_device[jj], 2))*delta_t + sigma_device[jj]*sqrt(delta_t)*Z; //tempnodevector.push_back(S_i); //*two_dim_indexGPU(S, i, jj, m, num_assets)=S_i; S_new[jj]=S_i; } } //printf("inside \n"); //if(idx==0){printf("before the call, m =%i /n", m);} if(i<m-1){ //S_weights(tempvec, S_Weights, X, S, m, b, sigma, delta, delta_t, asset_amount, r, i ); //S_weights(S_Weights, X_device, S, m, b, sigma_device, delta_device, delta_t, num_assets, r, i ); //right S_weights(S_Weights, X_device, S_new, m, b, sigma_device, delta_device, delta_t, num_assets, r, i, weight_denominator_device); } //printf("inside \n"); double con_val=0; //continuation value variable sum=0; if(i==m-1){ C=0;//continuation value at the last time step } else{ for(int k=0; k<b; k++){ //weight= * two_dim_indexGPU(S_Weights, i, k, m, b); //right weight= S_Weights[k]; //con_val=V[(m-1)-i-1][k]; con_val= *two_dim_indexGPU(V_device, (m-1-i-1), k, m, b); //con_val=0; sum+=(weight) * (con_val); } //con_val=inner_product(b, first_vector, second_vector); C=(1/(double)b)*sum; //continuation value // C=(1/(double)b)*con_val; } //printf("inside \n"); //H=Payoff(S, strike, asset_amount, i)*exp(-r*delta_t*((i+1))); //H=thePayOff(S, i, 0, m, num_assets, Vector, num_assets)*exp(-r*delta_t*((i+1))); //H=0; H= GeometricPayOffCallV(S_new, m, num_assets, num_assets, strike)*exp(-r*delta_t*((i+1))); i=i+1; /*for(int copy=0; copy<num_assets; copy++){ S_old[copy]=S_new[copy]; }*/ }while(H<C);//this will stop once H is less then the continuation value. at m-1, c=0 therefore m-1 is the max amount of loops. v_0=H; //if(idx==0){printf("result %i=%f", idx, v_0);} results_dev[idx]=v_0; delete[] S_new; //delete[] S_old; delete[] S_Weights; //return v_0; //printf("inside \n"); } } double PathEstimator(double strike, double r, double delta_t, int b, double m, double sigma[], double delta[], double X0[], double* X, double* weight_denominator, double* V, double asset_amount[], int num_assets, int Path_estimator_iterations, int iterator, int Final_iteration, hiprandState_t* States, hiprandState_t* states, int threads ){ //m=int(m); //for(int test=0; test<((m-1)*b); test++){ //printf("at the start of pathestimator den=%f /n", weight_denominator[test]); //} //printf("Ib serial X[0][0][0]= %f \n",*three_dim_index(X,0,0,0,m,b)); hipError_t error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } int N= Path_estimator_iterations; double* sigma_host; sigma_host =sigma; double* delta_host; delta_host =delta; double* X0_host; X0_host =X0; double* asset_amount_host; asset_amount_host =asset_amount; int m_int=(int)m; //printf("at the start of pathestimator m_int=%i /n", m_int); int X_N=(m_int) * b * (num_assets); int W_N=(m_int-1) * b; int V_N=(m_int) * b; int delta_N= num_assets; int sigma_N=num_assets; int X0_N=num_assets; int asset_amount_N = num_assets; double* X_device; double* V_device; double* weight_denominator_device; double* sigma_device; double* delta_device; double* X0_device; double* asset_amount_device; error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } hipMalloc((void**) &X_device, X_N*sizeof(double) ); hipMemcpy(X_device, X, X_N*sizeof(double), hipMemcpyHostToDevice); hipMalloc((void**) &V_device, V_N*sizeof(double) ); hipMemcpy(V_device, V, V_N*sizeof(double), hipMemcpyHostToDevice); hipMalloc((void**) &weight_denominator_device, W_N*sizeof(double) ); hipMemcpy(weight_denominator_device, weight_denominator, W_N*sizeof(double), hipMemcpyHostToDevice); hipMalloc((void**) &X0_device, X0_N*sizeof(double) ); hipMemcpy(X0_device, X0_host, X0_N*sizeof(double), hipMemcpyHostToDevice); hipMalloc((void**) &sigma_device, sigma_N*sizeof(double) ); hipMemcpy(sigma_device, sigma_host, sigma_N*sizeof(double), hipMemcpyHostToDevice); hipMalloc((void**) &delta_device, delta_N*sizeof(double) ); hipMemcpy(delta_device, delta_host, delta_N*sizeof(double), hipMemcpyHostToDevice); hipMalloc((void**) &asset_amount_device, asset_amount_N*sizeof(double) ); hipMemcpy(asset_amount_device, asset_amount_host, asset_amount_N*sizeof(double), hipMemcpyHostToDevice); hipMemcpy(states, States, threads*sizeof(hiprandState_t*), hipMemcpyHostToDevice); //dim3 gridDim((int)ceil(N/512.0)); //printf("the grid dim is:%i\n",(int)ceil(N/512.0)); //dim3 blockDim(512); dim3 gridDim((int)ceil(N/512.0)); dim3 blockDim(512.0); /*if(N>512){ gridDim()= ceil(N/521); } */ error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } double* results; results = new double[N]; double* results_dev; hipMalloc((void**) &results_dev, N*sizeof(double) ); // CALL RANDOM SEEDING KERNEL HERE error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } /* hiprandState_t* states; hipMalloc((void**) &states, N * sizeof(hiprandState_t)); init<<<gridDim, blockDim>>>(time(0), states); hipDeviceSynchronize(); */ error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } //printf("inside \n"); hipDeviceSetLimit(hipLimitMallocHeapSize, 80000000*sizeof(double)); //size_t size; //hipDeviceGetLimit(&size, hipLimitMallocHeapSize); //printf("Heap size found to be %d\n",(int)size); //printf("after"); //for(int test=0; test<V_N; test++){ //printf("N=%i, strike=%f, r=%f, delta_t=%f, num_a=%i, b=%i", N, strike, r, delta_t, num_assets,b); //}hipLaunchKernelGGL(( PathEstimatorKernel), dim3(gridDim), dim3(blockDim), 0, 0, X_device, weight_denominator_device, V_device, delta_device, sigma_device, X0_device, N, strike, r, delta_t, b, m_int, num_assets, states, results_dev, asset_amount_device); hipDeviceSynchronize(); error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } //printf("here"); hipMemcpy(results, results_dev, sizeof(double)*N, hipMemcpyDeviceToHost); error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("Found at line %d\n", __LINE__); exit(1); } //hipDeviceSynchronize(); //hipMemcpy(States, states, sizeof(hiprandState_t)*N, hipMemcpyDeviceToHost); hipMemcpy(States, states, sizeof(hiprandState_t)*threads, hipMemcpyDeviceToHost); error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("Found at line %d\n", __LINE__); exit(1); } double result=0; for(int f=0; f<Path_estimator_iterations; f++){ result+=results[f]; //printf("random %i =%f\n", f, results[f]); } result=(1/double(N))*result; delete[] results; error = hipGetLastError(); if( error != hipSuccess ) { std::cout << hipGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } hipFree(X_device); hipFree(V_device); hipFree(weight_denominator_device); hipFree(sigma_device); hipFree(delta_device); hipFree(X0_device); hipFree(results_dev); hipFree(asset_amount_device); if(iterator==Final_iteration-1){ hipFree(states); //printf("done, iter=%i",iterator); } //hipDeviceReset(); return result; //hipDeviceReset(); }
48681d8c54ddba67fcbf0ab23a9f7b840c113c26.cu
#include <cuda.h> #include <iostream> #include <math.h> #include <ctime> #include <cmath> #include "enum_header.h" #include <unistd.h> #include <stdio.h> /* we need these includes for CUDA's random number stuff */ #include <curand.h> #include <curand_kernel.h> // REMEMBER TO PUT __host__ __device__ IN FRONT OF CLASS METHODS #define PI 3.14159265358979323846 #define CHECK(x) do {\ cudaError_t err =(x);\ if (err !=cudaSuccess){\ fprintf(stderr, "API error"\ "%s:%d Returned:%d\n", \ __FILE__, __LINE__, err);\ exit(1);\ } while(0) //double* two_dim_index(double* vector, int i, int j, double m, int b); double* three_dim_index(double* matrix, int i, int j, int k, double m, int b, int num_assets); __device__ double* two_dim_indexGPU(double* vector, int i, int j, double m, int b){ //int m_int= (int)m; double* p; //specify index layout here p=&vector[b*(i)+(j)]; return p; } __device__ double* three_dim_indexGPU(double* matrix, int i, int j, int k, double m, int b, int num_assets){ int m_int = (int)m; double* p; //specify index layout here //p=&matrix[(m_int)*b*(k)+(m_int)*(j)+(i)]; p=&matrix[i*b*num_assets+j*num_assets+k]; return p; } __device__ double densityGPU(double Xold, double Xnew, double sigma, double r, double delta, double delta_t){ double f=0, x=0; //x=(1/(sigma*sqrt(delta_t)))*(log(Xnew)-log(Xold)-(r-delta-0.5*sigma*sigma)*delta_t); x=(1/(sigma*sqrt(delta_t)))*(Xnew-Xold-(r-delta-0.5*sigma*sigma)*delta_t); //f= (1/(sigma*sqrt(delta_t)*Xnew))*(1/(sqrt(2*PI)))*exp(-0.5*x*x); // this is the transition density f= (1/(sigma*sqrt(delta_t)))*(1/(sqrt(2*PI)))*exp(-0.5*x*x); return f; } /* __global__ void init(unsigned int seed, curandState_t* states) { int idx=blockDim.x*blockIdx.x + threadIdx.x; // we have to initialize the state curand_init(seed, // the seed can be the same for each core, here we pass the time in from the CPU idx, // the sequence number should be different for each core (unless you want all // cores to get the same sequence of numbers for some reason - use thread id! 0, // the offset is how much extra we advance in the sequence for each call, can be 0 &states[idx]); } */ __device__ double GeometricPayOffCallV(double* X, double m, int b, int num_assets, double Strike){ double h; h=1; for(int l=0; l<num_assets; l++){ // h*=exp(X[i][j][l]); //h*= exp(*two_dim_indexGPU(X, i, l, m, b)); h*=exp(X[l]); } h=pow(h,1.0/(num_assets)); if(h-Strike>0){ h=h-Strike; } else{ h=0; } return h; } __device__ double GeometricPayOffPutV(double* X, double m, int b, int num_assets, double Strike){ double h; h=1; for(int l=0; l<num_assets; l++){ // h*=exp(X[i][j][l]); //h*= exp(*two_dim_indexGPU(X, i, l, m, b)); h*=exp(X[l]); } h=pow(h,1.0/(num_assets)); if(Strike-h>0){ h=Strike-h; } else{ h=0; } return h; } __device__ void S_weights(double* S_Weights, double* X_device, double* S_new, int m, int b, double* sigma_device, double* delta_device, double delta_t, int num_assets, double r , int i, double* weight_denominator_device ){//note: S_new used to be just S //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("Beginning \n");} //double density_product, double sum, w_s; //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("in function m =%i /n",m);} for(int h=0; h<b; h++){ //h=k //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("Outside loop, i=%i \n", h);} sum=0; w_s=1; for(int kk=0; kk<num_assets; kk++){ //w_s*=densityGPU(*two_dim_indexGPU(S, i, kk, m, num_assets), *three_dim_indexGPU(X_device, (i+1), h, kk, m, b), sigma_device[kk], r, delta_device[kk], delta_t); w_s*=densityGPU(S_new[kk], *three_dim_indexGPU(X_device, (i+1), h, kk, m, b, num_assets), sigma_device[kk], r, delta_device[kk], delta_t); } /* clock_t start_time =clock(); clock_t stop_time =clock(); int time=stop_time-start_time; if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("result at i=%i , = %i\n",i, time);} */ /* density_product=1; //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("after first inside loop \n");} for(int g=0; g<b; g++){ //g=l //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("inside second loop i=%i \n", g);} for(int gg=0; gg<num_assets; gg++){ density_product*=densityGPU(*three_dim_indexGPU(X_device, i, g, gg, m, b), *three_dim_indexGPU(X_device, (i+1), h, gg, m, b), sigma_device[gg], r, delta_device[gg], delta_t); } sum+=(1/((double)b))*density_product; } */ sum = *two_dim_indexGPU(weight_denominator_device, i, h, m-1, b); if(sum==0){printf("division by zero in weights function of path estimator");} w_s = (((double)b)*w_s)/sum; //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("w_s=%f \n", w_s);} //*two_dim_indexGPU(S_Weights, i, h, m, b)=w_s; S_Weights[h]=w_s; } //if(blockDim.x*blockIdx.x + threadIdx.x==0){printf("End \n");} } __global__ void PathEstimatorKernel(double* X_device, double* weight_denominator_device, double* V_device, double* delta_device, double* sigma_device, double* X0_device, int N, double strike, double r, double delta_t, int b, int m, int num_assets, curandState_t* states, double* results_dev, double* asset_amount_device){ int idx =blockDim.x*blockIdx.x + threadIdx.x; //if(blockDim.x*blockIdx.x + threadIdx.x==N+1){printf("n+1 outside \n");} if(idx<N){ //printf("inside \n"); //if(blockDim.x*blockIdx.x + threadIdx.x==N-1){printf("n-1 \n");} //if(blockDim.x*blockIdx.x + threadIdx.x==N+1){printf("n+1 inside \n");} //GeometricPayOffPut thePayOff(strike); //GeometricPayOffPut payoff(strike); //enum Containers { vector, matrix }; //Containers Vector = vector; //Containers Matrix = matrix; double v_0, S_i, Z, C, H, sum, weight; //, w_s, sum_Z; //srand((unsigned)time(NULL)); //std::random_device rd; //std::default_random_engine generator; //generator.seed( rd() ); //std::normal_distribution<double> distribution(0.0,1.0); /// ARRAY CODE //const int S_N=(m)*num_assets; //const int S_W_N=(m)*b; const int S_N= num_assets; const int S_W_N= b; double* S_new; S_new= new double[S_N]; //double s_new[S_new_N]; //S_new=s_new; //double* S_old; //S_old=new double[S_N]; double* S_Weights; S_Weights=new double[S_W_N]; //double s_weights[S_W_new_N]; //S_Weights=s_weights; //double* S_new; //double* S_old; //double* S_Weights; /* double s_new[1]; //double s_old[1]; double s_weights[250]; S_new=s_new; //S_old=s_old; S_Weights=s_weights; */ //S_Weights=new double[250]; //S_new=new double[1]; //if(idx==0){printf("X[0][0][0]= %f \n",*three_dim_indexGPU(X_device,0,0,0,m,b));} //if(idx==0){printf("before the loop");} int i=0; do { if(i==0){ for(int ll=0; ll<num_assets; ll++){ //Z=boxmuller(); // NEED TO CHANGE THE RANDOM NUMBER GENERATOR //Z=distribution(generator); Z=curand_normal_double(&states[idx]); //printf("for idx=%i, r=%f",idx,Z); //printf("random number for idx %i is %f",idx,Z); S_i=X0_device[ll] + (r-delta_device[ll]-0.5*pow(sigma_device[ll], 2))*delta_t + sigma_device[ll]*sqrt(delta_t)*Z; //tempnodevector.push_back(S_i); //*two_dim_indexGPU(S, i, ll, m, num_assets)=S_i; S_new[ll]=S_i; } } else{ for(int jj=0; jj<num_assets; jj++){ //Z=boxmuller(); //Z=distribution(generator); Z=curand_normal_double(&states[idx]); //if(idx==0){printf("random number=%f /n", Z);} //S_i=(*two_dim_indexGPU(S, (i-1), jj, m, num_assets)) + (r-delta_device[jj]-0.5*pow(sigma_device[jj], 2))*delta_t + sigma_device[jj]*sqrt(delta_t)*Z; S_i=S_new[jj] + (r-delta_device[jj]-0.5*pow(sigma_device[jj], 2))*delta_t + sigma_device[jj]*sqrt(delta_t)*Z; //tempnodevector.push_back(S_i); //*two_dim_indexGPU(S, i, jj, m, num_assets)=S_i; S_new[jj]=S_i; } } //printf("inside \n"); //if(idx==0){printf("before the call, m =%i /n", m);} if(i<m-1){ //S_weights(tempvec, S_Weights, X, S, m, b, sigma, delta, delta_t, asset_amount, r, i ); //S_weights(S_Weights, X_device, S, m, b, sigma_device, delta_device, delta_t, num_assets, r, i ); //right S_weights(S_Weights, X_device, S_new, m, b, sigma_device, delta_device, delta_t, num_assets, r, i, weight_denominator_device); } //printf("inside \n"); double con_val=0; //continuation value variable sum=0; if(i==m-1){ C=0;//continuation value at the last time step } else{ for(int k=0; k<b; k++){ //weight= * two_dim_indexGPU(S_Weights, i, k, m, b); //right weight= S_Weights[k]; //con_val=V[(m-1)-i-1][k]; con_val= *two_dim_indexGPU(V_device, (m-1-i-1), k, m, b); //con_val=0; sum+=(weight) * (con_val); } //con_val=inner_product(b, first_vector, second_vector); C=(1/(double)b)*sum; //continuation value // C=(1/(double)b)*con_val; } //printf("inside \n"); //H=Payoff(S, strike, asset_amount, i)*exp(-r*delta_t*((i+1))); //H=thePayOff(S, i, 0, m, num_assets, Vector, num_assets)*exp(-r*delta_t*((i+1))); //H=0; H= GeometricPayOffCallV(S_new, m, num_assets, num_assets, strike)*exp(-r*delta_t*((i+1))); i=i+1; /*for(int copy=0; copy<num_assets; copy++){ S_old[copy]=S_new[copy]; }*/ }while(H<C);//this will stop once H is less then the continuation value. at m-1, c=0 therefore m-1 is the max amount of loops. v_0=H; //if(idx==0){printf("result %i=%f", idx, v_0);} results_dev[idx]=v_0; delete[] S_new; //delete[] S_old; delete[] S_Weights; //return v_0; //printf("inside \n"); } } double PathEstimator(double strike, double r, double delta_t, int b, double m, double sigma[], double delta[], double X0[], double* X, double* weight_denominator, double* V, double asset_amount[], int num_assets, int Path_estimator_iterations, int iterator, int Final_iteration, curandState_t* States, curandState_t* states, int threads ){ //m=int(m); //for(int test=0; test<((m-1)*b); test++){ //printf("at the start of pathestimator den=%f /n", weight_denominator[test]); //} //printf("Ib serial X[0][0][0]= %f \n",*three_dim_index(X,0,0,0,m,b)); cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } int N= Path_estimator_iterations; double* sigma_host; sigma_host =sigma; double* delta_host; delta_host =delta; double* X0_host; X0_host =X0; double* asset_amount_host; asset_amount_host =asset_amount; int m_int=(int)m; //printf("at the start of pathestimator m_int=%i /n", m_int); int X_N=(m_int) * b * (num_assets); int W_N=(m_int-1) * b; int V_N=(m_int) * b; int delta_N= num_assets; int sigma_N=num_assets; int X0_N=num_assets; int asset_amount_N = num_assets; double* X_device; double* V_device; double* weight_denominator_device; double* sigma_device; double* delta_device; double* X0_device; double* asset_amount_device; error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } cudaMalloc((void**) &X_device, X_N*sizeof(double) ); cudaMemcpy(X_device, X, X_N*sizeof(double), cudaMemcpyHostToDevice); cudaMalloc((void**) &V_device, V_N*sizeof(double) ); cudaMemcpy(V_device, V, V_N*sizeof(double), cudaMemcpyHostToDevice); cudaMalloc((void**) &weight_denominator_device, W_N*sizeof(double) ); cudaMemcpy(weight_denominator_device, weight_denominator, W_N*sizeof(double), cudaMemcpyHostToDevice); cudaMalloc((void**) &X0_device, X0_N*sizeof(double) ); cudaMemcpy(X0_device, X0_host, X0_N*sizeof(double), cudaMemcpyHostToDevice); cudaMalloc((void**) &sigma_device, sigma_N*sizeof(double) ); cudaMemcpy(sigma_device, sigma_host, sigma_N*sizeof(double), cudaMemcpyHostToDevice); cudaMalloc((void**) &delta_device, delta_N*sizeof(double) ); cudaMemcpy(delta_device, delta_host, delta_N*sizeof(double), cudaMemcpyHostToDevice); cudaMalloc((void**) &asset_amount_device, asset_amount_N*sizeof(double) ); cudaMemcpy(asset_amount_device, asset_amount_host, asset_amount_N*sizeof(double), cudaMemcpyHostToDevice); cudaMemcpy(states, States, threads*sizeof(curandState_t*), cudaMemcpyHostToDevice); //dim3 gridDim((int)ceil(N/512.0)); //printf("the grid dim is:%i\n",(int)ceil(N/512.0)); //dim3 blockDim(512); dim3 gridDim((int)ceil(N/512.0)); dim3 blockDim(512.0); /*if(N>512){ gridDim()= ceil(N/521); } */ error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } double* results; results = new double[N]; double* results_dev; cudaMalloc((void**) &results_dev, N*sizeof(double) ); // CALL RANDOM SEEDING KERNEL HERE error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } /* curandState_t* states; cudaMalloc((void**) &states, N * sizeof(curandState_t)); init<<<gridDim, blockDim>>>(time(0), states); cudaDeviceSynchronize(); */ error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } //printf("inside \n"); cudaDeviceSetLimit(cudaLimitMallocHeapSize, 80000000*sizeof(double)); //size_t size; //cudaDeviceGetLimit(&size, cudaLimitMallocHeapSize); //printf("Heap size found to be %d\n",(int)size); //printf("after"); //for(int test=0; test<V_N; test++){ //printf("N=%i, strike=%f, r=%f, delta_t=%f, num_a=%i, b=%i", N, strike, r, delta_t, num_assets,b); //} PathEstimatorKernel<<<gridDim, blockDim>>>(X_device, weight_denominator_device, V_device, delta_device, sigma_device, X0_device, N, strike, r, delta_t, b, m_int, num_assets, states, results_dev, asset_amount_device); cudaDeviceSynchronize(); error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } //printf("here"); cudaMemcpy(results, results_dev, sizeof(double)*N, cudaMemcpyDeviceToHost); error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("Found at line %d\n", __LINE__); exit(1); } //cudaDeviceSynchronize(); //cudaMemcpy(States, states, sizeof(curandState_t)*N, cudaMemcpyDeviceToHost); cudaMemcpy(States, states, sizeof(curandState_t)*threads, cudaMemcpyDeviceToHost); error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("Found at line %d\n", __LINE__); exit(1); } double result=0; for(int f=0; f<Path_estimator_iterations; f++){ result+=results[f]; //printf("random %i =%f\n", f, results[f]); } result=(1/double(N))*result; delete[] results; error = cudaGetLastError(); if( error != cudaSuccess ) { std::cout << cudaGetErrorString(error) << std::endl; printf("found at line %d\n", __LINE__); exit(1); } cudaFree(X_device); cudaFree(V_device); cudaFree(weight_denominator_device); cudaFree(sigma_device); cudaFree(delta_device); cudaFree(X0_device); cudaFree(results_dev); cudaFree(asset_amount_device); if(iterator==Final_iteration-1){ cudaFree(states); //printf("done, iter=%i",iterator); } //cudaDeviceReset(); return result; //cudaDeviceReset(); }
d1112ef48212c861247b42b9eed9cfbc7c235bd2.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "reader_writer.h" #include "cpu.h" #include "gpu.h" #include "helper.h" #include <assert.h> #define checkError(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(hipError_t code, const char *file, int line, bool abort=true) { if (code != hipSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", hipGetErrorString(code), file, line); if (abort) exit(code); } } int main(int argc, const char **argv) { if (argc != 4) { std::cerr << "Usage: ./md_hybrid [parameter file] [0-1] [bool]" << std::endl; std::cerr << "The second paramter specifies the initial percentage of domain assigned to cpu." << std::endl; std::cerr << "The third paramter specifies if dynamic load balancing is used." << std::endl; exit(EXIT_FAILURE); } bool dynamic_lb; bool update_border; if (std::string(argv[3]) == "true") { dynamic_lb = true; } else if (std::string(argv[3]) == "false") { dynamic_lb = false; } else { std::cerr << "Wrong argument" << std::endl; exit(EXIT_FAILURE); } std::vector<Particle> particles; Params params; // Read parameter file and retrieve data ParameterReader params_reader; params_reader.read(std::string(argv[1])); params = params_reader.get(); // Read input data and set num_part ParticleReader part_reader; params.num_part = part_reader.read(params); particles = part_reader.get(); assert(particles.size() == params.num_part); // Create OutputWriter OutputWriter output_writer; // Init linked list for cell and particle parallel approach std::vector<int> linked_particles(params.num_part); std::vector<int> linked_cells(params.cells0 * params.cells1 * params.cells2, -1); // Hybrid stuff std::vector<int> active_particles(params.num_part, -1); std::vector<Particle> filtered_particles(params.num_part); std::vector<Particle> tmp_filtered_particles(params.num_part); int cntr = 0; int tmp_cntr = 0; // 0.33 CPU 0.66 GPU //int cell_border = params.cells0 * 0.; double border_factor = std::stod(argv[2]); int cell_border = params.cells0 * border_factor; bool only_border = true; // Data on device Particle *d_particles; Params *d_params; int *d_linked_cells; int *d_linked_particles; // Hybrid stuff int *d_active_particles; Particle *d_filtered_particles; int* d_cntr; const long long nBytes = sizeof(Particle) * (params.num_part); checkError(hipMalloc(&d_particles, nBytes)); checkError(hipMalloc(&d_params, sizeof(Params))); checkError(hipMalloc(&d_linked_cells, sizeof(int) * params.cells0 * params.cells1 * params.cells2)); checkError(hipMalloc(&d_linked_particles, sizeof(int) * params.num_part)); checkError(hipMalloc(&d_active_particles, sizeof(int) * params.num_part)); checkError(hipMalloc(&d_filtered_particles, nBytes)); checkError(hipMalloc(&d_cntr, sizeof(int))); checkError(hipMemcpy(d_particles, &particles[0], nBytes, hipMemcpyHostToDevice)); checkError(hipMemcpy(d_params, &params, sizeof(Params), hipMemcpyHostToDevice)); checkError(hipMemcpy(d_linked_cells, &linked_cells[0], sizeof(int) * params.cells0 * params.cells1 * params.cells2, hipMemcpyHostToDevice)); checkError(hipMemcpy(d_linked_particles, &linked_particles[0], sizeof(int) * params.num_part, hipMemcpyHostToDevice)); checkError(hipMemset(d_cntr, 0, sizeof(int))); const dim3 threadsPerBlock(params.block_size); const dim3 numBlocks(params.num_part / params.block_size + 1); const dim3 numBlocksCells((params.cells0 * params.cells1 * params.cells2) / params.block_size + 1); // Variables for measurement hipEvent_t gpu_start, gpu_end; hipEventCreate(&gpu_start); hipEventCreate(&gpu_end); double total_start, total_end, exch_start, exch_end, cpu_start, cpu_end; double total_time = 0.; double cpu_time = 0., gpu_time = 0.; // Variables for iteration double time = 0.; size_t iter = 0, iter_v = 0; //TODO hipLaunchKernelGGL(( set_list), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_active_particles, params.num_part, -1); hipLaunchKernelGGL(( update_list), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, d_linked_cells, d_linked_particles, cell_border, d_active_particles, d_cntr); checkError(hipMemcpy(&cntr, d_cntr, sizeof(int), hipMemcpyDeviceToHost)); std::cout << "(initial) particles on gpu: " << cntr << std::endl; cntr = 0; update_list(params, particles, linked_cells, linked_particles, cell_border, active_particles, cntr); std::cout << "(initial) particles on cpu: " << cntr << std::endl; // Initial force calc. hipLaunchKernelGGL(( calc_force), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, d_linked_cells, d_linked_particles, d_active_particles); calc_force(params, particles, linked_cells, linked_particles, active_particles, cntr); while (time <= params.time_end) { if (iter % params.vtk_out_freq == 0) { only_border = false; checkError(hipMemset(d_cntr, 0, sizeof(int))); hipLaunchKernelGGL(( filter_particles), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, cell_border, d_filtered_particles, d_cntr, only_border); checkError(hipMemcpy(&tmp_cntr, d_cntr, sizeof(int), hipMemcpyDeviceToHost)); checkError(hipMemcpy(&filtered_particles[0], d_filtered_particles, sizeof(Particle)*tmp_cntr, hipMemcpyDeviceToHost)); replace_particles(particles, filtered_particles, tmp_cntr); output_writer.write_vtk(particles, params, iter_v); ++iter_v; } total_start = getSeconds(); hipLaunchKernelGGL(( update_pos), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, d_active_particles); update_pos(params, particles, active_particles, cntr); //Exchange exch_start = getSeconds(); /// When changing border, all particles have to be synchronized update_border = (iter % 100 == 0 && iter != 0); if ( dynamic_lb && update_border ) { only_border = false; } else { only_border = true; } checkError(hipMemset(d_cntr, 0, sizeof(int))); hipLaunchKernelGGL(( filter_particles), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, cell_border, d_filtered_particles, d_cntr, only_border); checkError(hipMemcpy(&tmp_cntr, d_cntr, sizeof(int), hipMemcpyDeviceToHost)); checkError(hipMemcpy(&tmp_filtered_particles[0], d_filtered_particles, sizeof(Particle)*tmp_cntr, hipMemcpyDeviceToHost)); cntr = 0; filter_particles(params, particles, cell_border, filtered_particles, cntr, only_border); checkError(hipMemcpy(d_filtered_particles, &filtered_particles[0], sizeof(Particle)*cntr, hipMemcpyHostToDevice)); replace_particles(particles, tmp_filtered_particles, tmp_cntr); hipLaunchKernelGGL(( replace_particles), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_particles, d_filtered_particles, cntr); checkError(hipDeviceSynchronize()); exch_end = getSeconds(); //Dynamic load balancing if ( dynamic_lb && update_border ) { //TODO case 0 or 1... error checking std::cout << "gpu: " << gpu_time << " cpu: " << cpu_time << std::endl; //only change if gpu/cpu not approx. equal if (std::abs(gpu_time/cpu_time - 1) > 0.1) border_factor = (gpu_time/cpu_time) * border_factor; if ((std::abs(gpu_time/cpu_time - 1) > 0.5) && ((border_factor < 0.01) || (border_factor > 0.99) )) border_factor = 0.5; std::cout << "time diff: " << std::abs(gpu_time/cpu_time - 1) << std::endl; cell_border = border_factor * params.cells0; std::cout << "new border: " << border_factor << std::endl << std::endl; gpu_time = 0; cpu_time = 0; } hipEventRecord(gpu_start); hipLaunchKernelGGL(( set_list), dim3(numBlocksCells), dim3(threadsPerBlock), 0, 0, d_linked_cells, params.cells0 * params.cells1 * params.cells2, -1); hipLaunchKernelGGL(( set_list), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_active_particles, params.num_part, -1); checkError(hipMemset(d_cntr, 0, sizeof(int))); hipLaunchKernelGGL(( update_list), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, d_linked_cells, d_linked_particles, cell_border, d_active_particles, d_cntr); hipLaunchKernelGGL(( calc_force), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, d_linked_cells, d_linked_particles, d_active_particles); hipLaunchKernelGGL(( calc_velocity), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, d_active_particles); hipEventRecord(gpu_end); cpu_start = getSeconds(); linked_cells.assign(linked_cells.size(), -1); active_particles.assign(active_particles.size(), -1); cntr = 0; update_list(params, particles, linked_cells, linked_particles, cell_border, active_particles, cntr); calc_force(params, particles, linked_cells, linked_particles, active_particles, cntr); calc_velocity(params, particles, active_particles, cntr); cpu_end = getSeconds(); hipEventSynchronize(gpu_end); float tmp_gpu_time = 0.; hipEventElapsedTime(&tmp_gpu_time, gpu_start, gpu_end); gpu_time += tmp_gpu_time/1000; total_end = getSeconds(); total_time += total_end - total_start; cpu_time += cpu_end - cpu_start; //TODO /* if (iter % 100 == 0 && iter != 0) std:: cout << "time/iter: " << total_time/iter << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "total: " << total_end - total_start << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "exch: " << exch_end - exch_start << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "cpu: " << cpu_end - cpu_start << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "gpu: " << tmp_gpu_time/1000 << std::endl; */ time += params.timestep_length; ++iter; } checkError(hipDeviceSynchronize()); // write last vtk file if (iter % params.vtk_out_freq == 0) { only_border = false; checkError(hipMemset(d_cntr, 0, sizeof(int))); hipLaunchKernelGGL(( filter_particles), dim3(numBlocks), dim3(threadsPerBlock), 0, 0, d_params, d_particles, cell_border, d_filtered_particles, d_cntr, only_border); checkError(hipMemcpy(&cntr, d_cntr, sizeof(int), hipMemcpyDeviceToHost)); checkError(hipMemcpy(&filtered_particles[0], d_filtered_particles, sizeof(Particle)*cntr, hipMemcpyDeviceToHost)); replace_particles(particles, filtered_particles, cntr); output_writer.write_vtk(particles, params, iter_v); } std:: cout << total_time << std::endl; checkError( hipPeekAtLastError() ); checkError( hipDeviceSynchronize() ); std:: cout << "after" << std::endl; /* checkError(hipFree(d_params)); checkError(hipFree(d_particles)); checkError(hipFree(d_linked_cells)); checkError(hipFree(d_linked_particles)); checkError(hipFree(d_active_particles)); checkError(hipFree(d_filtered_particles)); checkError(hipFree(d_cntr)); */ exit(EXIT_SUCCESS); }
d1112ef48212c861247b42b9eed9cfbc7c235bd2.cu
#include "reader_writer.h" #include "cpu.h" #include "gpu.h" #include "helper.h" #include <assert.h> #define checkError(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); } } int main(int argc, const char **argv) { if (argc != 4) { std::cerr << "Usage: ./md_hybrid [parameter file] [0-1] [bool]" << std::endl; std::cerr << "The second paramter specifies the initial percentage of domain assigned to cpu." << std::endl; std::cerr << "The third paramter specifies if dynamic load balancing is used." << std::endl; exit(EXIT_FAILURE); } bool dynamic_lb; bool update_border; if (std::string(argv[3]) == "true") { dynamic_lb = true; } else if (std::string(argv[3]) == "false") { dynamic_lb = false; } else { std::cerr << "Wrong argument" << std::endl; exit(EXIT_FAILURE); } std::vector<Particle> particles; Params params; // Read parameter file and retrieve data ParameterReader params_reader; params_reader.read(std::string(argv[1])); params = params_reader.get(); // Read input data and set num_part ParticleReader part_reader; params.num_part = part_reader.read(params); particles = part_reader.get(); assert(particles.size() == params.num_part); // Create OutputWriter OutputWriter output_writer; // Init linked list for cell and particle parallel approach std::vector<int> linked_particles(params.num_part); std::vector<int> linked_cells(params.cells0 * params.cells1 * params.cells2, -1); // Hybrid stuff std::vector<int> active_particles(params.num_part, -1); std::vector<Particle> filtered_particles(params.num_part); std::vector<Particle> tmp_filtered_particles(params.num_part); int cntr = 0; int tmp_cntr = 0; // 0.33 CPU 0.66 GPU //int cell_border = params.cells0 * 0.; double border_factor = std::stod(argv[2]); int cell_border = params.cells0 * border_factor; bool only_border = true; // Data on device Particle *d_particles; Params *d_params; int *d_linked_cells; int *d_linked_particles; // Hybrid stuff int *d_active_particles; Particle *d_filtered_particles; int* d_cntr; const long long nBytes = sizeof(Particle) * (params.num_part); checkError(cudaMalloc(&d_particles, nBytes)); checkError(cudaMalloc(&d_params, sizeof(Params))); checkError(cudaMalloc(&d_linked_cells, sizeof(int) * params.cells0 * params.cells1 * params.cells2)); checkError(cudaMalloc(&d_linked_particles, sizeof(int) * params.num_part)); checkError(cudaMalloc(&d_active_particles, sizeof(int) * params.num_part)); checkError(cudaMalloc(&d_filtered_particles, nBytes)); checkError(cudaMalloc(&d_cntr, sizeof(int))); checkError(cudaMemcpy(d_particles, &particles[0], nBytes, cudaMemcpyHostToDevice)); checkError(cudaMemcpy(d_params, &params, sizeof(Params), cudaMemcpyHostToDevice)); checkError(cudaMemcpy(d_linked_cells, &linked_cells[0], sizeof(int) * params.cells0 * params.cells1 * params.cells2, cudaMemcpyHostToDevice)); checkError(cudaMemcpy(d_linked_particles, &linked_particles[0], sizeof(int) * params.num_part, cudaMemcpyHostToDevice)); checkError(cudaMemset(d_cntr, 0, sizeof(int))); const dim3 threadsPerBlock(params.block_size); const dim3 numBlocks(params.num_part / params.block_size + 1); const dim3 numBlocksCells((params.cells0 * params.cells1 * params.cells2) / params.block_size + 1); // Variables for measurement cudaEvent_t gpu_start, gpu_end; cudaEventCreate(&gpu_start); cudaEventCreate(&gpu_end); double total_start, total_end, exch_start, exch_end, cpu_start, cpu_end; double total_time = 0.; double cpu_time = 0., gpu_time = 0.; // Variables for iteration double time = 0.; size_t iter = 0, iter_v = 0; //TODO set_list<<<numBlocks, threadsPerBlock>>>(d_active_particles, params.num_part, -1); update_list<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, d_linked_cells, d_linked_particles, cell_border, d_active_particles, d_cntr); checkError(cudaMemcpy(&cntr, d_cntr, sizeof(int), cudaMemcpyDeviceToHost)); std::cout << "(initial) particles on gpu: " << cntr << std::endl; cntr = 0; update_list(params, particles, linked_cells, linked_particles, cell_border, active_particles, cntr); std::cout << "(initial) particles on cpu: " << cntr << std::endl; // Initial force calc. calc_force<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, d_linked_cells, d_linked_particles, d_active_particles); calc_force(params, particles, linked_cells, linked_particles, active_particles, cntr); while (time <= params.time_end) { if (iter % params.vtk_out_freq == 0) { only_border = false; checkError(cudaMemset(d_cntr, 0, sizeof(int))); filter_particles<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, cell_border, d_filtered_particles, d_cntr, only_border); checkError(cudaMemcpy(&tmp_cntr, d_cntr, sizeof(int), cudaMemcpyDeviceToHost)); checkError(cudaMemcpy(&filtered_particles[0], d_filtered_particles, sizeof(Particle)*tmp_cntr, cudaMemcpyDeviceToHost)); replace_particles(particles, filtered_particles, tmp_cntr); output_writer.write_vtk(particles, params, iter_v); ++iter_v; } total_start = getSeconds(); update_pos<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, d_active_particles); update_pos(params, particles, active_particles, cntr); //Exchange exch_start = getSeconds(); /// When changing border, all particles have to be synchronized update_border = (iter % 100 == 0 && iter != 0); if ( dynamic_lb && update_border ) { only_border = false; } else { only_border = true; } checkError(cudaMemset(d_cntr, 0, sizeof(int))); filter_particles<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, cell_border, d_filtered_particles, d_cntr, only_border); checkError(cudaMemcpy(&tmp_cntr, d_cntr, sizeof(int), cudaMemcpyDeviceToHost)); checkError(cudaMemcpy(&tmp_filtered_particles[0], d_filtered_particles, sizeof(Particle)*tmp_cntr, cudaMemcpyDeviceToHost)); cntr = 0; filter_particles(params, particles, cell_border, filtered_particles, cntr, only_border); checkError(cudaMemcpy(d_filtered_particles, &filtered_particles[0], sizeof(Particle)*cntr, cudaMemcpyHostToDevice)); replace_particles(particles, tmp_filtered_particles, tmp_cntr); replace_particles<<<numBlocks, threadsPerBlock>>>(d_particles, d_filtered_particles, cntr); checkError(cudaDeviceSynchronize()); exch_end = getSeconds(); //Dynamic load balancing if ( dynamic_lb && update_border ) { //TODO case 0 or 1... error checking std::cout << "gpu: " << gpu_time << " cpu: " << cpu_time << std::endl; //only change if gpu/cpu not approx. equal if (std::abs(gpu_time/cpu_time - 1) > 0.1) border_factor = (gpu_time/cpu_time) * border_factor; if ((std::abs(gpu_time/cpu_time - 1) > 0.5) && ((border_factor < 0.01) || (border_factor > 0.99) )) border_factor = 0.5; std::cout << "time diff: " << std::abs(gpu_time/cpu_time - 1) << std::endl; cell_border = border_factor * params.cells0; std::cout << "new border: " << border_factor << std::endl << std::endl; gpu_time = 0; cpu_time = 0; } cudaEventRecord(gpu_start); set_list<<<numBlocksCells, threadsPerBlock>>>(d_linked_cells, params.cells0 * params.cells1 * params.cells2, -1); set_list<<<numBlocks, threadsPerBlock>>>(d_active_particles, params.num_part, -1); checkError(cudaMemset(d_cntr, 0, sizeof(int))); update_list<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, d_linked_cells, d_linked_particles, cell_border, d_active_particles, d_cntr); calc_force<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, d_linked_cells, d_linked_particles, d_active_particles); calc_velocity<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, d_active_particles); cudaEventRecord(gpu_end); cpu_start = getSeconds(); linked_cells.assign(linked_cells.size(), -1); active_particles.assign(active_particles.size(), -1); cntr = 0; update_list(params, particles, linked_cells, linked_particles, cell_border, active_particles, cntr); calc_force(params, particles, linked_cells, linked_particles, active_particles, cntr); calc_velocity(params, particles, active_particles, cntr); cpu_end = getSeconds(); cudaEventSynchronize(gpu_end); float tmp_gpu_time = 0.; cudaEventElapsedTime(&tmp_gpu_time, gpu_start, gpu_end); gpu_time += tmp_gpu_time/1000; total_end = getSeconds(); total_time += total_end - total_start; cpu_time += cpu_end - cpu_start; //TODO /* if (iter % 100 == 0 && iter != 0) std:: cout << "time/iter: " << total_time/iter << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "total: " << total_end - total_start << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "exch: " << exch_end - exch_start << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "cpu: " << cpu_end - cpu_start << std::endl; if (iter % 100 == 0 && iter != 0) std:: cout << "gpu: " << tmp_gpu_time/1000 << std::endl; */ time += params.timestep_length; ++iter; } checkError(cudaDeviceSynchronize()); // write last vtk file if (iter % params.vtk_out_freq == 0) { only_border = false; checkError(cudaMemset(d_cntr, 0, sizeof(int))); filter_particles<<<numBlocks, threadsPerBlock>>>(d_params, d_particles, cell_border, d_filtered_particles, d_cntr, only_border); checkError(cudaMemcpy(&cntr, d_cntr, sizeof(int), cudaMemcpyDeviceToHost)); checkError(cudaMemcpy(&filtered_particles[0], d_filtered_particles, sizeof(Particle)*cntr, cudaMemcpyDeviceToHost)); replace_particles(particles, filtered_particles, cntr); output_writer.write_vtk(particles, params, iter_v); } std:: cout << total_time << std::endl; checkError( cudaPeekAtLastError() ); checkError( cudaDeviceSynchronize() ); std:: cout << "after" << std::endl; /* checkError(cudaFree(d_params)); checkError(cudaFree(d_particles)); checkError(cudaFree(d_linked_cells)); checkError(cudaFree(d_linked_particles)); checkError(cudaFree(d_active_particles)); checkError(cudaFree(d_filtered_particles)); checkError(cudaFree(d_cntr)); */ exit(EXIT_SUCCESS); }
105f82659f1d3c6688d0a6d0d76c433ac4c30f8f.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #ifndef THC_GENERIC_FILE #define THC_GENERIC_FILE "THH/generic/THHTensorSort.hip" #else // In alignment with default sort on a c++ map, this function // will permute key and value tensors identically, and // in such a way that the 'key' tensor is ordered numerically void THCTensor_(sortKeyValueInplace)(THCState* state, THCTensor* key, THCudaLongTensor* value, int dim, bool dir) { THArgCheck(key->sizes().equals(value->sizes()), 2, "Key tensor must have same size as value tensor"); int dims = THCudaLongTensor_nDimensionLegacyNoScalars(state, value); THArgCheck(dims <= MAX_CUTORCH_DIMS, 3, CUTORCH_DIM_WARNING); dims = THCTensor_(nDimensionLegacyNoScalars)(state, key); THArgCheck(dims <= MAX_CUTORCH_DIMS, 2, CUTORCH_DIM_WARNING); ptrdiff_t inElements = THCTensor_(nElement)(state, key); if (inElements == 0) { return; } int64_t keySliceSize = THCTensor_(sizeLegacyNoScalars)(state, key, dim); ptrdiff_t keySlices = inElements / keySliceSize; // The amount of shared memory and block size is based on // 2^ceil(lg(n)); we choose that sorting implementation for a given // size. int64_t ceilPowerOf2 = nextHighestPowerOf2(keySliceSize); // FIXME: We'd have to find some other trick with Thrust to perform a // vectorized (key, value) sort by slice segment if (ceilPowerOf2 > 2048) { THError("sortKeyValueInplace only works for sizes <= 2048 at present"); } // The grid is based on the number of independent slices that we // have to sort; one block per slice dim3 grid; if (!THC_getGridFromTiles(keySlices, grid)) { THError("Slice to sort is too large"); } #define HANDLE_CASE(TYPE, A, SIZE) \ do { \ int blockSize = SIZE / 2; \ if (blockSize < 1) { \ blockSize = 1; \ } \ \ dim3 block(blockSize); \ \ if (dir) { \ hipLaunchKernelGGL(( bitonicSortKVInPlace<scalar_t, int64_t, A, -1, GTComp<scalar_t>, TYPE, SIZE>) \ , dim3(grid), dim3(block), 0, THCState_getCurrentStream(state), \ keyInfo, \ keySlices, \ (TYPE) keySliceSize, \ (TYPE) keyInfo.strides[collapseKeyDim], \ valueInfo, \ (TYPE) valueInfo.strides[collapseValueDim], \ GTComp<scalar_t>()); \ } else { \ hipLaunchKernelGGL(( bitonicSortKVInPlace<scalar_t, int64_t, A, -1, LTComp<scalar_t>, TYPE, SIZE>) \ , dim3(grid), dim3(block), 0, THCState_getCurrentStream(state), \ keyInfo, \ keySlices, \ (TYPE) keySliceSize, \ (TYPE) keyInfo.strides[collapseKeyDim], \ valueInfo, \ (TYPE) valueInfo.strides[collapseValueDim], \ LTComp<scalar_t>()); \ } \ } while (0) #define HANDLE_SORT_CASE(TYPE, A) \ { \ switch (ceilPowerOf2) { \ case 2048: \ HANDLE_CASE(TYPE, A, 2048); \ break; \ case 1024: \ case 512: \ case 256: \ HANDLE_CASE(TYPE, A, 1024); \ break; \ case 128: \ case 64: \ HANDLE_CASE(TYPE, A, 128); \ break; \ case 32: \ case 16: \ case 8: \ case 4: \ case 2: \ HANDLE_CASE(TYPE, A, 32); \ break; \ case 1: \ /* Nothing to do, data already sorted */ \ break; \ default: \ assert(false); \ } \ } // The constructed key/value tensor info is used to select the slice // we are sorting on a per-block basis if (THCTensor_canUse32BitIndexMath(state, key)) { TensorInfo<scalar_t, unsigned int> keyInfo = getTensorInfo<scalar_t, THCTensor, unsigned int>(state, key); keyInfo.reduceDim(dim); int collapseKeyDim = keyInfo.collapseDims(dim); TensorInfo<int64_t, unsigned int> valueInfo = getTensorInfo<int64_t, THCudaLongTensor, unsigned int>(state, value); valueInfo.reduceDim(dim); int collapseValueDim = valueInfo.collapseDims(dim); if (keyInfo.isContiguous()) { HANDLE_SORT_CASE(unsigned int, -2); } else { switch (keyInfo.dims) { case 2: HANDLE_SORT_CASE(unsigned int, 2); break; default: HANDLE_SORT_CASE(unsigned int, -1); break; } } } else { TensorInfo<scalar_t, uint64_t> keyInfo = getTensorInfo<scalar_t, THCTensor, uint64_t>(state, key); keyInfo.reduceDim(dim); int collapseKeyDim = keyInfo.collapseDims(dim); TensorInfo<int64_t, uint64_t> valueInfo = getTensorInfo<int64_t, THCudaLongTensor, uint64_t>(state, value); valueInfo.reduceDim(dim); int collapseValueDim = valueInfo.collapseDims(dim); // int64_t case is rare, just instantiate the generic version HANDLE_SORT_CASE(uint64_t, -1); } #undef HANDLE_CASE #undef HANDLE_SORT_CASE #undef HANDLE_A_CASE THCudaCheck(hipGetLastError()); } void THCTensor_(sortViaThrust)(THCState* state, THCTensor* sorted, THCudaLongTensor* indices, THCTensor* input, int dim, bool dir) { int nDims = THCTensor_(nDimensionLegacyAll)(state, input); ptrdiff_t totalElements = THCTensor_(nElement)(state, input); int64_t sliceSize = THCTensor_(sizeLegacyNoScalars)(state, input, dim); int64_t sliceStride = THTensor_strideLegacyNoScalars(input, dim); // We perform a vectorized segmented sort in Thrust. // Say we are sorting a (2, 3) tensor. We have in flattened form: // values 0.4 1.2 5.3 6.2 1.3 2.3 // indices 0 1 2 3 4 5 // where indices is a global index (across all slices) // First we sort by values, globally: // values 6.2 5.3 2.3 1.2 1.3 0.4 // indices 3 2 5 1 4 0 // Then we stable sort by segment, which is index / 3: // values 5.3 1.2 0.4 6.2 2.3 1.3 // indices 2 1 0 3 5 4 // Then we translate the global index to a per-slice Lua index // (index % 3) + 1: // values 5.3 1.2 0.4 6.2 2.3 1.3 // indices 3 2 1 1 3 2 // This method can only work if the slice we are sorting (`dim`) is // innermost, and both values and indices are contiguous. We do this // by re-arranging the input into this form as needed, which will // unfortunately allocate memory if the request is not in this form. // Vectorized sort is slower than iterated sort if the number of // slices is small (since we're sorting twice, instead of invoking a // smaller sort `numSlices` times), but the Thrust sort // implementation here is a catch-all, so we're not looking for // efficiency, but instead correctness. THCTensor_(copy)(state, sorted, input); THCTensor* trKeys = THCTensor_(newWithTensor)(state, sorted); THCudaLongTensor* trIndices = THCudaLongTensor_newWithTensor(state, indices); // Transpose dim to innermost if (dim != nDims - 1) { THCTensor_(transpose)(state, trKeys, NULL, dim, nDims - 1); THCudaLongTensor_transpose(state, trIndices, NULL, dim, nDims - 1); } // Thrust must operate on a contiguous layout THCTensor* trContigKey = THCTensor_(newContiguous)(state, trKeys); THCudaLongTensor* trContigIndices = THCudaLongTensor_newContiguous(state, trIndices); THCTensor_(free)(state, trKeys); THCudaLongTensor_free(state, trIndices); THCThrustAllocator thrustAlloc(state); thrust::device_ptr<scalar_t> keyIter(THCTensor_(data)(state, trContigKey)); // Since we are composing a global index across all segments rather // than a per-segment index, we treat the memory as int so we don't // have problems sorting slices < 2^24 but where the entire tensor // has more than 2^24 elements thrust::device_ptr<int64_t> indexIter((int64_t*) THCudaLongTensor_data(state, trContigIndices)); // Fill the indices with a global index across all slices thrust::counting_iterator<int64_t> countIter(0); thrust::copy( #if TORCH_HIP_VERSION >= 7000 thrust::hip::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif countIter, countIter + totalElements, indexIter); // First, we sort globally (across all slices) according to key // (the values we're sorting) if (dir) { thrust::stable_sort_by_key( #if TORCH_HIP_VERSION >= 7000 thrust::hip::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif keyIter, keyIter + totalElements, indexIter, ThrustGTOp<scalar_t>()); } else { thrust::stable_sort_by_key( #if TORCH_HIP_VERSION >= 7000 thrust::hip::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif keyIter, keyIter + totalElements, indexIter, ThrustLTOp<scalar_t>()); } // Then, re-sort according to slice that each index is // in. This completes the segment sort in Thrust, since we're // stably sorting here, preserving the relative order of values // per each slice thrust::stable_sort_by_key( #if TORCH_HIP_VERSION >= 7000 thrust::hip::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif indexIter, indexIter + totalElements, keyIter, SliceComp(sliceSize)); // Translate the global integer 0-based index to a per-slice real // Lua index thrust::for_each( #if TORCH_HIP_VERSION >= 7000 thrust::hip::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif indexIter, indexIter + totalElements, GlobalIndexToPerSliceIndex(sliceSize)); // Reverse the transposition as needed if (dim != nDims - 1) { THCTensor_(transpose)(state, trContigKey, NULL, dim, nDims - 1); THCudaLongTensor_transpose(state, trContigIndices, NULL, dim, nDims - 1); } // Then copy back to the expected output THCTensor_(freeCopyTo)(state, trContigKey, sorted); THCudaLongTensor_freeCopyTo(state, trContigIndices, indices); } void THCTensor_(sort)(THCState* state, THCTensor *sorted, THCudaLongTensor *indices, THCTensor *input, int dim, int order) { THCAssertSameGPU(THCTensor_(checkGPU)(state, 2, sorted, input)); THCAssertSameGPU(THCudaLongTensor_checkGPU(state, 1, indices)); int64_t dims = THCTensor_(nDimensionLegacyNoScalars)(state, sorted); THArgCheck(dims <= MAX_CUTORCH_DIMS, 2, CUTORCH_DIM_WARNING); dims = THCTensor_(nDimensionLegacyNoScalars)(state, input); THArgCheck(dims <= MAX_CUTORCH_DIMS, 4, CUTORCH_DIM_WARNING); dims = THCudaLongTensor_nDimensionLegacyNoScalars(state, indices); THArgCheck(dims <= MAX_CUTORCH_DIMS, 3, CUTORCH_DIM_WARNING); // Make sure sufficient output space is allocated THCTensor_(resizeAs)(state, sorted, input); THCudaLongTensor_resize(state, indices, input->sizes(), {}); // How large are the slices that we are sorting? int64_t sliceSize = THCTensor_(sizeLegacyNoScalars)(state, input, dim); // Workaround: // CUDA 8 uses more shared memory than 7.5 for bitonicSortKVInPlace, // and so for the double word types, // we get "too many resources requested for launch" in the 2048 case #if TORCH_HIP_VERSION >= 8000 #if defined(THC_REAL_IS_DOUBLE) || defined(THC_REAL_IS_LONG) int maxSliceSize = 1024; #else int maxSliceSize = 2048; #endif #else int maxSliceSize = 2048; #endif #ifdef __HIP_PLATFORM_HCC__ // TODO bitonicSortKVInPlace hangs on ROCm currently. if (0) { #else if (sliceSize <= maxSliceSize) { #endif // Fill `indices` (the values) with the // slice-relative index. THCudaLongTensor_fillSliceWithIndex(state, indices, dim); // We sort k/v pairs in-place; copy unsorted input to output THCTensor_(copy)(state, sorted, input); // Sort using our in-place k/v kernel that supports arbitrary // layout THCTensor_(sortKeyValueInplace)(state, sorted, indices, dim, order); } else { // Otherwise, fall back upon Thrust, which handles all other cases // (potentially slowly, with extra copies/memory allocations) THCTensor_(sortViaThrust)(state, sorted, indices, input, dim, (bool) order); } THCudaCheck(hipGetLastError()); } #endif
105f82659f1d3c6688d0a6d0d76c433ac4c30f8f.cu
#ifndef THC_GENERIC_FILE #define THC_GENERIC_FILE "THC/generic/THCTensorSort.cu" #else // In alignment with default sort on a c++ map, this function // will permute key and value tensors identically, and // in such a way that the 'key' tensor is ordered numerically void THCTensor_(sortKeyValueInplace)(THCState* state, THCTensor* key, THCudaLongTensor* value, int dim, bool dir) { THArgCheck(key->sizes().equals(value->sizes()), 2, "Key tensor must have same size as value tensor"); int dims = THCudaLongTensor_nDimensionLegacyNoScalars(state, value); THArgCheck(dims <= MAX_CUTORCH_DIMS, 3, CUTORCH_DIM_WARNING); dims = THCTensor_(nDimensionLegacyNoScalars)(state, key); THArgCheck(dims <= MAX_CUTORCH_DIMS, 2, CUTORCH_DIM_WARNING); ptrdiff_t inElements = THCTensor_(nElement)(state, key); if (inElements == 0) { return; } int64_t keySliceSize = THCTensor_(sizeLegacyNoScalars)(state, key, dim); ptrdiff_t keySlices = inElements / keySliceSize; // The amount of shared memory and block size is based on // 2^ceil(lg(n)); we choose that sorting implementation for a given // size. int64_t ceilPowerOf2 = nextHighestPowerOf2(keySliceSize); // FIXME: We'd have to find some other trick with Thrust to perform a // vectorized (key, value) sort by slice segment if (ceilPowerOf2 > 2048) { THError("sortKeyValueInplace only works for sizes <= 2048 at present"); } // The grid is based on the number of independent slices that we // have to sort; one block per slice dim3 grid; if (!THC_getGridFromTiles(keySlices, grid)) { THError("Slice to sort is too large"); } #define HANDLE_CASE(TYPE, A, SIZE) \ do { \ int blockSize = SIZE / 2; \ if (blockSize < 1) { \ blockSize = 1; \ } \ \ dim3 block(blockSize); \ \ if (dir) { \ bitonicSortKVInPlace<scalar_t, int64_t, A, -1, GTComp<scalar_t>, TYPE, SIZE> \ <<<grid, block, 0, THCState_getCurrentStream(state)>>>( \ keyInfo, \ keySlices, \ (TYPE) keySliceSize, \ (TYPE) keyInfo.strides[collapseKeyDim], \ valueInfo, \ (TYPE) valueInfo.strides[collapseValueDim], \ GTComp<scalar_t>()); \ } else { \ bitonicSortKVInPlace<scalar_t, int64_t, A, -1, LTComp<scalar_t>, TYPE, SIZE> \ <<<grid, block, 0, THCState_getCurrentStream(state)>>>( \ keyInfo, \ keySlices, \ (TYPE) keySliceSize, \ (TYPE) keyInfo.strides[collapseKeyDim], \ valueInfo, \ (TYPE) valueInfo.strides[collapseValueDim], \ LTComp<scalar_t>()); \ } \ } while (0) #define HANDLE_SORT_CASE(TYPE, A) \ { \ switch (ceilPowerOf2) { \ case 2048: \ HANDLE_CASE(TYPE, A, 2048); \ break; \ case 1024: \ case 512: \ case 256: \ HANDLE_CASE(TYPE, A, 1024); \ break; \ case 128: \ case 64: \ HANDLE_CASE(TYPE, A, 128); \ break; \ case 32: \ case 16: \ case 8: \ case 4: \ case 2: \ HANDLE_CASE(TYPE, A, 32); \ break; \ case 1: \ /* Nothing to do, data already sorted */ \ break; \ default: \ assert(false); \ } \ } // The constructed key/value tensor info is used to select the slice // we are sorting on a per-block basis if (THCTensor_canUse32BitIndexMath(state, key)) { TensorInfo<scalar_t, unsigned int> keyInfo = getTensorInfo<scalar_t, THCTensor, unsigned int>(state, key); keyInfo.reduceDim(dim); int collapseKeyDim = keyInfo.collapseDims(dim); TensorInfo<int64_t, unsigned int> valueInfo = getTensorInfo<int64_t, THCudaLongTensor, unsigned int>(state, value); valueInfo.reduceDim(dim); int collapseValueDim = valueInfo.collapseDims(dim); if (keyInfo.isContiguous()) { HANDLE_SORT_CASE(unsigned int, -2); } else { switch (keyInfo.dims) { case 2: HANDLE_SORT_CASE(unsigned int, 2); break; default: HANDLE_SORT_CASE(unsigned int, -1); break; } } } else { TensorInfo<scalar_t, uint64_t> keyInfo = getTensorInfo<scalar_t, THCTensor, uint64_t>(state, key); keyInfo.reduceDim(dim); int collapseKeyDim = keyInfo.collapseDims(dim); TensorInfo<int64_t, uint64_t> valueInfo = getTensorInfo<int64_t, THCudaLongTensor, uint64_t>(state, value); valueInfo.reduceDim(dim); int collapseValueDim = valueInfo.collapseDims(dim); // int64_t case is rare, just instantiate the generic version HANDLE_SORT_CASE(uint64_t, -1); } #undef HANDLE_CASE #undef HANDLE_SORT_CASE #undef HANDLE_A_CASE THCudaCheck(cudaGetLastError()); } void THCTensor_(sortViaThrust)(THCState* state, THCTensor* sorted, THCudaLongTensor* indices, THCTensor* input, int dim, bool dir) { int nDims = THCTensor_(nDimensionLegacyAll)(state, input); ptrdiff_t totalElements = THCTensor_(nElement)(state, input); int64_t sliceSize = THCTensor_(sizeLegacyNoScalars)(state, input, dim); int64_t sliceStride = THTensor_strideLegacyNoScalars(input, dim); // We perform a vectorized segmented sort in Thrust. // Say we are sorting a (2, 3) tensor. We have in flattened form: // values 0.4 1.2 5.3 6.2 1.3 2.3 // indices 0 1 2 3 4 5 // where indices is a global index (across all slices) // First we sort by values, globally: // values 6.2 5.3 2.3 1.2 1.3 0.4 // indices 3 2 5 1 4 0 // Then we stable sort by segment, which is index / 3: // values 5.3 1.2 0.4 6.2 2.3 1.3 // indices 2 1 0 3 5 4 // Then we translate the global index to a per-slice Lua index // (index % 3) + 1: // values 5.3 1.2 0.4 6.2 2.3 1.3 // indices 3 2 1 1 3 2 // This method can only work if the slice we are sorting (`dim`) is // innermost, and both values and indices are contiguous. We do this // by re-arranging the input into this form as needed, which will // unfortunately allocate memory if the request is not in this form. // Vectorized sort is slower than iterated sort if the number of // slices is small (since we're sorting twice, instead of invoking a // smaller sort `numSlices` times), but the Thrust sort // implementation here is a catch-all, so we're not looking for // efficiency, but instead correctness. THCTensor_(copy)(state, sorted, input); THCTensor* trKeys = THCTensor_(newWithTensor)(state, sorted); THCudaLongTensor* trIndices = THCudaLongTensor_newWithTensor(state, indices); // Transpose dim to innermost if (dim != nDims - 1) { THCTensor_(transpose)(state, trKeys, NULL, dim, nDims - 1); THCudaLongTensor_transpose(state, trIndices, NULL, dim, nDims - 1); } // Thrust must operate on a contiguous layout THCTensor* trContigKey = THCTensor_(newContiguous)(state, trKeys); THCudaLongTensor* trContigIndices = THCudaLongTensor_newContiguous(state, trIndices); THCTensor_(free)(state, trKeys); THCudaLongTensor_free(state, trIndices); THCThrustAllocator thrustAlloc(state); thrust::device_ptr<scalar_t> keyIter(THCTensor_(data)(state, trContigKey)); // Since we are composing a global index across all segments rather // than a per-segment index, we treat the memory as int so we don't // have problems sorting slices < 2^24 but where the entire tensor // has more than 2^24 elements thrust::device_ptr<int64_t> indexIter((int64_t*) THCudaLongTensor_data(state, trContigIndices)); // Fill the indices with a global index across all slices thrust::counting_iterator<int64_t> countIter(0); thrust::copy( #if CUDA_VERSION >= 7000 thrust::cuda::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif countIter, countIter + totalElements, indexIter); // First, we sort globally (across all slices) according to key // (the values we're sorting) if (dir) { thrust::stable_sort_by_key( #if CUDA_VERSION >= 7000 thrust::cuda::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif keyIter, keyIter + totalElements, indexIter, ThrustGTOp<scalar_t>()); } else { thrust::stable_sort_by_key( #if CUDA_VERSION >= 7000 thrust::cuda::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif keyIter, keyIter + totalElements, indexIter, ThrustLTOp<scalar_t>()); } // Then, re-sort according to slice that each index is // in. This completes the segment sort in Thrust, since we're // stably sorting here, preserving the relative order of values // per each slice thrust::stable_sort_by_key( #if CUDA_VERSION >= 7000 thrust::cuda::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif indexIter, indexIter + totalElements, keyIter, SliceComp(sliceSize)); // Translate the global integer 0-based index to a per-slice real // Lua index thrust::for_each( #if CUDA_VERSION >= 7000 thrust::cuda::par(thrustAlloc).on(THCState_getCurrentStream(state)), #endif indexIter, indexIter + totalElements, GlobalIndexToPerSliceIndex(sliceSize)); // Reverse the transposition as needed if (dim != nDims - 1) { THCTensor_(transpose)(state, trContigKey, NULL, dim, nDims - 1); THCudaLongTensor_transpose(state, trContigIndices, NULL, dim, nDims - 1); } // Then copy back to the expected output THCTensor_(freeCopyTo)(state, trContigKey, sorted); THCudaLongTensor_freeCopyTo(state, trContigIndices, indices); } void THCTensor_(sort)(THCState* state, THCTensor *sorted, THCudaLongTensor *indices, THCTensor *input, int dim, int order) { THCAssertSameGPU(THCTensor_(checkGPU)(state, 2, sorted, input)); THCAssertSameGPU(THCudaLongTensor_checkGPU(state, 1, indices)); int64_t dims = THCTensor_(nDimensionLegacyNoScalars)(state, sorted); THArgCheck(dims <= MAX_CUTORCH_DIMS, 2, CUTORCH_DIM_WARNING); dims = THCTensor_(nDimensionLegacyNoScalars)(state, input); THArgCheck(dims <= MAX_CUTORCH_DIMS, 4, CUTORCH_DIM_WARNING); dims = THCudaLongTensor_nDimensionLegacyNoScalars(state, indices); THArgCheck(dims <= MAX_CUTORCH_DIMS, 3, CUTORCH_DIM_WARNING); // Make sure sufficient output space is allocated THCTensor_(resizeAs)(state, sorted, input); THCudaLongTensor_resize(state, indices, input->sizes(), {}); // How large are the slices that we are sorting? int64_t sliceSize = THCTensor_(sizeLegacyNoScalars)(state, input, dim); // Workaround: // CUDA 8 uses more shared memory than 7.5 for bitonicSortKVInPlace, // and so for the double word types, // we get "too many resources requested for launch" in the 2048 case #if CUDA_VERSION >= 8000 #if defined(THC_REAL_IS_DOUBLE) || defined(THC_REAL_IS_LONG) int maxSliceSize = 1024; #else int maxSliceSize = 2048; #endif #else int maxSliceSize = 2048; #endif #ifdef __HIP_PLATFORM_HCC__ // TODO bitonicSortKVInPlace hangs on ROCm currently. if (0) { #else if (sliceSize <= maxSliceSize) { #endif // Fill `indices` (the values) with the // slice-relative index. THCudaLongTensor_fillSliceWithIndex(state, indices, dim); // We sort k/v pairs in-place; copy unsorted input to output THCTensor_(copy)(state, sorted, input); // Sort using our in-place k/v kernel that supports arbitrary // layout THCTensor_(sortKeyValueInplace)(state, sorted, indices, dim, order); } else { // Otherwise, fall back upon Thrust, which handles all other cases // (potentially slowly, with extra copies/memory allocations) THCTensor_(sortViaThrust)(state, sorted, indices, input, dim, (bool) order); } THCudaCheck(cudaGetLastError()); } #endif
bea6912a79a98f9a3f31ab7ffadd86188df14589.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * Demonstrates how to use the d_vec_t class on CUDA devices. */ #include <iostream> #include "types.hpp" #include "types.cuh" using namespace types; template<class T> __global__ void increment(d_vec_t<T> d_vec){ for(size_t i=0; i<d_vec.size(); ++i){ d_vec(i) += 1; } } int main(){ vec_t<real_t> v = vec_t<real_t>(10,1.0); std::cout << "Before increment: " << v(9) << std::endl; // Set up device vector using v d_vec_t<real_t> d_vec = d_vec_t<real_t>(&v); // increment vector on device hipLaunchKernelGGL(( increment), dim3(1),dim3(1), 0, 0, d_vec); hipLaunchKernelGGL(( increment), dim3(1),dim3(1), 0, 0, d_vec); // Old way, required members of d_vec_t to be public //vec_t<real_t> w(&d_vec); //std::cout << "After increment: " << w(0) << std::endl; //vec_t<real_t> x(d_vec.host_vec()); //std::cout << "After increment: " << x(9) << std::endl; v.copy(d_vec.host_vec()); std::cout << "After increment: " << v(9) << std::endl; return 0; }
bea6912a79a98f9a3f31ab7ffadd86188df14589.cu
/** * Demonstrates how to use the d_vec_t class on CUDA devices. */ #include <iostream> #include "types.hpp" #include "types.cuh" using namespace types; template<class T> __global__ void increment(d_vec_t<T> d_vec){ for(size_t i=0; i<d_vec.size(); ++i){ d_vec(i) += 1; } } int main(){ vec_t<real_t> v = vec_t<real_t>(10,1.0); std::cout << "Before increment: " << v(9) << std::endl; // Set up device vector using v d_vec_t<real_t> d_vec = d_vec_t<real_t>(&v); // increment vector on device increment<<<1,1>>>(d_vec); increment<<<1,1>>>(d_vec); // Old way, required members of d_vec_t to be public //vec_t<real_t> w(&d_vec); //std::cout << "After increment: " << w(0) << std::endl; //vec_t<real_t> x(d_vec.host_vec()); //std::cout << "After increment: " << x(9) << std::endl; v.copy(d_vec.host_vec()); std::cout << "After increment: " << v(9) << std::endl; return 0; }
2557e07e0c792fb801299a3caae371cee97bbb08.hip
// !!! This is a file automatically generated by hipify!!! // From Appendix B.15 of the CUDA-C Programming Guide. #include <assert.h> #include <hip/hip_runtime.h> // assert() is only supported // for devices of compute capability 2.0 and higher #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) #undef assert #define assert(arg) #endif __global__ void testAssert(void) { int is_one = 1; int should_be_one = 0; // This will have no effect assert(is_one); // This will halt kernel execution assert(should_be_one); } int main(int argc, char* argv[]) { hipLaunchKernelGGL(( testAssert), dim3(1),dim3(1), 0, 0, ); hipDeviceSynchronize(); hipDeviceReset(); return 0; }
2557e07e0c792fb801299a3caae371cee97bbb08.cu
// From Appendix B.15 of the CUDA-C Programming Guide. #include <assert.h> #include <cuda.h> // assert() is only supported // for devices of compute capability 2.0 and higher #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) #undef assert #define assert(arg) #endif __global__ void testAssert(void) { int is_one = 1; int should_be_one = 0; // This will have no effect assert(is_one); // This will halt kernel execution assert(should_be_one); } int main(int argc, char* argv[]) { testAssert<<<1,1>>>(); cudaDeviceSynchronize(); cudaDeviceReset(); return 0; }
49841480e26e49b01f40ae0c0a1090923cd30dc7.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __device__ int2 devInt2[10]; __global__ void regOperation() { int2 f = devInt2[1]; devInt2[0] = f; } __global__ void regOperation2() { int2 f = devInt2[1]; devInt2[0].x = f.x; devInt2[0].y = f.y; }
49841480e26e49b01f40ae0c0a1090923cd30dc7.cu
#include "includes.h" __device__ int2 devInt2[10]; __global__ void regOperation() { int2 f = devInt2[1]; devInt2[0] = f; } __global__ void regOperation2() { int2 f = devInt2[1]; devInt2[0].x = f.x; devInt2[0].y = f.y; }
52a34f180b1bf36486963f1fb7ca305c4e614ee5.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void g_One_Bgrad(float* _delta, float* bgrad, int rows, int cols, int channels) { extern __shared__ float _sum[]; int channel = blockIdx.x; int col = blockIdx.y; int row = threadIdx.x; float delta = _delta[channel * rows * cols + row * cols + col]; _sum[row] = delta; __syncthreads(); int len = rows; while(len != 1) { __syncthreads(); int skip = (len + 1) >> 1; if(threadIdx.x < (len >> 1)) { _sum[threadIdx.x] += _sum[threadIdx.x + skip]; } len = (len + 1) >> 1; } __syncthreads(); if(threadIdx.x == 0) { bgrad[channel * cols + col] = _sum[0] / rows; } }
52a34f180b1bf36486963f1fb7ca305c4e614ee5.cu
#include "includes.h" __global__ void g_One_Bgrad(float* _delta, float* bgrad, int rows, int cols, int channels) { extern __shared__ float _sum[]; int channel = blockIdx.x; int col = blockIdx.y; int row = threadIdx.x; float delta = _delta[channel * rows * cols + row * cols + col]; _sum[row] = delta; __syncthreads(); int len = rows; while(len != 1) { __syncthreads(); int skip = (len + 1) >> 1; if(threadIdx.x < (len >> 1)) { _sum[threadIdx.x] += _sum[threadIdx.x + skip]; } len = (len + 1) >> 1; } __syncthreads(); if(threadIdx.x == 0) { bgrad[channel * cols + col] = _sum[0] / rows; } }
28303b9382271e3a3aee6d6ee25f47230bf23c0a.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "Timer.h" //#include "ScanTrans.cu.h" #define T 64 // Transpose matrix sequentially int seqTrans(float** h_in, float** h_out, int x_size, int y_size) { for (int y = 0; y < y_size; y++) { for (int x = 0; x < x_size; x++) { h_out[x][y] = h_in[y][x]; } } return 1; } __global__ void naiveParTrans(float* d_in, float* d_out, int x_size, int y_size) { int gidx = blockIdx.x * blockDim.x + threadIdx.x; int gidy = blockIdx.y * blockDim.y + threadIdx.y; if (gidx < x_size && gidy < y_size) { d_out[gidx*y_size+gidy] = d_in[gidy*x_size + gidx]; } } __global__ void matTranspose(float* d_in, float* d_out, int x_size, int y_size) { __shared__ float tile[T][T+1]; int tidx = threadIdx.x; int tidy = threadIdx.y; int j = blockIdx.x*T + tidx; int i = blockIdx.y*T + tidy; if (j < y_size && i < x_size) { tile[tidy][tidx] = d_in[i*y_size+j]; } __syncthreads(); i = blockIdx.y*T + threadIdx.x; j = blockIdx.x*T + threadIdx.y; if (j < y_size && i < x_size) { d_out[j*x_size+i] = tile[tidx][tidy]; } } // Helper function for deallocating main memory matrices int deallocMatr(float** matr, int y_size) { for (int i = 0; i < y_size; i++) { free(matr[i]); } free(matr); return 1; } int main() { int dim_x = 2048; int dim_y = 2048; dim3 block (T, T, 1); dim3 grid (dim_x, dim_y, 1); int num_threads = dim_x*dim_y; size_t size = num_threads*sizeof(float); // Allocate space for h_in and d_in, and initialize it float** h_in = (float**) malloc(dim_y*sizeof(float*)); float* d_in_tmp = (float*) malloc(size); float* d_naiv_in; float* d_tiled_in; int position; hipMalloc((void**)&d_naiv_in, size); hipMalloc((void**)&d_tiled_in, size); for (int i = 0; i < dim_y; i++) { float* tmp_h = (float*) malloc(dim_x*sizeof(float)); for (int j = 0; j < dim_x; j++) { tmp_h[j] = (float) j; position = (i*dim_x+j); d_in_tmp[position] = (float) j; } h_in[i] = tmp_h; } hipMemcpy(d_naiv_in, d_in_tmp, size, hipMemcpyHostToDevice); hipMemcpy(d_tiled_in, d_in_tmp, size, hipMemcpyHostToDevice); float* d_out_tmp = (float*) malloc(size); // Allocate space for h_out and d_out. float** h_out = (float**) malloc(dim_x*sizeof(float*)); float* d_naiv_out; float* d_tiled_out; hipMalloc((void**)&d_naiv_out, size); hipMalloc((void**)&d_tiled_out, size); for (int i = 0; i < dim_x; i++) { float* tmp_h = (float*) malloc(dim_y*sizeof(float)); for (int j = 0; j < dim_y; j++) { tmp_h[j] = 0.0; position = (i*dim_x+j); d_out_tmp[position] = (float) 0; } h_out[i] = tmp_h; } hipMemcpy(d_naiv_out, d_out_tmp, size, hipMemcpyHostToDevice); hipMemcpy(d_tiled_out, d_out_tmp, size, hipMemcpyHostToDevice); // Create timers for sequential run unsigned long int t_elapsed; struct timeval t_start, t_end, t_diff; gettimeofday(&t_start, NULL); // Run sequentially seqTrans(h_in, h_out, dim_x, dim_y); gettimeofday(&t_end, NULL); timeval_subtract(&t_diff, &t_end, &t_start); t_elapsed = (t_diff.tv_sec*1e6+t_diff.tv_usec); printf("CPU Transpositioning done in: %lu microsecs\n", t_elapsed); gettimeofday(&t_start, NULL); // Run naive parallel hipLaunchKernelGGL(( naiveParTrans), dim3(grid), dim3(block) , 0, 0, d_naiv_in, d_naiv_out, dim_x, dim_y); hipDeviceSynchronize(); gettimeofday(&t_end, NULL); timeval_subtract(&t_diff, &t_end, &t_start); t_elapsed = (t_diff.tv_sec*1e6+t_diff.tv_usec); printf("Naive GPU Transpositioning done in: %lu microsecs\n", t_elapsed); float* d_naiv_res = (float*) malloc(size); hipMemcpy(d_naiv_res, d_naiv_out, size, hipMemcpyDeviceToHost); gettimeofday(&t_start, NULL); hipLaunchKernelGGL(( matTranspose), dim3(grid), dim3(block) , 0, 0, d_tiled_in, d_tiled_out, dim_x, dim_y); hipDeviceSynchronize(); gettimeofday(&t_end, NULL); timeval_subtract(&t_diff, &t_end, &t_start); t_elapsed = (t_diff.tv_sec*1e6+t_diff.tv_usec); printf("Memory Coalesced GPU Transpositioning done in: %lu microsecs\n", t_elapsed); float* d_tiled_res = (float*) malloc(size); hipMemcpy(d_tiled_res, d_tiled_out, size, hipMemcpyDeviceToHost); bool isEqual = true; // Validate: for (int x = 0; x < dim_x; x++) { for (int y = 0; y < dim_y; y++) { if (abs(h_out[x][y] - d_naiv_res[x*dim_y+y]) > 0.00005 && abs(d_naiv_res[x*dim_y+y]-d_tiled_res[x*dim_y+y]) > 0.00005 && isEqual) { printf("INVALID: %.1f != %.1f != %.1f\n", h_out[x][y], d_naiv_res[x*dim_y+y], d_tiled_res[x*dim_y+y]); isEqual = false; } } } if (isEqual) { printf("Valid\n"); } deallocMatr(h_out, dim_x); deallocMatr(h_in, dim_y); free(d_naiv_res); free(d_tiled_res); free(d_out_tmp); free(d_in_tmp); hipFree(d_naiv_out); hipFree(d_naiv_in); hipFree(d_tiled_out); hipFree(d_tiled_in); return 1; }
28303b9382271e3a3aee6d6ee25f47230bf23c0a.cu
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "Timer.h" //#include "ScanTrans.cu.h" #define T 64 // Transpose matrix sequentially int seqTrans(float** h_in, float** h_out, int x_size, int y_size) { for (int y = 0; y < y_size; y++) { for (int x = 0; x < x_size; x++) { h_out[x][y] = h_in[y][x]; } } return 1; } __global__ void naiveParTrans(float* d_in, float* d_out, int x_size, int y_size) { int gidx = blockIdx.x * blockDim.x + threadIdx.x; int gidy = blockIdx.y * blockDim.y + threadIdx.y; if (gidx < x_size && gidy < y_size) { d_out[gidx*y_size+gidy] = d_in[gidy*x_size + gidx]; } } __global__ void matTranspose(float* d_in, float* d_out, int x_size, int y_size) { __shared__ float tile[T][T+1]; int tidx = threadIdx.x; int tidy = threadIdx.y; int j = blockIdx.x*T + tidx; int i = blockIdx.y*T + tidy; if (j < y_size && i < x_size) { tile[tidy][tidx] = d_in[i*y_size+j]; } __syncthreads(); i = blockIdx.y*T + threadIdx.x; j = blockIdx.x*T + threadIdx.y; if (j < y_size && i < x_size) { d_out[j*x_size+i] = tile[tidx][tidy]; } } // Helper function for deallocating main memory matrices int deallocMatr(float** matr, int y_size) { for (int i = 0; i < y_size; i++) { free(matr[i]); } free(matr); return 1; } int main() { int dim_x = 2048; int dim_y = 2048; dim3 block (T, T, 1); dim3 grid (dim_x, dim_y, 1); int num_threads = dim_x*dim_y; size_t size = num_threads*sizeof(float); // Allocate space for h_in and d_in, and initialize it float** h_in = (float**) malloc(dim_y*sizeof(float*)); float* d_in_tmp = (float*) malloc(size); float* d_naiv_in; float* d_tiled_in; int position; cudaMalloc((void**)&d_naiv_in, size); cudaMalloc((void**)&d_tiled_in, size); for (int i = 0; i < dim_y; i++) { float* tmp_h = (float*) malloc(dim_x*sizeof(float)); for (int j = 0; j < dim_x; j++) { tmp_h[j] = (float) j; position = (i*dim_x+j); d_in_tmp[position] = (float) j; } h_in[i] = tmp_h; } cudaMemcpy(d_naiv_in, d_in_tmp, size, cudaMemcpyHostToDevice); cudaMemcpy(d_tiled_in, d_in_tmp, size, cudaMemcpyHostToDevice); float* d_out_tmp = (float*) malloc(size); // Allocate space for h_out and d_out. float** h_out = (float**) malloc(dim_x*sizeof(float*)); float* d_naiv_out; float* d_tiled_out; cudaMalloc((void**)&d_naiv_out, size); cudaMalloc((void**)&d_tiled_out, size); for (int i = 0; i < dim_x; i++) { float* tmp_h = (float*) malloc(dim_y*sizeof(float)); for (int j = 0; j < dim_y; j++) { tmp_h[j] = 0.0; position = (i*dim_x+j); d_out_tmp[position] = (float) 0; } h_out[i] = tmp_h; } cudaMemcpy(d_naiv_out, d_out_tmp, size, cudaMemcpyHostToDevice); cudaMemcpy(d_tiled_out, d_out_tmp, size, cudaMemcpyHostToDevice); // Create timers for sequential run unsigned long int t_elapsed; struct timeval t_start, t_end, t_diff; gettimeofday(&t_start, NULL); // Run sequentially seqTrans(h_in, h_out, dim_x, dim_y); gettimeofday(&t_end, NULL); timeval_subtract(&t_diff, &t_end, &t_start); t_elapsed = (t_diff.tv_sec*1e6+t_diff.tv_usec); printf("CPU Transpositioning done in: %lu microsecs\n", t_elapsed); gettimeofday(&t_start, NULL); // Run naive parallel naiveParTrans<<< grid, block >>>(d_naiv_in, d_naiv_out, dim_x, dim_y); cudaThreadSynchronize(); gettimeofday(&t_end, NULL); timeval_subtract(&t_diff, &t_end, &t_start); t_elapsed = (t_diff.tv_sec*1e6+t_diff.tv_usec); printf("Naive GPU Transpositioning done in: %lu microsecs\n", t_elapsed); float* d_naiv_res = (float*) malloc(size); cudaMemcpy(d_naiv_res, d_naiv_out, size, cudaMemcpyDeviceToHost); gettimeofday(&t_start, NULL); matTranspose<<< grid, block >>>(d_tiled_in, d_tiled_out, dim_x, dim_y); cudaThreadSynchronize(); gettimeofday(&t_end, NULL); timeval_subtract(&t_diff, &t_end, &t_start); t_elapsed = (t_diff.tv_sec*1e6+t_diff.tv_usec); printf("Memory Coalesced GPU Transpositioning done in: %lu microsecs\n", t_elapsed); float* d_tiled_res = (float*) malloc(size); cudaMemcpy(d_tiled_res, d_tiled_out, size, cudaMemcpyDeviceToHost); bool isEqual = true; // Validate: for (int x = 0; x < dim_x; x++) { for (int y = 0; y < dim_y; y++) { if (abs(h_out[x][y] - d_naiv_res[x*dim_y+y]) > 0.00005 && abs(d_naiv_res[x*dim_y+y]-d_tiled_res[x*dim_y+y]) > 0.00005 && isEqual) { printf("INVALID: %.1f != %.1f != %.1f\n", h_out[x][y], d_naiv_res[x*dim_y+y], d_tiled_res[x*dim_y+y]); isEqual = false; } } } if (isEqual) { printf("Valid\n"); } deallocMatr(h_out, dim_x); deallocMatr(h_in, dim_y); free(d_naiv_res); free(d_tiled_res); free(d_out_tmp); free(d_in_tmp); cudaFree(d_naiv_out); cudaFree(d_naiv_in); cudaFree(d_tiled_out); cudaFree(d_tiled_in); return 1; }
bd6866c4dc37ae52c0349692c1af34ab040fc05e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Homework 1 // Color to Greyscale Conversion //A common way to represent color images is known as RGBA - the color //is specified by how much Red, Green, and Blue is in it. //The 'A' stands for Alpha and is used for transparency; it will be //ignored in this homework. //Each channel Red, Blue, Green, and Alpha is represented by one byte. //Since we are using one byte for each color there are 256 different //possible values for each color. This means we use 4 bytes per pixel. //Greyscale images are represented by a single intensity value per pixel //which is one byte in size. //To convert an image from color to grayscale one simple method is to //set the intensity to the average of the RGB channels. But we will //use a more sophisticated method that takes into account how the eye //perceives color and weights the channels unequally. //The eye responds most strongly to green followed by red and then blue. //The NTSC (National Television System Committee) recommends the following //formula for color to greyscale conversion: //I = .299f * R + .587f * G + .114f * B //Notice the trailing f's on the numbers which indicate that they are //single precision floating point constants and not double precision //constants. //You should fill in the kernel as well as set the block and grid sizes //so that the entire image is processed. #include "reference_calc.cpp" #include "utils.h" #include <stdio.h> #include <math.h> __global__ void rgba_to_greyscale(const uchar4* const rgbaImage, unsigned char* const greyImage, int numRows, int numCols) { //TODO //Fill in the kernel to convert from color to greyscale //the mapping from components of a uchar4 to RGBA is: // .x -> R ; .y -> G ; .z -> B ; .w -> A // //The output (greyImage) at each pixel should be the result of //applying the formula: output = .299f * R + .587f * G + .114f * B; //Note: We will be ignoring the alpha channel for this conversion //First create a mapping from the 2D block and grid locations //to an absolute 2D location in the image, then use that to //calculate a 1D offset int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; if(row > numRows || col > numCols) { return; } // This thread corresponds to a valid pixel int pixel = col + row * numCols; // Minimize global memory access. uchar4 rgba = rgbaImage[pixel]; unsigned char r = rgba.x; unsigned char g = rgba.y; unsigned char b = rgba.z; float channelSum = .299f * r + .587f * g + .114f * b; greyImage[pixel] = channelSum; } void your_rgba_to_greyscale(const uchar4 * const h_rgbaImage, uchar4 * const d_rgbaImage, unsigned char* const d_greyImage, size_t numRows, size_t numCols) { const dim3 blockSize(32, 32, 1); //TODO const dim3 gridSize( ceil((double)numCols/32), ceil((double)numRows/32), 1); //TODO hipLaunchKernelGGL(( rgba_to_greyscale), dim3(gridSize), dim3(blockSize), 0, 0, d_rgbaImage, d_greyImage, numRows, numCols); hipDeviceSynchronize(); checkCudaErrors(hipGetLastError()); }
bd6866c4dc37ae52c0349692c1af34ab040fc05e.cu
// Homework 1 // Color to Greyscale Conversion //A common way to represent color images is known as RGBA - the color //is specified by how much Red, Green, and Blue is in it. //The 'A' stands for Alpha and is used for transparency; it will be //ignored in this homework. //Each channel Red, Blue, Green, and Alpha is represented by one byte. //Since we are using one byte for each color there are 256 different //possible values for each color. This means we use 4 bytes per pixel. //Greyscale images are represented by a single intensity value per pixel //which is one byte in size. //To convert an image from color to grayscale one simple method is to //set the intensity to the average of the RGB channels. But we will //use a more sophisticated method that takes into account how the eye //perceives color and weights the channels unequally. //The eye responds most strongly to green followed by red and then blue. //The NTSC (National Television System Committee) recommends the following //formula for color to greyscale conversion: //I = .299f * R + .587f * G + .114f * B //Notice the trailing f's on the numbers which indicate that they are //single precision floating point constants and not double precision //constants. //You should fill in the kernel as well as set the block and grid sizes //so that the entire image is processed. #include "reference_calc.cpp" #include "utils.h" #include <stdio.h> #include <math.h> __global__ void rgba_to_greyscale(const uchar4* const rgbaImage, unsigned char* const greyImage, int numRows, int numCols) { //TODO //Fill in the kernel to convert from color to greyscale //the mapping from components of a uchar4 to RGBA is: // .x -> R ; .y -> G ; .z -> B ; .w -> A // //The output (greyImage) at each pixel should be the result of //applying the formula: output = .299f * R + .587f * G + .114f * B; //Note: We will be ignoring the alpha channel for this conversion //First create a mapping from the 2D block and grid locations //to an absolute 2D location in the image, then use that to //calculate a 1D offset int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; if(row > numRows || col > numCols) { return; } // This thread corresponds to a valid pixel int pixel = col + row * numCols; // Minimize global memory access. uchar4 rgba = rgbaImage[pixel]; unsigned char r = rgba.x; unsigned char g = rgba.y; unsigned char b = rgba.z; float channelSum = .299f * r + .587f * g + .114f * b; greyImage[pixel] = channelSum; } void your_rgba_to_greyscale(const uchar4 * const h_rgbaImage, uchar4 * const d_rgbaImage, unsigned char* const d_greyImage, size_t numRows, size_t numCols) { const dim3 blockSize(32, 32, 1); //TODO const dim3 gridSize( ceil((double)numCols/32), ceil((double)numRows/32), 1); //TODO rgba_to_greyscale<<<gridSize, blockSize>>>(d_rgbaImage, d_greyImage, numRows, numCols); cudaDeviceSynchronize(); checkCudaErrors(cudaGetLastError()); }
aec07b0a4a026775ebb0a6c7e3dddb7fcaf3371a.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> __global__ void addArrays(int* a, int* b,int* c) { int i = threadIdx.x; c[i] = a[i] + b[i]; } int main() { const int count = 5; const int size = count * sizeof(int); int ha[] = {1,2,3,4,5}; int hb[] = {10,20,30,40,50}; int hc[count]; int *da, *db, *dc; hipMalloc(&da,size); hipMalloc(&db,size); hipMalloc(&dc,size); hipMemcpy(da,ha,size,hipMemcpyHostToDevice); hipMemcpy(db,hb,size,hipMemcpyHostToDevice); hipLaunchKernelGGL(( addArrays) , dim3(1),dim3(count), 0, 0, da,db,dc); hipMemcpy(hc,dc,size,hipMemcpyDeviceToHost); for(int i = 0; i < count;i++) printf("%d ",hc[i]); }
aec07b0a4a026775ebb0a6c7e3dddb7fcaf3371a.cu
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> __global__ void addArrays(int* a, int* b,int* c) { int i = threadIdx.x; c[i] = a[i] + b[i]; } int main() { const int count = 5; const int size = count * sizeof(int); int ha[] = {1,2,3,4,5}; int hb[] = {10,20,30,40,50}; int hc[count]; int *da, *db, *dc; cudaMalloc(&da,size); cudaMalloc(&db,size); cudaMalloc(&dc,size); cudaMemcpy(da,ha,size,cudaMemcpyHostToDevice); cudaMemcpy(db,hb,size,cudaMemcpyHostToDevice); addArrays <<<1,count>>>(da,db,dc); cudaMemcpy(hc,dc,size,cudaMemcpyDeviceToHost); for(int i = 0; i < count;i++) printf("%d ",hc[i]); }
ce321314dbf447837046d2c26ca7e9d288cfc982.hip
// !!! This is a file automatically generated by hipify!!! #include <ATen/Dispatch.h> #include <ATen/native/DispatchStub.h> #include <ATen/native/hip/Loops.cuh> #include <ATen/native/BinaryOps.h> #include <ATen/native/TensorIterator.h> #include <type_traits> // NOTE: CUDA on Windows requires that the enclosing function // of a __device__ lambda not have internal linkage. namespace at { namespace native { void remainder_kernel_cuda(TensorIteratorBase& iter) { if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "remainder_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { scalar_t r = a % b; if (!std::is_unsigned<scalar_t>::value && (r != 0) && ((r < 0) != (b < 0))) { r += b; } return r; }); }); } else { AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.common_dtype(), "remainder_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { auto mod = ::fmod(a, b); if (!std::is_unsigned<scalar_t>::value && (mod != 0) && ((b < 0) != (mod < 0))) { mod += b; } return mod; }); }); } } void fmod_kernel_cuda(TensorIterator& iter) { if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "fmod_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return a % b; }); }); } else { AT_DISPATCH_FLOATING_TYPES_AND(kHalf, iter.common_dtype(), "fmod_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { return ::fmod(a, b); }); }); } } REGISTER_DISPATCH(remainder_stub, &remainder_kernel_cuda); REGISTER_DISPATCH(fmod_stub, &fmod_kernel_cuda); }} // namespace at::native
ce321314dbf447837046d2c26ca7e9d288cfc982.cu
#include <ATen/Dispatch.h> #include <ATen/native/DispatchStub.h> #include <ATen/native/cuda/Loops.cuh> #include <ATen/native/BinaryOps.h> #include <ATen/native/TensorIterator.h> #include <type_traits> // NOTE: CUDA on Windows requires that the enclosing function // of a __device__ lambda not have internal linkage. namespace at { namespace native { void remainder_kernel_cuda(TensorIteratorBase& iter) { if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "remainder_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { scalar_t r = a % b; if (!std::is_unsigned<scalar_t>::value && (r != 0) && ((r < 0) != (b < 0))) { r += b; } return r; }); }); } else { AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.common_dtype(), "remainder_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { auto mod = ::fmod(a, b); if (!std::is_unsigned<scalar_t>::value && (mod != 0) && ((b < 0) != (mod < 0))) { mod += b; } return mod; }); }); } } void fmod_kernel_cuda(TensorIterator& iter) { if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "fmod_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return a % b; }); }); } else { AT_DISPATCH_FLOATING_TYPES_AND(kHalf, iter.common_dtype(), "fmod_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { return ::fmod(a, b); }); }); } } REGISTER_DISPATCH(remainder_stub, &remainder_kernel_cuda); REGISTER_DISPATCH(fmod_stub, &fmod_kernel_cuda); }} // namespace at::native
bc18db52d7261dae50d17167f3601c2e32d7c1a3.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * Derived from the nVIDIA CUDA 8.0 samples by * * Eyal Rozenberg <E.Rozenberg@cwi.nl> * * The derivation is specifically permitted in the nVIDIA CUDA Samples EULA * and the deriver is the owner of this code according to the EULA. * * Use this reasonably. If you want to discuss licensing formalities, please * contact the author. * * Modified by VinInn for testing math funcs */ /* to run test foreach f ( $CMSSW_BASE/test/$SCRAM_ARCH/DFM_Vector* ) echo $f; $f end */ #include "cuda/api_wrappers.h" #include <iostream> #include <iomanip> #include <memory> #include <algorithm> #include <chrono> #include<random> #include<cassert> std::mt19937 eng; std::mt19937 eng2; std::uniform_real_distribution<float> rgen(0.,1.); #include<DataFormats/Math/interface/approx_log.h> #include<DataFormats/Math/interface/approx_exp.h> #include<DataFormats/Math/interface/approx_atan2.h> constexpr float myExp(float x) { return unsafe_expf<6>(x); } constexpr float myLog(float x) { return unsafe_logf<6>(x); } #ifdef __NVCC__ #define inline __host__ __device__ inline #include<vdt/sin.h> #undef inline #else #include<vdt/sin.h> #endif __host__ __device__ inline float mySin(float x) { return vdt::fast_sinf(x); } constexpr int USEEXP=0, USESIN=1, USELOG=2; template<int USE, bool ADDY=false> // __host__ __device__ constexpr float testFunc(float x, float y) { float ret=0; if(USE==USEEXP) ret = myExp(x); else if(USE==USESIN) ret = mySin(x); else ret = myLog(x); return ADDY ? ret+y : ret; } template<int USE, bool ADDY> __global__ void vectorOp(const float *A, const float *B, float *C, int numElements) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < numElements) { C[i] = testFunc<USE,ADDY>(A[i],B[i]); } } template<int USE, bool ADDY> void vectorOpH(const float *A, const float *B, float *C, int numElements) { for (int i=0; i<numElements; ++i) { C[i] = testFunc<USE,ADDY>(A[i],B[i]); } } template<int USE, bool ADDY=false> void go() { auto start = std::chrono::high_resolution_clock::now(); auto delta = start - start; if (cuda::device::count() == 0) { std::cerr << "No CUDA devices on this system" << "\n"; exit(EXIT_FAILURE); } auto current_device = cuda::device::current::get(); int numElements = 200000; size_t size = numElements * sizeof(float); std::cout << "[Vector of " << numElements << " elements]\n"; auto h_A = std::make_unique<float[]>(numElements); auto h_B = std::make_unique<float[]>(numElements); auto h_C = std::make_unique<float[]>(numElements); auto h_C2 = std::make_unique<float[]>(numElements); std::generate(h_A.get(), h_A.get() + numElements, [&](){return rgen(eng);}); std::generate(h_B.get(), h_B.get() + numElements, [&](){return rgen(eng);}); delta -= (std::chrono::high_resolution_clock::now()-start); auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements); auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements); auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements); cuda::memory::copy(d_A.get(), h_A.get(), size); cuda::memory::copy(d_B.get(), h_B.get(), size); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda alloc+copy took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; // Launch the Vector OP CUDA Kernel int threadsPerBlock = 256; int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock; std::cout << "CUDA kernel launch with " << blocksPerGrid << " blocks of " << threadsPerBlock << " threads\n"; delta -= (std::chrono::high_resolution_clock::now()-start); cuda::launch( vectorOp<USE,ADDY>, { blocksPerGrid, threadsPerBlock }, d_A.get(), d_B.get(), d_C.get(), numElements ); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; delta -= (std::chrono::high_resolution_clock::now()-start); cuda::launch( vectorOp<USE,ADDY>, { blocksPerGrid, threadsPerBlock }, d_A.get(), d_B.get(), d_C.get(), numElements ); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; delta -= (std::chrono::high_resolution_clock::now()-start); cuda::memory::copy(h_C.get(), d_C.get(), size); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda copy back took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; // on host now... delta -= (std::chrono::high_resolution_clock::now()-start); vectorOpH<USE,ADDY>(h_A.get(),h_B.get(),h_C2.get(),numElements); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"host computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; delta -= (std::chrono::high_resolution_clock::now()-start); vectorOpH<USE,ADDY>(h_A.get(),h_B.get(),h_C2.get(),numElements); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"host computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; // Verify that the result vector is correct double ave = 0; int maxDiff = 0; long long ndiff=0; double fave = 0; float fmaxDiff = 0; for (int i = 0; i < numElements; ++i) { approx_math::binary32 g,c; g.f = testFunc<USE,ADDY>(h_A[i],h_B[i]); c.f = h_C[i]; auto diff = std::abs(g.i32-c.i32); maxDiff = ::max(diff,maxDiff); ave += diff; if (diff!=0) ++ndiff; auto fdiff = std::abs(g.f-c.f); fave += fdiff; fmaxDiff = ::max(fdiff,fmaxDiff); // if (diff>7) // std::cerr << "Large diff at element " << i << ' ' << diff << ' ' << std::hexfloat // << g.f << "!=" << c.f << "\n"; } std::cout << "ndiff ave, max " << ndiff << ' ' << ave/numElements << ' ' << maxDiff << std::endl; std::cout << "float ave, max " << fave/numElements << ' ' << fmaxDiff << std::endl; if (! ndiff) { std::cout << "Test PASSED\n"; std::cout << "SUCCESS"<< std::endl; } hipDeviceSynchronize(); } int main() { try { go<USEEXP>(); go<USESIN>(); go<USELOG>(); go<USELOG,true>(); } catch(cuda::runtime_error ex) { std::cout << "cuda error " << ex.what() << std::endl; } catch(...) { std::cout << "a non cuda error" << std::endl; } return 0; }
bc18db52d7261dae50d17167f3601c2e32d7c1a3.cu
/** * Derived from the nVIDIA CUDA 8.0 samples by * * Eyal Rozenberg <E.Rozenberg@cwi.nl> * * The derivation is specifically permitted in the nVIDIA CUDA Samples EULA * and the deriver is the owner of this code according to the EULA. * * Use this reasonably. If you want to discuss licensing formalities, please * contact the author. * * Modified by VinInn for testing math funcs */ /* to run test foreach f ( $CMSSW_BASE/test/$SCRAM_ARCH/DFM_Vector* ) echo $f; $f end */ #include "cuda/api_wrappers.h" #include <iostream> #include <iomanip> #include <memory> #include <algorithm> #include <chrono> #include<random> #include<cassert> std::mt19937 eng; std::mt19937 eng2; std::uniform_real_distribution<float> rgen(0.,1.); #include<DataFormats/Math/interface/approx_log.h> #include<DataFormats/Math/interface/approx_exp.h> #include<DataFormats/Math/interface/approx_atan2.h> constexpr float myExp(float x) { return unsafe_expf<6>(x); } constexpr float myLog(float x) { return unsafe_logf<6>(x); } #ifdef __NVCC__ #define inline __host__ __device__ inline #include<vdt/sin.h> #undef inline #else #include<vdt/sin.h> #endif __host__ __device__ inline float mySin(float x) { return vdt::fast_sinf(x); } constexpr int USEEXP=0, USESIN=1, USELOG=2; template<int USE, bool ADDY=false> // __host__ __device__ constexpr float testFunc(float x, float y) { float ret=0; if(USE==USEEXP) ret = myExp(x); else if(USE==USESIN) ret = mySin(x); else ret = myLog(x); return ADDY ? ret+y : ret; } template<int USE, bool ADDY> __global__ void vectorOp(const float *A, const float *B, float *C, int numElements) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < numElements) { C[i] = testFunc<USE,ADDY>(A[i],B[i]); } } template<int USE, bool ADDY> void vectorOpH(const float *A, const float *B, float *C, int numElements) { for (int i=0; i<numElements; ++i) { C[i] = testFunc<USE,ADDY>(A[i],B[i]); } } template<int USE, bool ADDY=false> void go() { auto start = std::chrono::high_resolution_clock::now(); auto delta = start - start; if (cuda::device::count() == 0) { std::cerr << "No CUDA devices on this system" << "\n"; exit(EXIT_FAILURE); } auto current_device = cuda::device::current::get(); int numElements = 200000; size_t size = numElements * sizeof(float); std::cout << "[Vector of " << numElements << " elements]\n"; auto h_A = std::make_unique<float[]>(numElements); auto h_B = std::make_unique<float[]>(numElements); auto h_C = std::make_unique<float[]>(numElements); auto h_C2 = std::make_unique<float[]>(numElements); std::generate(h_A.get(), h_A.get() + numElements, [&](){return rgen(eng);}); std::generate(h_B.get(), h_B.get() + numElements, [&](){return rgen(eng);}); delta -= (std::chrono::high_resolution_clock::now()-start); auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements); auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements); auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements); cuda::memory::copy(d_A.get(), h_A.get(), size); cuda::memory::copy(d_B.get(), h_B.get(), size); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda alloc+copy took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; // Launch the Vector OP CUDA Kernel int threadsPerBlock = 256; int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock; std::cout << "CUDA kernel launch with " << blocksPerGrid << " blocks of " << threadsPerBlock << " threads\n"; delta -= (std::chrono::high_resolution_clock::now()-start); cuda::launch( vectorOp<USE,ADDY>, { blocksPerGrid, threadsPerBlock }, d_A.get(), d_B.get(), d_C.get(), numElements ); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; delta -= (std::chrono::high_resolution_clock::now()-start); cuda::launch( vectorOp<USE,ADDY>, { blocksPerGrid, threadsPerBlock }, d_A.get(), d_B.get(), d_C.get(), numElements ); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; delta -= (std::chrono::high_resolution_clock::now()-start); cuda::memory::copy(h_C.get(), d_C.get(), size); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"cuda copy back took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; // on host now... delta -= (std::chrono::high_resolution_clock::now()-start); vectorOpH<USE,ADDY>(h_A.get(),h_B.get(),h_C2.get(),numElements); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"host computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; delta -= (std::chrono::high_resolution_clock::now()-start); vectorOpH<USE,ADDY>(h_A.get(),h_B.get(),h_C2.get(),numElements); delta += (std::chrono::high_resolution_clock::now()-start); std::cout <<"host computation took " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << " ms" << std::endl; // Verify that the result vector is correct double ave = 0; int maxDiff = 0; long long ndiff=0; double fave = 0; float fmaxDiff = 0; for (int i = 0; i < numElements; ++i) { approx_math::binary32 g,c; g.f = testFunc<USE,ADDY>(h_A[i],h_B[i]); c.f = h_C[i]; auto diff = std::abs(g.i32-c.i32); maxDiff = std::max(diff,maxDiff); ave += diff; if (diff!=0) ++ndiff; auto fdiff = std::abs(g.f-c.f); fave += fdiff; fmaxDiff = std::max(fdiff,fmaxDiff); // if (diff>7) // std::cerr << "Large diff at element " << i << ' ' << diff << ' ' << std::hexfloat // << g.f << "!=" << c.f << "\n"; } std::cout << "ndiff ave, max " << ndiff << ' ' << ave/numElements << ' ' << maxDiff << std::endl; std::cout << "float ave, max " << fave/numElements << ' ' << fmaxDiff << std::endl; if (! ndiff) { std::cout << "Test PASSED\n"; std::cout << "SUCCESS"<< std::endl; } cudaDeviceSynchronize(); } int main() { try { go<USEEXP>(); go<USESIN>(); go<USELOG>(); go<USELOG,true>(); } catch(cuda::runtime_error ex) { std::cout << "cuda error " << ex.what() << std::endl; } catch(...) { std::cout << "a non cuda error" << std::endl; } return 0; }
538919842bbb62e4896d93ef06e2d3039c42bc97.hip
// !!! This is a file automatically generated by hipify!!! #define TORCH_ASSERT_ONLY_METHOD_OPERATORS #include <ATen/core/Tensor.h> #include <ATen/AccumulateType.h> #include <ATen/Dispatch.h> #include <ATen/div_rtn.h> #include <ATen/hip/HIPBlas.h> #include <ATen/native/ConvUtils.h> #include <ATen/native/Resize.h> #include <ATen/native/hip/im2col.cuh> #ifndef AT_PER_OPERATOR_HEADERS #include <ATen/Functions.h> #include <ATen/NativeFunctions.h> #else #include <ATen/ops/_slow_conv2d_forward_native.h> #include <ATen/ops/_slow_conv2d_backward_native.h> #include <ATen/ops/empty.h> #include <ATen/ops/sum.h> #endif namespace at::native { namespace { void slow_conv2d_shape_check( const Tensor& input, const Tensor& grad_output, const Tensor& weight, const Tensor& bias, int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW, bool weight_nullable) { TORCH_CHECK(kW > 0 && kH > 0, "kernel size should be greater than zero, but got kH: ", kH, " kW: ", kW); TORCH_CHECK(dW > 0 && dH > 0, "stride should be greater than zero, but got dH: ", dH, " dW: ", dW); TORCH_CHECK(weight_nullable || weight.defined(), "weight tensor is expected to be non-nullable"); TORCH_CHECK(!weight.defined() || ((weight.numel() > 0) && (weight.dim() == 2)), "non-empty 2D weight tensor expected, but got: ", weight.sizes()); TORCH_CHECK(!bias.defined() || (bias.dim() == 1 && bias.sizes()[0] == weight.sizes()[0]), "Expected bias to have shape [", weight.sizes()[0], "] but got ", bias.sizes()); const auto in_sizes = input.sizes(); constexpr int ndim = 4; constexpr int dimf = 1; constexpr int dimh = 2; constexpr int dimw = 3; TORCH_CHECK(in_sizes.size() == ndim, "Expected 4D input tensor, but got ", in_sizes); // Allow for empty batch size but not other dimensions const bool valid_empty = c10::multiply_integers(in_sizes.slice(1)) != 0; TORCH_CHECK(valid_empty, "non-empty input tensor expected but got: ", in_sizes); int64_t inputHeight = in_sizes[dimh]; int64_t inputWidth = in_sizes[dimw]; int64_t exactInputHeight = inputHeight + 2 * padH; int64_t exactInputWidth = inputWidth + 2 * padW; TORCH_CHECK(exactInputHeight >= kH && exactInputWidth >= kW, "Calculated padded input size per channel: ", IntArrayRef{exactInputHeight, exactInputWidth}, ". Kernel size: ", IntArrayRef{kH, kW}, ". Kernel size can't be greater than actual input size"); // NOTE: can't use conv_output_size if the weight isn't defined auto outputHeight = div_rtn<int64_t>(exactInputHeight - kH, dH) + 1; auto outputWidth = div_rtn<int64_t>(exactInputWidth - kW, dW) + 1; TORCH_CHECK(outputWidth >= 1 && outputHeight >= 1, "Given input size per channel: ", IntArrayRef{inputHeight, inputWidth}, ". Calculated output size per channel: ", IntArrayRef{outputHeight, outputWidth}, ". Output size is too small"); if (weight.defined()) { const auto w_sizes = weight.sizes(); int64_t nInputPlane = w_sizes[1]; if (w_sizes.size() == 2) { nInputPlane /= (kH * kW); } TORCH_CHECK(in_sizes[dimf] == nInputPlane, "Expected input dim ", dimf, " to have size ", nInputPlane, " but got ", in_sizes[dimf]); } if (grad_output.defined()) { const auto gO_sizes = grad_output.sizes(); TORCH_CHECK(gO_sizes.size() == ndim, "Expected grad_output to have ", ndim, " dimensions but got shape", gO_sizes); if (weight.defined()) { const auto w_sizes = weight.sizes(); TORCH_CHECK(gO_sizes[dimf] == w_sizes[0], "Expected dim ", dimf, " to have size ", w_sizes[0], " but got ", gO_sizes[dimf]); } else if (bias.defined()) { const auto b_sizes = bias.sizes(); int64_t nOutputPlane = b_sizes.size() == 0 ? 1 : b_sizes[0]; TORCH_CHECK(gO_sizes[dimf] == nOutputPlane, "Expected grad_output dim ", dimf, " to have size ", nOutputPlane, " but got ", gO_sizes[dimf]); } TORCH_CHECK(gO_sizes[dimh] == outputHeight, "Expected grad_output dim ", dimh, " to have size ", outputHeight, " but got ", gO_sizes[dimh]); TORCH_CHECK(gO_sizes[dimw] == outputWidth, "Expected grad_output dim ", dimw, " to have size ", outputWidth, " but got ", gO_sizes[dimw]); } } Tensor new_view_weight_MM2d(const Tensor& weight_) { auto weight = weight_.expect_contiguous(); const auto w_sizes = weight->sizes(); TORCH_CHECK(w_sizes.size() == 4); int64_t s1 = w_sizes[0]; int64_t s2 = c10::multiply_integers(w_sizes.slice(1)); return weight->view({s1, s2}); } void slow_conv2d_forward( const Tensor &input, const Tensor &output, const Tensor &weight_, const Tensor &bias, int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW) { auto weight = new_view_weight_MM2d(weight_); slow_conv2d_shape_check( input, {}, weight, bias, kH, kW, dH, dW, padH, padW, /*weight_nullable*/false); constexpr int dimf = 1; constexpr int dimh = 2; constexpr int dimw = 3; auto in_sizes = input.sizes(); int64_t batchSize = in_sizes[0]; int64_t nInputPlane = in_sizes[dimf]; int64_t inputHeight = in_sizes[dimh]; int64_t inputWidth = in_sizes[dimw]; int64_t nOutputPlane = weight.sizes()[0]; int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; // Resize output resize_output(output, {batchSize, nOutputPlane, outputHeight, outputWidth}); // Create temporary columns at::Tensor columns; const bool requires_columns = ( kW != 1 || kH != 1 || dW != 1 || dH != 1 || padH != 0 || padW != 0); if (requires_columns) { columns = at::empty({nInputPlane * kW * kH, outputHeight * outputWidth}, input.options()); } if (bias.defined()) { TORCH_CHECK(bias.scalar_type() == input.scalar_type(), "Expected bias to have type ", input.scalar_type(), " but got ", bias.scalar_type()); output.copy_(bias.view({-1, 1, 1})); } else { output.zero_(); } AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "slow_conv2d_cuda", [&] { // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per output: auto input_n = input.select(0, elt); auto output_n = output.select(0, elt); if (requires_columns) { // Extract columns: at::native::im2col( c10::hip::getCurrentHIPStreamMasqueradingAsCUDA(), input_n.data_ptr<scalar_t>(), nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, 1, 1, columns.data_ptr<scalar_t>() ); } // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = nOutputPlane; int64_t n = outputHeight * outputWidth; int64_t k = nInputPlane*kH*kW; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) auto gemm_in_ptr = requires_columns ? columns.data_ptr<scalar_t>() : input_n.data_ptr<scalar_t>(); at::cuda::blas::gemm( 'n', 'n', n, m, k, scalar_t(1), gemm_in_ptr, n, weight.data_ptr<scalar_t>(), k, scalar_t(1), output_n.data_ptr<scalar_t>(), n ); } }); } void slow_conv2d_backward( const Tensor &input, const Tensor &grad_output, const Tensor &grad_input, const Tensor &weight_, const Tensor &grad_columns, int kH, int kW, int dH, int dW, int padH, int padW) { Tensor weight = new_view_weight_MM2d(weight_); slow_conv2d_shape_check(input, grad_output, weight, {}, kH, kW, dH, dW, padH, padW, /*weight_nullable=*/false); // Params auto weight_sizes = weight.sizes(); int nInputPlane = weight_sizes[1]/(kW*kH); int nOutputPlane = weight_sizes[0]; TORCH_INTERNAL_ASSERT(grad_output.is_contiguous()); auto input_sizes = input.sizes(); int64_t inputWidth = input_sizes[3]; int64_t inputHeight = input_sizes[2]; auto output_sizes = grad_output.sizes(); int64_t outputWidth = output_sizes[3]; int64_t outputHeight = output_sizes[2]; // Batch size + input planes int64_t batchSize = input_sizes[0]; // Resize output resize_output(grad_input, input_sizes); TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous"); // Resize temporary columns resize_output(grad_columns, {nInputPlane*kW*kH, outputHeight*outputWidth}); TORCH_CHECK(grad_columns.is_contiguous(), "grad_columns must be contiguous"); AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "slow_conv2d_backward_cuda", [&] { // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per sample: auto grad_input_n = grad_input.select(0, elt); auto grad_output_n = grad_output.select(0, elt); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = nInputPlane*kW*kH; int64_t n = grad_columns.sizes()[1]; int64_t k = nOutputPlane; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) at::cuda::blas::gemm<scalar_t>( 'n', 't', n, m, k, scalar_t(1), grad_output_n.data_ptr<scalar_t>(), n, weight.data_ptr<scalar_t>(), m, scalar_t(0), grad_columns.data_ptr<scalar_t>(), n ); // Unpack columns back into input: using acc_t = at::acc_type<scalar_t, true>; at::native::col2im<scalar_t, acc_t>( c10::hip::getCurrentHIPStreamMasqueradingAsCUDA(), grad_columns.data_ptr<scalar_t>(), nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, 1, 1, grad_input_n.data_ptr<scalar_t>() ); } }); } void slow_conv2d_grad_weight( const Tensor &input, const Tensor &grad_output, const Tensor &grad_weight_, const Tensor &columns, int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW) { TORCH_CHECK(grad_weight_.is_contiguous(), "grad_weight needs to be contiguous"); auto grad_weight = new_view_weight_MM2d(grad_weight_); slow_conv2d_shape_check(input, grad_output, grad_weight, {}, kH, kW, dH, dW, padH, padW, /*weight_nullable=*/true); // Params TORCH_INTERNAL_ASSERT(input.is_contiguous()); TORCH_INTERNAL_ASSERT(grad_output.is_contiguous()); auto input_sizes = input.sizes(); int64_t nInputPlane = input_sizes[1]; int64_t nOutputPlane = grad_output.sizes()[1]; int64_t inputWidth = input_sizes[3]; int64_t inputHeight = input_sizes[2]; int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; // Batch size + input planes int64_t batchSize = input_sizes[0]; // Resize temporary columns resize_output(columns, {nInputPlane * kH * kW, outputHeight * outputWidth}); const bool requires_columns = ( kW != 1 || kH != 1 || dW != 1 || dH != 1 || padH != 0 || padW != 0); AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "slow_conv2d_grad_weight_cuda", [&] { // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per output: auto grad_output_n = grad_output.select(0, elt); // Matrix mulitply per output: auto input_n = input.select(0, elt); if (requires_columns) { // Extract columns: at::native::im2col<scalar_t>( c10::hip::getCurrentHIPStreamMasqueradingAsCUDA(), input_n.data_ptr<scalar_t>(), nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, 1, 1, columns.data_ptr<scalar_t>() ); } // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = nOutputPlane; int64_t n = nInputPlane*kW*kH; int64_t k = columns.sizes()[1]; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) auto gemm_in_ptr = requires_columns ? columns.data_ptr<scalar_t>() : input_n.data_ptr<scalar_t>(); at::cuda::blas::gemm( 't', 'n', n, m, k, scalar_t(1), gemm_in_ptr, k, grad_output_n.data_ptr<scalar_t>(), k, scalar_t(1), grad_weight.data_ptr<scalar_t>(), n ); } }); } } // namespace (anonymous) Tensor& slow_conv2d_forward_out_cuda( const Tensor &self_, const Tensor &weight_, IntArrayRef kernel_size, const c10::optional<Tensor> &bias_, IntArrayRef stride, IntArrayRef padding, Tensor &output) { TORCH_CHECK(kernel_size.size() == 2); TORCH_CHECK(stride.size() == 2); TORCH_CHECK(padding.size() == 2); auto self = self_.expect_contiguous(); auto weight = weight_.expect_contiguous(); auto bias = [&] { if (bias_.has_value() && bias_->defined()) { return bias_->expect_contiguous(); } return MaybeOwned<Tensor>::owned(c10::in_place); }(); slow_conv2d_forward( *self, output, *weight, *bias, kernel_size[0], kernel_size[1], stride[0], stride[1], padding[0], padding[1] ); return output; } Tensor slow_conv2d_forward_cuda( const Tensor &self, const Tensor &weight, IntArrayRef kernel_size, const c10::optional<Tensor> &bias, IntArrayRef stride, IntArrayRef padding) { auto output = at::empty({0}, self.options()); return slow_conv2d_forward_out_cuda( self, weight, kernel_size, bias, stride, padding, output); } std::tuple<Tensor&, Tensor&, Tensor&> slow_conv2d_backward_out_cuda( const Tensor& grad_output_, const Tensor& self_, const Tensor& weight_, IntArrayRef kernel_size, IntArrayRef stride, IntArrayRef padding, Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias) { auto grad_output = grad_output_.expect_contiguous(); Tensor columns = at::empty({0}, self_.options()); if (grad_input.defined()) { resize_output(grad_input, self_.sizes()); auto weight = weight_.expect_contiguous(); slow_conv2d_backward( self_, *grad_output, grad_input, *weight, columns, kernel_size[0], kernel_size[1], stride[0], stride[1], padding[0], padding[1]); } if (grad_bias.defined()) { at::sum_out(grad_bias, *grad_output, IntArrayRef{0, 2, 3}); } if (grad_weight.defined()) { resize_output(grad_weight, weight_.sizes()); grad_weight.zero_(); auto self = self_.expect_contiguous(); slow_conv2d_grad_weight( *self, *grad_output, grad_weight, columns, kernel_size[0], kernel_size[1], stride[0], stride[1], padding[0], padding[1] ); } return std::tuple<Tensor&, Tensor&, Tensor&>{ grad_input, grad_weight, grad_bias}; } std::tuple<Tensor, Tensor, Tensor> slow_conv2d_backward_cuda( const Tensor& grad_output, const Tensor& self, const Tensor& weight, IntArrayRef kernel_size, IntArrayRef stride, IntArrayRef padding, std::array<bool, 3> output_mask) { Tensor grad_input; Tensor grad_weight; Tensor grad_bias; if (output_mask[0]) { grad_input = at::empty({0}, grad_output.options()); } if (output_mask[1]) { grad_weight = at::empty({0}, grad_output.options()); } if (output_mask[2]) { grad_bias = at::empty({0}, grad_output.options()); } return native::slow_conv2d_backward_out_cuda( grad_output, self, weight, kernel_size, stride, padding, grad_input, grad_weight, grad_bias); } } // namespace at::native
538919842bbb62e4896d93ef06e2d3039c42bc97.cu
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS #include <ATen/core/Tensor.h> #include <ATen/AccumulateType.h> #include <ATen/Dispatch.h> #include <ATen/div_rtn.h> #include <ATen/cuda/CUDABlas.h> #include <ATen/native/ConvUtils.h> #include <ATen/native/Resize.h> #include <ATen/native/cuda/im2col.cuh> #ifndef AT_PER_OPERATOR_HEADERS #include <ATen/Functions.h> #include <ATen/NativeFunctions.h> #else #include <ATen/ops/_slow_conv2d_forward_native.h> #include <ATen/ops/_slow_conv2d_backward_native.h> #include <ATen/ops/empty.h> #include <ATen/ops/sum.h> #endif namespace at::native { namespace { void slow_conv2d_shape_check( const Tensor& input, const Tensor& grad_output, const Tensor& weight, const Tensor& bias, int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW, bool weight_nullable) { TORCH_CHECK(kW > 0 && kH > 0, "kernel size should be greater than zero, but got kH: ", kH, " kW: ", kW); TORCH_CHECK(dW > 0 && dH > 0, "stride should be greater than zero, but got dH: ", dH, " dW: ", dW); TORCH_CHECK(weight_nullable || weight.defined(), "weight tensor is expected to be non-nullable"); TORCH_CHECK(!weight.defined() || ((weight.numel() > 0) && (weight.dim() == 2)), "non-empty 2D weight tensor expected, but got: ", weight.sizes()); TORCH_CHECK(!bias.defined() || (bias.dim() == 1 && bias.sizes()[0] == weight.sizes()[0]), "Expected bias to have shape [", weight.sizes()[0], "] but got ", bias.sizes()); const auto in_sizes = input.sizes(); constexpr int ndim = 4; constexpr int dimf = 1; constexpr int dimh = 2; constexpr int dimw = 3; TORCH_CHECK(in_sizes.size() == ndim, "Expected 4D input tensor, but got ", in_sizes); // Allow for empty batch size but not other dimensions const bool valid_empty = c10::multiply_integers(in_sizes.slice(1)) != 0; TORCH_CHECK(valid_empty, "non-empty input tensor expected but got: ", in_sizes); int64_t inputHeight = in_sizes[dimh]; int64_t inputWidth = in_sizes[dimw]; int64_t exactInputHeight = inputHeight + 2 * padH; int64_t exactInputWidth = inputWidth + 2 * padW; TORCH_CHECK(exactInputHeight >= kH && exactInputWidth >= kW, "Calculated padded input size per channel: ", IntArrayRef{exactInputHeight, exactInputWidth}, ". Kernel size: ", IntArrayRef{kH, kW}, ". Kernel size can't be greater than actual input size"); // NOTE: can't use conv_output_size if the weight isn't defined auto outputHeight = div_rtn<int64_t>(exactInputHeight - kH, dH) + 1; auto outputWidth = div_rtn<int64_t>(exactInputWidth - kW, dW) + 1; TORCH_CHECK(outputWidth >= 1 && outputHeight >= 1, "Given input size per channel: ", IntArrayRef{inputHeight, inputWidth}, ". Calculated output size per channel: ", IntArrayRef{outputHeight, outputWidth}, ". Output size is too small"); if (weight.defined()) { const auto w_sizes = weight.sizes(); int64_t nInputPlane = w_sizes[1]; if (w_sizes.size() == 2) { nInputPlane /= (kH * kW); } TORCH_CHECK(in_sizes[dimf] == nInputPlane, "Expected input dim ", dimf, " to have size ", nInputPlane, " but got ", in_sizes[dimf]); } if (grad_output.defined()) { const auto gO_sizes = grad_output.sizes(); TORCH_CHECK(gO_sizes.size() == ndim, "Expected grad_output to have ", ndim, " dimensions but got shape", gO_sizes); if (weight.defined()) { const auto w_sizes = weight.sizes(); TORCH_CHECK(gO_sizes[dimf] == w_sizes[0], "Expected dim ", dimf, " to have size ", w_sizes[0], " but got ", gO_sizes[dimf]); } else if (bias.defined()) { const auto b_sizes = bias.sizes(); int64_t nOutputPlane = b_sizes.size() == 0 ? 1 : b_sizes[0]; TORCH_CHECK(gO_sizes[dimf] == nOutputPlane, "Expected grad_output dim ", dimf, " to have size ", nOutputPlane, " but got ", gO_sizes[dimf]); } TORCH_CHECK(gO_sizes[dimh] == outputHeight, "Expected grad_output dim ", dimh, " to have size ", outputHeight, " but got ", gO_sizes[dimh]); TORCH_CHECK(gO_sizes[dimw] == outputWidth, "Expected grad_output dim ", dimw, " to have size ", outputWidth, " but got ", gO_sizes[dimw]); } } Tensor new_view_weight_MM2d(const Tensor& weight_) { auto weight = weight_.expect_contiguous(); const auto w_sizes = weight->sizes(); TORCH_CHECK(w_sizes.size() == 4); int64_t s1 = w_sizes[0]; int64_t s2 = c10::multiply_integers(w_sizes.slice(1)); return weight->view({s1, s2}); } void slow_conv2d_forward( const Tensor &input, const Tensor &output, const Tensor &weight_, const Tensor &bias, int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW) { auto weight = new_view_weight_MM2d(weight_); slow_conv2d_shape_check( input, {}, weight, bias, kH, kW, dH, dW, padH, padW, /*weight_nullable*/false); constexpr int dimf = 1; constexpr int dimh = 2; constexpr int dimw = 3; auto in_sizes = input.sizes(); int64_t batchSize = in_sizes[0]; int64_t nInputPlane = in_sizes[dimf]; int64_t inputHeight = in_sizes[dimh]; int64_t inputWidth = in_sizes[dimw]; int64_t nOutputPlane = weight.sizes()[0]; int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; // Resize output resize_output(output, {batchSize, nOutputPlane, outputHeight, outputWidth}); // Create temporary columns at::Tensor columns; const bool requires_columns = ( kW != 1 || kH != 1 || dW != 1 || dH != 1 || padH != 0 || padW != 0); if (requires_columns) { columns = at::empty({nInputPlane * kW * kH, outputHeight * outputWidth}, input.options()); } if (bias.defined()) { TORCH_CHECK(bias.scalar_type() == input.scalar_type(), "Expected bias to have type ", input.scalar_type(), " but got ", bias.scalar_type()); output.copy_(bias.view({-1, 1, 1})); } else { output.zero_(); } AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "slow_conv2d_cuda", [&] { // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per output: auto input_n = input.select(0, elt); auto output_n = output.select(0, elt); if (requires_columns) { // Extract columns: at::native::im2col( c10::cuda::getCurrentCUDAStream(), input_n.data_ptr<scalar_t>(), nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, 1, 1, columns.data_ptr<scalar_t>() ); } // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = nOutputPlane; int64_t n = outputHeight * outputWidth; int64_t k = nInputPlane*kH*kW; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) auto gemm_in_ptr = requires_columns ? columns.data_ptr<scalar_t>() : input_n.data_ptr<scalar_t>(); at::cuda::blas::gemm( 'n', 'n', n, m, k, scalar_t(1), gemm_in_ptr, n, weight.data_ptr<scalar_t>(), k, scalar_t(1), output_n.data_ptr<scalar_t>(), n ); } }); } void slow_conv2d_backward( const Tensor &input, const Tensor &grad_output, const Tensor &grad_input, const Tensor &weight_, const Tensor &grad_columns, int kH, int kW, int dH, int dW, int padH, int padW) { Tensor weight = new_view_weight_MM2d(weight_); slow_conv2d_shape_check(input, grad_output, weight, {}, kH, kW, dH, dW, padH, padW, /*weight_nullable=*/false); // Params auto weight_sizes = weight.sizes(); int nInputPlane = weight_sizes[1]/(kW*kH); int nOutputPlane = weight_sizes[0]; TORCH_INTERNAL_ASSERT(grad_output.is_contiguous()); auto input_sizes = input.sizes(); int64_t inputWidth = input_sizes[3]; int64_t inputHeight = input_sizes[2]; auto output_sizes = grad_output.sizes(); int64_t outputWidth = output_sizes[3]; int64_t outputHeight = output_sizes[2]; // Batch size + input planes int64_t batchSize = input_sizes[0]; // Resize output resize_output(grad_input, input_sizes); TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous"); // Resize temporary columns resize_output(grad_columns, {nInputPlane*kW*kH, outputHeight*outputWidth}); TORCH_CHECK(grad_columns.is_contiguous(), "grad_columns must be contiguous"); AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "slow_conv2d_backward_cuda", [&] { // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per sample: auto grad_input_n = grad_input.select(0, elt); auto grad_output_n = grad_output.select(0, elt); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = nInputPlane*kW*kH; int64_t n = grad_columns.sizes()[1]; int64_t k = nOutputPlane; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) at::cuda::blas::gemm<scalar_t>( 'n', 't', n, m, k, scalar_t(1), grad_output_n.data_ptr<scalar_t>(), n, weight.data_ptr<scalar_t>(), m, scalar_t(0), grad_columns.data_ptr<scalar_t>(), n ); // Unpack columns back into input: using acc_t = at::acc_type<scalar_t, true>; at::native::col2im<scalar_t, acc_t>( c10::cuda::getCurrentCUDAStream(), grad_columns.data_ptr<scalar_t>(), nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, 1, 1, grad_input_n.data_ptr<scalar_t>() ); } }); } void slow_conv2d_grad_weight( const Tensor &input, const Tensor &grad_output, const Tensor &grad_weight_, const Tensor &columns, int64_t kH, int64_t kW, int64_t dH, int64_t dW, int64_t padH, int64_t padW) { TORCH_CHECK(grad_weight_.is_contiguous(), "grad_weight needs to be contiguous"); auto grad_weight = new_view_weight_MM2d(grad_weight_); slow_conv2d_shape_check(input, grad_output, grad_weight, {}, kH, kW, dH, dW, padH, padW, /*weight_nullable=*/true); // Params TORCH_INTERNAL_ASSERT(input.is_contiguous()); TORCH_INTERNAL_ASSERT(grad_output.is_contiguous()); auto input_sizes = input.sizes(); int64_t nInputPlane = input_sizes[1]; int64_t nOutputPlane = grad_output.sizes()[1]; int64_t inputWidth = input_sizes[3]; int64_t inputHeight = input_sizes[2]; int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; // Batch size + input planes int64_t batchSize = input_sizes[0]; // Resize temporary columns resize_output(columns, {nInputPlane * kH * kW, outputHeight * outputWidth}); const bool requires_columns = ( kW != 1 || kH != 1 || dW != 1 || dH != 1 || padH != 0 || padW != 0); AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "slow_conv2d_grad_weight_cuda", [&] { // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per output: auto grad_output_n = grad_output.select(0, elt); // Matrix mulitply per output: auto input_n = input.select(0, elt); if (requires_columns) { // Extract columns: at::native::im2col<scalar_t>( c10::cuda::getCurrentCUDAStream(), input_n.data_ptr<scalar_t>(), nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, 1, 1, columns.data_ptr<scalar_t>() ); } // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = nOutputPlane; int64_t n = nInputPlane*kW*kH; int64_t k = columns.sizes()[1]; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) auto gemm_in_ptr = requires_columns ? columns.data_ptr<scalar_t>() : input_n.data_ptr<scalar_t>(); at::cuda::blas::gemm( 't', 'n', n, m, k, scalar_t(1), gemm_in_ptr, k, grad_output_n.data_ptr<scalar_t>(), k, scalar_t(1), grad_weight.data_ptr<scalar_t>(), n ); } }); } } // namespace (anonymous) Tensor& slow_conv2d_forward_out_cuda( const Tensor &self_, const Tensor &weight_, IntArrayRef kernel_size, const c10::optional<Tensor> &bias_, IntArrayRef stride, IntArrayRef padding, Tensor &output) { TORCH_CHECK(kernel_size.size() == 2); TORCH_CHECK(stride.size() == 2); TORCH_CHECK(padding.size() == 2); auto self = self_.expect_contiguous(); auto weight = weight_.expect_contiguous(); auto bias = [&] { if (bias_.has_value() && bias_->defined()) { return bias_->expect_contiguous(); } return MaybeOwned<Tensor>::owned(c10::in_place); }(); slow_conv2d_forward( *self, output, *weight, *bias, kernel_size[0], kernel_size[1], stride[0], stride[1], padding[0], padding[1] ); return output; } Tensor slow_conv2d_forward_cuda( const Tensor &self, const Tensor &weight, IntArrayRef kernel_size, const c10::optional<Tensor> &bias, IntArrayRef stride, IntArrayRef padding) { auto output = at::empty({0}, self.options()); return slow_conv2d_forward_out_cuda( self, weight, kernel_size, bias, stride, padding, output); } std::tuple<Tensor&, Tensor&, Tensor&> slow_conv2d_backward_out_cuda( const Tensor& grad_output_, const Tensor& self_, const Tensor& weight_, IntArrayRef kernel_size, IntArrayRef stride, IntArrayRef padding, Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias) { auto grad_output = grad_output_.expect_contiguous(); Tensor columns = at::empty({0}, self_.options()); if (grad_input.defined()) { resize_output(grad_input, self_.sizes()); auto weight = weight_.expect_contiguous(); slow_conv2d_backward( self_, *grad_output, grad_input, *weight, columns, kernel_size[0], kernel_size[1], stride[0], stride[1], padding[0], padding[1]); } if (grad_bias.defined()) { at::sum_out(grad_bias, *grad_output, IntArrayRef{0, 2, 3}); } if (grad_weight.defined()) { resize_output(grad_weight, weight_.sizes()); grad_weight.zero_(); auto self = self_.expect_contiguous(); slow_conv2d_grad_weight( *self, *grad_output, grad_weight, columns, kernel_size[0], kernel_size[1], stride[0], stride[1], padding[0], padding[1] ); } return std::tuple<Tensor&, Tensor&, Tensor&>{ grad_input, grad_weight, grad_bias}; } std::tuple<Tensor, Tensor, Tensor> slow_conv2d_backward_cuda( const Tensor& grad_output, const Tensor& self, const Tensor& weight, IntArrayRef kernel_size, IntArrayRef stride, IntArrayRef padding, std::array<bool, 3> output_mask) { Tensor grad_input; Tensor grad_weight; Tensor grad_bias; if (output_mask[0]) { grad_input = at::empty({0}, grad_output.options()); } if (output_mask[1]) { grad_weight = at::empty({0}, grad_output.options()); } if (output_mask[2]) { grad_bias = at::empty({0}, grad_output.options()); } return native::slow_conv2d_backward_out_cuda( grad_output, self, weight, kernel_size, stride, padding, grad_input, grad_weight, grad_bias); } } // namespace at::native
a5554aebb224be1eeeb1f98f28dbc5519a4c2609.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "utils.h" #include "common.h" // Kernel for fast unfold+copy // (borrowed from Caffe: https://github.com/BVLC/caffe/blob/master/src/caffe/layers/conv_layer.cu) __global__ void im2col_kernel_v(const int n, const float* data_im, const int height, const int width, const int ksize_h, const int ksize_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int height_col, const int width_col, float* data_col) { CUDA_KERNEL_LOOP(index, n) { int w_out = index % width_col; index /= width_col; int h_out = index % height_col; int channel_in = index / height_col; int channel_out = channel_in * ksize_h * ksize_w; int h_in = h_out * stride_h - pad_h; int w_in = w_out * stride_w - pad_w; data_col += (channel_out * height_col + h_out) * width_col + w_out; data_im += (channel_in * height + h_in) * width + w_in; for (int i = 0; i < ksize_h; ++i) { for (int j = 0; j < ksize_w; ++j) { int h = h_in + i; int w = w_in + j; *data_col = (h >= 0 && w >= 0 && h < height && w < width) ? data_im[i * width + j] : 0; data_col += height_col * width_col; } } } } __global__ void conv_vertical_naive_output(const int n, float *y, const float *x, const float *w, const int iH, const int iW, const int kL) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { int oH = iH - kL + 1; int x_offset = (i/(oH*iW))*iH*iW + i%(oH*iW); int w_offset = (i/(oH*iW))*kL; for (int k = 0; k < kL; k++) { y[i] += w[w_offset + k]*x[x_offset + k*iW]; } } } __global__ void conv_vertical_naive_gradInput(const int n, float *dx, const float *dy, const float *w, const int oH, const int oW, const int kL) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { int iH = oH + kL - 1; int iC = i/(iH*oW); int row = (i%(iH*oW))/oW; int dy_offset = iC*oH*oW + i%(iH*oW); int w_offset = iC*kL; int k_begin = max(0, row-oH+1); int k_end = min(kL, row+1); dx[i] = 0.0f; for (int k = k_begin; k < k_end; k++) { dx[i] += w[w_offset + k]*dy[dy_offset - k*oW]; } } } __global__ void conv_vertical_naive_gradParam(const int n, float *dw, const float *x, const float *dy, const int kL, const int oH, const int oW) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { int dy_offset = (i/kL)*oH*oW; int x_offset = (i/kL)*oH*oW + (i%kL)*oW; for (int k = 0; k < oH*oW; k++) { dw[i] += dy[dy_offset + k]*x[x_offset + k]; } } } __global__ void conv_vertical_naive_gradWeight(const int n, float *y, const float *x, const int kL, const int iC) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { y[i] = x[(i/kL)*kL*iC + i]; } } static int cunnconv1d_VerticalConvolution_updateOutput(lua_State *L) { THCState *state = getCutorchState(L); THCudaTensor *input = (THCudaTensor*)luaT_checkudata(L, 2, "torch.CudaTensor"); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); THCudaTensor *weight = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "weight", "torch.CudaTensor"); THCudaTensor *bias = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "bias", "torch.CudaTensor"); THCudaTensor *ones = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "ones", "torch.CudaTensor"); THCudaTensor *output = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "output", "torch.CudaTensor"); const int device = THCudaTensor_getDevice(state, weight); luaL_argcheck(L, THCudaTensor_getDevice(state, bias) == device, 1, "weight and bias need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, output) == device || THCudaTensor_getDevice(state, output) == -1, 1, "weight and output need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, input) == device, 2, "weight and input need to be on the same device"); luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D (batch mode) tensor is expected"); // change to batch mode int batch = 1; if (input->nDimension == 3) { luaL_argcheck(L, input->size[0] == nInputPlane, 2, "input channels and nInputPlane dont match"); batch = 0; THCudaTensor_resize4d(state, input, 1, input->size[0], input->size[1], input->size[2]); } else { luaL_argcheck(L, input->size[1] == nInputPlane, 2, "input channels and nInputPlane dont match"); } long batchSize = input->size[0]; long inputHeight = input->size[2]; long inputWidth = input->size[3]; long outputHeight = inputHeight - weight->size[1] + 1; long outputWidth = inputWidth; THCudaTensor_resize4d(state, output, batchSize, nOutputPlane, outputHeight, outputWidth); if (ones->nDimension != 2 || ones->size[0]*ones->size[1] < outputHeight*outputWidth) { THCudaTensor_resize2d(state, ones, outputHeight, outputWidth); THCudaTensor_fill(state, ones, 1); } THCudaTensor *input_n = THCudaTensor_new(state); THCudaTensor *output_n = THCudaTensor_new(state); for (int elt = 0; elt < batchSize; elt ++) { // select each batch THCudaTensor_select(state, input_n, input, 0, elt); THCudaTensor_select(state, output_n, output, 0, elt); // fill biases THCudaBlas_gemm( state, 't', 'n', outputHeight*outputWidth, nOutputPlane, 1, 1, THCudaTensor_data(state, ones), 1, THCudaTensor_data(state, bias), 1, 0, THCudaTensor_data(state, output_n), outputHeight*outputWidth ); // convolve long num_threads = nOutputPlane*outputHeight*outputWidth; hipLaunchKernelGGL(( conv_vertical_naive_output) , dim3(GET_BLOCKS(num_threads)), dim3(CUDA_NUM_THREADS), 0, 0, num_threads, THCudaTensor_data(state, output_n), THCudaTensor_data(state, input_n), THCudaTensor_data(state, weight), inputHeight, inputWidth, weight->size[1]); } THCudaTensor_free(state, input_n); THCudaTensor_free(state, output_n); // revert to single batch if (batch == 0) { THCudaTensor_resize3d(state, output, nOutputPlane, outputHeight, outputWidth); THCudaTensor_resize3d(state, input, nInputPlane, inputHeight, inputWidth); } return 1; } static int cunnconv1d_VerticalConvolution_updateGradInput(lua_State *L) { THCState *state = getCutorchState(L); THCudaTensor *input = (THCudaTensor *)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor *gradOutput = (THCudaTensor *)luaT_checkudata(L, 3, "torch.CudaTensor"); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); THCudaTensor *weight = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "weight", "torch.CudaTensor"); THCudaTensor *gradInput = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "gradInput", "torch.CudaTensor"); const int device = THCudaTensor_getDevice(state, weight); luaL_argcheck(L, THCudaTensor_getDevice(state, input) == device, 2, "weight and input need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, gradInput) == device || THCudaTensor_getDevice(state, gradInput) == -1, 2, "weight and gradInput need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, gradOutput) == device || THCudaTensor_getDevice(state, gradOutput) == -1, 2, "weight and gradOutput need to be on the same device"); luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D (batch mode) tensor is expected"); int batch = 1; if (input->nDimension == 3) { batch = 0; THCudaTensor_resize4d(state, input, 1, input->size[0], input->size[1], input->size[2]); THCudaTensor_resize4d(state, gradOutput, 1, gradOutput->size[0], gradOutput->size[1], gradOutput->size[2]); } long batchSize = input->size[0]; long inputHeight = input->size[2]; long inputWidth = input->size[3]; long outputHeight = inputHeight - weight->size[1] + 1; long outputWidth = inputWidth; THCudaTensor_resize4d(state, gradInput, batchSize, nInputPlane, inputHeight, inputWidth); THCudaTensor *gradInput_n = THCudaTensor_new(state); THCudaTensor *gradOutput_n = THCudaTensor_new(state); for (int elt = 0; elt < batchSize; elt ++) { // select each batch in 2D THCudaTensor_select(state, gradInput_n, gradInput, 0, elt); THCudaTensor_select(state, gradOutput_n, gradOutput, 0, elt); // convolve long num_threads = nInputPlane*inputHeight*inputWidth; hipLaunchKernelGGL(( conv_vertical_naive_gradInput) , dim3(GET_BLOCKS(num_threads)), dim3(CUDA_NUM_THREADS), 0, 0, num_threads, THCudaTensor_data(state, gradInput_n), THCudaTensor_data(state, gradOutput_n), THCudaTensor_data(state, weight), outputHeight, outputWidth, weight->size[1]); } THCudaTensor_free(state, gradInput_n); THCudaTensor_free(state, gradOutput_n); // revert to single batch if (batch == 0) { THCudaTensor_resize3d(state, input, nInputPlane, inputHeight, inputWidth); THCudaTensor_resize3d(state, gradInput, nInputPlane, inputHeight, inputWidth); THCudaTensor_resize3d(state, gradOutput, nOutputPlane, outputHeight, outputWidth); } return 1; } static int cunnconv1d_VerticalConvolution_accGradParameters(lua_State *L) { THCState *state = getCutorchState(L); THCudaTensor *input = (THCudaTensor *)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor *gradOutput = (THCudaTensor *)luaT_checkudata(L, 3, "torch.CudaTensor"); float scale = luaL_optnumber(L, 4, 1); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); int kL = luaT_getfieldcheckint(L, 1, "kL"); THCudaTensor *gradWeight = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "gradWeight", "torch.CudaTensor"); THCudaTensor *gradBias = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "gradBias", "torch.CudaTensor"); THCudaTensor *ones = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "ones", "torch.CudaTensor"); THCudaTensor *finput = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "finput", "torch.CudaTensor"); THCudaTensor *fgradWeight = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "fgradWeight", "torch.CudaTensor"); const int device = THCudaTensor_getDevice(state, gradWeight); luaL_argcheck(L, THCudaTensor_getDevice(state, gradBias) == device, 1, "gradWeight and gradBias need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, input) == device, 1, "gradWeight and input need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, gradOutput) == device, 1, "gradWeight and gradOutput need to be on the same device"); luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D (batch mode) tensor is expected"); // change to batch mode int batch = 1; if (input->nDimension == 3) { batch = 0; THCudaTensor_resize4d(state, input, 1, input->size[0], input->size[1], input->size[2]); THCudaTensor_resize4d(state, gradOutput, 1, gradOutput->size[0], gradOutput->size[1], gradOutput->size[2]); } long batchSize = input->size[0]; long inputHeight = input->size[2]; long inputWidth = input->size[3]; long outputHeight = inputHeight - kL + 1; long outputWidth = inputWidth; if (ones->nDimension != 2 || ones->size[0]*ones->size[1] < outputHeight*outputWidth) { THCudaTensor_resize2d(state, ones, outputHeight, outputWidth); THCudaTensor_fill(state, ones, 1); } THCudaTensor_resize2d(state, finput, kL*nInputPlane, outputHeight*outputWidth); THCudaTensor_resize2d(state, fgradWeight, nOutputPlane, kL*nInputPlane); THCudaTensor *input_n = THCudaTensor_new(state); THCudaTensor *gradOutput_n = THCudaTensor_new(state); for (int elt = 0; elt < batchSize; elt ++) { // select each batch THCudaTensor_select(state, input_n, input, 0, elt); THCudaTensor_select(state, gradOutput_n, gradOutput, 0, elt); // unroll long num_threads = nInputPlane*outputHeight*outputWidth; hipLaunchKernelGGL(( im2col_kernel_v) , dim3(GET_BLOCKS(num_threads)), dim3(CUDA_NUM_THREADS), 0, 0, num_threads, THCudaTensor_data(state, input_n), inputHeight, inputWidth, kL, 1, 0, 0, 1, 1, outputHeight, outputWidth, THCudaTensor_data(state, finput) ); // convolve THCudaBlas_gemm( state, 't', 'n', kL*nInputPlane, nOutputPlane, outputHeight*outputWidth, scale, THCudaTensor_data(state, finput), outputHeight*outputWidth, THCudaTensor_data(state, gradOutput_n), outputHeight*outputWidth, (elt > 0), THCudaTensor_data(state, fgradWeight), kL*nInputPlane ); // fill biases THCudaBlas_gemv( state, 't', outputHeight*outputWidth, nOutputPlane, scale, THCudaTensor_data(state, gradOutput_n), outputHeight*outputWidth, THCudaTensor_data(state, ones), 1, 1, THCudaTensor_data(state, gradBias), 1 ); } // extract gradWeight long num_threads_ = kL*nInputPlane; hipLaunchKernelGGL(( conv_vertical_naive_gradWeight) , dim3(GET_BLOCKS(num_threads_)), dim3(CUDA_NUM_THREADS), 0, 0, num_threads_, THCudaTensor_data(state, gradWeight), THCudaTensor_data(state, fgradWeight), kL, nInputPlane ); THCudaTensor_free(state, input_n); THCudaTensor_free(state, gradOutput_n); if (batch == 0) { THCudaTensor_resize3d(state, gradOutput, nOutputPlane, outputHeight, outputWidth); THCudaTensor_resize3d(state, input, nInputPlane, inputHeight, inputWidth); } return 0; } static const struct luaL_Reg cunnconv1d_VerticalConvolution__ [] = { {"VerticalConvolution_updateOutput", cunnconv1d_VerticalConvolution_updateOutput}, {"VerticalConvolution_updateGradInput", cunnconv1d_VerticalConvolution_updateGradInput}, {"VerticalConvolution_accGradParameters", cunnconv1d_VerticalConvolution_accGradParameters}, {NULL, NULL} }; void cunnconv1d_VerticalConvolution_init(lua_State *L) { luaT_pushmetatable(L, "torch.CudaTensor"); luaT_registeratname(L, cunnconv1d_VerticalConvolution__, "nn"); lua_pop(L,1); }
a5554aebb224be1eeeb1f98f28dbc5519a4c2609.cu
#include "utils.h" #include "common.h" // Kernel for fast unfold+copy // (borrowed from Caffe: https://github.com/BVLC/caffe/blob/master/src/caffe/layers/conv_layer.cu) __global__ void im2col_kernel_v(const int n, const float* data_im, const int height, const int width, const int ksize_h, const int ksize_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int height_col, const int width_col, float* data_col) { CUDA_KERNEL_LOOP(index, n) { int w_out = index % width_col; index /= width_col; int h_out = index % height_col; int channel_in = index / height_col; int channel_out = channel_in * ksize_h * ksize_w; int h_in = h_out * stride_h - pad_h; int w_in = w_out * stride_w - pad_w; data_col += (channel_out * height_col + h_out) * width_col + w_out; data_im += (channel_in * height + h_in) * width + w_in; for (int i = 0; i < ksize_h; ++i) { for (int j = 0; j < ksize_w; ++j) { int h = h_in + i; int w = w_in + j; *data_col = (h >= 0 && w >= 0 && h < height && w < width) ? data_im[i * width + j] : 0; data_col += height_col * width_col; } } } } __global__ void conv_vertical_naive_output(const int n, float *y, const float *x, const float *w, const int iH, const int iW, const int kL) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { int oH = iH - kL + 1; int x_offset = (i/(oH*iW))*iH*iW + i%(oH*iW); int w_offset = (i/(oH*iW))*kL; for (int k = 0; k < kL; k++) { y[i] += w[w_offset + k]*x[x_offset + k*iW]; } } } __global__ void conv_vertical_naive_gradInput(const int n, float *dx, const float *dy, const float *w, const int oH, const int oW, const int kL) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { int iH = oH + kL - 1; int iC = i/(iH*oW); int row = (i%(iH*oW))/oW; int dy_offset = iC*oH*oW + i%(iH*oW); int w_offset = iC*kL; int k_begin = max(0, row-oH+1); int k_end = min(kL, row+1); dx[i] = 0.0f; for (int k = k_begin; k < k_end; k++) { dx[i] += w[w_offset + k]*dy[dy_offset - k*oW]; } } } __global__ void conv_vertical_naive_gradParam(const int n, float *dw, const float *x, const float *dy, const int kL, const int oH, const int oW) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { int dy_offset = (i/kL)*oH*oW; int x_offset = (i/kL)*oH*oW + (i%kL)*oW; for (int k = 0; k < oH*oW; k++) { dw[i] += dy[dy_offset + k]*x[x_offset + k]; } } } __global__ void conv_vertical_naive_gradWeight(const int n, float *y, const float *x, const int kL, const int iC) { for (int i = blockIdx.x*blockDim.x+threadIdx.x; i < n; i += blockDim.x*gridDim.x) { y[i] = x[(i/kL)*kL*iC + i]; } } static int cunnconv1d_VerticalConvolution_updateOutput(lua_State *L) { THCState *state = getCutorchState(L); THCudaTensor *input = (THCudaTensor*)luaT_checkudata(L, 2, "torch.CudaTensor"); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); THCudaTensor *weight = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "weight", "torch.CudaTensor"); THCudaTensor *bias = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "bias", "torch.CudaTensor"); THCudaTensor *ones = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "ones", "torch.CudaTensor"); THCudaTensor *output = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "output", "torch.CudaTensor"); const int device = THCudaTensor_getDevice(state, weight); luaL_argcheck(L, THCudaTensor_getDevice(state, bias) == device, 1, "weight and bias need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, output) == device || THCudaTensor_getDevice(state, output) == -1, 1, "weight and output need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, input) == device, 2, "weight and input need to be on the same device"); luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D (batch mode) tensor is expected"); // change to batch mode int batch = 1; if (input->nDimension == 3) { luaL_argcheck(L, input->size[0] == nInputPlane, 2, "input channels and nInputPlane dont match"); batch = 0; THCudaTensor_resize4d(state, input, 1, input->size[0], input->size[1], input->size[2]); } else { luaL_argcheck(L, input->size[1] == nInputPlane, 2, "input channels and nInputPlane dont match"); } long batchSize = input->size[0]; long inputHeight = input->size[2]; long inputWidth = input->size[3]; long outputHeight = inputHeight - weight->size[1] + 1; long outputWidth = inputWidth; THCudaTensor_resize4d(state, output, batchSize, nOutputPlane, outputHeight, outputWidth); if (ones->nDimension != 2 || ones->size[0]*ones->size[1] < outputHeight*outputWidth) { THCudaTensor_resize2d(state, ones, outputHeight, outputWidth); THCudaTensor_fill(state, ones, 1); } THCudaTensor *input_n = THCudaTensor_new(state); THCudaTensor *output_n = THCudaTensor_new(state); for (int elt = 0; elt < batchSize; elt ++) { // select each batch THCudaTensor_select(state, input_n, input, 0, elt); THCudaTensor_select(state, output_n, output, 0, elt); // fill biases THCudaBlas_gemm( state, 't', 'n', outputHeight*outputWidth, nOutputPlane, 1, 1, THCudaTensor_data(state, ones), 1, THCudaTensor_data(state, bias), 1, 0, THCudaTensor_data(state, output_n), outputHeight*outputWidth ); // convolve long num_threads = nOutputPlane*outputHeight*outputWidth; conv_vertical_naive_output <<<GET_BLOCKS(num_threads), CUDA_NUM_THREADS>>> (num_threads, THCudaTensor_data(state, output_n), THCudaTensor_data(state, input_n), THCudaTensor_data(state, weight), inputHeight, inputWidth, weight->size[1]); } THCudaTensor_free(state, input_n); THCudaTensor_free(state, output_n); // revert to single batch if (batch == 0) { THCudaTensor_resize3d(state, output, nOutputPlane, outputHeight, outputWidth); THCudaTensor_resize3d(state, input, nInputPlane, inputHeight, inputWidth); } return 1; } static int cunnconv1d_VerticalConvolution_updateGradInput(lua_State *L) { THCState *state = getCutorchState(L); THCudaTensor *input = (THCudaTensor *)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor *gradOutput = (THCudaTensor *)luaT_checkudata(L, 3, "torch.CudaTensor"); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); THCudaTensor *weight = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "weight", "torch.CudaTensor"); THCudaTensor *gradInput = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "gradInput", "torch.CudaTensor"); const int device = THCudaTensor_getDevice(state, weight); luaL_argcheck(L, THCudaTensor_getDevice(state, input) == device, 2, "weight and input need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, gradInput) == device || THCudaTensor_getDevice(state, gradInput) == -1, 2, "weight and gradInput need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, gradOutput) == device || THCudaTensor_getDevice(state, gradOutput) == -1, 2, "weight and gradOutput need to be on the same device"); luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D (batch mode) tensor is expected"); int batch = 1; if (input->nDimension == 3) { batch = 0; THCudaTensor_resize4d(state, input, 1, input->size[0], input->size[1], input->size[2]); THCudaTensor_resize4d(state, gradOutput, 1, gradOutput->size[0], gradOutput->size[1], gradOutput->size[2]); } long batchSize = input->size[0]; long inputHeight = input->size[2]; long inputWidth = input->size[3]; long outputHeight = inputHeight - weight->size[1] + 1; long outputWidth = inputWidth; THCudaTensor_resize4d(state, gradInput, batchSize, nInputPlane, inputHeight, inputWidth); THCudaTensor *gradInput_n = THCudaTensor_new(state); THCudaTensor *gradOutput_n = THCudaTensor_new(state); for (int elt = 0; elt < batchSize; elt ++) { // select each batch in 2D THCudaTensor_select(state, gradInput_n, gradInput, 0, elt); THCudaTensor_select(state, gradOutput_n, gradOutput, 0, elt); // convolve long num_threads = nInputPlane*inputHeight*inputWidth; conv_vertical_naive_gradInput <<<GET_BLOCKS(num_threads), CUDA_NUM_THREADS>>> (num_threads, THCudaTensor_data(state, gradInput_n), THCudaTensor_data(state, gradOutput_n), THCudaTensor_data(state, weight), outputHeight, outputWidth, weight->size[1]); } THCudaTensor_free(state, gradInput_n); THCudaTensor_free(state, gradOutput_n); // revert to single batch if (batch == 0) { THCudaTensor_resize3d(state, input, nInputPlane, inputHeight, inputWidth); THCudaTensor_resize3d(state, gradInput, nInputPlane, inputHeight, inputWidth); THCudaTensor_resize3d(state, gradOutput, nOutputPlane, outputHeight, outputWidth); } return 1; } static int cunnconv1d_VerticalConvolution_accGradParameters(lua_State *L) { THCState *state = getCutorchState(L); THCudaTensor *input = (THCudaTensor *)luaT_checkudata(L, 2, "torch.CudaTensor"); THCudaTensor *gradOutput = (THCudaTensor *)luaT_checkudata(L, 3, "torch.CudaTensor"); float scale = luaL_optnumber(L, 4, 1); int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane"); int nOutputPlane = luaT_getfieldcheckint(L, 1, "nOutputPlane"); int kL = luaT_getfieldcheckint(L, 1, "kL"); THCudaTensor *gradWeight = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "gradWeight", "torch.CudaTensor"); THCudaTensor *gradBias = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "gradBias", "torch.CudaTensor"); THCudaTensor *ones = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "ones", "torch.CudaTensor"); THCudaTensor *finput = (THCudaTensor*)luaT_getfieldcheckudata(L, 1, "finput", "torch.CudaTensor"); THCudaTensor *fgradWeight = (THCudaTensor *)luaT_getfieldcheckudata(L, 1, "fgradWeight", "torch.CudaTensor"); const int device = THCudaTensor_getDevice(state, gradWeight); luaL_argcheck(L, THCudaTensor_getDevice(state, gradBias) == device, 1, "gradWeight and gradBias need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, input) == device, 1, "gradWeight and input need to be on the same device"); luaL_argcheck(L, THCudaTensor_getDevice(state, gradOutput) == device, 1, "gradWeight and gradOutput need to be on the same device"); luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D (batch mode) tensor is expected"); // change to batch mode int batch = 1; if (input->nDimension == 3) { batch = 0; THCudaTensor_resize4d(state, input, 1, input->size[0], input->size[1], input->size[2]); THCudaTensor_resize4d(state, gradOutput, 1, gradOutput->size[0], gradOutput->size[1], gradOutput->size[2]); } long batchSize = input->size[0]; long inputHeight = input->size[2]; long inputWidth = input->size[3]; long outputHeight = inputHeight - kL + 1; long outputWidth = inputWidth; if (ones->nDimension != 2 || ones->size[0]*ones->size[1] < outputHeight*outputWidth) { THCudaTensor_resize2d(state, ones, outputHeight, outputWidth); THCudaTensor_fill(state, ones, 1); } THCudaTensor_resize2d(state, finput, kL*nInputPlane, outputHeight*outputWidth); THCudaTensor_resize2d(state, fgradWeight, nOutputPlane, kL*nInputPlane); THCudaTensor *input_n = THCudaTensor_new(state); THCudaTensor *gradOutput_n = THCudaTensor_new(state); for (int elt = 0; elt < batchSize; elt ++) { // select each batch THCudaTensor_select(state, input_n, input, 0, elt); THCudaTensor_select(state, gradOutput_n, gradOutput, 0, elt); // unroll long num_threads = nInputPlane*outputHeight*outputWidth; im2col_kernel_v <<<GET_BLOCKS(num_threads), CUDA_NUM_THREADS>>> ( num_threads, THCudaTensor_data(state, input_n), inputHeight, inputWidth, kL, 1, 0, 0, 1, 1, outputHeight, outputWidth, THCudaTensor_data(state, finput) ); // convolve THCudaBlas_gemm( state, 't', 'n', kL*nInputPlane, nOutputPlane, outputHeight*outputWidth, scale, THCudaTensor_data(state, finput), outputHeight*outputWidth, THCudaTensor_data(state, gradOutput_n), outputHeight*outputWidth, (elt > 0), THCudaTensor_data(state, fgradWeight), kL*nInputPlane ); // fill biases THCudaBlas_gemv( state, 't', outputHeight*outputWidth, nOutputPlane, scale, THCudaTensor_data(state, gradOutput_n), outputHeight*outputWidth, THCudaTensor_data(state, ones), 1, 1, THCudaTensor_data(state, gradBias), 1 ); } // extract gradWeight long num_threads_ = kL*nInputPlane; conv_vertical_naive_gradWeight <<<GET_BLOCKS(num_threads_), CUDA_NUM_THREADS>>> ( num_threads_, THCudaTensor_data(state, gradWeight), THCudaTensor_data(state, fgradWeight), kL, nInputPlane ); THCudaTensor_free(state, input_n); THCudaTensor_free(state, gradOutput_n); if (batch == 0) { THCudaTensor_resize3d(state, gradOutput, nOutputPlane, outputHeight, outputWidth); THCudaTensor_resize3d(state, input, nInputPlane, inputHeight, inputWidth); } return 0; } static const struct luaL_Reg cunnconv1d_VerticalConvolution__ [] = { {"VerticalConvolution_updateOutput", cunnconv1d_VerticalConvolution_updateOutput}, {"VerticalConvolution_updateGradInput", cunnconv1d_VerticalConvolution_updateGradInput}, {"VerticalConvolution_accGradParameters", cunnconv1d_VerticalConvolution_accGradParameters}, {NULL, NULL} }; void cunnconv1d_VerticalConvolution_init(lua_State *L) { luaT_pushmetatable(L, "torch.CudaTensor"); luaT_registeratname(L, cunnconv1d_VerticalConvolution__, "nn"); lua_pop(L,1); }
f66486c0b11264cab1f9a258e906b3ef854bf04c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <hipcub/hipcub.hpp> #include "caffe2/core/context_gpu.h" #include "caffe2/operators/reduce_front_back_sum_mean_ops.h" namespace caffe2 { namespace { template <typename T, bool NORMALIZE> __global__ void columnwise_fill_kernel( const int rows, const int cols, const T* dY, const int* lengths, T* dX) { CUDA_1D_KERNEL_LOOP(i, rows * cols) { int row = i / cols; int col = i % cols; if (lengths == nullptr) { dX[i] = NORMALIZE ? dY[col] / rows : dY[col]; } else if (row < lengths[col]) { dX[i] = NORMALIZE ? dY[col] / lengths[col] : dY[col]; } else { dX[i] = 0; } } } template <typename T, bool NORMALIZE> __global__ void rowwise_fill_kernel( const int rows, const int cols, const T* dY, const int* lengths, T* dX) { CUDA_1D_KERNEL_LOOP(i, rows * cols) { int row = i / cols; int col = i % cols; if (lengths == nullptr) { dX[i] = NORMALIZE ? dY[row] / cols : dY[row]; } else if (col < lengths[row]) { dX[i] = NORMALIZE ? dY[row] / lengths[row] : dY[row]; } else { dX[i] = 0; } } } template <typename T, bool NORMALIZE> __global__ void rowwise_sum_kernel( const int rows, const int cols, const T* data, const int* lengths, T* out) { typedef hipcub::BlockReduce<float, CAFFE_CUDA_NUM_THREADS> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; for (int rowIndex = blockIdx.x; rowIndex < rows; rowIndex += gridDim.x) { T sum = 0; const int rowOffset = rowIndex * cols; const int length = lengths == nullptr ? cols : lengths[rowIndex]; for (int colIndex = threadIdx.x; colIndex < length; colIndex += blockDim.x) { sum += data[rowOffset + colIndex]; } sum = BlockReduce(temp_storage).Reduce(sum, hipcub::Sum()); if (threadIdx.x == 0) { out[rowIndex] = NORMALIZE ? sum / length : sum; } __syncthreads(); } } template <typename T, bool NORMALIZE> __global__ void columnwise_sum_kernel( const int rows, const int cols, const T* data, const int* lengths, T* out) { typedef hipcub::BlockReduce<float, CAFFE_CUDA_NUM_THREADS> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; for (int colIndex = blockIdx.x; colIndex < cols; colIndex += gridDim.x) { T sum = 0; const int length = lengths == nullptr ? rows : lengths[colIndex]; for (int rowIndex = threadIdx.x; rowIndex < length; rowIndex += blockDim.x) { sum += data[rowIndex * cols + colIndex]; } sum = BlockReduce(temp_storage).Reduce(sum, hipcub::Sum()); if (threadIdx.x == 0) { out[colIndex] = NORMALIZE ? sum / length : sum; } __syncthreads(); } } } // anonymous namespace /*** Sum Ops ***/ // ReduceFrontSum: columnwise sum template <> template <typename T> void SumReduceDimsOp<CUDAContext, true, false>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { hipLaunchKernelGGL(( columnwise_sum_kernel<T, false>) , dim3(::min(cols, CAFFE_MAXIMUM_NUM_BLOCKS)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, in_data, lengths_data, out_data); } // ReduceBackSum: rowwise sum template <> template <typename T> void SumReduceDimsOp<CUDAContext, false, false>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { hipLaunchKernelGGL(( rowwise_sum_kernel<T, false>) , dim3(::min(rows, CAFFE_MAXIMUM_NUM_BLOCKS)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, in_data, lengths_data, out_data); } // ReduceFrontSumGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, true, false>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { hipLaunchKernelGGL(( columnwise_fill_kernel<T, false>) , dim3(CAFFE_GET_BLOCKS(rows * cols)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, dYdata, lengths_data, dXdata); } // ReduceBackSumGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, false, false>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { hipLaunchKernelGGL(( rowwise_fill_kernel<T, false>) , dim3(CAFFE_GET_BLOCKS(rows * cols)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, dYdata, lengths_data, dXdata); } REGISTER_CUDA_OPERATOR( ReduceFrontSum, SumReduceDimsOp<CUDAContext, true, false>); REGISTER_CUDA_OPERATOR( ReduceFrontSumGradient, SumReduceDimsGradientOp<CUDAContext, true, false>); REGISTER_CUDA_OPERATOR( ReduceBackSum, SumReduceDimsOp<CUDAContext, false, false>); REGISTER_CUDA_OPERATOR( ReduceBackSumGradient, SumReduceDimsGradientOp<CUDAContext, false, false>); /*** Mean Ops ***/ // ReduceFrontMean: columnwise mean template <> template <typename T> void SumReduceDimsOp<CUDAContext, true, true>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { hipLaunchKernelGGL(( columnwise_sum_kernel<T, true>) , dim3(::min(cols, CAFFE_MAXIMUM_NUM_BLOCKS)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, in_data, lengths_data, out_data); } // ReduceBackMean: rowwise mean template <> template <typename T> void SumReduceDimsOp<CUDAContext, false, true>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { hipLaunchKernelGGL(( rowwise_sum_kernel<T, true>) , dim3(::min(rows, CAFFE_MAXIMUM_NUM_BLOCKS)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, in_data, lengths_data, out_data); } // ReduceFrontMeanGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, true, true>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { hipLaunchKernelGGL(( columnwise_fill_kernel<T, true>) , dim3(CAFFE_GET_BLOCKS(rows * cols)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, dYdata, lengths_data, dXdata); } // ReduceBackMeanGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, false, true>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { hipLaunchKernelGGL(( rowwise_fill_kernel<T, true>) , dim3(CAFFE_GET_BLOCKS(rows * cols)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), rows, cols, dYdata, lengths_data, dXdata); } REGISTER_CUDA_OPERATOR( ReduceFrontMean, SumReduceDimsOp<CUDAContext, true, true>); REGISTER_CUDA_OPERATOR( ReduceFrontMeanGradient, SumReduceDimsGradientOp<CUDAContext, true, true>); REGISTER_CUDA_OPERATOR( ReduceBackMean, SumReduceDimsOp<CUDAContext, false, true>); REGISTER_CUDA_OPERATOR( ReduceBackMeanGradient, SumReduceDimsGradientOp<CUDAContext, false, true>); } // namespace caffe2
f66486c0b11264cab1f9a258e906b3ef854bf04c.cu
#include <cub/block/block_reduce.cuh> #include "caffe2/core/context_gpu.h" #include "caffe2/operators/reduce_front_back_sum_mean_ops.h" namespace caffe2 { namespace { template <typename T, bool NORMALIZE> __global__ void columnwise_fill_kernel( const int rows, const int cols, const T* dY, const int* lengths, T* dX) { CUDA_1D_KERNEL_LOOP(i, rows * cols) { int row = i / cols; int col = i % cols; if (lengths == nullptr) { dX[i] = NORMALIZE ? dY[col] / rows : dY[col]; } else if (row < lengths[col]) { dX[i] = NORMALIZE ? dY[col] / lengths[col] : dY[col]; } else { dX[i] = 0; } } } template <typename T, bool NORMALIZE> __global__ void rowwise_fill_kernel( const int rows, const int cols, const T* dY, const int* lengths, T* dX) { CUDA_1D_KERNEL_LOOP(i, rows * cols) { int row = i / cols; int col = i % cols; if (lengths == nullptr) { dX[i] = NORMALIZE ? dY[row] / cols : dY[row]; } else if (col < lengths[row]) { dX[i] = NORMALIZE ? dY[row] / lengths[row] : dY[row]; } else { dX[i] = 0; } } } template <typename T, bool NORMALIZE> __global__ void rowwise_sum_kernel( const int rows, const int cols, const T* data, const int* lengths, T* out) { typedef cub::BlockReduce<float, CAFFE_CUDA_NUM_THREADS> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; for (int rowIndex = blockIdx.x; rowIndex < rows; rowIndex += gridDim.x) { T sum = 0; const int rowOffset = rowIndex * cols; const int length = lengths == nullptr ? cols : lengths[rowIndex]; for (int colIndex = threadIdx.x; colIndex < length; colIndex += blockDim.x) { sum += data[rowOffset + colIndex]; } sum = BlockReduce(temp_storage).Reduce(sum, cub::Sum()); if (threadIdx.x == 0) { out[rowIndex] = NORMALIZE ? sum / length : sum; } __syncthreads(); } } template <typename T, bool NORMALIZE> __global__ void columnwise_sum_kernel( const int rows, const int cols, const T* data, const int* lengths, T* out) { typedef cub::BlockReduce<float, CAFFE_CUDA_NUM_THREADS> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; for (int colIndex = blockIdx.x; colIndex < cols; colIndex += gridDim.x) { T sum = 0; const int length = lengths == nullptr ? rows : lengths[colIndex]; for (int rowIndex = threadIdx.x; rowIndex < length; rowIndex += blockDim.x) { sum += data[rowIndex * cols + colIndex]; } sum = BlockReduce(temp_storage).Reduce(sum, cub::Sum()); if (threadIdx.x == 0) { out[colIndex] = NORMALIZE ? sum / length : sum; } __syncthreads(); } } } // anonymous namespace /*** Sum Ops ***/ // ReduceFrontSum: columnwise sum template <> template <typename T> void SumReduceDimsOp<CUDAContext, true, false>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { columnwise_sum_kernel<T, false> <<<std::min(cols, CAFFE_MAXIMUM_NUM_BLOCKS), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, in_data, lengths_data, out_data); } // ReduceBackSum: rowwise sum template <> template <typename T> void SumReduceDimsOp<CUDAContext, false, false>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { rowwise_sum_kernel<T, false> <<<std::min(rows, CAFFE_MAXIMUM_NUM_BLOCKS), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, in_data, lengths_data, out_data); } // ReduceFrontSumGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, true, false>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { columnwise_fill_kernel<T, false> <<<CAFFE_GET_BLOCKS(rows * cols), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, dYdata, lengths_data, dXdata); } // ReduceBackSumGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, false, false>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { rowwise_fill_kernel<T, false> <<<CAFFE_GET_BLOCKS(rows * cols), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, dYdata, lengths_data, dXdata); } REGISTER_CUDA_OPERATOR( ReduceFrontSum, SumReduceDimsOp<CUDAContext, true, false>); REGISTER_CUDA_OPERATOR( ReduceFrontSumGradient, SumReduceDimsGradientOp<CUDAContext, true, false>); REGISTER_CUDA_OPERATOR( ReduceBackSum, SumReduceDimsOp<CUDAContext, false, false>); REGISTER_CUDA_OPERATOR( ReduceBackSumGradient, SumReduceDimsGradientOp<CUDAContext, false, false>); /*** Mean Ops ***/ // ReduceFrontMean: columnwise mean template <> template <typename T> void SumReduceDimsOp<CUDAContext, true, true>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { columnwise_sum_kernel<T, true> <<<std::min(cols, CAFFE_MAXIMUM_NUM_BLOCKS), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, in_data, lengths_data, out_data); } // ReduceBackMean: rowwise mean template <> template <typename T> void SumReduceDimsOp<CUDAContext, false, true>::Compute( int rows, int cols, const T* in_data, const int* lengths_data, T* out_data) { rowwise_sum_kernel<T, true> <<<std::min(rows, CAFFE_MAXIMUM_NUM_BLOCKS), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, in_data, lengths_data, out_data); } // ReduceFrontMeanGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, true, true>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { columnwise_fill_kernel<T, true> <<<CAFFE_GET_BLOCKS(rows * cols), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, dYdata, lengths_data, dXdata); } // ReduceBackMeanGradient template <> template <typename T> void SumReduceDimsGradientOp<CUDAContext, false, true>::Compute( int rows, int cols, const T* dYdata, const int* lengths_data, T* dXdata) { rowwise_fill_kernel<T, true> <<<CAFFE_GET_BLOCKS(rows * cols), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>(rows, cols, dYdata, lengths_data, dXdata); } REGISTER_CUDA_OPERATOR( ReduceFrontMean, SumReduceDimsOp<CUDAContext, true, true>); REGISTER_CUDA_OPERATOR( ReduceFrontMeanGradient, SumReduceDimsGradientOp<CUDAContext, true, true>); REGISTER_CUDA_OPERATOR( ReduceBackMean, SumReduceDimsOp<CUDAContext, false, true>); REGISTER_CUDA_OPERATOR( ReduceBackMeanGradient, SumReduceDimsGradientOp<CUDAContext, false, true>); } // namespace caffe2
7a67c0cc3dbe4c12d49e1a573fffb220f3d3f75a.hip
// !!! This is a file automatically generated by hipify!!! /*! * Copyright 2020 XGBoost contributors */ #include <memory> #include <type_traits> #include <algorithm> #include "../common/hist_util.cuh" #include "simple_batch_iterator.h" #include "iterative_device_dmatrix.h" #include "sparse_page_source.h" #include "ellpack_page.cuh" #include "proxy_dmatrix.h" #include "device_adapter_hip.cuh" namespace xgboost { namespace data { template <typename Fn> decltype(auto) Dispatch(DMatrixProxy const* proxy, Fn fn) { if (proxy->Adapter().type() == typeid(std::shared_ptr<CupyAdapter>)) { auto value = dmlc::get<std::shared_ptr<CupyAdapter>>( proxy->Adapter())->Value(); return fn(value); } else if (proxy->Adapter().type() == typeid(std::shared_ptr<CudfAdapter>)) { auto value = dmlc::get<std::shared_ptr<CudfAdapter>>( proxy->Adapter())->Value(); return fn(value); } else { LOG(FATAL) << "Unknown type: " << proxy->Adapter().type().name(); auto value = dmlc::get<std::shared_ptr<CudfAdapter>>( proxy->Adapter())->Value(); return fn(value); } } void IterativeDeviceDMatrix::Initialize(DataIterHandle iter_handle, float missing, int nthread) { // A handle passed to external iterator. auto handle = static_cast<std::shared_ptr<DMatrix>*>(proxy_); CHECK(handle); DMatrixProxy* proxy = static_cast<DMatrixProxy*>(handle->get()); CHECK(proxy); // The external iterator auto iter = DataIterProxy<DataIterResetCallback, XGDMatrixCallbackNext>{ iter_handle, reset_, next_}; dh::XGBCachingDeviceAllocator<char> alloc; auto num_rows = [&]() { return Dispatch(proxy, [](auto const &value) { return value.NumRows(); }); }; auto num_cols = [&]() { return Dispatch(proxy, [](auto const &value) { return value.NumCols(); }); }; size_t row_stride = 0; size_t nnz = 0; // Sketch for all batches. iter.Reset(); std::vector<common::SketchContainer> sketch_containers; size_t batches = 0; size_t accumulated_rows = 0; bst_feature_t cols = 0; int32_t device = -1; while (iter.Next()) { device = proxy->DeviceIdx(); dh::safe_cuda(hipSetDevice(device)); if (cols == 0) { cols = num_cols(); } else { CHECK_EQ(cols, num_cols()) << "Inconsistent number of columns."; } sketch_containers.emplace_back(batch_param_.max_bin, num_cols(), num_rows(), device); auto* p_sketch = &sketch_containers.back(); proxy->Info().weights_.SetDevice(device); Dispatch(proxy, [&](auto const &value) { common::AdapterDeviceSketchWeighted(value, batch_param_.max_bin, proxy->Info(), missing, p_sketch); }); auto batch_rows = num_rows(); accumulated_rows += batch_rows; dh::caching_device_vector<size_t> row_counts(batch_rows + 1, 0); common::Span<size_t> row_counts_span(row_counts.data().get(), row_counts.size()); row_stride = ::max(row_stride, Dispatch(proxy, [=](auto const &value) { return GetRowCounts(value, row_counts_span, device, missing); })); nnz += thrust::reduce(thrust::hip::par(alloc), row_counts.begin(), row_counts.end()); batches++; } if (device < 0) { // error or empty this->page_.reset(new EllpackPage); return; } common::SketchContainer final_sketch(batch_param_.max_bin, cols, accumulated_rows, device); for (auto const& sketch : sketch_containers) { final_sketch.Merge(sketch.ColumnsPtr(), sketch.Data()); final_sketch.FixError(); } sketch_containers.clear(); sketch_containers.shrink_to_fit(); common::HistogramCuts cuts; final_sketch.MakeCuts(&cuts); this->info_.num_col_ = cols; this->info_.num_row_ = accumulated_rows; this->info_.num_nonzero_ = nnz; auto init_page = [this, &proxy, &cuts, row_stride, accumulated_rows]() { if (!page_) { // Should be put inside the while loop to protect against empty batch. In // that case device id is invalid. page_.reset(new EllpackPage); *(page_->Impl()) = EllpackPageImpl(proxy->DeviceIdx(), cuts, this->IsDense(), row_stride, accumulated_rows); } }; // Construct the final ellpack page. size_t offset = 0; iter.Reset(); size_t n_batches_for_verification = 0; while (iter.Next()) { init_page(); auto device = proxy->DeviceIdx(); dh::safe_cuda(hipSetDevice(device)); auto rows = num_rows(); dh::caching_device_vector<size_t> row_counts(rows + 1, 0); common::Span<size_t> row_counts_span(row_counts.data().get(), row_counts.size()); Dispatch(proxy, [=](auto const& value) { return GetRowCounts(value, row_counts_span, device, missing); }); auto is_dense = this->IsDense(); auto new_impl = Dispatch(proxy, [&](auto const &value) { return EllpackPageImpl(value, missing, device, is_dense, nthread, row_counts_span, row_stride, rows, cols, cuts); }); size_t num_elements = page_->Impl()->Copy(device, &new_impl, offset); offset += num_elements; proxy->Info().num_row_ = num_rows(); proxy->Info().num_col_ = cols; if (batches != 1) { this->info_.Extend(std::move(proxy->Info()), false); } n_batches_for_verification++; } CHECK_EQ(batches, n_batches_for_verification) << "Different number of batches returned between 2 iterations"; if (batches == 1) { this->info_ = std::move(proxy->Info()); CHECK_EQ(proxy->Info().labels_.Size(), 0); } iter.Reset(); // Synchronise worker columns rabit::Allreduce<rabit::op::Max>(&info_.num_col_, 1); } BatchSet<EllpackPage> IterativeDeviceDMatrix::GetEllpackBatches(const BatchParam& param) { CHECK(page_); auto begin_iter = BatchIterator<EllpackPage>(new SimpleBatchIteratorImpl<EllpackPage>(page_.get())); return BatchSet<EllpackPage>(begin_iter); } } // namespace data } // namespace xgboost
7a67c0cc3dbe4c12d49e1a573fffb220f3d3f75a.cu
/*! * Copyright 2020 XGBoost contributors */ #include <memory> #include <type_traits> #include <algorithm> #include "../common/hist_util.cuh" #include "simple_batch_iterator.h" #include "iterative_device_dmatrix.h" #include "sparse_page_source.h" #include "ellpack_page.cuh" #include "proxy_dmatrix.h" #include "device_adapter.cuh" namespace xgboost { namespace data { template <typename Fn> decltype(auto) Dispatch(DMatrixProxy const* proxy, Fn fn) { if (proxy->Adapter().type() == typeid(std::shared_ptr<CupyAdapter>)) { auto value = dmlc::get<std::shared_ptr<CupyAdapter>>( proxy->Adapter())->Value(); return fn(value); } else if (proxy->Adapter().type() == typeid(std::shared_ptr<CudfAdapter>)) { auto value = dmlc::get<std::shared_ptr<CudfAdapter>>( proxy->Adapter())->Value(); return fn(value); } else { LOG(FATAL) << "Unknown type: " << proxy->Adapter().type().name(); auto value = dmlc::get<std::shared_ptr<CudfAdapter>>( proxy->Adapter())->Value(); return fn(value); } } void IterativeDeviceDMatrix::Initialize(DataIterHandle iter_handle, float missing, int nthread) { // A handle passed to external iterator. auto handle = static_cast<std::shared_ptr<DMatrix>*>(proxy_); CHECK(handle); DMatrixProxy* proxy = static_cast<DMatrixProxy*>(handle->get()); CHECK(proxy); // The external iterator auto iter = DataIterProxy<DataIterResetCallback, XGDMatrixCallbackNext>{ iter_handle, reset_, next_}; dh::XGBCachingDeviceAllocator<char> alloc; auto num_rows = [&]() { return Dispatch(proxy, [](auto const &value) { return value.NumRows(); }); }; auto num_cols = [&]() { return Dispatch(proxy, [](auto const &value) { return value.NumCols(); }); }; size_t row_stride = 0; size_t nnz = 0; // Sketch for all batches. iter.Reset(); std::vector<common::SketchContainer> sketch_containers; size_t batches = 0; size_t accumulated_rows = 0; bst_feature_t cols = 0; int32_t device = -1; while (iter.Next()) { device = proxy->DeviceIdx(); dh::safe_cuda(cudaSetDevice(device)); if (cols == 0) { cols = num_cols(); } else { CHECK_EQ(cols, num_cols()) << "Inconsistent number of columns."; } sketch_containers.emplace_back(batch_param_.max_bin, num_cols(), num_rows(), device); auto* p_sketch = &sketch_containers.back(); proxy->Info().weights_.SetDevice(device); Dispatch(proxy, [&](auto const &value) { common::AdapterDeviceSketchWeighted(value, batch_param_.max_bin, proxy->Info(), missing, p_sketch); }); auto batch_rows = num_rows(); accumulated_rows += batch_rows; dh::caching_device_vector<size_t> row_counts(batch_rows + 1, 0); common::Span<size_t> row_counts_span(row_counts.data().get(), row_counts.size()); row_stride = std::max(row_stride, Dispatch(proxy, [=](auto const &value) { return GetRowCounts(value, row_counts_span, device, missing); })); nnz += thrust::reduce(thrust::cuda::par(alloc), row_counts.begin(), row_counts.end()); batches++; } if (device < 0) { // error or empty this->page_.reset(new EllpackPage); return; } common::SketchContainer final_sketch(batch_param_.max_bin, cols, accumulated_rows, device); for (auto const& sketch : sketch_containers) { final_sketch.Merge(sketch.ColumnsPtr(), sketch.Data()); final_sketch.FixError(); } sketch_containers.clear(); sketch_containers.shrink_to_fit(); common::HistogramCuts cuts; final_sketch.MakeCuts(&cuts); this->info_.num_col_ = cols; this->info_.num_row_ = accumulated_rows; this->info_.num_nonzero_ = nnz; auto init_page = [this, &proxy, &cuts, row_stride, accumulated_rows]() { if (!page_) { // Should be put inside the while loop to protect against empty batch. In // that case device id is invalid. page_.reset(new EllpackPage); *(page_->Impl()) = EllpackPageImpl(proxy->DeviceIdx(), cuts, this->IsDense(), row_stride, accumulated_rows); } }; // Construct the final ellpack page. size_t offset = 0; iter.Reset(); size_t n_batches_for_verification = 0; while (iter.Next()) { init_page(); auto device = proxy->DeviceIdx(); dh::safe_cuda(cudaSetDevice(device)); auto rows = num_rows(); dh::caching_device_vector<size_t> row_counts(rows + 1, 0); common::Span<size_t> row_counts_span(row_counts.data().get(), row_counts.size()); Dispatch(proxy, [=](auto const& value) { return GetRowCounts(value, row_counts_span, device, missing); }); auto is_dense = this->IsDense(); auto new_impl = Dispatch(proxy, [&](auto const &value) { return EllpackPageImpl(value, missing, device, is_dense, nthread, row_counts_span, row_stride, rows, cols, cuts); }); size_t num_elements = page_->Impl()->Copy(device, &new_impl, offset); offset += num_elements; proxy->Info().num_row_ = num_rows(); proxy->Info().num_col_ = cols; if (batches != 1) { this->info_.Extend(std::move(proxy->Info()), false); } n_batches_for_verification++; } CHECK_EQ(batches, n_batches_for_verification) << "Different number of batches returned between 2 iterations"; if (batches == 1) { this->info_ = std::move(proxy->Info()); CHECK_EQ(proxy->Info().labels_.Size(), 0); } iter.Reset(); // Synchronise worker columns rabit::Allreduce<rabit::op::Max>(&info_.num_col_, 1); } BatchSet<EllpackPage> IterativeDeviceDMatrix::GetEllpackBatches(const BatchParam& param) { CHECK(page_); auto begin_iter = BatchIterator<EllpackPage>(new SimpleBatchIteratorImpl<EllpackPage>(page_.get())); return BatchSet<EllpackPage>(begin_iter); } } // namespace data } // namespace xgboost
e61017c22ed304d8ef52687cfee62bac778519bc.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "THHUNN.h" #include "common.h" #include "THHHalf.h" #include "THHHalfAutoNumerics.cuh" // Kernel for fast unfold+copy // Borrowed from Theano // Authors: Arjun Jain, Frdric Bastien, Jan Schlter, Nicolas Ballas template <typename Dtype> __global__ void im3d2col_kernel(const int n, const Dtype* data_im, const int height, const int width, const int depth, const int kernel_h, const int kernel_w, const int kernel_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, const int height_col, const int width_col, const int depth_col, Dtype* data_col) { CUDA_KERNEL_LOOP(index, n) { int d_out = index % depth_col; int w_index = index / depth_col; int w_out = w_index % width_col; int h_index = w_index / width_col; int h_out = h_index % height_col; int channel_in = h_index / height_col; //channel_in = 1; int channel_out = channel_in * kernel_h * kernel_w * kernel_d; int h_in = h_out * stride_h - pad_h; int w_in = w_out * stride_w - pad_w; int d_in = d_out * stride_d - pad_d; Dtype* data_col_ptr = data_col; data_col_ptr += channel_out * (height_col * width_col * depth_col) + h_out * (width_col * depth_col) + w_out * depth_col + d_out; const Dtype* data_im_ptr = data_im; data_im_ptr += channel_in * (height * width * depth) + h_in * (width * depth) + w_in * depth + d_in; for (int i = 0; i < kernel_h; ++i) { int h = h_in + i; for (int j = 0; j < kernel_w; ++j) { int w = w_in + j; for (int k = 0; k < kernel_d; ++k) { int d = d_in + k; *data_col_ptr = (h >= 0 && w >= 0 && d >= 0 && h < height && w < width && d < depth) ? data_im_ptr[i * (width * depth) + j *depth + k] : ScalarConvert<int, Dtype>::to(0); data_col_ptr += height_col * width_col * depth_col; } } } } } template <typename Dtype> void im3d2col(hipStream_t stream, const Dtype* data_im, const int channels, const int height, const int width, const int depth, const int kernel_h, const int kernel_w, const int kernel_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, Dtype* data_col) { // We are going to launch channels * height_col * width_col * depth_col kernels, each // kernel responsible for copying a single-channel grid. int height_col = (height + 2 * pad_h - kernel_h) / stride_h + 1; int width_col = (width + 2 * pad_w - kernel_w) / stride_w + 1; int depth_col = (depth + 2 * pad_d - kernel_d) / stride_d + 1; int num_kernels = channels * height_col * width_col * depth_col; hipLaunchKernelGGL(( im3d2col_kernel), dim3(GET_BLOCKS(num_kernels)), dim3(CUDA_NUM_THREADS), 0, stream, num_kernels, data_im, height, width, depth, kernel_h, kernel_w, kernel_d, pad_h, pad_w, pad_d, stride_h, stride_w, stride_d, height_col, width_col, depth_col, data_col); THCudaCheck(hipGetLastError()); } template <typename Dtype, typename Acctype> __global__ void col2im3d_kernel(const int n, const Dtype* data_col, const int height, const int width, const int depth, const int channels, const int patch_h, const int patch_w, const int patch_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, const int height_col, const int width_col, const int depth_col, Dtype* data_im) { CUDA_KERNEL_LOOP(index, n) { Acctype val = 0; int d = index % depth + pad_d; int w_index = index / depth; int w = w_index % width + pad_w; int h_index = w_index / width; int h = h_index % height + pad_h; int c = h_index / height; // compute the start and end of the output int d_col_start = (d < patch_d) ? 0 : (d - patch_d) / stride_d + 1; int d_col_end = min(d / stride_d + 1, depth_col); int w_col_start = (w < patch_w) ? 0 : (w - patch_w) / stride_w + 1; int w_col_end = min(w / stride_w + 1, width_col); int h_col_start = (h < patch_h) ? 0 : (h - patch_h) / stride_h + 1; int h_col_end = min(h / stride_h + 1, height_col); int offset = (c * patch_h * patch_w * patch_d + h * patch_w * patch_d + w * patch_d + d) * height_col * width_col * depth_col; int coeff_h_col = (1 - stride_h * patch_w * patch_d * height_col) * width_col * depth_col; int coeff_w_col = (1 - stride_w * patch_d * height_col * width_col) * depth_col; int coeff_d_col = (1 - stride_d * height_col * width_col * depth_col); for (int d_col = d_col_start; d_col < d_col_end; ++d_col) for (int h_col = h_col_start; h_col < h_col_end; ++h_col) { for (int w_col = w_col_start; w_col < w_col_end; ++w_col) { val += data_col[offset + h_col * coeff_h_col + w_col * coeff_w_col + d_col * coeff_d_col]; } } data_im[index] = ScalarConvert<Acctype, Dtype>::to(val); } } template <typename Dtype, typename Acctype> void col2im3d(hipStream_t stream, const Dtype* data_col, const int channels, const int height, const int width, const int depth, const int patch_h, const int patch_w, const int patch_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, Dtype* data_im) { int height_col = (height + 2 * pad_h - patch_h) / stride_h + 1; int width_col = (width + 2 * pad_w - patch_w) / stride_w + 1; int depth_col = (depth + 2 * pad_d - patch_d) / stride_d + 1; int num_kernels = channels * height * width * depth; // To avoid involving atomic operations, we will launch one kernel per // bottom dimension, and then in the kernel add up the top dimensions. hipLaunchKernelGGL(( col2im3d_kernel<Dtype, Acctype>), dim3(GET_BLOCKS(num_kernels)), dim3(CUDA_NUM_THREADS), 0, stream, num_kernels, data_col, height, width, depth, channels, patch_h, patch_w, patch_d, pad_h, pad_w, pad_d, stride_h, stride_w, stride_d, height_col, width_col, depth_col, data_im); THCudaCheck(hipGetLastError()); } #include "generic/VolumetricConvolution.cu" #include "THHGenerateFloatTypes.h"
e61017c22ed304d8ef52687cfee62bac778519bc.cu
#include "THCUNN.h" #include "common.h" #include "THCHalf.h" #include "THCHalfAutoNumerics.cuh" // Kernel for fast unfold+copy // Borrowed from Theano // Authors: Arjun Jain, Frédéric Bastien, Jan Schlüter, Nicolas Ballas template <typename Dtype> __global__ void im3d2col_kernel(const int n, const Dtype* data_im, const int height, const int width, const int depth, const int kernel_h, const int kernel_w, const int kernel_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, const int height_col, const int width_col, const int depth_col, Dtype* data_col) { CUDA_KERNEL_LOOP(index, n) { int d_out = index % depth_col; int w_index = index / depth_col; int w_out = w_index % width_col; int h_index = w_index / width_col; int h_out = h_index % height_col; int channel_in = h_index / height_col; //channel_in = 1; int channel_out = channel_in * kernel_h * kernel_w * kernel_d; int h_in = h_out * stride_h - pad_h; int w_in = w_out * stride_w - pad_w; int d_in = d_out * stride_d - pad_d; Dtype* data_col_ptr = data_col; data_col_ptr += channel_out * (height_col * width_col * depth_col) + h_out * (width_col * depth_col) + w_out * depth_col + d_out; const Dtype* data_im_ptr = data_im; data_im_ptr += channel_in * (height * width * depth) + h_in * (width * depth) + w_in * depth + d_in; for (int i = 0; i < kernel_h; ++i) { int h = h_in + i; for (int j = 0; j < kernel_w; ++j) { int w = w_in + j; for (int k = 0; k < kernel_d; ++k) { int d = d_in + k; *data_col_ptr = (h >= 0 && w >= 0 && d >= 0 && h < height && w < width && d < depth) ? data_im_ptr[i * (width * depth) + j *depth + k] : ScalarConvert<int, Dtype>::to(0); data_col_ptr += height_col * width_col * depth_col; } } } } } template <typename Dtype> void im3d2col(cudaStream_t stream, const Dtype* data_im, const int channels, const int height, const int width, const int depth, const int kernel_h, const int kernel_w, const int kernel_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, Dtype* data_col) { // We are going to launch channels * height_col * width_col * depth_col kernels, each // kernel responsible for copying a single-channel grid. int height_col = (height + 2 * pad_h - kernel_h) / stride_h + 1; int width_col = (width + 2 * pad_w - kernel_w) / stride_w + 1; int depth_col = (depth + 2 * pad_d - kernel_d) / stride_d + 1; int num_kernels = channels * height_col * width_col * depth_col; im3d2col_kernel<<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS, 0, stream>>>(num_kernels, data_im, height, width, depth, kernel_h, kernel_w, kernel_d, pad_h, pad_w, pad_d, stride_h, stride_w, stride_d, height_col, width_col, depth_col, data_col); THCudaCheck(cudaGetLastError()); } template <typename Dtype, typename Acctype> __global__ void col2im3d_kernel(const int n, const Dtype* data_col, const int height, const int width, const int depth, const int channels, const int patch_h, const int patch_w, const int patch_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, const int height_col, const int width_col, const int depth_col, Dtype* data_im) { CUDA_KERNEL_LOOP(index, n) { Acctype val = 0; int d = index % depth + pad_d; int w_index = index / depth; int w = w_index % width + pad_w; int h_index = w_index / width; int h = h_index % height + pad_h; int c = h_index / height; // compute the start and end of the output int d_col_start = (d < patch_d) ? 0 : (d - patch_d) / stride_d + 1; int d_col_end = min(d / stride_d + 1, depth_col); int w_col_start = (w < patch_w) ? 0 : (w - patch_w) / stride_w + 1; int w_col_end = min(w / stride_w + 1, width_col); int h_col_start = (h < patch_h) ? 0 : (h - patch_h) / stride_h + 1; int h_col_end = min(h / stride_h + 1, height_col); int offset = (c * patch_h * patch_w * patch_d + h * patch_w * patch_d + w * patch_d + d) * height_col * width_col * depth_col; int coeff_h_col = (1 - stride_h * patch_w * patch_d * height_col) * width_col * depth_col; int coeff_w_col = (1 - stride_w * patch_d * height_col * width_col) * depth_col; int coeff_d_col = (1 - stride_d * height_col * width_col * depth_col); for (int d_col = d_col_start; d_col < d_col_end; ++d_col) for (int h_col = h_col_start; h_col < h_col_end; ++h_col) { for (int w_col = w_col_start; w_col < w_col_end; ++w_col) { val += data_col[offset + h_col * coeff_h_col + w_col * coeff_w_col + d_col * coeff_d_col]; } } data_im[index] = ScalarConvert<Acctype, Dtype>::to(val); } } template <typename Dtype, typename Acctype> void col2im3d(cudaStream_t stream, const Dtype* data_col, const int channels, const int height, const int width, const int depth, const int patch_h, const int patch_w, const int patch_d, const int pad_h, const int pad_w, const int pad_d, const int stride_h, const int stride_w, const int stride_d, Dtype* data_im) { int height_col = (height + 2 * pad_h - patch_h) / stride_h + 1; int width_col = (width + 2 * pad_w - patch_w) / stride_w + 1; int depth_col = (depth + 2 * pad_d - patch_d) / stride_d + 1; int num_kernels = channels * height * width * depth; // To avoid involving atomic operations, we will launch one kernel per // bottom dimension, and then in the kernel add up the top dimensions. col2im3d_kernel<Dtype, Acctype><<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS, 0, stream>>>(num_kernels, data_col, height, width, depth, channels, patch_h, patch_w, patch_d, pad_h, pad_w, pad_d, stride_h, stride_w, stride_d, height_col, width_col, depth_col, data_im); THCudaCheck(cudaGetLastError()); } #include "generic/VolumetricConvolution.cu" #include "THCGenerateFloatTypes.h"
2fdf9e25c40d7f122ca7eb5e306cf693492f1cde.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /***************************************************************** * Copyright (c) 2017. Palo Alto Research Center * * All rights reserved. * *****************************************************************/ #include "hml_pagerank.h" #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include "hml_tsv2_utils.h" #include "hml_file_utils.h" using namespace std; #define cHmlBlocksPerGrid 128 #define cHmlThreadsPerBlock 128 #define cHmlPagerankPartitionSizeInit 1024 #define cHmlPagerankMaxNumPartitions 32 typedef pair<int, float> PagerankPair; /* global variables defined here */ /* WARNING: Do NOT change the names of these texture variables */ /* Make sure the same names are used in hml_...kernel_template.h */ texture<uint32_t, 1> texDataR; texture<uint32_t, 1> texDataE; texture<uint32_t, 1> texDataD; texture<float, 1> texDataVec0; texture<float, 1> texDataVec1; bool hmlPagerankPairComparator(const PagerankPair &p1, const PagerankPair &p2) { return p1.second > p2.second; } void hmlPagerankPrintTopVertices(FILE *file, float *map, uint32_t numVertices, uint32_t printTopK) { float scoreSum = 0.0; printTopK = min(printTopK, numVertices); if(printTopK > 0) { vector<PagerankPair> pageRankPairVector; for(size_t i = 0; i < numVertices; ++i) { pageRankPairVector.push_back(make_pair(i, map[i])); } sort(pageRankPairVector.begin(), pageRankPairVector.end(), hmlPagerankPairComparator); fprintf(file, "; vertex_id=pagerank_score\n"); for(size_t i = 0; i < printTopK; ++i) { fprintf(file, "%d=%8.6f\n", pageRankPairVector[i].first, pageRankPairVector[i].second); scoreSum += pageRankPairVector[i].second; } fprintf(stderr, "; Info: Top %d score sum = %f\n", printTopK, scoreSum); } } static HmlErrCode hmlPagerankInitVectors(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; uint32_t v; float *vector0; uint32_t numVertices = max(pagerank->core.maxSrcVertex, pagerank->core.maxDestVertex) + 1; if(!pagerank->vector0) { MALLOC(pagerank->vector0, float, numVertices); } if(!pagerank->vector1) { MALLOC(pagerank->vector1, float, numVertices); } vector0 = pagerank->vector0; for(v = 0; v < numVertices; ++v) { vector0[v] = 1.0f / (float)numVertices; } HML_NORMAL_RETURN; } HmlErrCode hmlPagerankCpu(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; float dampingFactor = pagerank->dampingFactor; uint32_t numIters = pagerank->numIters; uint32_t *outDegreeArr = pagerank->outDegreeArr; uint32_t *R = pagerank->core.R; uint32_t *E = pagerank->core.E; uint32_t *e; uint32_t v; uint32_t maxNumSrcVertices = pagerank->core.maxNumSrcVertices; uint32_t numVertices = max(pagerank->core.maxSrcVertex, pagerank->core.maxDestVertex) + 1; float oneMinusDoverN = (1.0f - dampingFactor) / (float)numVertices; float inputProbSum; float *vectorPre; float *vectorNow; float *vectorTmp; hmlPagerankInitVectors(pagerank); vectorPre = pagerank->vector0; vectorNow = pagerank->vector1; while(numIters--) { for(v = 0; v < maxNumSrcVertices; ++v) { inputProbSum = 0.0; for(e = &E[R[v]]; e < &E[R[v + 1]]; ++e) { inputProbSum += vectorPre[*e] / outDegreeArr[*e]; } vectorNow[v] = oneMinusDoverN + dampingFactor * inputProbSum; } /* swap the vectors */ vectorTmp = vectorPre; vectorPre = vectorNow; vectorNow = vectorTmp; } HML_NORMAL_RETURN; } /* partition 'graph' into 'numPartitions' s.t. for all vertices * v in partition p, the following property holds: * minOutDeg[p] <= out-degree(v) < minOutDeg[p + 1], * except for the last partition p = numParititions - 1, for which * it holds: * minOutDeg[numPartitions - 1] <= out-degree(v) < infinity * Thus, minOutDeg[] has 'numPartitions' elements. * The output is stored in vertexRank, an array of size * (graph->maxSrcVertex - graph->minSrcVertex + 1) elements. * vertexRank[] must be allocated by the caller of this function. * vertexRank[r] stores the id of vertex v in partition p s.t. * vertexRank[r] == v && partitionPrefixSize[p - 1] <= r && * r < partitionPrefixSize[p], except for the first partition p = 0, where * 0 <= r < partitionPrefixSize[0] * The actual size of vertexRank is given by: * partitionPrefixSize[numPartitions - 1], which should never exceed * numSrcVertices (see below). It's the caller's responsibility to * resize vertexRank afterwards to free its unused portion. */ void hmlPagerankPartitionVertexByOutDeg(HmlGraphCore *core, uint32_t *minOutDeg, uint32_t numPartitions, uint32_t *vertexRank, uint32_t *partitionPrefixSize) { uint32_t **partitions; uint32_t p; uint32_t v; uint32_t outDeg; uint32_t *R = core->R; uint32_t *pPartitionAllocSize; /* allocation size */ uint32_t **partitionPtr; uint32_t **partitionEndPtr; /* actual used size */ uint32_t numSrcVertices = core->maxSrcVertex - core->minSrcVertex + 1; uint32_t prefixSize = 0; MALLOC(partitions, uint32_t *, numPartitions); MALLOC(partitionPtr, uint32_t *, numPartitions); MALLOC(partitionEndPtr, uint32_t *, numPartitions); MALLOC(pPartitionAllocSize, uint32_t, numPartitions); for(p = 0; p < numPartitions; ++p) { MALLOC(partitions[p], uint32_t, cHmlPagerankPartitionSizeInit); pPartitionAllocSize[p] = cHmlPagerankPartitionSizeInit; partitionPtr[p] = partitions[p]; partitionEndPtr[p] = partitions[p] + cHmlPagerankPartitionSizeInit; } for(v = core->minSrcVertex; v <= core->maxSrcVertex; ++v) { outDeg = R[v + 1] - R[v]; /* each page takes one 32-bit word */ /* use linear scan to find which partition this vertex belongs to */ for(p = 0; p < numPartitions && minOutDeg[p] <= outDeg; ++p); if(p > 0) { --p; if(partitionPtr[p] == partitionEndPtr[p]) { REALLOC(partitions[p], uint32_t, pPartitionAllocSize[p] * 2); partitionPtr[p] = partitions[p] + pPartitionAllocSize[p]; pPartitionAllocSize[p] *= 2; partitionEndPtr[p] = partitions[p] + pPartitionAllocSize[p]; } *partitionPtr[p]++ = v; } } for(p = 0; p < numPartitions; ++p) { prefixSize += partitionPtr[p] - partitions[p]; partitionPrefixSize[p] = prefixSize; if(prefixSize > numSrcVertices) { fprintf(stderr, "; Error: prefixSize = %d > numSrcVertices = %d\n", prefixSize, numSrcVertices); exit(EXIT_FAILURE); } memcpy((void *)vertexRank, partitions[p], sizeof(uint32_t) * (partitionPtr[p] - partitions[p])); vertexRank += partitionPtr[p] - partitions[p]; } /* free memory */ for(p = 0; p < numPartitions; ++p) { FREE(partitions[p]); FREE(partitionPtr); FREE(partitionEndPtr); FREE(pPartitionAllocSize); } FREE(partitions); } HmlErrCode hmlPagerankGpuInit(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; HmlGraphCore *core = &pagerank->core; uint32_t minSrcVertex = core->minSrcVertex; uint32_t maxSrcVertex = core->maxSrcVertex; uint32_t numSrcVertices = maxSrcVertex - minSrcVertex + 1; uint32_t numVertices = max(maxSrcVertex, core->maxDestVertex) + 1; uint32_t *vertexRank; /* array of vertex ids sorted by out-degree */ uint32_t minOutDeg[cHmlPagerankMaxNumPartitions]; /* min out-deg of each partition */ uint32_t partitionPrefixSize[cHmlPagerankMaxNumPartitions]; /* cumulative size */ uint32_t vertexRankSize; size_t freeBytes; size_t totalBytes; double cpuStart; double cpuEnd; double wallStart; double wallEnd; if(!pagerank->vector0) { MALLOC(pagerank->vector0, float, numVertices); } /* get free gpu memory size */ if(pagerank->verbosity >= 2) { HANDLE_ERROR(hipMemGetInfo(&freeBytes, &totalBytes)); fprintf(stderr, "; Info: GPU memory: %ld bytes free, %ld bytes total\n", freeBytes, totalBytes); } /* create device graph */ hmlGetSecs(&cpuStart, &wallStart); hmlGraphCoreCopyToGpu(&pagerank->core, &pagerank->gpuCore); hipDeviceSynchronize(); hmlGetSecs(&cpuEnd, &wallEnd); if(pagerank->verbosity >= 2) { fprintf(stderr, "; Info: Load graph to device: wall time = %.2lf\n", (wallEnd - wallStart) * 1000); } if(numVertices > cHmlMaxCudaTexture1DLinear) { hmlPrintf("; Error: Number of vertices exceeds the maximum " "texture 1D size\n"); HML_ERR_GEN(true, cHmlErrGeneral); } if(pagerank->useTextureMem && pagerank->gpuCore.maxNumSrcVertices <= cHmlMaxCudaTexture1DLinear && core->numEdges <= cHmlMaxCudaTexture1DLinear) { hmlGraphCoreBindTexture(&pagerank->gpuCore, texDataR, texDataE); } else { pagerank->useTextureMem = false; } hmlPagerankKernelSetup(pagerank->kernelEven, pagerank->kernelOdd, minOutDeg, cHmlPagerankMaxNumKernels, pagerank->useTextureMem, &pagerank->numPartitions, pagerank->kernelArgs); /* create vertexRank mapping */ hmlGetSecs(&cpuStart, &wallStart); /* allocate vertexRank[] on CPU */ MALLOC(vertexRank, uint32_t, numSrcVertices); hmlPagerankPartitionVertexByOutDeg(&pagerank->core, minOutDeg, pagerank->numPartitions, vertexRank, partitionPrefixSize); //hmlGetSecs(&cpuEnd, &wallEnd); //fprintf(stderr, "; Info: Partition vertices on CPU: " // "cpu time = %.2lf, wall time = %.2lf\n", // (cpuEnd - cpuStart* 1000, (wallEnd - wallStart) * 1000); vertexRankSize = partitionPrefixSize[pagerank->numPartitions - 1]; /* resize vertexRank */ REALLOC(vertexRank, uint32_t, vertexRankSize); /* allocate gpuVertexRank[] on device */ HANDLE_ERROR(hipMalloc(&pagerank->gpuVertexRank, sizeof(uint32_t) * vertexRankSize)); /* copy vertexRank[] to gpuVertexRank[] */ HANDLE_ERROR(hipMemcpy(pagerank->gpuVertexRank, vertexRank, sizeof(uint32_t) * vertexRankSize, hipMemcpyHostToDevice)); hipDeviceSynchronize(); hmlGetSecs(&cpuEnd, &wallEnd); if(pagerank->verbosity >= 2) { fprintf(stderr, "; Info: Partition and copy vertice ranks to device: " "wall time = %.2lf\n", (wallEnd - wallStart) * 1000); fprintf(stderr, "; Info: Number of pages with in-coming link: %d (%.2lf%%)\n", vertexRankSize, 100 * vertexRankSize/(double)(numVertices)); fprintf(stderr, "; Info: Partitioned graph size = %.2lf MB\n", (core->maxNumSrcVertices + core->numEdges + vertexRankSize) * sizeof(uint32_t) / (double)(1024 * 1024)); } /* print vertex ranks for small graphs */ if(pagerank->verbosity >= 3 && vertexRankSize <= 100) { for(uint32_t r = 0; r < vertexRankSize; ++r) { fprintf(stderr, "; Info: rank %3d = vertex %3d\n", r, vertexRank[r]); } } /* set the kernel arguments */ hmlPagerankKernelArgSet(pagerank->kernelArgs, pagerank->numPartitions, minOutDeg, partitionPrefixSize); /* print kernel params */ if(pagerank->verbosity >= 2) { hmlPagerankKernelArgPrint(pagerank->kernelArgs, pagerank->numPartitions); } pagerank->gpuVector0 = hmlDeviceFloatArrayAllocBind(numVertices, texDataVec0); pagerank->gpuVector1 = hmlDeviceFloatArrayAllocBind(numVertices, texDataVec1); pagerank->gpuOutDegreeArr = hmlDeviceUint32ArrayAllocBind(pagerank->outDegreeArrSize, texDataD); /* copy outDegreeArr[] from cpu to gpu */ HANDLE_ERROR(hipMemcpy(pagerank->gpuOutDegreeArr, pagerank->outDegreeArr, sizeof(uint32_t) * pagerank->outDegreeArrSize, hipMemcpyHostToDevice)); FREE(vertexRank); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankGpu(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; HmlGraphCore *gpuCore = &pagerank->gpuCore; uint32_t *gpuVertexRank = pagerank->gpuVertexRank; float dampingFactor = pagerank->dampingFactor; uint32_t numVertices = max(gpuCore->maxSrcVertex, gpuCore->maxDestVertex) + 1; float oneMinusDoverN = (1.0 - dampingFactor) / (float)numVertices; float *gpuVector0 = pagerank->gpuVector0; float *gpuVector1 = pagerank->gpuVector1; float initVal = (float) 1.0 / (float) numVertices; uint32_t numPartitions = pagerank->numPartitions; double cpuStart; double cpuEnd; double wallStart; double wallEnd; HmlPagerankKernel *kernelEven = pagerank->kernelEven; HmlPagerankKernel *kernelOdd = pagerank->kernelOdd; HmlPagerankKernelArg *kernelArgs = pagerank->kernelArgs; hmlGetSecs(&cpuStart, &wallStart); hipLaunchKernelGGL(( hmlPagerankInitKernel), dim3(cHmlBlocksPerGrid), dim3(cHmlThreadsPerBlock), 0, 0, gpuVector0, initVal, numVertices); for(uint32_t iter = 0; iter < pagerank->numIters; ++iter) { //fprintf(stderr, "; Info: iter = %d\n", iter); if(iter % 2 == 0) { hipLaunchKernelGGL(( hmlPagerankInitKernel), dim3(cHmlBlocksPerGrid), dim3(cHmlThreadsPerBlock), 0, 0, gpuVector1, oneMinusDoverN, numVertices); for(uint32_t p = 0; p < numPartitions; ++p) { kernelEven[kernelArgs[p]hipLaunchKernelGGL((.id)], dim3(kernelArgs[p].grid), dim3(kernelArgs[p].block), 0, 0, gpuVector1, gpuCore->R, gpuCore->E, gpuVertexRank, kernelArgs[p].minVertexRank, kernelArgs[p].maxVertexRank, dampingFactor); } } else { hipLaunchKernelGGL(( hmlPagerankInitKernel), dim3(cHmlBlocksPerGrid), dim3(cHmlThreadsPerBlock), 0, 0, gpuVector0, oneMinusDoverN, numVertices); for(uint32_t p = 0; p < numPartitions; ++p) { kernelOdd[kernelArgs[p]hipLaunchKernelGGL((.id)], dim3(kernelArgs[p].grid), dim3(kernelArgs[p].block), 0, 0, gpuVector0, gpuCore->R, gpuCore->E, gpuVertexRank, kernelArgs[p].minVertexRank, kernelArgs[p].maxVertexRank, dampingFactor); } } } hipDeviceSynchronize(); hmlGetSecs(&cpuEnd, &wallEnd); if(pagerank->verbosity >= 1) { fprintf(stderr, "; Info: GPU pagerank: wall time = %.2lf\n", (wallEnd - wallStart) * 1000); } HANDLE_ERROR(hipMemcpy(pagerank->vector0, gpuVector0, sizeof(float) * numVertices, hipMemcpyDeviceToHost)); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankInit(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; memset(pagerank, 0, sizeof(HmlPagerank)); pagerank->dampingFactor = cHmlPagerankDampingFactorDefault; pagerank->topK = 100; /* do NOT use texture memory for R and E */ HML_NORMAL_RETURN; } HmlErrCode hmlPagerankDelete(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; FREE(pagerank->vector0); FREE(pagerank->vector1); FREE(pagerank->topKVertexValue); hmlGraphCoreDelete(&pagerank->core); /* free GPU stuff */ HANDLE_ERROR(hipFree(pagerank->gpuVector0)); HANDLE_ERROR(hipFree(pagerank->gpuVector1)); HANDLE_ERROR(hipFree(pagerank->gpuOutDegreeArr)); if(pagerank->gpuCore.numEdges > 0) { hmlGraphCoreGpuDelete(&pagerank->gpuCore); } HANDLE_ERROR(hipFree(pagerank->gpuVertexRank)); HANDLE_ERROR(hipUnbindTexture(texDataVec0)); HANDLE_ERROR(hipUnbindTexture(texDataVec1)); HANDLE_ERROR(hipUnbindTexture(texDataD)); if(pagerank->useTextureMem) { hmlGraphCoreUnbindTexture(texDataR, texDataE); } memset(pagerank, 0, sizeof(HmlPagerank)); HML_NORMAL_RETURN; } static HmlErrCode hmlPagerankReadDegreeFile(HmlPagerank *pagerank, FILE *file) { HML_ERR_PROLOGUE; hmlTsv2InOutDegreeReadFile(file, &pagerank->inDegreeArr, &pagerank->inDegreeArrSize, &pagerank->outDegreeArr, &pagerank->outDegreeArrSize, &pagerank->numEdges); HML_NORMAL_RETURN; } static HmlErrCode hmlPagerankDegreeCountFile(HmlPagerank *pagerank, FILE *file) { HML_ERR_PROLOGUE; hmlTsv2InOutDegreeCountFile(file, &pagerank->inDegreeArr, &pagerank->inDegreeArrSize, &pagerank->outDegreeArr, &pagerank->outDegreeArrSize, &pagerank->numEdges); rewind(file); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankSetInputFiles(HmlPagerank *pagerank, FILE *graphFile, FILE *inOutDegreeFile) { HML_ERR_PROLOGUE; if(inOutDegreeFile) { hmlPagerankReadDegreeFile(pagerank, inOutDegreeFile); } else { hmlPagerankDegreeCountFile(pagerank, graphFile); } pagerank->graphFile = graphFile; pagerank->inOutDegreeFile = inOutDegreeFile; pagerank->maxNumSrcVertices = pagerank->inDegreeArrSize; HML_NORMAL_RETURN; } HmlErrCode hmlPagerankReadTsv2InFile(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; hmlGraphCoreInit(&pagerank->core, pagerank->maxNumSrcVertices, pagerank->numEdges); hmlGraphCoreSetR(&pagerank->core, pagerank->inDegreeArr, 0, pagerank->maxNumSrcVertices - 1); hmlGraphCoreReadTsv2File(&pagerank->core, pagerank->graphFile, true); /* once the tsv2 file is read, pagerank->core.D is useless */ hmlGraphCoreDeleteD(&pagerank->core); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankFindTopK(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; uint32_t v; uint32_t u; float *vector = pagerank->vector0; float minTopKValue; uint32_t topK = pagerank->topK; uint32_t numVertices = max(pagerank->core.maxSrcVertex, pagerank->core.maxDestVertex) + 1; HmlVertexfloat *topKVertexValue; HML_ERR_GEN(topK == 0, cHmlErrGeneral); HML_ERR_GEN(topK > numVertices, cHmlErrGeneral); if(!pagerank->topKVertexValue) { MALLOC(pagerank->topKVertexValue, HmlVertexfloat, topK); } topKVertexValue = pagerank->topKVertexValue; /* insert the first vertex-value pair */ topKVertexValue[0].vertex = 0; topKVertexValue[0].value = vector[0]; for(v = 1; v < topK; ++v) { for(u = v; u > 0 && topKVertexValue[u - 1].value < vector[v]; --u) { topKVertexValue[u].value = topKVertexValue[u - 1].value; topKVertexValue[u].vertex = topKVertexValue[u - 1].vertex; } topKVertexValue[u].value = vector[v]; topKVertexValue[u].vertex = v; } minTopKValue = topKVertexValue[topK - 1].value; for(v = topK; v < numVertices; ++v) { if(minTopKValue >= vector[v]) { continue; } for(u = topK - 1; u > 0 && topKVertexValue[u - 1].value < vector[v]; --u) { topKVertexValue[u].value = topKVertexValue[u - 1].value; topKVertexValue[u].vertex = topKVertexValue[u - 1].vertex; } topKVertexValue[u].value = vector[v]; topKVertexValue[u].vertex = v; minTopKValue = topKVertexValue[topK - 1].value; } HML_NORMAL_RETURN; } HmlErrCode hmlPagerankPrintTopK(HmlPagerank *pagerank, FILE *file) { HML_ERR_PROLOGUE; uint32_t v; HmlVertexfloat *topKVertexValue = pagerank->topKVertexValue; if(file == stdout) { hmlFileSetBinaryMode(file); } fprintf(file, "; vertex_id=pagerank_score\n"); for(v = 0; v < pagerank->topK; ++v) { fprintf(file, "%u=%8.6f\n", topKVertexValue[v].vertex, topKVertexValue[v].value); } HML_NORMAL_RETURN; }
2fdf9e25c40d7f122ca7eb5e306cf693492f1cde.cu
/***************************************************************** * Copyright (c) 2017. Palo Alto Research Center * * All rights reserved. * *****************************************************************/ #include "hml_pagerank.h" #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include "hml_tsv2_utils.h" #include "hml_file_utils.h" using namespace std; #define cHmlBlocksPerGrid 128 #define cHmlThreadsPerBlock 128 #define cHmlPagerankPartitionSizeInit 1024 #define cHmlPagerankMaxNumPartitions 32 typedef pair<int, float> PagerankPair; /* global variables defined here */ /* WARNING: Do NOT change the names of these texture variables */ /* Make sure the same names are used in hml_...kernel_template.h */ texture<uint32_t, 1> texDataR; texture<uint32_t, 1> texDataE; texture<uint32_t, 1> texDataD; texture<float, 1> texDataVec0; texture<float, 1> texDataVec1; bool hmlPagerankPairComparator(const PagerankPair &p1, const PagerankPair &p2) { return p1.second > p2.second; } void hmlPagerankPrintTopVertices(FILE *file, float *map, uint32_t numVertices, uint32_t printTopK) { float scoreSum = 0.0; printTopK = min(printTopK, numVertices); if(printTopK > 0) { vector<PagerankPair> pageRankPairVector; for(size_t i = 0; i < numVertices; ++i) { pageRankPairVector.push_back(make_pair(i, map[i])); } sort(pageRankPairVector.begin(), pageRankPairVector.end(), hmlPagerankPairComparator); fprintf(file, "; vertex_id=pagerank_score\n"); for(size_t i = 0; i < printTopK; ++i) { fprintf(file, "%d=%8.6f\n", pageRankPairVector[i].first, pageRankPairVector[i].second); scoreSum += pageRankPairVector[i].second; } fprintf(stderr, "; Info: Top %d score sum = %f\n", printTopK, scoreSum); } } static HmlErrCode hmlPagerankInitVectors(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; uint32_t v; float *vector0; uint32_t numVertices = max(pagerank->core.maxSrcVertex, pagerank->core.maxDestVertex) + 1; if(!pagerank->vector0) { MALLOC(pagerank->vector0, float, numVertices); } if(!pagerank->vector1) { MALLOC(pagerank->vector1, float, numVertices); } vector0 = pagerank->vector0; for(v = 0; v < numVertices; ++v) { vector0[v] = 1.0f / (float)numVertices; } HML_NORMAL_RETURN; } HmlErrCode hmlPagerankCpu(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; float dampingFactor = pagerank->dampingFactor; uint32_t numIters = pagerank->numIters; uint32_t *outDegreeArr = pagerank->outDegreeArr; uint32_t *R = pagerank->core.R; uint32_t *E = pagerank->core.E; uint32_t *e; uint32_t v; uint32_t maxNumSrcVertices = pagerank->core.maxNumSrcVertices; uint32_t numVertices = max(pagerank->core.maxSrcVertex, pagerank->core.maxDestVertex) + 1; float oneMinusDoverN = (1.0f - dampingFactor) / (float)numVertices; float inputProbSum; float *vectorPre; float *vectorNow; float *vectorTmp; hmlPagerankInitVectors(pagerank); vectorPre = pagerank->vector0; vectorNow = pagerank->vector1; while(numIters--) { for(v = 0; v < maxNumSrcVertices; ++v) { inputProbSum = 0.0; for(e = &E[R[v]]; e < &E[R[v + 1]]; ++e) { inputProbSum += vectorPre[*e] / outDegreeArr[*e]; } vectorNow[v] = oneMinusDoverN + dampingFactor * inputProbSum; } /* swap the vectors */ vectorTmp = vectorPre; vectorPre = vectorNow; vectorNow = vectorTmp; } HML_NORMAL_RETURN; } /* partition 'graph' into 'numPartitions' s.t. for all vertices * v in partition p, the following property holds: * minOutDeg[p] <= out-degree(v) < minOutDeg[p + 1], * except for the last partition p = numParititions - 1, for which * it holds: * minOutDeg[numPartitions - 1] <= out-degree(v) < infinity * Thus, minOutDeg[] has 'numPartitions' elements. * The output is stored in vertexRank, an array of size * (graph->maxSrcVertex - graph->minSrcVertex + 1) elements. * vertexRank[] must be allocated by the caller of this function. * vertexRank[r] stores the id of vertex v in partition p s.t. * vertexRank[r] == v && partitionPrefixSize[p - 1] <= r && * r < partitionPrefixSize[p], except for the first partition p = 0, where * 0 <= r < partitionPrefixSize[0] * The actual size of vertexRank is given by: * partitionPrefixSize[numPartitions - 1], which should never exceed * numSrcVertices (see below). It's the caller's responsibility to * resize vertexRank afterwards to free its unused portion. */ void hmlPagerankPartitionVertexByOutDeg(HmlGraphCore *core, uint32_t *minOutDeg, uint32_t numPartitions, uint32_t *vertexRank, uint32_t *partitionPrefixSize) { uint32_t **partitions; uint32_t p; uint32_t v; uint32_t outDeg; uint32_t *R = core->R; uint32_t *pPartitionAllocSize; /* allocation size */ uint32_t **partitionPtr; uint32_t **partitionEndPtr; /* actual used size */ uint32_t numSrcVertices = core->maxSrcVertex - core->minSrcVertex + 1; uint32_t prefixSize = 0; MALLOC(partitions, uint32_t *, numPartitions); MALLOC(partitionPtr, uint32_t *, numPartitions); MALLOC(partitionEndPtr, uint32_t *, numPartitions); MALLOC(pPartitionAllocSize, uint32_t, numPartitions); for(p = 0; p < numPartitions; ++p) { MALLOC(partitions[p], uint32_t, cHmlPagerankPartitionSizeInit); pPartitionAllocSize[p] = cHmlPagerankPartitionSizeInit; partitionPtr[p] = partitions[p]; partitionEndPtr[p] = partitions[p] + cHmlPagerankPartitionSizeInit; } for(v = core->minSrcVertex; v <= core->maxSrcVertex; ++v) { outDeg = R[v + 1] - R[v]; /* each page takes one 32-bit word */ /* use linear scan to find which partition this vertex belongs to */ for(p = 0; p < numPartitions && minOutDeg[p] <= outDeg; ++p); if(p > 0) { --p; if(partitionPtr[p] == partitionEndPtr[p]) { REALLOC(partitions[p], uint32_t, pPartitionAllocSize[p] * 2); partitionPtr[p] = partitions[p] + pPartitionAllocSize[p]; pPartitionAllocSize[p] *= 2; partitionEndPtr[p] = partitions[p] + pPartitionAllocSize[p]; } *partitionPtr[p]++ = v; } } for(p = 0; p < numPartitions; ++p) { prefixSize += partitionPtr[p] - partitions[p]; partitionPrefixSize[p] = prefixSize; if(prefixSize > numSrcVertices) { fprintf(stderr, "; Error: prefixSize = %d > numSrcVertices = %d\n", prefixSize, numSrcVertices); exit(EXIT_FAILURE); } memcpy((void *)vertexRank, partitions[p], sizeof(uint32_t) * (partitionPtr[p] - partitions[p])); vertexRank += partitionPtr[p] - partitions[p]; } /* free memory */ for(p = 0; p < numPartitions; ++p) { FREE(partitions[p]); FREE(partitionPtr); FREE(partitionEndPtr); FREE(pPartitionAllocSize); } FREE(partitions); } HmlErrCode hmlPagerankGpuInit(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; HmlGraphCore *core = &pagerank->core; uint32_t minSrcVertex = core->minSrcVertex; uint32_t maxSrcVertex = core->maxSrcVertex; uint32_t numSrcVertices = maxSrcVertex - minSrcVertex + 1; uint32_t numVertices = max(maxSrcVertex, core->maxDestVertex) + 1; uint32_t *vertexRank; /* array of vertex ids sorted by out-degree */ uint32_t minOutDeg[cHmlPagerankMaxNumPartitions]; /* min out-deg of each partition */ uint32_t partitionPrefixSize[cHmlPagerankMaxNumPartitions]; /* cumulative size */ uint32_t vertexRankSize; size_t freeBytes; size_t totalBytes; double cpuStart; double cpuEnd; double wallStart; double wallEnd; if(!pagerank->vector0) { MALLOC(pagerank->vector0, float, numVertices); } /* get free gpu memory size */ if(pagerank->verbosity >= 2) { HANDLE_ERROR(cudaMemGetInfo(&freeBytes, &totalBytes)); fprintf(stderr, "; Info: GPU memory: %ld bytes free, %ld bytes total\n", freeBytes, totalBytes); } /* create device graph */ hmlGetSecs(&cpuStart, &wallStart); hmlGraphCoreCopyToGpu(&pagerank->core, &pagerank->gpuCore); cudaDeviceSynchronize(); hmlGetSecs(&cpuEnd, &wallEnd); if(pagerank->verbosity >= 2) { fprintf(stderr, "; Info: Load graph to device: wall time = %.2lf\n", (wallEnd - wallStart) * 1000); } if(numVertices > cHmlMaxCudaTexture1DLinear) { hmlPrintf("; Error: Number of vertices exceeds the maximum " "texture 1D size\n"); HML_ERR_GEN(true, cHmlErrGeneral); } if(pagerank->useTextureMem && pagerank->gpuCore.maxNumSrcVertices <= cHmlMaxCudaTexture1DLinear && core->numEdges <= cHmlMaxCudaTexture1DLinear) { hmlGraphCoreBindTexture(&pagerank->gpuCore, texDataR, texDataE); } else { pagerank->useTextureMem = false; } hmlPagerankKernelSetup(pagerank->kernelEven, pagerank->kernelOdd, minOutDeg, cHmlPagerankMaxNumKernels, pagerank->useTextureMem, &pagerank->numPartitions, pagerank->kernelArgs); /* create vertexRank mapping */ hmlGetSecs(&cpuStart, &wallStart); /* allocate vertexRank[] on CPU */ MALLOC(vertexRank, uint32_t, numSrcVertices); hmlPagerankPartitionVertexByOutDeg(&pagerank->core, minOutDeg, pagerank->numPartitions, vertexRank, partitionPrefixSize); //hmlGetSecs(&cpuEnd, &wallEnd); //fprintf(stderr, "; Info: Partition vertices on CPU: " // "cpu time = %.2lf, wall time = %.2lf\n", // (cpuEnd - cpuStart* 1000, (wallEnd - wallStart) * 1000); vertexRankSize = partitionPrefixSize[pagerank->numPartitions - 1]; /* resize vertexRank */ REALLOC(vertexRank, uint32_t, vertexRankSize); /* allocate gpuVertexRank[] on device */ HANDLE_ERROR(cudaMalloc(&pagerank->gpuVertexRank, sizeof(uint32_t) * vertexRankSize)); /* copy vertexRank[] to gpuVertexRank[] */ HANDLE_ERROR(cudaMemcpy(pagerank->gpuVertexRank, vertexRank, sizeof(uint32_t) * vertexRankSize, cudaMemcpyHostToDevice)); cudaDeviceSynchronize(); hmlGetSecs(&cpuEnd, &wallEnd); if(pagerank->verbosity >= 2) { fprintf(stderr, "; Info: Partition and copy vertice ranks to device: " "wall time = %.2lf\n", (wallEnd - wallStart) * 1000); fprintf(stderr, "; Info: Number of pages with in-coming link: %d (%.2lf%%)\n", vertexRankSize, 100 * vertexRankSize/(double)(numVertices)); fprintf(stderr, "; Info: Partitioned graph size = %.2lf MB\n", (core->maxNumSrcVertices + core->numEdges + vertexRankSize) * sizeof(uint32_t) / (double)(1024 * 1024)); } /* print vertex ranks for small graphs */ if(pagerank->verbosity >= 3 && vertexRankSize <= 100) { for(uint32_t r = 0; r < vertexRankSize; ++r) { fprintf(stderr, "; Info: rank %3d = vertex %3d\n", r, vertexRank[r]); } } /* set the kernel arguments */ hmlPagerankKernelArgSet(pagerank->kernelArgs, pagerank->numPartitions, minOutDeg, partitionPrefixSize); /* print kernel params */ if(pagerank->verbosity >= 2) { hmlPagerankKernelArgPrint(pagerank->kernelArgs, pagerank->numPartitions); } pagerank->gpuVector0 = hmlDeviceFloatArrayAllocBind(numVertices, texDataVec0); pagerank->gpuVector1 = hmlDeviceFloatArrayAllocBind(numVertices, texDataVec1); pagerank->gpuOutDegreeArr = hmlDeviceUint32ArrayAllocBind(pagerank->outDegreeArrSize, texDataD); /* copy outDegreeArr[] from cpu to gpu */ HANDLE_ERROR(cudaMemcpy(pagerank->gpuOutDegreeArr, pagerank->outDegreeArr, sizeof(uint32_t) * pagerank->outDegreeArrSize, cudaMemcpyHostToDevice)); FREE(vertexRank); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankGpu(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; HmlGraphCore *gpuCore = &pagerank->gpuCore; uint32_t *gpuVertexRank = pagerank->gpuVertexRank; float dampingFactor = pagerank->dampingFactor; uint32_t numVertices = max(gpuCore->maxSrcVertex, gpuCore->maxDestVertex) + 1; float oneMinusDoverN = (1.0 - dampingFactor) / (float)numVertices; float *gpuVector0 = pagerank->gpuVector0; float *gpuVector1 = pagerank->gpuVector1; float initVal = (float) 1.0 / (float) numVertices; uint32_t numPartitions = pagerank->numPartitions; double cpuStart; double cpuEnd; double wallStart; double wallEnd; HmlPagerankKernel *kernelEven = pagerank->kernelEven; HmlPagerankKernel *kernelOdd = pagerank->kernelOdd; HmlPagerankKernelArg *kernelArgs = pagerank->kernelArgs; hmlGetSecs(&cpuStart, &wallStart); hmlPagerankInitKernel<<<cHmlBlocksPerGrid, cHmlThreadsPerBlock>>> (gpuVector0, initVal, numVertices); for(uint32_t iter = 0; iter < pagerank->numIters; ++iter) { //fprintf(stderr, "; Info: iter = %d\n", iter); if(iter % 2 == 0) { hmlPagerankInitKernel<<<cHmlBlocksPerGrid, cHmlThreadsPerBlock>>> (gpuVector1, oneMinusDoverN, numVertices); for(uint32_t p = 0; p < numPartitions; ++p) { kernelEven[kernelArgs[p].id]<<<kernelArgs[p].grid, kernelArgs[p].block>>> (gpuVector1, gpuCore->R, gpuCore->E, gpuVertexRank, kernelArgs[p].minVertexRank, kernelArgs[p].maxVertexRank, dampingFactor); } } else { hmlPagerankInitKernel<<<cHmlBlocksPerGrid, cHmlThreadsPerBlock>>> (gpuVector0, oneMinusDoverN, numVertices); for(uint32_t p = 0; p < numPartitions; ++p) { kernelOdd[kernelArgs[p].id]<<<kernelArgs[p].grid, kernelArgs[p].block>>> (gpuVector0, gpuCore->R, gpuCore->E, gpuVertexRank, kernelArgs[p].minVertexRank, kernelArgs[p].maxVertexRank, dampingFactor); } } } cudaDeviceSynchronize(); hmlGetSecs(&cpuEnd, &wallEnd); if(pagerank->verbosity >= 1) { fprintf(stderr, "; Info: GPU pagerank: wall time = %.2lf\n", (wallEnd - wallStart) * 1000); } HANDLE_ERROR(cudaMemcpy(pagerank->vector0, gpuVector0, sizeof(float) * numVertices, cudaMemcpyDeviceToHost)); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankInit(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; memset(pagerank, 0, sizeof(HmlPagerank)); pagerank->dampingFactor = cHmlPagerankDampingFactorDefault; pagerank->topK = 100; /* do NOT use texture memory for R and E */ HML_NORMAL_RETURN; } HmlErrCode hmlPagerankDelete(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; FREE(pagerank->vector0); FREE(pagerank->vector1); FREE(pagerank->topKVertexValue); hmlGraphCoreDelete(&pagerank->core); /* free GPU stuff */ HANDLE_ERROR(cudaFree(pagerank->gpuVector0)); HANDLE_ERROR(cudaFree(pagerank->gpuVector1)); HANDLE_ERROR(cudaFree(pagerank->gpuOutDegreeArr)); if(pagerank->gpuCore.numEdges > 0) { hmlGraphCoreGpuDelete(&pagerank->gpuCore); } HANDLE_ERROR(cudaFree(pagerank->gpuVertexRank)); HANDLE_ERROR(cudaUnbindTexture(texDataVec0)); HANDLE_ERROR(cudaUnbindTexture(texDataVec1)); HANDLE_ERROR(cudaUnbindTexture(texDataD)); if(pagerank->useTextureMem) { hmlGraphCoreUnbindTexture(texDataR, texDataE); } memset(pagerank, 0, sizeof(HmlPagerank)); HML_NORMAL_RETURN; } static HmlErrCode hmlPagerankReadDegreeFile(HmlPagerank *pagerank, FILE *file) { HML_ERR_PROLOGUE; hmlTsv2InOutDegreeReadFile(file, &pagerank->inDegreeArr, &pagerank->inDegreeArrSize, &pagerank->outDegreeArr, &pagerank->outDegreeArrSize, &pagerank->numEdges); HML_NORMAL_RETURN; } static HmlErrCode hmlPagerankDegreeCountFile(HmlPagerank *pagerank, FILE *file) { HML_ERR_PROLOGUE; hmlTsv2InOutDegreeCountFile(file, &pagerank->inDegreeArr, &pagerank->inDegreeArrSize, &pagerank->outDegreeArr, &pagerank->outDegreeArrSize, &pagerank->numEdges); rewind(file); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankSetInputFiles(HmlPagerank *pagerank, FILE *graphFile, FILE *inOutDegreeFile) { HML_ERR_PROLOGUE; if(inOutDegreeFile) { hmlPagerankReadDegreeFile(pagerank, inOutDegreeFile); } else { hmlPagerankDegreeCountFile(pagerank, graphFile); } pagerank->graphFile = graphFile; pagerank->inOutDegreeFile = inOutDegreeFile; pagerank->maxNumSrcVertices = pagerank->inDegreeArrSize; HML_NORMAL_RETURN; } HmlErrCode hmlPagerankReadTsv2InFile(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; hmlGraphCoreInit(&pagerank->core, pagerank->maxNumSrcVertices, pagerank->numEdges); hmlGraphCoreSetR(&pagerank->core, pagerank->inDegreeArr, 0, pagerank->maxNumSrcVertices - 1); hmlGraphCoreReadTsv2File(&pagerank->core, pagerank->graphFile, true); /* once the tsv2 file is read, pagerank->core.D is useless */ hmlGraphCoreDeleteD(&pagerank->core); HML_NORMAL_RETURN; } HmlErrCode hmlPagerankFindTopK(HmlPagerank *pagerank) { HML_ERR_PROLOGUE; uint32_t v; uint32_t u; float *vector = pagerank->vector0; float minTopKValue; uint32_t topK = pagerank->topK; uint32_t numVertices = max(pagerank->core.maxSrcVertex, pagerank->core.maxDestVertex) + 1; HmlVertexfloat *topKVertexValue; HML_ERR_GEN(topK == 0, cHmlErrGeneral); HML_ERR_GEN(topK > numVertices, cHmlErrGeneral); if(!pagerank->topKVertexValue) { MALLOC(pagerank->topKVertexValue, HmlVertexfloat, topK); } topKVertexValue = pagerank->topKVertexValue; /* insert the first vertex-value pair */ topKVertexValue[0].vertex = 0; topKVertexValue[0].value = vector[0]; for(v = 1; v < topK; ++v) { for(u = v; u > 0 && topKVertexValue[u - 1].value < vector[v]; --u) { topKVertexValue[u].value = topKVertexValue[u - 1].value; topKVertexValue[u].vertex = topKVertexValue[u - 1].vertex; } topKVertexValue[u].value = vector[v]; topKVertexValue[u].vertex = v; } minTopKValue = topKVertexValue[topK - 1].value; for(v = topK; v < numVertices; ++v) { if(minTopKValue >= vector[v]) { continue; } for(u = topK - 1; u > 0 && topKVertexValue[u - 1].value < vector[v]; --u) { topKVertexValue[u].value = topKVertexValue[u - 1].value; topKVertexValue[u].vertex = topKVertexValue[u - 1].vertex; } topKVertexValue[u].value = vector[v]; topKVertexValue[u].vertex = v; minTopKValue = topKVertexValue[topK - 1].value; } HML_NORMAL_RETURN; } HmlErrCode hmlPagerankPrintTopK(HmlPagerank *pagerank, FILE *file) { HML_ERR_PROLOGUE; uint32_t v; HmlVertexfloat *topKVertexValue = pagerank->topKVertexValue; if(file == stdout) { hmlFileSetBinaryMode(file); } fprintf(file, "; vertex_id=pagerank_score\n"); for(v = 0; v < pagerank->topK; ++v) { fprintf(file, "%u=%8.6f\n", topKVertexValue[v].vertex, topKVertexValue[v].value); } HML_NORMAL_RETURN; }
4f6634cabd46ee7f5dbaa91dd3f28fa1415407f7.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include<bits/stdc++.h> #include<fstream> #include<sstream> #include<stdio.h> #include<thrust/device_vector.h> #include<thrust/copy.h> #include<thrust/scan.h> #include <thrust/sort.h> #include<cuda.h> #include<hiprand/hiprand.h> #include<hiprand/hiprand_kernel.h> #include<cuda_runtime.h> #include<thrust/extrema.h> using namespace std; typedef pair<long int,long int> Point; struct convexHull { Point point; long int label; long int distance; int mark; }; struct assignMax { long int max; Point p; int l; int index; }; Point *hull; Point *lhull; long int inputLength,itr; Point leftmost_point make_pair(INT_MAX,0),rightmost_point make_pair(INT_MIN,0); convexHull *hostInput; convexHull *deviceInput; convexHull *original; Point *deviceHull; long int hull_length = 2; long int lhull_length = 2; convexHull *appendPoint; long int append_point_len = 0; assignMax *devMax; assignMax *hostMax; bool flag = false; int maxlabel = 1; /*comparsion for sorting*/ bool comparision(Point a,Point b) { return (a.first<b.first); } bool labelsort(convexHull a, convexHull b) { return a.label<b.label; } __global__ void calculate_perpendicularDistance_And_markNegDistance(convexHull *input,Point *devHull,long int size) { long int Idx = threadIdx.x+blockIdx.x*blockDim.x; /* calculate perpendicular point*/ if((Idx)<size) { Point P = input[Idx].point; long int lb = input[Idx].label; Point min = devHull[lb]; Point max = devHull[lb+1]; input[Idx].distance=(P.second-min.second)*(max.first-min.first)-(max.second-min.second)*(P.first-min.first); if(input[Idx].distance<0) { input[Idx].mark = -1; }else { input[Idx].mark = 1; } } } __global__ void scan(convexHull *input,assignMax *store,int size,bool upper) { int Idx = blockIdx.x*blockDim.x+threadIdx.x; /*find index in cuda*/ long int itr = 0; if(upper) { for(;itr<size;) { if(Idx==input[itr].label) { while(itr<size&&Idx==input[itr].label) { if((input[itr].distance>0)&&(store[Idx].max<input[itr].distance)) { store[Idx].max = input[itr].distance; store[Idx].p.first = input[itr].point.first; store[Idx].p.second = input[itr].point.second; store[Idx].l = input[itr].label; store[Idx].index = itr; } itr++; } break; } itr++; } } else { for(;itr<size;) { if(Idx==input[itr].label) { while(itr<size&&Idx==input[itr].label) { if((input[itr].distance<0)&&(store[Idx].max>input[itr].distance)) { store[Idx].max = input[itr].distance; store[Idx].p.first = input[itr].point.first; store[Idx].p.second = input[itr].point.second; store[Idx].l = input[itr].label; store[Idx].index = itr; } itr++; } break; } itr++; } } } __global__ void update_label(convexHull *ptr, assignMax *M,long int size) { int idx = threadIdx.x+blockIdx.x*blockDim.x; int l = M[idx].l; long int i=0; for(;i<size;i++) { if(l==ptr[i].label&&M[idx].p.first<=ptr[i].point.first) { ptr[i].label = ptr[i].label+1; } } } void initialize(convexHull ptr[],long int n) { long int i=0; for(;i<n;i++) { if(leftmost_point.first>ptr[i].point.first) { leftmost_point = ptr[i].point; } if(rightmost_point.first<ptr[i].point.first) { rightmost_point = ptr[i].point; } } } void initialize_Max(assignMax ptr[],long int n,bool upper) { long int i=0; for(;i<n;i++) { if(upper) { ptr[i].max = INT_MIN; } else { ptr[i].max = INT_MAX; } ptr[i].p = {INT_MIN,INT_MIN}; ptr[i].l = -1; ptr[i].index = -1; } } void update_Hull(int labels,bool upper) { flag = true; if(upper) { for(int k=0;k<labels;k++) { flag = true; for(long int hull_itr=0;hull_itr<hull_length;hull_itr++) { if((hostInput[hostMax[k].index].point.first==hull[hull_itr].first)&&(hostInput[hostMax[k].index].point.second==hull[hull_itr].second)) { // for distinct point flag = false; break; } } if(flag&&hostMax[k].l!=-1) { hull[hull_length] = hostInput[hostMax[k].index].point; hull_length++; } } }else { for(int k=0;k<labels;k++) { flag = true; for(long int hull_itr=0;hull_itr<lhull_length;hull_itr++) { if((hostInput[hostMax[k].index].point.first==lhull[hull_itr].first)&&(hostInput[hostMax[k].index].point.second==lhull[hull_itr].second)) { // for distinct point flag = false; break; } } if(flag&&hostMax[k].l!=-1) { lhull[lhull_length] = hostInput[hostMax[k].index].point; lhull_length++; } } } } void update_And_Remove_MarkPoints(convexHull p[],long int &p_len,convexHull ap[],long int &ap_len) { long int i=0; for(long int k=0;k<p_len;k++) { if(p[k].mark==-1) { ap[ap_len].point.first = p[k].point.first; ap[ap_len].point.second = p[k].point.second; ap[ap_len].label = p[k].label; ap[ap_len].distance = p[k].distance; ap[ap_len].mark = p[k].mark; ap_len++; }else { p[i] = p[k]; i++; } } p_len = i; } void printOutput() { int it = 0; for(;it<hull_length;it++) { cout<<hull[it].first<<" "<<hull[it].second<<endl; } } int main(int argc, char *argv[]) { wbTime_start(Generic, "Importing data and creating memory on host"); ifstream file; file.open(argv[2]); file>>inputLength; wbTime_stop(Generic, "Importing data and creating memory on host"); /* initialization */ hostInput = new convexHull[inputLength]; deviceInput = new convexHull[inputLength]; original = new convexHull[inputLength]; hull = new Point[inputLength]; deviceHull = new Point[inputLength]; appendPoint = new convexHull[inputLength]; /* @endregion */ /*Assigining Value*/ for(itr=0;itr<inputLength;itr++) { file>>hostInput[itr].point.first; file>>hostInput[itr].point.second; hostInput[itr].label = 0; original[itr].label = 0; original[itr].distance = 0; hostInput[itr].distance = 0; original[itr].point.first = hostInput[itr].point.first; original[itr].point.second = hostInput[itr].point.second; } file.close(); int threads_per_block = 512; dim3 blocks(ceil(inputLength/threads_per_block)+1,1,1); //find the left and righ most point form region initialize(hostInput,inputLength); hull[0] = leftmost_point; hull[1] = rightmost_point; flag = false; //GpuTimer time; //time.Start(); /* @params [upper convexHull] @descriptor {finding the point which is the part of lower hull} */ bool lower_flag = false; int prev_len = 2; clock_t t = clock(); do { //compute upperhull hipMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); hipMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),hipMemcpyHostToDevice); hipMalloc((void **)&deviceHull,inputLength*sizeof(Point)); hipMemcpy(deviceHull,hull,inputLength*sizeof(Point),hipMemcpyHostToDevice); hipLaunchKernelGGL(( calculate_perpendicularDistance_And_markNegDistance), dim3(blocks),dim3(threads_per_block), 0, 0, deviceInput,deviceHull,inputLength); hipMemcpy(hostInput,deviceInput,inputLength*sizeof(convexHull),hipMemcpyDeviceToHost); /*sort based on the label*/ std::sort(hostInput,hostInput+inputLength,labelsort); int label_thread = hostInput[inputLength-1].label+1; devMax = new assignMax[label_thread]; hostMax = new assignMax[label_thread]; initialize_Max(hostMax,label_thread,true); hipMalloc((void **)&devMax,label_thread*sizeof(assignMax)); hipMemcpy(devMax,hostMax,label_thread*sizeof(assignMax),hipMemcpyHostToDevice); hipMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); hipMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),hipMemcpyHostToDevice); hipLaunchKernelGGL(( scan), dim3(1),dim3(label_thread), 0, 0, deviceInput,devMax,inputLength,true); hipMemcpy(hostMax,devMax,label_thread*sizeof(assignMax),hipMemcpyDeviceToHost); /* @method update hull @description [which have distinct points in hull] */ prev_len = hull_length; update_Hull(label_thread,true); if(lower_flag==false){ //update_And_Mark update_And_Remove_MarkPoints(hostInput,inputLength,appendPoint,append_point_len); lower_flag = true; } /*sort label_partition*/ hipMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); hipMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),hipMemcpyHostToDevice); hipLaunchKernelGGL(( update_label), dim3(1),dim3(label_thread), 0, 0, deviceInput,devMax,inputLength); hipMemcpy(hostInput,deviceInput,sizeof(convexHull)*inputLength,hipMemcpyDeviceToHost); maxlabel = label_thread; std::sort(hull,hull+hull_length,comparision); hipDeviceSynchronize(); }while(prev_len!=hull_length); /* [upper hull] finding the point which is the part of upper hull, having -ve perpendicular distance */ appendPoint[append_point_len].point = leftmost_point; appendPoint[append_point_len].label = 0; append_point_len++; appendPoint[append_point_len].point = rightmost_point; appendPoint[append_point_len].label = 0; append_point_len++; inputLength = append_point_len; thrust::device_vector<convexHull> temp(appendPoint,appendPoint+append_point_len); thrust::copy(temp.begin(),temp.end(),hostInput); lhull = new Point[inputLength]; lhull[0] = leftmost_point; lhull[1] = rightmost_point; maxlabel = 1; do { hipMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); hipMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),hipMemcpyHostToDevice); hipMalloc((void **)&deviceHull,inputLength*sizeof(Point)); hipMemcpy(deviceHull,lhull,inputLength*sizeof(Point),hipMemcpyHostToDevice); hipLaunchKernelGGL(( calculate_perpendicularDistance_And_markNegDistance), dim3(blocks),dim3(threads_per_block), 0, 0, deviceInput,deviceHull,inputLength); hipMemcpy(hostInput,deviceInput,inputLength*sizeof(convexHull),hipMemcpyDeviceToHost); /*sort based on the label*/ std::sort(hostInput,hostInput+inputLength,labelsort);//findlabel(inputLength)+1; int label_thread = hostInput[inputLength-1].label+1; devMax = new assignMax[label_thread]; hostMax = new assignMax[label_thread]; initialize_Max(hostMax,label_thread,false); hipMalloc((void **)&devMax,label_thread*sizeof(assignMax)); hipMemcpy(devMax,hostMax,label_thread*sizeof(assignMax),hipMemcpyHostToDevice); hipMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); hipMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),hipMemcpyHostToDevice); hipLaunchKernelGGL(( scan), dim3(1),dim3(label_thread), 0, 0, deviceInput,devMax,inputLength,false); hipMemcpy(hostMax,devMax,label_thread*sizeof(assignMax),hipMemcpyDeviceToHost); /* method update hull description [which have distinct points in hull */ prev_len = lhull_length; update_Hull(label_thread,false); hipMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); hipMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),hipMemcpyHostToDevice); hipLaunchKernelGGL(( update_label), dim3(1),dim3(label_thread), 0, 0, deviceInput,devMax,inputLength); hipMemcpy(hostInput,deviceInput,sizeof(convexHull)*inputLength,hipMemcpyDeviceToHost); maxlabel = label_thread; std::sort(lhull,lhull+lhull_length,comparision); hipDeviceSynchronize(); }while(prev_len!=lhull_length); /* param update the upperhull and lower hull */ for(int j=0;j<lhull_length;j++) { bool check = true; for(int k=0;k<hull_length;k++){ if(hull[k].first==lhull[j].first&&hull[k].second==lhull[j].second) { check = false; break; } } if(check) { hull[hull_length++] = lhull[j]; } } printOutput(); hipDeviceSynchronize(); return 0; }
4f6634cabd46ee7f5dbaa91dd3f28fa1415407f7.cu
#include<bits/stdc++.h> #include<fstream> #include<sstream> #include<stdio.h> #include<thrust/device_vector.h> #include<thrust/copy.h> #include<thrust/scan.h> #include <thrust/sort.h> #include<cuda.h> #include<curand.h> #include<curand_kernel.h> #include<cuda_runtime.h> #include<thrust/extrema.h> using namespace std; typedef pair<long int,long int> Point; struct convexHull { Point point; long int label; long int distance; int mark; }; struct assignMax { long int max; Point p; int l; int index; }; Point *hull; Point *lhull; long int inputLength,itr; Point leftmost_point make_pair(INT_MAX,0),rightmost_point make_pair(INT_MIN,0); convexHull *hostInput; convexHull *deviceInput; convexHull *original; Point *deviceHull; long int hull_length = 2; long int lhull_length = 2; convexHull *appendPoint; long int append_point_len = 0; assignMax *devMax; assignMax *hostMax; bool flag = false; int maxlabel = 1; /*comparsion for sorting*/ bool comparision(Point a,Point b) { return (a.first<b.first); } bool labelsort(convexHull a, convexHull b) { return a.label<b.label; } __global__ void calculate_perpendicularDistance_And_markNegDistance(convexHull *input,Point *devHull,long int size) { long int Idx = threadIdx.x+blockIdx.x*blockDim.x; /* calculate perpendicular point*/ if((Idx)<size) { Point P = input[Idx].point; long int lb = input[Idx].label; Point min = devHull[lb]; Point max = devHull[lb+1]; input[Idx].distance=(P.second-min.second)*(max.first-min.first)-(max.second-min.second)*(P.first-min.first); if(input[Idx].distance<0) { input[Idx].mark = -1; }else { input[Idx].mark = 1; } } } __global__ void scan(convexHull *input,assignMax *store,int size,bool upper) { int Idx = blockIdx.x*blockDim.x+threadIdx.x; /*find index in cuda*/ long int itr = 0; if(upper) { for(;itr<size;) { if(Idx==input[itr].label) { while(itr<size&&Idx==input[itr].label) { if((input[itr].distance>0)&&(store[Idx].max<input[itr].distance)) { store[Idx].max = input[itr].distance; store[Idx].p.first = input[itr].point.first; store[Idx].p.second = input[itr].point.second; store[Idx].l = input[itr].label; store[Idx].index = itr; } itr++; } break; } itr++; } } else { for(;itr<size;) { if(Idx==input[itr].label) { while(itr<size&&Idx==input[itr].label) { if((input[itr].distance<0)&&(store[Idx].max>input[itr].distance)) { store[Idx].max = input[itr].distance; store[Idx].p.first = input[itr].point.first; store[Idx].p.second = input[itr].point.second; store[Idx].l = input[itr].label; store[Idx].index = itr; } itr++; } break; } itr++; } } } __global__ void update_label(convexHull *ptr, assignMax *M,long int size) { int idx = threadIdx.x+blockIdx.x*blockDim.x; int l = M[idx].l; long int i=0; for(;i<size;i++) { if(l==ptr[i].label&&M[idx].p.first<=ptr[i].point.first) { ptr[i].label = ptr[i].label+1; } } } void initialize(convexHull ptr[],long int n) { long int i=0; for(;i<n;i++) { if(leftmost_point.first>ptr[i].point.first) { leftmost_point = ptr[i].point; } if(rightmost_point.first<ptr[i].point.first) { rightmost_point = ptr[i].point; } } } void initialize_Max(assignMax ptr[],long int n,bool upper) { long int i=0; for(;i<n;i++) { if(upper) { ptr[i].max = INT_MIN; } else { ptr[i].max = INT_MAX; } ptr[i].p = {INT_MIN,INT_MIN}; ptr[i].l = -1; ptr[i].index = -1; } } void update_Hull(int labels,bool upper) { flag = true; if(upper) { for(int k=0;k<labels;k++) { flag = true; for(long int hull_itr=0;hull_itr<hull_length;hull_itr++) { if((hostInput[hostMax[k].index].point.first==hull[hull_itr].first)&&(hostInput[hostMax[k].index].point.second==hull[hull_itr].second)) { // for distinct point flag = false; break; } } if(flag&&hostMax[k].l!=-1) { hull[hull_length] = hostInput[hostMax[k].index].point; hull_length++; } } }else { for(int k=0;k<labels;k++) { flag = true; for(long int hull_itr=0;hull_itr<lhull_length;hull_itr++) { if((hostInput[hostMax[k].index].point.first==lhull[hull_itr].first)&&(hostInput[hostMax[k].index].point.second==lhull[hull_itr].second)) { // for distinct point flag = false; break; } } if(flag&&hostMax[k].l!=-1) { lhull[lhull_length] = hostInput[hostMax[k].index].point; lhull_length++; } } } } void update_And_Remove_MarkPoints(convexHull p[],long int &p_len,convexHull ap[],long int &ap_len) { long int i=0; for(long int k=0;k<p_len;k++) { if(p[k].mark==-1) { ap[ap_len].point.first = p[k].point.first; ap[ap_len].point.second = p[k].point.second; ap[ap_len].label = p[k].label; ap[ap_len].distance = p[k].distance; ap[ap_len].mark = p[k].mark; ap_len++; }else { p[i] = p[k]; i++; } } p_len = i; } void printOutput() { int it = 0; for(;it<hull_length;it++) { cout<<hull[it].first<<" "<<hull[it].second<<endl; } } int main(int argc, char *argv[]) { wbTime_start(Generic, "Importing data and creating memory on host"); ifstream file; file.open(argv[2]); file>>inputLength; wbTime_stop(Generic, "Importing data and creating memory on host"); /* initialization */ hostInput = new convexHull[inputLength]; deviceInput = new convexHull[inputLength]; original = new convexHull[inputLength]; hull = new Point[inputLength]; deviceHull = new Point[inputLength]; appendPoint = new convexHull[inputLength]; /* @endregion */ /*Assigining Value*/ for(itr=0;itr<inputLength;itr++) { file>>hostInput[itr].point.first; file>>hostInput[itr].point.second; hostInput[itr].label = 0; original[itr].label = 0; original[itr].distance = 0; hostInput[itr].distance = 0; original[itr].point.first = hostInput[itr].point.first; original[itr].point.second = hostInput[itr].point.second; } file.close(); int threads_per_block = 512; dim3 blocks(ceil(inputLength/threads_per_block)+1,1,1); //find the left and righ most point form region initialize(hostInput,inputLength); hull[0] = leftmost_point; hull[1] = rightmost_point; flag = false; //GpuTimer time; //time.Start(); /* @params [upper convexHull] @descriptor {finding the point which is the part of lower hull} */ bool lower_flag = false; int prev_len = 2; clock_t t = clock(); do { //compute upperhull cudaMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); cudaMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),cudaMemcpyHostToDevice); cudaMalloc((void **)&deviceHull,inputLength*sizeof(Point)); cudaMemcpy(deviceHull,hull,inputLength*sizeof(Point),cudaMemcpyHostToDevice); calculate_perpendicularDistance_And_markNegDistance<<<blocks,threads_per_block>>>(deviceInput,deviceHull,inputLength); cudaMemcpy(hostInput,deviceInput,inputLength*sizeof(convexHull),cudaMemcpyDeviceToHost); /*sort based on the label*/ std::sort(hostInput,hostInput+inputLength,labelsort); int label_thread = hostInput[inputLength-1].label+1; devMax = new assignMax[label_thread]; hostMax = new assignMax[label_thread]; initialize_Max(hostMax,label_thread,true); cudaMalloc((void **)&devMax,label_thread*sizeof(assignMax)); cudaMemcpy(devMax,hostMax,label_thread*sizeof(assignMax),cudaMemcpyHostToDevice); cudaMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); cudaMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),cudaMemcpyHostToDevice); scan<<<1,label_thread>>>(deviceInput,devMax,inputLength,true); cudaMemcpy(hostMax,devMax,label_thread*sizeof(assignMax),cudaMemcpyDeviceToHost); /* @method update hull @description [which have distinct points in hull] */ prev_len = hull_length; update_Hull(label_thread,true); if(lower_flag==false){ //update_And_Mark update_And_Remove_MarkPoints(hostInput,inputLength,appendPoint,append_point_len); lower_flag = true; } /*sort label_partition*/ cudaMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); cudaMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),cudaMemcpyHostToDevice); update_label<<<1,label_thread>>>(deviceInput,devMax,inputLength); cudaMemcpy(hostInput,deviceInput,sizeof(convexHull)*inputLength,cudaMemcpyDeviceToHost); maxlabel = label_thread; std::sort(hull,hull+hull_length,comparision); cudaDeviceSynchronize(); }while(prev_len!=hull_length); /* [upper hull] finding the point which is the part of upper hull, having -ve perpendicular distance */ appendPoint[append_point_len].point = leftmost_point; appendPoint[append_point_len].label = 0; append_point_len++; appendPoint[append_point_len].point = rightmost_point; appendPoint[append_point_len].label = 0; append_point_len++; inputLength = append_point_len; thrust::device_vector<convexHull> temp(appendPoint,appendPoint+append_point_len); thrust::copy(temp.begin(),temp.end(),hostInput); lhull = new Point[inputLength]; lhull[0] = leftmost_point; lhull[1] = rightmost_point; maxlabel = 1; do { cudaMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); cudaMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),cudaMemcpyHostToDevice); cudaMalloc((void **)&deviceHull,inputLength*sizeof(Point)); cudaMemcpy(deviceHull,lhull,inputLength*sizeof(Point),cudaMemcpyHostToDevice); calculate_perpendicularDistance_And_markNegDistance<<<blocks,threads_per_block>>>(deviceInput,deviceHull,inputLength); cudaMemcpy(hostInput,deviceInput,inputLength*sizeof(convexHull),cudaMemcpyDeviceToHost); /*sort based on the label*/ std::sort(hostInput,hostInput+inputLength,labelsort);//findlabel(inputLength)+1; int label_thread = hostInput[inputLength-1].label+1; devMax = new assignMax[label_thread]; hostMax = new assignMax[label_thread]; initialize_Max(hostMax,label_thread,false); cudaMalloc((void **)&devMax,label_thread*sizeof(assignMax)); cudaMemcpy(devMax,hostMax,label_thread*sizeof(assignMax),cudaMemcpyHostToDevice); cudaMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); cudaMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),cudaMemcpyHostToDevice); scan<<<1,label_thread>>>(deviceInput,devMax,inputLength,false); cudaMemcpy(hostMax,devMax,label_thread*sizeof(assignMax),cudaMemcpyDeviceToHost); /* method update hull description [which have distinct points in hull */ prev_len = lhull_length; update_Hull(label_thread,false); cudaMalloc((void **)&deviceInput,inputLength*sizeof(convexHull)); cudaMemcpy(deviceInput,hostInput,inputLength*sizeof(convexHull),cudaMemcpyHostToDevice); update_label<<<1,label_thread>>>(deviceInput,devMax,inputLength); cudaMemcpy(hostInput,deviceInput,sizeof(convexHull)*inputLength,cudaMemcpyDeviceToHost); maxlabel = label_thread; std::sort(lhull,lhull+lhull_length,comparision); cudaDeviceSynchronize(); }while(prev_len!=lhull_length); /* param update the upperhull and lower hull */ for(int j=0;j<lhull_length;j++) { bool check = true; for(int k=0;k<hull_length;k++){ if(hull[k].first==lhull[j].first&&hull[k].second==lhull[j].second) { check = false; break; } } if(check) { hull[hull_length++] = lhull[j]; } } printOutput(); cudaDeviceSynchronize(); return 0; }
ab208ae9ff8298112a9fe5ed8c6a012bce9cb276.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include<stdio.h> #include<stdlib.h> #define N 100 #define THREADS_PER_BLOCKS 10 //space for functions __global__ void reverseArrayBlock(int *dev_a,int *dev_b){ int bx = blockIdx.x; int tx = threadIdx.x; int old_id = blockDim.x*bx + tx; int new_id = (blockDim.x*gridDim.x) - 1 - old_id; dev_b[old_id] = dev_a[new_id]; } int main(void){ //pointer for host memory int *h_a; //pointer for device memory int *dev_a; int *dev_b; // compute number of blocks needed int numblocks = N/THREADS_PER_BLOCKS; //allocate host and device memory int mem_size = N*(sizeof(int)); h_a = (int*)malloc(mem_size); hipMalloc((void**)&dev_a,mem_size); hipMalloc((void**)&dev_b,mem_size); //initialize array for (int i = 0;i<N;i++){h_a[i]=i;} // copy host array yo device array (in order to launch kernel) hipMemcpy(dev_a,h_a,mem_size,hipMemcpyHostToDevice); //launch kernel hipLaunchKernelGGL(( reverseArrayBlock), dim3(N/THREADS_PER_BLOCKS),dim3(THREADS_PER_BLOCKS), 0, 0, dev_a,dev_b); //device to host copy hipMemcpy(h_a,dev_b,mem_size,hipMemcpyDeviceToHost); for (int i =0; i<N;i++){printf("%d ",h_a[i]);} // free davice memory hipFree(dev_a); hipFree(dev_b); //free host_memory free(h_a); return 0; }
ab208ae9ff8298112a9fe5ed8c6a012bce9cb276.cu
#include<stdio.h> #include<stdlib.h> #define N 100 #define THREADS_PER_BLOCKS 10 //space for functions __global__ void reverseArrayBlock(int *dev_a,int *dev_b){ int bx = blockIdx.x; int tx = threadIdx.x; int old_id = blockDim.x*bx + tx; int new_id = (blockDim.x*gridDim.x) - 1 - old_id; dev_b[old_id] = dev_a[new_id]; } int main(void){ //pointer for host memory int *h_a; //pointer for device memory int *dev_a; int *dev_b; // compute number of blocks needed int numblocks = N/THREADS_PER_BLOCKS; //allocate host and device memory int mem_size = N*(sizeof(int)); h_a = (int*)malloc(mem_size); cudaMalloc((void**)&dev_a,mem_size); cudaMalloc((void**)&dev_b,mem_size); //initialize array for (int i = 0;i<N;i++){h_a[i]=i;} // copy host array yo device array (in order to launch kernel) cudaMemcpy(dev_a,h_a,mem_size,cudaMemcpyHostToDevice); //launch kernel reverseArrayBlock<<<N/THREADS_PER_BLOCKS,THREADS_PER_BLOCKS>>>(dev_a,dev_b); //device to host copy cudaMemcpy(h_a,dev_b,mem_size,cudaMemcpyDeviceToHost); for (int i =0; i<N;i++){printf("%d ",h_a[i]);} // free davice memory cudaFree(dev_a); cudaFree(dev_b); //free host_memory free(h_a); return 0; }
e0669b3329261178fd55a3aa0c94441da1b4cb8d.hip
// !!! This is a file automatically generated by hipify!!! #include "mex.h" #include <math.h> #include "stdio.h" #include <time.h> #include <string.h> #include <windows.h> #include <process.h> #include <hip/hip_runtime.h> #include <hipfft.h> #include <npp.h> #define THREADS_PER_BLOCK 128 // timing functions double PCFreq = 0.0; __int64 CounterStart = 0; int StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) printf("QueryPerformanceFrequency failed!\n"); PCFreq = ((double)li.QuadPart)/1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; return (int)CounterStart; } int GetCounter() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return (int)li.QuadPart; } //// === Cuda kernels === // let's try with block-wise per nprimePt, thread-wise per fft point, so that maybe we can improve occupancy // no occupancy change, but slightly faster? // the d_in_buffer is now Dec*nprimePts + L length ie cyclelen + L __global__ void wola_front_sm_tuned_delay(int N, int L, int Dec, int nprimePts, Npp16sc *d_in_buffer, Npp32fc *d_out, Npp32f *d_ftapg) { extern __shared__ float s[]; Npp32f *d_ftap = s; // int index = blockIdx.x * blockDim.x + threadIdx.x; // int stride = blockDim.x * gridDim.x; for (int l = threadIdx.x; l < L; l += blockDim.x){ d_ftap[l] = d_ftapg[l]; } // wait for copies to shared mem to end __syncthreads(); Npp32f re, im; // oh snap writing to stack first almost halves the kernel time lol int n; // Npp16sc *d_in = &d_in_buffer[L]; for (int nprime = blockIdx.x; nprime < nprimePts; nprime+=gridDim.x){ n = nprime*Dec; for (int a = threadIdx.x; a<N; a+=blockDim.x){ re = 0; im = 0; for (int b = 0; b < L/N; b++){ // if (n - (b*N+a) >= 0){ re = re + (Npp32f)(d_in_buffer[L + n - (b*N+a)].re) * d_ftap[b*N+a]; im = im + (Npp32f)(d_in_buffer[L + n - (b*N+a)].im) * d_ftap[b*N+a]; // } } // if(re == 0 && im == 0){printf("%i, %i, %g %g\n", blockIdx.x, threadIdx.x, re, im);} d_out[nprime*N + a].re = re; d_out[nprime*N + a].im = im; } } } /* The gateway function */ // calling arguments, out = (signal, f_tap, N, Dec) void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // Timing int start_t = StartCounter(); int end_t; // declare variables Npp16sc *h_indata; Npp16sc *h_indata_matlab; // non-pinned Npp16sc *d_indata_buffer0, *d_indata_buffer1; float *h_ftap; Npp32f *d_ftap; int datalen; // length of indata int L; // length of filter int N; // number of channels int Dec; // decimation factor // declare outputs int nprimePts; int cycles; Npp32fc *d_outdata_buffer0, *d_outdata_buffer1; Npp32fc *h_outdata; mxComplexSingle *h_outdata_matlab; // non-pinned // //reserve stuff for threads // int t; // HANDLE ThreadList[NUM_THREADS]; // handles to threads /* check for proper number of arguments */ if (nrhs!=5){ mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","5 Inputs required."); } // get inputs and check h_indata_matlab = (Npp16sc*)mxGetComplexInt16s(prhs[0]); datalen = (int)mxGetM(prhs[0]) * (int)mxGetN(prhs[0]); h_ftap = (float*)mxGetSingles(prhs[1]); L = (int)mxGetM(prhs[1]) * (int)mxGetN(prhs[1]); if (L > 8192){ mexErrMsgTxt("ERROR: Length of filter only supported up to 8192!"); } N = (int)mxGetScalar(prhs[2]); if (L%N != 0){ mexErrMsgTxt("ERROR: Filter taps length must be factor multiple of fft length!"); } Dec = (int)mxGetScalar(prhs[3]); if (Dec != N){ mexErrMsgTxt("ERROR: Decimation must be equal to number of channels! Other decimation ratios not yet implemented!"); } cycles = (int)mxGetScalar(prhs[4]); if (datalen % cycles != 0){ mexErrMsgTxt("ERROR: Cycles must be a factor of input data length!"); } int cyclelen = datalen/cycles; /* create the output matrix */ if (datalen%Dec!=0){ mexErrMsgTxt("ERROR: Input data must be a multiple of supplied decimation factor!"); } nprimePts = datalen/Dec; plhs[0] = mxCreateNumericMatrix(N,nprimePts, mxSINGLE_CLASS,mxCOMPLEX); h_outdata_matlab = mxGetComplexSingles(plhs[0]); int outlen = nprimePts * N; int cycle_nprimePts = nprimePts/cycles; int cycleOutlen = outlen/cycles; // allocate device memory hipMalloc((void**)&d_ftap, sizeof(Npp32f)*L); hipMalloc((void**)&d_indata_buffer0, sizeof(Npp16sc)*(cyclelen+L)); // allocate more for the delay, in a continguous fashion! hipMalloc((void**)&d_indata_buffer1, sizeof(Npp16sc)*(cyclelen+L)); // allocate the waiting buffer hipMalloc((void**)&d_outdata_buffer0, sizeof(Npp32fc)*cycleOutlen); hipMalloc((void**)&d_outdata_buffer1, sizeof(Npp32fc)*cycleOutlen); // allocate pinned host memory for async transfers hipHostMalloc((void**)&h_indata, sizeof(Npp16sc)*datalen); hipHostMalloc((void**)&h_outdata, sizeof(Npp32fc)*outlen); // initialize input data by memcpy start_t = GetCounter(); memcpy(h_indata, h_indata_matlab, sizeof(Npp16sc) * datalen); end_t = GetCounter(); printf("Copying input to pinned memory, took %g ms.\n", (end_t - start_t)/PCFreq); // cufft parameters, batchmode hipfftHandle batchplan; int fftlen[1] = {N}; int istride = 1; int inembed[1] = {N * cycle_nprimePts}; int idist = N; int ostride = 1; int onembed[1] = {N * cycle_nprimePts}; int odist = N; hipfftResult cfr = hipfftPlanMany(&batchplan,1,fftlen, inembed,istride,idist, onembed,ostride,odist, HIPFFT_C2C,cycle_nprimePts); if (cfr != HIPFFT_SUCCESS){mexErrMsgTxt("cufft Plan failed!\n");} // make a stream for compute and for copying to enable async stuff (seems like having this number of streams is the only way to ensure the overlapped transfers..) hipStream_t computeStream; hipStream_t copyStreamHtoD; hipStream_t copyStreamDtoH; hipStream_t copyStreamDtoD; hipStreamCreate(&computeStream); hipStreamCreate(&copyStreamHtoD); hipStreamCreate(&copyStreamDtoD); hipStreamCreate(&copyStreamDtoH); hipfftSetStream(batchplan, computeStream); // copy the f_tap hipMemcpy(d_ftap,h_ftap,L*sizeof(Npp32f), hipMemcpyHostToDevice); // make sure we zero the first buffer's delay nppSetStream(computeStream); nppsZero_16sc(d_indata_buffer0, L + cyclelen); // issue the first copies! hipMemcpy(&d_indata_buffer0[L], h_indata, cyclelen*sizeof(Npp16sc), hipMemcpyHostToDevice); // use non-async? // assign pointers for clarity? Npp16sc *d_indata_current = d_indata_buffer0; Npp16sc *d_indata_waiting = d_indata_buffer1; Npp16sc *d_indata_swap; // used to swap them later Npp32fc *d_outdata_current = d_outdata_buffer0; Npp32fc *d_outdata_copying = d_outdata_buffer1; Npp32fc *d_outdata_swap; // ==start the computational loop== int i; for (i = 0; i < cycles-1; i++){ // only cycle to -1 of the total, otherwise you will copy out of bounds // for (i=0;i<1;i++){ // wait for previous async transfers of the next batch data to end hipStreamSynchronize(copyStreamHtoD); hipStreamSynchronize(copyStreamDtoD); // copy the end of the first buffer into the delay of the waiting buffer hipMemcpyAsync(&d_indata_waiting[0], &d_indata_current[cyclelen], L*sizeof(Npp16sc), hipMemcpyDeviceToDevice, copyStreamDtoD); hipStreamQuery(copyStreamDtoD); // copy the new cycle's data after that into the rest of the waiting buffer hipMemcpyAsync(&d_indata_waiting[L], &h_indata[(i+1)*cyclelen], (cyclelen)*sizeof(Npp16sc), hipMemcpyHostToDevice, copyStreamHtoD); hipStreamQuery(copyStreamHtoD); // run the kernel on the computeStream hipLaunchKernelGGL(( wola_front_sm_tuned_delay), dim3(cycle_nprimePts), dim3(THREADS_PER_BLOCK), sizeof(Npp32f) * L , computeStream, N, L, Dec, cycle_nprimePts, d_indata_current, d_outdata_current, d_ftap); hipStreamQuery(computeStream); // for the consequent ones, copy the pinned to non-pinned (EMBED THIS AT THIS POSITION IN THE CODE BECAUSE THE WOLA_FRONT IS THE LONGEST CALL AND CPU MEMCPY IS BLOCKING) if (i>0){ memcpy(&h_outdata_matlab[(i-1)*cycleOutlen], &h_outdata[(i-1)*cycleOutlen], sizeof(Npp32fc)*cycleOutlen); } // wait for compute stream to finish then do the ffts // hipStreamSynchronize(computeStream); cfr = hipfftExecC2C(batchplan, (hipfftComplex*)d_outdata_current, (hipfftComplex*)d_outdata_current, HIPFFT_BACKWARD); // try in-place? if(cfr!=HIPFFT_SUCCESS){printf("ERROR WHILE COMPUTING CUFFT ON ITERATION %i\n", i);} // then wait for the compute stream to finish hipStreamSynchronize(computeStream); // swap pointers and copy the output back to host hipStreamSynchronize(copyStreamDtoH); d_outdata_swap = d_outdata_current; d_outdata_current = d_outdata_copying; // at this point the d_outdata_current is ready for writing to already d_outdata_copying = d_outdata_swap; hipMemcpyAsync(&h_outdata[i*cycleOutlen], d_outdata_copying, cycleOutlen*sizeof(Npp32fc), hipMemcpyDeviceToHost, copyStreamDtoH); hipStreamQuery(copyStreamDtoH); // swap pointers d_indata_swap = d_indata_current; d_indata_current = d_indata_waiting; // so waiting -> current d_indata_waiting = d_indata_swap; // and current -> waiting } // wait for data to transfer in hipStreamSynchronize(copyStreamHtoD); hipStreamSynchronize(copyStreamDtoD); // run the kernel on the computeStream hipLaunchKernelGGL(( wola_front_sm_tuned_delay), dim3(cycle_nprimePts), dim3(THREADS_PER_BLOCK), sizeof(Npp32f) * L , computeStream, N, L, Dec, cycle_nprimePts, d_indata_current, d_outdata_current, d_ftap); hipStreamQuery(computeStream); // again, embed the memcpy here memcpy(&h_outdata_matlab[(cycles-2)*cycleOutlen], &h_outdata[(cycles-2)*cycleOutlen], sizeof(Npp32fc)*cycleOutlen); // wait for compute stream to finish then do the ffts // hipStreamSynchronize(computeStream); cfr = hipfftExecC2C(batchplan, (hipfftComplex*)d_outdata_current, (hipfftComplex*)d_outdata_current, HIPFFT_BACKWARD); // try in-place? if(cfr!=HIPFFT_SUCCESS){printf("ERROR WHILE COMPUTING CUFFT ON ITERATION %i\n", i);} // then wait for the compute stream to finish hipStreamSynchronize(computeStream); // swap pointers and copy the output back to host hipStreamSynchronize(copyStreamDtoH); d_outdata_swap = d_outdata_current; d_outdata_current = d_outdata_copying; // at this point the d_outdata_current is ready for writing to already d_outdata_copying = d_outdata_swap; hipMemcpyAsync(&h_outdata[(cycles-1)*cycleOutlen], d_outdata_copying, cycleOutlen*sizeof(Npp32fc), hipMemcpyDeviceToHost, copyStreamDtoH); hipStreamQuery(copyStreamDtoH); // wait for all of it to finish hipDeviceSynchronize(); // final memcpy for the final batch memcpy(&h_outdata_matlab[(cycles-1)*cycleOutlen], &h_outdata[(cycles-1)*cycleOutlen], sizeof(Npp32fc)*cycleOutlen); // // copy output to matlab array // start_t = GetCounter(); // memcpy(h_outdata_matlab, h_outdata, sizeof(Npp32fc)*outlen); // end_t = GetCounter(); // printf("Copying output from pinned mem to matlab array, took %g ms.\n", (end_t - start_t)/PCFreq); // ==end of computational loop== // cleanup hipFree(d_indata_buffer0); hipFree(d_indata_buffer1); hipFree(d_ftap); hipFree(d_outdata_buffer0); hipFree(d_outdata_buffer1); hipHostFree(h_indata); hipHostFree(h_outdata); hipfftDestroy(batchplan); hipStreamDestroy(copyStreamHtoD); hipStreamDestroy(copyStreamDtoH); hipStreamDestroy(copyStreamDtoD); hipStreamDestroy(computeStream); }
e0669b3329261178fd55a3aa0c94441da1b4cb8d.cu
#include "mex.h" #include <math.h> #include "stdio.h" #include <time.h> #include <string.h> #include <windows.h> #include <process.h> #include <cuda_runtime.h> #include <cufft.h> #include <npp.h> #define THREADS_PER_BLOCK 128 // timing functions double PCFreq = 0.0; __int64 CounterStart = 0; int StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) printf("QueryPerformanceFrequency failed!\n"); PCFreq = ((double)li.QuadPart)/1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; return (int)CounterStart; } int GetCounter() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return (int)li.QuadPart; } //// === Cuda kernels === // let's try with block-wise per nprimePt, thread-wise per fft point, so that maybe we can improve occupancy // no occupancy change, but slightly faster? // the d_in_buffer is now Dec*nprimePts + L length ie cyclelen + L __global__ void wola_front_sm_tuned_delay(int N, int L, int Dec, int nprimePts, Npp16sc *d_in_buffer, Npp32fc *d_out, Npp32f *d_ftapg) { extern __shared__ float s[]; Npp32f *d_ftap = s; // int index = blockIdx.x * blockDim.x + threadIdx.x; // int stride = blockDim.x * gridDim.x; for (int l = threadIdx.x; l < L; l += blockDim.x){ d_ftap[l] = d_ftapg[l]; } // wait for copies to shared mem to end __syncthreads(); Npp32f re, im; // oh snap writing to stack first almost halves the kernel time lol int n; // Npp16sc *d_in = &d_in_buffer[L]; for (int nprime = blockIdx.x; nprime < nprimePts; nprime+=gridDim.x){ n = nprime*Dec; for (int a = threadIdx.x; a<N; a+=blockDim.x){ re = 0; im = 0; for (int b = 0; b < L/N; b++){ // if (n - (b*N+a) >= 0){ re = re + (Npp32f)(d_in_buffer[L + n - (b*N+a)].re) * d_ftap[b*N+a]; im = im + (Npp32f)(d_in_buffer[L + n - (b*N+a)].im) * d_ftap[b*N+a]; // } } // if(re == 0 && im == 0){printf("%i, %i, %g %g\n", blockIdx.x, threadIdx.x, re, im);} d_out[nprime*N + a].re = re; d_out[nprime*N + a].im = im; } } } /* The gateway function */ // calling arguments, out = (signal, f_tap, N, Dec) void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // Timing int start_t = StartCounter(); int end_t; // declare variables Npp16sc *h_indata; Npp16sc *h_indata_matlab; // non-pinned Npp16sc *d_indata_buffer0, *d_indata_buffer1; float *h_ftap; Npp32f *d_ftap; int datalen; // length of indata int L; // length of filter int N; // number of channels int Dec; // decimation factor // declare outputs int nprimePts; int cycles; Npp32fc *d_outdata_buffer0, *d_outdata_buffer1; Npp32fc *h_outdata; mxComplexSingle *h_outdata_matlab; // non-pinned // //reserve stuff for threads // int t; // HANDLE ThreadList[NUM_THREADS]; // handles to threads /* check for proper number of arguments */ if (nrhs!=5){ mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","5 Inputs required."); } // get inputs and check h_indata_matlab = (Npp16sc*)mxGetComplexInt16s(prhs[0]); datalen = (int)mxGetM(prhs[0]) * (int)mxGetN(prhs[0]); h_ftap = (float*)mxGetSingles(prhs[1]); L = (int)mxGetM(prhs[1]) * (int)mxGetN(prhs[1]); if (L > 8192){ mexErrMsgTxt("ERROR: Length of filter only supported up to 8192!"); } N = (int)mxGetScalar(prhs[2]); if (L%N != 0){ mexErrMsgTxt("ERROR: Filter taps length must be factor multiple of fft length!"); } Dec = (int)mxGetScalar(prhs[3]); if (Dec != N){ mexErrMsgTxt("ERROR: Decimation must be equal to number of channels! Other decimation ratios not yet implemented!"); } cycles = (int)mxGetScalar(prhs[4]); if (datalen % cycles != 0){ mexErrMsgTxt("ERROR: Cycles must be a factor of input data length!"); } int cyclelen = datalen/cycles; /* create the output matrix */ if (datalen%Dec!=0){ mexErrMsgTxt("ERROR: Input data must be a multiple of supplied decimation factor!"); } nprimePts = datalen/Dec; plhs[0] = mxCreateNumericMatrix(N,nprimePts, mxSINGLE_CLASS,mxCOMPLEX); h_outdata_matlab = mxGetComplexSingles(plhs[0]); int outlen = nprimePts * N; int cycle_nprimePts = nprimePts/cycles; int cycleOutlen = outlen/cycles; // allocate device memory cudaMalloc((void**)&d_ftap, sizeof(Npp32f)*L); cudaMalloc((void**)&d_indata_buffer0, sizeof(Npp16sc)*(cyclelen+L)); // allocate more for the delay, in a continguous fashion! cudaMalloc((void**)&d_indata_buffer1, sizeof(Npp16sc)*(cyclelen+L)); // allocate the waiting buffer cudaMalloc((void**)&d_outdata_buffer0, sizeof(Npp32fc)*cycleOutlen); cudaMalloc((void**)&d_outdata_buffer1, sizeof(Npp32fc)*cycleOutlen); // allocate pinned host memory for async transfers cudaMallocHost((void**)&h_indata, sizeof(Npp16sc)*datalen); cudaMallocHost((void**)&h_outdata, sizeof(Npp32fc)*outlen); // initialize input data by memcpy start_t = GetCounter(); memcpy(h_indata, h_indata_matlab, sizeof(Npp16sc) * datalen); end_t = GetCounter(); printf("Copying input to pinned memory, took %g ms.\n", (end_t - start_t)/PCFreq); // cufft parameters, batchmode cufftHandle batchplan; int fftlen[1] = {N}; int istride = 1; int inembed[1] = {N * cycle_nprimePts}; int idist = N; int ostride = 1; int onembed[1] = {N * cycle_nprimePts}; int odist = N; cufftResult cfr = cufftPlanMany(&batchplan,1,fftlen, inembed,istride,idist, onembed,ostride,odist, CUFFT_C2C,cycle_nprimePts); if (cfr != CUFFT_SUCCESS){mexErrMsgTxt("cufft Plan failed!\n");} // make a stream for compute and for copying to enable async stuff (seems like having this number of streams is the only way to ensure the overlapped transfers..) cudaStream_t computeStream; cudaStream_t copyStreamHtoD; cudaStream_t copyStreamDtoH; cudaStream_t copyStreamDtoD; cudaStreamCreate(&computeStream); cudaStreamCreate(&copyStreamHtoD); cudaStreamCreate(&copyStreamDtoD); cudaStreamCreate(&copyStreamDtoH); cufftSetStream(batchplan, computeStream); // copy the f_tap cudaMemcpy(d_ftap,h_ftap,L*sizeof(Npp32f), cudaMemcpyHostToDevice); // make sure we zero the first buffer's delay nppSetStream(computeStream); nppsZero_16sc(d_indata_buffer0, L + cyclelen); // issue the first copies! cudaMemcpy(&d_indata_buffer0[L], h_indata, cyclelen*sizeof(Npp16sc), cudaMemcpyHostToDevice); // use non-async? // assign pointers for clarity? Npp16sc *d_indata_current = d_indata_buffer0; Npp16sc *d_indata_waiting = d_indata_buffer1; Npp16sc *d_indata_swap; // used to swap them later Npp32fc *d_outdata_current = d_outdata_buffer0; Npp32fc *d_outdata_copying = d_outdata_buffer1; Npp32fc *d_outdata_swap; // ==start the computational loop== int i; for (i = 0; i < cycles-1; i++){ // only cycle to -1 of the total, otherwise you will copy out of bounds // for (i=0;i<1;i++){ // wait for previous async transfers of the next batch data to end cudaStreamSynchronize(copyStreamHtoD); cudaStreamSynchronize(copyStreamDtoD); // copy the end of the first buffer into the delay of the waiting buffer cudaMemcpyAsync(&d_indata_waiting[0], &d_indata_current[cyclelen], L*sizeof(Npp16sc), cudaMemcpyDeviceToDevice, copyStreamDtoD); cudaStreamQuery(copyStreamDtoD); // copy the new cycle's data after that into the rest of the waiting buffer cudaMemcpyAsync(&d_indata_waiting[L], &h_indata[(i+1)*cyclelen], (cyclelen)*sizeof(Npp16sc), cudaMemcpyHostToDevice, copyStreamHtoD); cudaStreamQuery(copyStreamHtoD); // run the kernel on the computeStream wola_front_sm_tuned_delay<<<cycle_nprimePts, THREADS_PER_BLOCK, sizeof(Npp32f) * L , computeStream>>>(N, L, Dec, cycle_nprimePts, d_indata_current, d_outdata_current, d_ftap); cudaStreamQuery(computeStream); // for the consequent ones, copy the pinned to non-pinned (EMBED THIS AT THIS POSITION IN THE CODE BECAUSE THE WOLA_FRONT IS THE LONGEST CALL AND CPU MEMCPY IS BLOCKING) if (i>0){ memcpy(&h_outdata_matlab[(i-1)*cycleOutlen], &h_outdata[(i-1)*cycleOutlen], sizeof(Npp32fc)*cycleOutlen); } // wait for compute stream to finish then do the ffts // cudaStreamSynchronize(computeStream); cfr = cufftExecC2C(batchplan, (cufftComplex*)d_outdata_current, (cufftComplex*)d_outdata_current, CUFFT_INVERSE); // try in-place? if(cfr!=CUFFT_SUCCESS){printf("ERROR WHILE COMPUTING CUFFT ON ITERATION %i\n", i);} // then wait for the compute stream to finish cudaStreamSynchronize(computeStream); // swap pointers and copy the output back to host cudaStreamSynchronize(copyStreamDtoH); d_outdata_swap = d_outdata_current; d_outdata_current = d_outdata_copying; // at this point the d_outdata_current is ready for writing to already d_outdata_copying = d_outdata_swap; cudaMemcpyAsync(&h_outdata[i*cycleOutlen], d_outdata_copying, cycleOutlen*sizeof(Npp32fc), cudaMemcpyDeviceToHost, copyStreamDtoH); cudaStreamQuery(copyStreamDtoH); // swap pointers d_indata_swap = d_indata_current; d_indata_current = d_indata_waiting; // so waiting -> current d_indata_waiting = d_indata_swap; // and current -> waiting } // wait for data to transfer in cudaStreamSynchronize(copyStreamHtoD); cudaStreamSynchronize(copyStreamDtoD); // run the kernel on the computeStream wola_front_sm_tuned_delay<<<cycle_nprimePts, THREADS_PER_BLOCK, sizeof(Npp32f) * L , computeStream>>>(N, L, Dec, cycle_nprimePts, d_indata_current, d_outdata_current, d_ftap); cudaStreamQuery(computeStream); // again, embed the memcpy here memcpy(&h_outdata_matlab[(cycles-2)*cycleOutlen], &h_outdata[(cycles-2)*cycleOutlen], sizeof(Npp32fc)*cycleOutlen); // wait for compute stream to finish then do the ffts // cudaStreamSynchronize(computeStream); cfr = cufftExecC2C(batchplan, (cufftComplex*)d_outdata_current, (cufftComplex*)d_outdata_current, CUFFT_INVERSE); // try in-place? if(cfr!=CUFFT_SUCCESS){printf("ERROR WHILE COMPUTING CUFFT ON ITERATION %i\n", i);} // then wait for the compute stream to finish cudaStreamSynchronize(computeStream); // swap pointers and copy the output back to host cudaStreamSynchronize(copyStreamDtoH); d_outdata_swap = d_outdata_current; d_outdata_current = d_outdata_copying; // at this point the d_outdata_current is ready for writing to already d_outdata_copying = d_outdata_swap; cudaMemcpyAsync(&h_outdata[(cycles-1)*cycleOutlen], d_outdata_copying, cycleOutlen*sizeof(Npp32fc), cudaMemcpyDeviceToHost, copyStreamDtoH); cudaStreamQuery(copyStreamDtoH); // wait for all of it to finish cudaDeviceSynchronize(); // final memcpy for the final batch memcpy(&h_outdata_matlab[(cycles-1)*cycleOutlen], &h_outdata[(cycles-1)*cycleOutlen], sizeof(Npp32fc)*cycleOutlen); // // copy output to matlab array // start_t = GetCounter(); // memcpy(h_outdata_matlab, h_outdata, sizeof(Npp32fc)*outlen); // end_t = GetCounter(); // printf("Copying output from pinned mem to matlab array, took %g ms.\n", (end_t - start_t)/PCFreq); // ==end of computational loop== // cleanup cudaFree(d_indata_buffer0); cudaFree(d_indata_buffer1); cudaFree(d_ftap); cudaFree(d_outdata_buffer0); cudaFree(d_outdata_buffer1); cudaFreeHost(h_indata); cudaFreeHost(h_outdata); cufftDestroy(batchplan); cudaStreamDestroy(copyStreamHtoD); cudaStreamDestroy(copyStreamDtoH); cudaStreamDestroy(copyStreamDtoD); cudaStreamDestroy(computeStream); }
8c1366b40742a7117ffd5959c92ee31d6ae7bd86.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #define WP 32 #define BM (WP-1) #define dt unsigned short #define dts 2 #define TGTG 1 #define TGNTG 0 #define LBMAX 0xffff #define LB2MAX 0xffffffff typedef unsigned int uint; typedef unsigned char uchar; typedef unsigned short ushort; #define W 512 #define HWW 8 #define rep 2 #define HW (W/2) #define QW (W/4) #define HWP (WP/2) #define QWP (WP/4) #define EWP (WP/8) #define XWP (WP/16) #define TN (W/(rep*2)) #define WN (TN/WP) #define MASKAD (~(-1 << HWW)) __device__ __inline__ static void detectRuns512(ushort* pt, uchar* ct, uchar* ps, uchar* px, ushort* tbf, uint cp2) { uint* ps4 = (uint*)ps; uint* pt2 = (uint*)pt; ushort* ct2 = (ushort*)ct; uint cp = cp2 >> 1;//threadIdx.x + threadIdx.y * WP; // uint cp2 = cp << 1; uint t0, t1, t2, t3, t4, t5; t0 = ps4[cp]; t0 = __byte_perm(t0, 0, 0x3120); t0 &= 0x1010101; t0 |= t0 >> 15; t0 |= t0 >> 6; t0 &= 0xf; // now t0 has the 4 pixels in its 4 less significant bits t1 = px[cp]; t5 = 0; if ((t1 & 0x3))// && (t0 & 0x3) t5 = 0x1; if ((t1 & 0xc))// && (t0 & 0xc) t5 |= 0x100; ct2[cp] = t5;// | ((ct2[cp] & 0xf0f) << 4); t1 = t1 | t0; px[cp] = t0 | (px[cp] << 4); t3 = W; t4 = W; t5 = 0; if (t1 & 0x3) t3 = cp2; if (t1 & 0xc) t4 = cp2 + 1; if ((t1 & 0x6) == 0x6) t4 = t3; t0 = W; if (t1 & 0x8) t0 = t4; pt2[cp] = t0; t0 = __ballot_sync(0xffffffff, (t1 & 0xf) != 0xf); t0 <<= (WP - threadIdx.x); t0 = __clz(t0); t5 = (t0 == WP) && ((t1 & 0xf) == 0xf); t0 = max((int)0, ((int)threadIdx.x) - 1 - ((int)t0)); t2 = pt2[threadIdx.y * WP + t0]; if (t2 == W) t2 = (t0 + 1 + threadIdx.y * WP) * 2; // __syncthreads(); if (threadIdx.x != 0 && (t1 & 0x1)) { if (t3 == cp2) t3 = t2; if (t4 == cp2) t4 = t2; } if (threadIdx.x == (WP - 1)) { t5 = t5 ? t4 : t4 + HW; t5 = (t1 & 0x8) ? t5 : (W + HW); tbf[threadIdx.y] = t5; } __syncthreads(); if (threadIdx.y != 0) { t5 = tbf[threadIdx.x]; t0 = __ballot_sync(0xffffffff, (t5 & HW) != 0); t0 <<= (WP - threadIdx.y); t0 = __clz(t0); t0 = max((int)0, ((int)threadIdx.y) - 1 - ((int)t0)); t1 = tbf[t0]; if (t1 & W) t1 = (t0 + 1) * WP * 2; t1 = t1 & MASKAD; //remove tags cp2 = threadIdx.y * WP * 2; if (px[cp2 >> 1] & 0x11) { if (t3 == cp2) t3 = t1; if (t4 == cp2) t4 = t1; } } t4 <<= 16; t4 |= t3; pt2[cp] = t4; } __global__ void static pass1_512(ushort* pt, uchar* ps, ushort* b, ushort* b2, uint h, ushort* eb) { __shared__ __align__(4) ushort lk0[HW]; //upper link __shared__ __align__(4) ushort lk1[HW]; //back up of current link // __shared__ __align__(4) ushort lk2[HW]; //new value of current link __shared__ __align__(4) ushort lk3[HW]; //down linked last block __shared__ __align__(4) ushort lk4[HW]; //botton link __shared__ uchar ct[HW]; //connection tag of each block __shared__ uchar px[QW]; //value of four pixels __shared__ ushort tbf[WP]; uint blockIdxx = blockIdx.x; uint cp = (threadIdx.x + threadIdx.y * WP) << 1; // if(blockIdxx != 10) // return; ps = ps + blockIdxx * h * W; pt = pt + blockIdxx * h * HW / 2; eb = eb + blockIdxx * HW * 9; h += 2; //calucate 2 more lines px[cp >> 1] = 0; // ((ushort*)ct)[cp>>1] = 0; detectRuns512(lk0, ct, ps, px, tbf, cp); ps += W; /* {//no error //cp = threadIdx.x + threadIdx.y*WP; ((uint*)(eb))[cp>>1] = 0; ((uint*)(eb+HW))[cp>>1] = 0; ((uint*)(eb+2*HW))[cp>>1] = 0; ((uint*)(eb+3*HW))[cp>>1] = 0; ((uint*)(eb+4*HW))[cp>>1] = 0; ((uint*)(eb+5*HW))[cp>>1] = 0; ((uint*)(eb+6*HW))[cp>>1] = 0; ((uint*)(eb+7*HW))[cp>>1] = 0; ((uint*)(eb+8*HW))[cp>>1] = 0; } */ for (int hh = 1; hh < h; hh++) { detectRuns512(lk1, ct, ps, px, tbf, cp); ps += W; uint lt0 = ((uint*)lk0)[cp >> 1]; //backup lk0 ((uint*)lk0)[cp >> 1] = lt0 | ((HW << 16) | HW);//((uint*)lk0)[cp>>1];//(W << 16) | W;//initialize lk2 __syncthreads(); uint lt1 = ((uint*)lk1)[cp >> 1]; //back up lk1, because lk1 will modified next { ushort t0; t0 = lt0; if (ct[cp]) {// every one write lk0 && lk1[lk0[cp]] > lk1[cp] lk0[t0] = lt1; } cp++; t0 = lt0 >> 16; if (ct[cp]) { lk0[t0] = lt1 >> 16; } cp--; __syncthreads(); } do { ushort t0, t1, t2; bool changed = 0; t1 = lt1; t0 = lt0; t2 = t1; if (ct[cp]) { t2 = lk0[t0]; if (t1 != t2) changed = 1; if (t2 < t1)//update self lk1[t1] = t2; } cp++; t1 = lt1 >> 16; t0 = lt0 >> 16; t2 = t1; if (ct[cp]) { t2 = lk0[t0]; if (t1 != t2) changed = 1; if (t2 < t1) lk1[t1] = t2; } cp--; changed = __syncthreads_or(changed); t1 = lt1; if (t1 < HW) t1 = lk1[t1]; lt1 = __byte_perm(lt1, t1, 0x3254); t1 = lt1 >> 16; if (t1 < HW) t1 = lk1[t1]; lt1 = __byte_perm(lt1, t1, 0x5410); if (!changed) break; t1 = lt1; t0 = lt0; if (ct[cp] && (lk0[t0] > t1)) {// min write lk0[t0] = t1; } cp++; t1 = lt1 >> 16; t0 = lt0 >> 16; if (ct[cp] && (lk0[t0] > t1)) { lk0[t0] = t1; } cp--; __syncthreads(); } while (1); ((uint*)lk1)[cp >> 1] = lt1; if ((hh & 0x1) && (hh != 1)) {//only odd line write out //resolve linkage by lk3, lk4 ushort t0, t1, t2; t0 = lk3[cp]; t2 = t0; if (t0 >= HW && t0 < W) t2 = lk3[t0 - HW]; if (t2 < HW) { t2 = lk0[t2]; if (t2 < HW) t0 = t2; else if (t0 < HW) t0 = cp | HW; } cp++; t1 = lk3[cp]; t2 = t1; if (t1 >= HW && t1 < W) t2 = lk3[t1 - HW]; if (t2 < HW) { t2 = lk0[t2]; if (t2 < HW) t1 = t2; else if (t1 < HW) t1 = cp | HW; } cp--; uint t3 = (t1 << 16) | t0; ((uint*)lk3)[cp >> 1] = t3;//write back, next iter, lk4 will use it //((uint*)pt)[cp>>1] = t3;//((uint*)lk3)[cp>>1]((uint*)lk3)[cp>>1] //pt += HW; } else ((uint*)lk3)[cp >> 1] = ((uint*)lk0)[cp >> 1];//t2; if((hh & 0x1) == 0) __syncthreads(); ((uint*)lk0)[cp >> 1] = ((uint*)lk1)[cp >> 1]; if (hh < 4) ((uint*)lk4)[cp >> 1] = ((uint*)lk3)[cp >> 1];//t2; else if ((hh & 0x1)) {// && (hh != 1) ushort t0, t1; t0 = lk4[cp]; t1 = t0; if (t0 < HW) { t0 = lk3[t0]; if (t0 >= HW && t0 < W) { lk3[t0 - HW] = 0x8000 | cp; t0 = t1 | 0x8000; } else if (t0 & 0x8000) t0 = t1 | 0x8000; } lk4[cp] = t0; cp++; t0 = lk4[cp]; t1 = t0; if (t0 < HW) { t0 = lk3[t0]; if (t0 >= HW && t0 < W) { lk3[t0 - HW] = 0x8000 | cp; t0 = t1 | 0x8000; } else if (t0 & 0x8000) t0 = t1 | 0x8000; } lk4[cp] = t0; cp--; } __syncthreads(); if ((hh & 0x1) && (hh != 1)) { ushort t0; ((uint*)pt)[cp >> 1] = ((uint*)lk3)[cp >> 1]; pt += HW; t0 = lk4[cp]; if (t0 & 0x8000) t0 = (lk3[t0 & MASKAD] & MASKAD) | HW; lk4[cp] = t0; cp++; t0 = lk4[cp]; if (t0 & 0x8000) t0 = (lk3[t0 & MASKAD] & MASKAD) | HW; lk4[cp] = t0; cp--; } } //write out info for pass2 { b += blockIdxx * 2 * HW; b2 += blockIdxx * 2 * HW; ((uint*)b)[cp >> 1] = ((uint*)lk4)[cp >> 1]; // ((uint*)b2)[cp>>1] = ((uint*)lk4)[cp>>1]; b += HW; b2 += HW; ((uint*)b)[cp >> 1] = ((uint*)lk1)[cp >> 1]; // ((uint*)b2)[cp>>1] = ((uint*)lk1)[cp>>1]; } // if(threadIdx.x == 0 && threadIdx.y == 0) // printf("%d end\n", blockIdx.x); } __global__ void static pass2_512(ushort* ib, uint* glabel, uint h, uint pitch) { __shared__ uint lk0[HW]; //last tag __shared__ ushort lk1[HW]; //current link __shared__ uint lk2[HW]; //current tag __shared__ ushort lk3[HW]; //bottom flattened link to current __shared__ uint labels; uint cp = threadIdx.x; ushort* b = ib + (h * (pitch + 1) * blockIdx.x + 1) * HW; { ushort tmp = b[cp]; lk0[cp] = tmp; lk3[cp] = tmp; lk2[cp] = W; b += HW * pitch; } labels = 0; __syncthreads(); for (int i = 1; i < h; i++) { ushort tmp, tmp1; //load a new block info tmp = b[cp];//the upper line connection info to bottom line // lk1[cp] = tmp; if (i > 1) { tmp1 = lk3[cp]; //update if (tmp1 < HW) tmp1 = tmp; lk3[cp] = tmp1; } b += HW; //lk2[cp] = b[cp];//the bottom line tags, this proc try to unify this line tmp1 = b[cp]; lk2[cp] = tmp1 + HW;//tmp1 < HW ? tmp1 + HW : tmp1; // b+=HW*pitch; __syncthreads(); ushort lt0 = lk0[cp]; if (tmp < HW)//every one write lk2[tmp] = lt0; else if (tmp < W) lk1[tmp - HW] = lt0; __syncthreads(); do { bool changed = 0; if (tmp < HW) { changed = lk2[tmp] != lt0; if (lk2[tmp] < lt0) lk0[lt0] = lk2[tmp]; } else if (tmp < W) { changed = lk1[tmp - HW] != lt0; if (lk1[tmp - HW] < lt0) lk0[lt0] = lk1[tmp - HW]; } changed = __syncthreads_or(changed); if (lt0 < HW) lt0 = lk0[lt0]; if (!changed) break; if (tmp < HW) { if (lk2[tmp] > lt0) lk2[tmp] = lt0; } else if (tmp < W) { if (lt0 < lk1[tmp - HW]) lk1[tmp - HW] = lt0; } __syncthreads(); } while (1); //write out lk2 info, ???link back to bottom? b -= HW * (pitch + 1); b[cp] = lt0; b += HW * (pitch + pitch + 1); tmp = lk2[cp]; if (tmp < HW)// && tmp < W)// && lk2[cp] == cp, if dateset correct, this is not necessary lk0[tmp] = cp; //atomicMin(lk0+tmp, cp); __syncthreads(); //head link together tmp = lk2[cp]; if (tmp < HW) tmp = lk0[tmp]; else if (tmp < W) tmp = tmp - HW; lk2[cp] = tmp; __syncthreads(); //all leaf in lk2 updates tmp = lk2[cp]; if (tmp < HW) tmp = lk2[tmp]; lk0[cp] = tmp;//so lk0 contains the last block line tags // __syncthreads(); } b -= HW * pitch; b[cp] = lk0[cp]; b = ib + (h * (pitch + 1) * (blockIdx.x + 1) - 1) * HW; //back ward tag assign { ushort tmp = b[cp], res = LBMAX; if (tmp == cp) res = atomicInc(&labels, 0x8000);//(h-1) << 12; lk2[cp] = res; __syncthreads(); if (tmp < HW) res = lk2[tmp]; lk2[cp] = res; //last line tags b[cp] = res; b -= HW; } __syncthreads(); for (int i = h - 2; i >= 0; i--) { ushort tmp, tmp2;//, tmp4; tmp = b[cp]; //next link info //lk1[cp] = tmp; b -= HW * pitch; tmp2 = b[cp];//current link info lk1[cp] = tmp2; lk0[cp] = LBMAX;//final tags __syncthreads(); /* tmp4 = W; if(tmp >= HW && tmp < W){//race to resolve linked by current block tmp4 = tmp - HW; lk1[tmp4] = tmp2; } __syncthreads(); do{ bool changed = 0; if(tmp4 < HW){ changed = lk1[tmp4] != tmp2; if(tmp2 > lk1[tmp4]) lk1[tmp2] = lk1[tmp4]; } changed = __syncthreads_or(changed); if(tmp2 < HW) tmp2 = lk1[tmp2]; if(!changed) break; if(tmp4 < HW && tmp2 < lk1[tmp4]) lk1[tmp4] = tmp2; __syncthreads(); }while(1); */ if (tmp < HW) {//next linked if (tmp2 < HW) lk0[tmp2] = lk2[tmp]; // else // tmp2 = W; } __syncthreads(); if (tmp2 == cp && lk0[cp] == LBMAX) {//current linked lk0[cp] = atomicInc(&labels, 0x8000);//((h-1) << 12) - HW; } __syncthreads(); tmp = LBMAX; if (tmp2 < HW) tmp = lk0[tmp2]; //write out tags b[cp] = tmp; b -= HW; //switch buffer lk2[cp] = tmp; __syncthreads(); } //update first line link info // b = ib + (h*(pitch+1)*blockIdx.x) * HW; // b[cp] = lk3[cp]; *glabel = labels; } __global__ void static pass3_512(ushort* pt, ushort* ps, ushort* b, uint* label, uint h) { __shared__ ushort cur[W / 2]; //last tag __shared__ ushort lst[W / 2]; //current link __shared__ ushort bot[W / 2]; //current tag __shared__ ushort lnk[W / 2]; //current link to last // __shared__ uint llabel; uint cp = (threadIdx.x + threadIdx.y * WP) << 1; pt = pt + (blockIdx.x * h + h - 1) * HW; ps = ps + (blockIdx.x * h + h - 1) * HW; if (blockIdx.x == 0) { ((uint*)bot)[cp >> 1] = LB2MAX; b += HW; } else { b += (blockIdx.x * 2 - 1) * HW; ((uint*)bot)[cp >> 1] = ((uint*)b)[cp >> 1]; b += 2 * HW; } ((uint*)cur)[cp >> 1] = ((uint*)b)[cp >> 1]; __syncthreads(); for (int i = h - 1; i >= 0; i--) { //load current link ((uint*)lnk)[cp >> 1] = ((uint*)ps)[cp >> 1]; ps -= HW; //switch cur last ((uint*)lst)[cp >> 1] = ((uint*)cur)[cp >> 1]; //clear cur ((uint*)cur)[cp >> 1] = LB2MAX; // llabel = 0; __syncthreads(); if (lnk[cp] < HW) {//link to last cur[cp] = lst[lnk[cp]]; } else if (lnk[cp] < W && lnk[cp] == (HW + cp)) {//link to local, and a head, assigning new label if (blockIdx.x != 0 && i == 0) cur[cp] = bot[cp]; else cur[cp] = atomicInc(label, LBMAX); } if (lnk[cp] & 0x8000) {//link to bottom if (blockIdx.x == 0) cur[cp] = atomicInc(label, LBMAX); else cur[cp] = bot[lnk[cp] & MASKAD]; } cp++; if (lnk[cp] < HW) {//link to last cur[cp] = lst[lnk[cp]]; } else if (lnk[cp] < W && lnk[cp] == (HW + cp)) {//link to local, and a head, assigning new label if (blockIdx.x != 0 && i == 0) cur[cp] = bot[cp]; else cur[cp] = atomicInc(label, LBMAX); } if (lnk[cp] & 0x8000) {//link to bottom if (blockIdx.x == 0) cur[cp] = atomicInc(label, LBMAX); else cur[cp] = bot[lnk[cp] & MASKAD]; } cp--; __syncthreads(); if (lnk[cp] >= HW && lnk[cp] < W) cur[cp] = cur[lnk[cp] - HW]; cp++; if (lnk[cp] >= HW && lnk[cp] < W) cur[cp] = cur[lnk[cp] - HW]; cp--; //write out ((uint*)pt)[cp >> 1] = ((uint*)cur)[cp >> 1]; pt -= HW; __syncthreads(); } } void chen_label_512(uchar* cbpt, uchar* cbpt2, uchar* cbps, uchar* cbb, uchar* cbb2, uchar* cbglabel, uint h, uint bn, uchar* cbeb) { ushort* pt = (ushort*)cbpt; ushort* pt2 = (ushort*)cbpt2; uchar* ps = (uchar*)cbps; ushort* b = (ushort*)cbb; ushort* b2 = (ushort*)cbb2; uint* glabel = (uint*)cbglabel; ushort* eb = (ushort*)cbeb; dim3 threads(WP, TN / WP, 1); dim3 grid(bn, 1, 1); dim3 threads2(HW, 1, 1); dim3 grid2(1, 1, 1); pass1_512 << <grid, threads >> > (pt2, ps, b, b2, (h - 2) / bn, eb); pass2_512 << <grid2, threads2 >> > (b, glabel, bn, 1); pass3_512 << <grid, threads >> > (pt, pt2, b, glabel, (h - 2) / (bn * 2)); }
8c1366b40742a7117ffd5959c92ee31d6ae7bd86.cu
#define WP 32 #define BM (WP-1) #define dt unsigned short #define dts 2 #define TGTG 1 #define TGNTG 0 #define LBMAX 0xffff #define LB2MAX 0xffffffff typedef unsigned int uint; typedef unsigned char uchar; typedef unsigned short ushort; #define W 512 #define HWW 8 #define rep 2 #define HW (W/2) #define QW (W/4) #define HWP (WP/2) #define QWP (WP/4) #define EWP (WP/8) #define XWP (WP/16) #define TN (W/(rep*2)) #define WN (TN/WP) #define MASKAD (~(-1 << HWW)) __device__ __inline__ static void detectRuns512(ushort* pt, uchar* ct, uchar* ps, uchar* px, ushort* tbf, uint cp2) { uint* ps4 = (uint*)ps; uint* pt2 = (uint*)pt; ushort* ct2 = (ushort*)ct; uint cp = cp2 >> 1;//threadIdx.x + threadIdx.y * WP; // uint cp2 = cp << 1; uint t0, t1, t2, t3, t4, t5; t0 = ps4[cp]; t0 = __byte_perm(t0, 0, 0x3120); t0 &= 0x1010101; t0 |= t0 >> 15; t0 |= t0 >> 6; t0 &= 0xf; // now t0 has the 4 pixels in its 4 less significant bits t1 = px[cp]; t5 = 0; if ((t1 & 0x3))// && (t0 & 0x3) t5 = 0x1; if ((t1 & 0xc))// && (t0 & 0xc) t5 |= 0x100; ct2[cp] = t5;// | ((ct2[cp] & 0xf0f) << 4); t1 = t1 | t0; px[cp] = t0 | (px[cp] << 4); t3 = W; t4 = W; t5 = 0; if (t1 & 0x3) t3 = cp2; if (t1 & 0xc) t4 = cp2 + 1; if ((t1 & 0x6) == 0x6) t4 = t3; t0 = W; if (t1 & 0x8) t0 = t4; pt2[cp] = t0; t0 = __ballot_sync(0xffffffff, (t1 & 0xf) != 0xf); t0 <<= (WP - threadIdx.x); t0 = __clz(t0); t5 = (t0 == WP) && ((t1 & 0xf) == 0xf); t0 = max((int)0, ((int)threadIdx.x) - 1 - ((int)t0)); t2 = pt2[threadIdx.y * WP + t0]; if (t2 == W) t2 = (t0 + 1 + threadIdx.y * WP) * 2; // __syncthreads(); if (threadIdx.x != 0 && (t1 & 0x1)) { if (t3 == cp2) t3 = t2; if (t4 == cp2) t4 = t2; } if (threadIdx.x == (WP - 1)) { t5 = t5 ? t4 : t4 + HW; t5 = (t1 & 0x8) ? t5 : (W + HW); tbf[threadIdx.y] = t5; } __syncthreads(); if (threadIdx.y != 0) { t5 = tbf[threadIdx.x]; t0 = __ballot_sync(0xffffffff, (t5 & HW) != 0); t0 <<= (WP - threadIdx.y); t0 = __clz(t0); t0 = max((int)0, ((int)threadIdx.y) - 1 - ((int)t0)); t1 = tbf[t0]; if (t1 & W) t1 = (t0 + 1) * WP * 2; t1 = t1 & MASKAD; //remove tags cp2 = threadIdx.y * WP * 2; if (px[cp2 >> 1] & 0x11) { if (t3 == cp2) t3 = t1; if (t4 == cp2) t4 = t1; } } t4 <<= 16; t4 |= t3; pt2[cp] = t4; } __global__ void static pass1_512(ushort* pt, uchar* ps, ushort* b, ushort* b2, uint h, ushort* eb) { __shared__ __align__(4) ushort lk0[HW]; //upper link __shared__ __align__(4) ushort lk1[HW]; //back up of current link // __shared__ __align__(4) ushort lk2[HW]; //new value of current link __shared__ __align__(4) ushort lk3[HW]; //down linked last block __shared__ __align__(4) ushort lk4[HW]; //botton link __shared__ uchar ct[HW]; //connection tag of each block __shared__ uchar px[QW]; //value of four pixels __shared__ ushort tbf[WP]; uint blockIdxx = blockIdx.x; uint cp = (threadIdx.x + threadIdx.y * WP) << 1; // if(blockIdxx != 10) // return; ps = ps + blockIdxx * h * W; pt = pt + blockIdxx * h * HW / 2; eb = eb + blockIdxx * HW * 9; h += 2; //calucate 2 more lines px[cp >> 1] = 0; // ((ushort*)ct)[cp>>1] = 0; detectRuns512(lk0, ct, ps, px, tbf, cp); ps += W; /* {//no error //cp = threadIdx.x + threadIdx.y*WP; ((uint*)(eb))[cp>>1] = 0; ((uint*)(eb+HW))[cp>>1] = 0; ((uint*)(eb+2*HW))[cp>>1] = 0; ((uint*)(eb+3*HW))[cp>>1] = 0; ((uint*)(eb+4*HW))[cp>>1] = 0; ((uint*)(eb+5*HW))[cp>>1] = 0; ((uint*)(eb+6*HW))[cp>>1] = 0; ((uint*)(eb+7*HW))[cp>>1] = 0; ((uint*)(eb+8*HW))[cp>>1] = 0; } */ for (int hh = 1; hh < h; hh++) { detectRuns512(lk1, ct, ps, px, tbf, cp); ps += W; uint lt0 = ((uint*)lk0)[cp >> 1]; //backup lk0 ((uint*)lk0)[cp >> 1] = lt0 | ((HW << 16) | HW);//((uint*)lk0)[cp>>1];//(W << 16) | W;//initialize lk2 __syncthreads(); uint lt1 = ((uint*)lk1)[cp >> 1]; //back up lk1, because lk1 will modified next { ushort t0; t0 = lt0; if (ct[cp]) {// every one write lk0 && lk1[lk0[cp]] > lk1[cp] lk0[t0] = lt1; } cp++; t0 = lt0 >> 16; if (ct[cp]) { lk0[t0] = lt1 >> 16; } cp--; __syncthreads(); } do { ushort t0, t1, t2; bool changed = 0; t1 = lt1; t0 = lt0; t2 = t1; if (ct[cp]) { t2 = lk0[t0]; if (t1 != t2) changed = 1; if (t2 < t1)//update self lk1[t1] = t2; } cp++; t1 = lt1 >> 16; t0 = lt0 >> 16; t2 = t1; if (ct[cp]) { t2 = lk0[t0]; if (t1 != t2) changed = 1; if (t2 < t1) lk1[t1] = t2; } cp--; changed = __syncthreads_or(changed); t1 = lt1; if (t1 < HW) t1 = lk1[t1]; lt1 = __byte_perm(lt1, t1, 0x3254); t1 = lt1 >> 16; if (t1 < HW) t1 = lk1[t1]; lt1 = __byte_perm(lt1, t1, 0x5410); if (!changed) break; t1 = lt1; t0 = lt0; if (ct[cp] && (lk0[t0] > t1)) {// min write lk0[t0] = t1; } cp++; t1 = lt1 >> 16; t0 = lt0 >> 16; if (ct[cp] && (lk0[t0] > t1)) { lk0[t0] = t1; } cp--; __syncthreads(); } while (1); ((uint*)lk1)[cp >> 1] = lt1; if ((hh & 0x1) && (hh != 1)) {//only odd line write out //resolve linkage by lk3, lk4 ushort t0, t1, t2; t0 = lk3[cp]; t2 = t0; if (t0 >= HW && t0 < W) t2 = lk3[t0 - HW]; if (t2 < HW) { t2 = lk0[t2]; if (t2 < HW) t0 = t2; else if (t0 < HW) t0 = cp | HW; } cp++; t1 = lk3[cp]; t2 = t1; if (t1 >= HW && t1 < W) t2 = lk3[t1 - HW]; if (t2 < HW) { t2 = lk0[t2]; if (t2 < HW) t1 = t2; else if (t1 < HW) t1 = cp | HW; } cp--; uint t3 = (t1 << 16) | t0; ((uint*)lk3)[cp >> 1] = t3;//write back, next iter, lk4 will use it //((uint*)pt)[cp>>1] = t3;//((uint*)lk3)[cp>>1]((uint*)lk3)[cp>>1] //pt += HW; } else ((uint*)lk3)[cp >> 1] = ((uint*)lk0)[cp >> 1];//t2; if((hh & 0x1) == 0) __syncthreads(); ((uint*)lk0)[cp >> 1] = ((uint*)lk1)[cp >> 1]; if (hh < 4) ((uint*)lk4)[cp >> 1] = ((uint*)lk3)[cp >> 1];//t2; else if ((hh & 0x1)) {// && (hh != 1) ushort t0, t1; t0 = lk4[cp]; t1 = t0; if (t0 < HW) { t0 = lk3[t0]; if (t0 >= HW && t0 < W) { lk3[t0 - HW] = 0x8000 | cp; t0 = t1 | 0x8000; } else if (t0 & 0x8000) t0 = t1 | 0x8000; } lk4[cp] = t0; cp++; t0 = lk4[cp]; t1 = t0; if (t0 < HW) { t0 = lk3[t0]; if (t0 >= HW && t0 < W) { lk3[t0 - HW] = 0x8000 | cp; t0 = t1 | 0x8000; } else if (t0 & 0x8000) t0 = t1 | 0x8000; } lk4[cp] = t0; cp--; } __syncthreads(); if ((hh & 0x1) && (hh != 1)) { ushort t0; ((uint*)pt)[cp >> 1] = ((uint*)lk3)[cp >> 1]; pt += HW; t0 = lk4[cp]; if (t0 & 0x8000) t0 = (lk3[t0 & MASKAD] & MASKAD) | HW; lk4[cp] = t0; cp++; t0 = lk4[cp]; if (t0 & 0x8000) t0 = (lk3[t0 & MASKAD] & MASKAD) | HW; lk4[cp] = t0; cp--; } } //write out info for pass2 { b += blockIdxx * 2 * HW; b2 += blockIdxx * 2 * HW; ((uint*)b)[cp >> 1] = ((uint*)lk4)[cp >> 1]; // ((uint*)b2)[cp>>1] = ((uint*)lk4)[cp>>1]; b += HW; b2 += HW; ((uint*)b)[cp >> 1] = ((uint*)lk1)[cp >> 1]; // ((uint*)b2)[cp>>1] = ((uint*)lk1)[cp>>1]; } // if(threadIdx.x == 0 && threadIdx.y == 0) // printf("%d end\n", blockIdx.x); } __global__ void static pass2_512(ushort* ib, uint* glabel, uint h, uint pitch) { __shared__ uint lk0[HW]; //last tag __shared__ ushort lk1[HW]; //current link __shared__ uint lk2[HW]; //current tag __shared__ ushort lk3[HW]; //bottom flattened link to current __shared__ uint labels; uint cp = threadIdx.x; ushort* b = ib + (h * (pitch + 1) * blockIdx.x + 1) * HW; { ushort tmp = b[cp]; lk0[cp] = tmp; lk3[cp] = tmp; lk2[cp] = W; b += HW * pitch; } labels = 0; __syncthreads(); for (int i = 1; i < h; i++) { ushort tmp, tmp1; //load a new block info tmp = b[cp];//the upper line connection info to bottom line // lk1[cp] = tmp; if (i > 1) { tmp1 = lk3[cp]; //update if (tmp1 < HW) tmp1 = tmp; lk3[cp] = tmp1; } b += HW; //lk2[cp] = b[cp];//the bottom line tags, this proc try to unify this line tmp1 = b[cp]; lk2[cp] = tmp1 + HW;//tmp1 < HW ? tmp1 + HW : tmp1; // b+=HW*pitch; __syncthreads(); ushort lt0 = lk0[cp]; if (tmp < HW)//every one write lk2[tmp] = lt0; else if (tmp < W) lk1[tmp - HW] = lt0; __syncthreads(); do { bool changed = 0; if (tmp < HW) { changed = lk2[tmp] != lt0; if (lk2[tmp] < lt0) lk0[lt0] = lk2[tmp]; } else if (tmp < W) { changed = lk1[tmp - HW] != lt0; if (lk1[tmp - HW] < lt0) lk0[lt0] = lk1[tmp - HW]; } changed = __syncthreads_or(changed); if (lt0 < HW) lt0 = lk0[lt0]; if (!changed) break; if (tmp < HW) { if (lk2[tmp] > lt0) lk2[tmp] = lt0; } else if (tmp < W) { if (lt0 < lk1[tmp - HW]) lk1[tmp - HW] = lt0; } __syncthreads(); } while (1); //write out lk2 info, ???link back to bottom? b -= HW * (pitch + 1); b[cp] = lt0; b += HW * (pitch + pitch + 1); tmp = lk2[cp]; if (tmp < HW)// && tmp < W)// && lk2[cp] == cp, if dateset correct, this is not necessary lk0[tmp] = cp; //atomicMin(lk0+tmp, cp); __syncthreads(); //head link together tmp = lk2[cp]; if (tmp < HW) tmp = lk0[tmp]; else if (tmp < W) tmp = tmp - HW; lk2[cp] = tmp; __syncthreads(); //all leaf in lk2 updates tmp = lk2[cp]; if (tmp < HW) tmp = lk2[tmp]; lk0[cp] = tmp;//so lk0 contains the last block line tags // __syncthreads(); } b -= HW * pitch; b[cp] = lk0[cp]; b = ib + (h * (pitch + 1) * (blockIdx.x + 1) - 1) * HW; //back ward tag assign { ushort tmp = b[cp], res = LBMAX; if (tmp == cp) res = atomicInc(&labels, 0x8000);//(h-1) << 12; lk2[cp] = res; __syncthreads(); if (tmp < HW) res = lk2[tmp]; lk2[cp] = res; //last line tags b[cp] = res; b -= HW; } __syncthreads(); for (int i = h - 2; i >= 0; i--) { ushort tmp, tmp2;//, tmp4; tmp = b[cp]; //next link info //lk1[cp] = tmp; b -= HW * pitch; tmp2 = b[cp];//current link info lk1[cp] = tmp2; lk0[cp] = LBMAX;//final tags __syncthreads(); /* tmp4 = W; if(tmp >= HW && tmp < W){//race to resolve linked by current block tmp4 = tmp - HW; lk1[tmp4] = tmp2; } __syncthreads(); do{ bool changed = 0; if(tmp4 < HW){ changed = lk1[tmp4] != tmp2; if(tmp2 > lk1[tmp4]) lk1[tmp2] = lk1[tmp4]; } changed = __syncthreads_or(changed); if(tmp2 < HW) tmp2 = lk1[tmp2]; if(!changed) break; if(tmp4 < HW && tmp2 < lk1[tmp4]) lk1[tmp4] = tmp2; __syncthreads(); }while(1); */ if (tmp < HW) {//next linked if (tmp2 < HW) lk0[tmp2] = lk2[tmp]; // else // tmp2 = W; } __syncthreads(); if (tmp2 == cp && lk0[cp] == LBMAX) {//current linked lk0[cp] = atomicInc(&labels, 0x8000);//((h-1) << 12) - HW; } __syncthreads(); tmp = LBMAX; if (tmp2 < HW) tmp = lk0[tmp2]; //write out tags b[cp] = tmp; b -= HW; //switch buffer lk2[cp] = tmp; __syncthreads(); } //update first line link info // b = ib + (h*(pitch+1)*blockIdx.x) * HW; // b[cp] = lk3[cp]; *glabel = labels; } __global__ void static pass3_512(ushort* pt, ushort* ps, ushort* b, uint* label, uint h) { __shared__ ushort cur[W / 2]; //last tag __shared__ ushort lst[W / 2]; //current link __shared__ ushort bot[W / 2]; //current tag __shared__ ushort lnk[W / 2]; //current link to last // __shared__ uint llabel; uint cp = (threadIdx.x + threadIdx.y * WP) << 1; pt = pt + (blockIdx.x * h + h - 1) * HW; ps = ps + (blockIdx.x * h + h - 1) * HW; if (blockIdx.x == 0) { ((uint*)bot)[cp >> 1] = LB2MAX; b += HW; } else { b += (blockIdx.x * 2 - 1) * HW; ((uint*)bot)[cp >> 1] = ((uint*)b)[cp >> 1]; b += 2 * HW; } ((uint*)cur)[cp >> 1] = ((uint*)b)[cp >> 1]; __syncthreads(); for (int i = h - 1; i >= 0; i--) { //load current link ((uint*)lnk)[cp >> 1] = ((uint*)ps)[cp >> 1]; ps -= HW; //switch cur last ((uint*)lst)[cp >> 1] = ((uint*)cur)[cp >> 1]; //clear cur ((uint*)cur)[cp >> 1] = LB2MAX; // llabel = 0; __syncthreads(); if (lnk[cp] < HW) {//link to last cur[cp] = lst[lnk[cp]]; } else if (lnk[cp] < W && lnk[cp] == (HW + cp)) {//link to local, and a head, assigning new label if (blockIdx.x != 0 && i == 0) cur[cp] = bot[cp]; else cur[cp] = atomicInc(label, LBMAX); } if (lnk[cp] & 0x8000) {//link to bottom if (blockIdx.x == 0) cur[cp] = atomicInc(label, LBMAX); else cur[cp] = bot[lnk[cp] & MASKAD]; } cp++; if (lnk[cp] < HW) {//link to last cur[cp] = lst[lnk[cp]]; } else if (lnk[cp] < W && lnk[cp] == (HW + cp)) {//link to local, and a head, assigning new label if (blockIdx.x != 0 && i == 0) cur[cp] = bot[cp]; else cur[cp] = atomicInc(label, LBMAX); } if (lnk[cp] & 0x8000) {//link to bottom if (blockIdx.x == 0) cur[cp] = atomicInc(label, LBMAX); else cur[cp] = bot[lnk[cp] & MASKAD]; } cp--; __syncthreads(); if (lnk[cp] >= HW && lnk[cp] < W) cur[cp] = cur[lnk[cp] - HW]; cp++; if (lnk[cp] >= HW && lnk[cp] < W) cur[cp] = cur[lnk[cp] - HW]; cp--; //write out ((uint*)pt)[cp >> 1] = ((uint*)cur)[cp >> 1]; pt -= HW; __syncthreads(); } } void chen_label_512(uchar* cbpt, uchar* cbpt2, uchar* cbps, uchar* cbb, uchar* cbb2, uchar* cbglabel, uint h, uint bn, uchar* cbeb) { ushort* pt = (ushort*)cbpt; ushort* pt2 = (ushort*)cbpt2; uchar* ps = (uchar*)cbps; ushort* b = (ushort*)cbb; ushort* b2 = (ushort*)cbb2; uint* glabel = (uint*)cbglabel; ushort* eb = (ushort*)cbeb; dim3 threads(WP, TN / WP, 1); dim3 grid(bn, 1, 1); dim3 threads2(HW, 1, 1); dim3 grid2(1, 1, 1); pass1_512 << <grid, threads >> > (pt2, ps, b, b2, (h - 2) / bn, eb); pass2_512 << <grid2, threads2 >> > (b, glabel, bn, 1); pass3_512 << <grid, threads >> > (pt, pt2, b, glabel, (h - 2) / (bn * 2)); }